PHP kézikönyv

Stig Sæther Bakken
Alexander Aulbach
Egon Schmid
Jim Winstead
Lars Torben Wilson
Rasmus Lerdorf
Andrei Zmievski
Jouni Ahto

Szerkesztette

Stig Sæther Bakken
Egon Schmid
Fordítók:
Csontos András
Heilig Szabolcs
Hojtsy Gábor
Kontra Gergely
Papp Győző
Tóth Attila
Varanka Zoltán
Másképpen segített:
Jouni Ahto

02-02-2004

Copyright

Copyright © 1997 - 2003 by the PHP Documentation Group. This material may be distributed only subject to the terms and conditions set forth in the Open Publication License, v1.0 or later (the latest version is presently available at http://www.opencontent.org/openpub/).

Distribution of substantively modified versions of this document is prohibited without the explicit permission of the copyright holder.

Distribution of the work or derivative of the work in any standard (paper) book form is prohibited unless prior permission is obtained from the copyright holder.

The members of the PHP Documentation Group are listed on the front page of this manual. In case you would like to contact the group, please write to phpdoc@lists.php.net.

The 'Extending PHP 4.0' section of this manual is copyright © 2000 by Zend Technologies, Ltd. This material may be distributed only subject to the terms and conditions set forth in the Open Publication License, v1.0 or later (the latest version is presently available at http://www.opencontent.org/openpub/).

A magyar copyright megegyezik az angol feltételekkel. A PHP kézikönyv magyar fordításának oldala a http://weblabor.hu/ címen található. A fordítók nevei szintén a fedlapon olvashatóak.


Tartalom
Előszó
I. Első lépések
1. Bevezetés a PHP-be
2. A simple tutorial
3. Telepítés
4. Runtime Configuration
II. A nyelv alapjai
5. Alapvető szintaxis
6. Típusok
7. Változók
8. Állandók
9. Kifejezések
10. Operátorok
11. Vezérlési szerkezetek
12. Függvények
13. Osztályok, objektumok
14. Referenciák
III. Biztonság
15. Security
IV. Szolgáltatások
16. HTTP hitelesítés PHP-vel
17. Sütik (cookie-k)
18. Fájlfeltöltés kezelése
19. Távoli állományok kezelése
20. Kapcsolatkezelés
21. Állandó adatbázis kapcsolatok
22. Safe Mode
23. Parancssori programozás a PHP-ben
V. Függvény referencia
I. Apache-specifikus függvények
II. Tömbkezelő függvények
III. Aspell függvények [ellenjavallt]
IV. BCMath tetszőleges pontosságú matematikai függvények
V. Bzip2 tömörítési függvények
VI. Naptár függvények
VII. CCVS függvények
VIII. COM támogató függvények Windowshoz
IX. Osztály/Objektum függvények
X. ClibPDF függvények
XI. Crack functions
XII. CURL, Client URL Library Functions
XIII. Cybercash payment függvények
XIV. Cyrus IMAP administration functions
XV. Character type functions
XVI. Database (dbm-style) abstraction layer functions
XVII. Dátummal és időponttal kapcsolatos függvények
XVIII. dBase functions
XIX. DBM Functions [deprecated]
XX. dbx függvények
XXI. DB++ Functions
XXII. Direct IO functions
XXIII. Könyvtárkezelő függvények
XXIV. DOM XML függvények
XXV. .NET functions
XXVI. Error Handling and Logging Functions
XXVII. File alteration monitor functions
XXVIII. FrontBase Functions
XXIX. filePro függvények
XXX. Filesystem functions
XXXI. Forms Data Format functions
XXXII. FriBiDi functions
XXXIII. FTP functions
XXXIV. Függvénykezelő függvények
XXXV. GNU Gettext
XXXVI. GMP functions
XXXVII. HTTP functions
XXXVIII. Hyperwave functions
XXXIX. Hyperwave API functions
XL. iconv functions
XLI. Képmanipuláló függvények
XLII. IMAP, POP3 and NNTP functions
XLIII. Informix functions
XLIV. InterBase functions
XLV. Ingres II functions
XLVI. IRC Gateway Functions
XLVII. PHP / Java Integration
XLVIII. LDAP functions
XLIX. LZF Functions
L. Mail függvények
LI. mailparse functions
LII. Matematikai függvények
LIII. Multi-Byte String Functions
LIV. MCAL functions
LV. Mcrypt Encryption Functions
LVI. MCVE Payment Functions
LVII. Mhash függvények
LVIII. Mimetype Functions
LIX. Microsoft SQL Server functions
LX. Ming függvénykönyvtár Flash mozik előállításához
LXI. Miscellaneous functions
LXII. mnoGoSearch Functions
LXIII. mSQL functions
LXIV. MySQL függvények
LXV. Improved MySQL Extension
LXVI. Mohawk Software session handler functions
LXVII. muscat functions
LXVIII. Hálózatkezelési Függvények
LXIX. Ncurses terminal screen control functions
LXX. Lotus Notes functions
LXXI. NSAPI-specific Functions
LXXII. Unified ODBC functions
LXXIII. Object Aggregation/Composition Functions
LXXIV. Oracle 8 függvények
LXXV. OpenSSL functions
LXXVI. Oracle függvények
LXXVII. Ovrimos SQL functions
LXXVIII. Kimenet Szabályozó Függvények
LXXIX. Object property and method call overloading
LXXX. PDF functions
LXXXI. Verisign Payflow Pro functions
LXXXII. PHP Options&Information
LXXXIII. POSIX functions
LXXXIV. PostgreSQL függvények
LXXXV. Process Control Functions
LXXXVI. Programfuttató függvények
LXXXVII. Printer functions
LXXXVIII. Pspell Functions
LXXXIX. GNU Readline
XC. GNU Recode függvények
XCI. Reguláris kifejezések függvényei (Perl kompatibilis)
XCII. qtdom functions
XCIII. Regular Expression Functions (POSIX Extended)
XCIV. Semaphore, Shared Memory and IPC Functions
XCV. SESAM database functions
XCVI. Munkamenet kezelő függvények
XCVII. Shared Memory Functions
XCVIII. SimpleXML functions
XCIX. SQLite
C. Shockwave Flash functions
CI. SNMP functions
CII. Socket functions
CIII. Stream functions
CIV. String functions
CV. Sybase functions
CVI. Tidy Functions
CVII. Tokenizer functions
CVIII. URL függvények
CIX. Változókkal kapcsolatos függvények
CX. vpopmail függvények
CXI. W32api functions
CXII. WDDX függvények
CXIII. XML értelmező függvények
CXIV. XML-RPC functions
CXV. XSLT függvények
CXVI. YAZ functions
CXVII. YP/NIS Functions
CXVIII. Zip Fájl függvények (csak olvasáshoz)
CXIX. Zlib Compression Functions
VI. Zend API
24. Overview
25. Extension Possibilities
26. Source Layout
27. PHP's Automatic Build System
28. Creating Extensions
29. Using Extensions
30. Troubleshooting
31. Source Discussion
32. Accepting Arguments
33. Creating Variables
34. Duplicating Variable Contents: The Copy Constructor
35. Returning Values
36. Printing Information
37. Startup and Shutdown Functions
38. Calling User Functions
39. Initialization File Support
40. Where to Go from Here
41. Reference: Some Configuration Macros
42. API Macros
VII. PHP API: Felület, kiegészítések írásához
43. Streams API for PHP Extension Authors
VIII. GYIK: Gyakran Ismételt Kérdések
44. General Information
45. Mailing lists
46. Obtaining PHP
47. Database issues
48. Installation
49. Build Problems
50. Using PHP
51. PHP and HTML
52. PHP and COM
53. PHP and other languages
54. Migrating from PHP 2 to PHP 3
55. Migrating from PHP 3 to PHP 4
56. Miscellaneous Questions
IX. Függelékek
A. History of PHP and related projects
B. Migrating from PHP 4 to PHP 5
C. Migrating from PHP 3 to PHP 4
D. Migrating from PHP/FI 2 to PHP 3
E. A PHP debuggere
F. Extending PHP 3
G. Álnevek listája
H. List of Reserved Words
I. Erőforrás típusok listája
J. List of Supported Protocols/Wrappers
K. List of Supported Socket Transports
L. PHP type comparison tables
M. List of Parser Tokens
N. About the manual
O. Open Publication License
P. Függvények listája
Q. Hiányzó elemek

Előszó

A PHP, bővebben "PHP: Hypertext Preprocessor" egy széles körben használt, nyílt forráskódú, általános célú programozási nyelv, különösen jó web-fejlesztés támogatással, és HTML-be ágyazási képességekkel. A szintakszisa a C, Java és Perl nyelvekre épül, könnyen megtanulható. A nyelv fő célja lehetőséget teremteni dinamikusan generált weboldalak gyors készítésére, de a PHP ennél sokkal többre is képes.

Ez a kézikönyv legfőképpen függvény referenciaként használható, azonban a nyelvi elemek ismertetése is megtalálható benne, a főbb PHP szolgáltatások leírása, és más kapcsolódó információk mellett.

Ez a kézikönyv számos nyelven és formátumban letölthető a http://www.php.net/docs.php címen. A letöltések a tartalom változásával frissülnek. Ha érdekel, hogyan készül ez a kézikönyv, olvasd el az 'About the manual' című függeléket.

A magyar kézikönyvet téritésmentesen készítjük, szabadidőnkben. A le nem fordított fejezetek mindig a legfrissebb angol szöveggel jelennek meg, ezért vegyes nyelvű oldalakkal igen ritkán fogsz találkozni. Időnként az azonban előfordulhat, hogy bizonyos már lefordított fejezetek nem teljesen aktuálisak. Emiatt ha mindig aktuális és pontos információra van szükséged, és értesz angolul, érdemes ezt a kézikönyvet az angol változattal párhuzamosan használni. Az esetleges kellemetlenségekért elnézést kérünk.

A PHP kézikönyv magyar fordításának oldala a http://phpdoc.weblabor.hu címen található. Ha szeretnél bekapcsolódni a fordításba, látogasd meg ezt a címet.

Lásd még: A PHP története


1. Fejezet. Bevezetés a PHP-be

Mi az a PHP?

A PHP (rekurzív rövidítéssel "PHP: Hypertext Preprocessor") széles körben használt általános célú szkriptnyelv, amely kifejezetten alkalmas - akár HTML-be ágyazott - webalkalmazások fejlesztésére.

Egyszerű meghatározás, de mit is jelent ez valójában? Egy példán bemutatva:

Példa 1-1. Egy bevezető példa

<html>
    <head>
        <title>Példa</title>
    </head>
    <body>

        <?php
        echo "Helló, Én egy PHP szkript vagyok!";
        ?>

    </body>
</html>

Vedd észre, hogy ez mennyire különbözik más nyelveken (például Perl vagy C) írt hagyományos szkripttől. Sok parancsból álló programok helyett csak egy HTML fájlba kell egy kevés programkódot beépíteni, hogy a megfelelő HTML kimenetet produkálja. A PHP kódblokkokat speciális kezdő és befejező jelölések közé kell elhelyezni, és ezek biztosítják, hogy a feldolgozás során a váltogathasd a "PHP módot".

Az különbözteti meg a PHP-t a kliens oldali nyelvektől - pl. JavaScript -, hogy a kód a kiszolgálón fut. Az első példában látható oldal eredményét böngészőben megnézve, nem lehet megállapítani, hogy milyen kód állíthatta azt elő. Ezen felül a webszervert be lehet állítani úgy, hogy a PHP feldolgozzon minden HTML fájlt PHP blokkokat keresve, ezek után már tényleg nincs rá mód, hogy kitalálják, mit is rejt egy-egy programod.

A legjobb dolog a PHP használatában, hogy különösen egyszerű egy kezdő számára, de számos, fejlett szolgáltatást nyújt professzionális programozó számára is. Ne ijesszen el a PHP hosszú szolgáltatás listája. Gyors léptekkel lehet haladni a PHP használatában, és pár órán belül már egyszerű szkriptek írására is képes lehetsz.

Habár a PHP fejlesztésében a szerver-oldali programozás kapja a legnagyobb hangsúlyt, annál sokkal többet tud. Olvasd tovább ezt a fejezetet a következő - Mit tud a PHP? - című résszel folytatva!


Mit tud a PHP?

Bármit. A PHP főleg szerver-oldali szkriptek írására készült, azaz bármire képes, amit más CGI programok el tudnak végezni, ilyen funkciók az űrlap adatok feldolgozása, dinamikus tartalom generálása, vagy sütik küldése és fogadása. De a PHP ennél sokkal többet tud.

Három fő területen használnak PHP programokat.

  • Szerver oldali programozás. Ez a hagyományos, és fő használati formája a PHP-nek. Három komponens szükséges ahhoz, hogy ezt a formát használhasd. Az első a PHP értelmező (CGI vagy szerver modul formájában), egy webszerver és egy webböngésző. Egy webszerverrel mindenképpen rendelkezni kell, megfelelően telepített és beállított PHP-vel. A PHP program kimenetét a webböngészővel lehet megtekinteni, a szerveren keresztül elérve a szkriptet. Lásd a telepítési utasításokatc. részt további információkért!

  • Parancssori programozás. PHP programok szerver és böngésző nélkül is futtathatóak. Ha ilyen környezetben szeretnéd használni a PHP-t, csak a PHP értelmezőre van szükséged. Ebben a formában gyakran valamilyen ütemező program segítségével (cron *nix és Linux alatt, Task Scheduler Windows alatt) futtatott programokat írnak, vagy egyszerű szövegfeldolgozó szkripteket készítenek. Lásd a Parancssori használat című függeléket további információért!

  • Kliens-oldali ablakozós alkalmazások írása. A PHP valószínűleg nem a legjobb nyelv ablakozós alkalmazások írásához, de ha nagyon jól ismered a PHP-t, és szeretnél néhány fejlett PHP szolgáltatást használni a kliens-oldali programjaidban, a PHP-GTK-t is használhatod ilyen programok írásához. Ezt használva lehetőséged van operációs rendszerfüggetlen programok írására is. A PHP-GTK a PHP egy kiterjesztése, nem érhető el a hivatalos PHP csomagban. Ha további információkra van szükséged látogsd meg a PHP-GTK webhelyet!

A PHP használható a legfontosabb operációs rendszereken, beleértve a Linuxot, sok Unix változatot (beleértve a HP-UX, Solaris és OpenBSD rendszereket), a Microsoft Windows-t, a Mac OS X rendszert, a RISC OS-t, és másokat. A PHP a legtöbb webszervert is támogatja, beleértve az Apache, Microsoft Internet Information Server, Personal Web Server, Netscape és iPlanet szervereket, az Oreilly Website Pro, Caudium, Xitami, OmniHTTPd, és más szervereket. A legtöbb szerverhez a PHP modul szintű támogatást nyújt, de más a CGI szabványt támogató szerverekkel is együtt tud működni CGI feldolgozóként.

Összességében a PHP használatakor szabadon választhatsz operációs rendszert és webszervert. Ráadásul a függvény-alapú és objektum orientált programozás, vagy ezek keveréke közötti választás is rajtad áll. Bár nem minden szokásos OOP szolgáltatás került megvalósításra a PHP-ben, sok eljáráskönytár és nagyobb alkalmazás is egyedüliként/kizárólagosan az OOP-t használja, például a PEAR könyvtár.

A PHP képességei nem csak HTML kimenet előállítására korlátozódnak. Képeket, PDF állományokat vagy akár Flash mozikat (libswf vagy Ming kiterjesztéssel) is létrehozhatsz futásidőben. Természetesen egyszerűen generálhatsz bármilyen szöveges kimenetet, mint az XHTML vagy bármilyen más XML. A PHP elő tudja állítani ezeket az állományokat, és el tudja menteni a szerven a közvetlen kiküldésük helyett, valamilyen szerver-oldali gyorsítótárat valósítva meg ezzel.

Az egyik legjobb és legfontosabb tulajdonsága a nyelvnek az adatbázisok széles körű támogatása. Adatbázisokat kezelő weblap készítése PHP segítségével hihetetlenül egyszerű. A következő adatbázisok támogatja jelenleg:

Adabas DIngresOracle (OCI7 és OCI8)
dBaseInterBaseOvrimos
EmpressFrontBasePostgreSQL
FilePro (csak olvasásra)mSQLSolid
HyperwaveDirect MS-SQLSybase
IBM DB2MySQLVelocis
InformixODBCUnix dbm

A PHP rendelkezik egy DBX adatbázis absztrakciós kiterjesztéssel is, amellyel egyöntetűen és áttetszű módon lehet kezelni bármilyen adatbázist, amit ez a kiterjesztés támogat. Ezen kívül a PHP támogatja az ODBC-t, ezért bármilyen más, ezt a szabványt támogató adatbázishoz is lehet kapcsolódni.

A PHP támogatja a kommunikációt más szolgáltatásokkal is különböző protokollok segítségével, úgy mint LDAP, IMAP, SNMP, NNTP, POP3, HTTP, COM (Windows rendszeren), és számos más. Sőt, nyithatsz hálózati foglalatokat is (socket) és kommunikálhatsz más protokolokkal is. A PHP támogatja a WDDX komplex adatcseréket, ami bármely más web programozási nyelvvel való kommunikációt megkönnyíheti. A PHP szintén rendelkezik a Java objektumok létrehozásának, és átlátszóan PHP objektummokként való kezelésének képességével. A CORBA kiterjesztés távoli objektumok elérésére használható.

A PHP rendkívül jó szövegfeldolgozó képességekkel rendelkezik, a POSIX és Perl reguláris kifejezésektől az XML állományok kezeléséig. Az XML dokumentumok feldologozásához és eléréséhez a SAX és DOM szabványok is használhatóak. Az XSLT kiterjesztés XML dokumentumok általakítására használható.

Ha elektornikus üzleti környezetben használod a PHP-t, hasznosnak fogod találni a Cybercash, CyberMUT, VerySign Payflow Pro and CCVS függvényeket az internetes fizetést megvalósító programokban.

Végül, de nem utolsósorban a PHP számos más érdekes kiterjesztéssel szolgálhat, mint például az mnoGoSearch kereső függvények, az IRC átjáró függvények, tömörítő eszközök (gzip, bz2), naptár átalakítás, fordítás...

Ahogy látható, ez az oldal nem elegendő a PHP minden szolgáltatásának és előnyének felsorolásához. Lásd a PHP telepítése és a függvény referencia részeket további információkért!


2. Fejezet. A simple tutorial

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

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


What do I need?

In this tutorial we assume that your server has activated support for PHP and that all files ending in .php are handled by PHP. On most servers, this is the default extension for PHP files, but ask your server administrator to be sure. If your server supports PHP, then you do not need to do anything. Just create your .php files, put them in your web directory and the server will automatically parse them for you. There is no need to compile anything nor do you need to install any extra tools. Think of these PHP-enabled files as simple HTML files with a whole new family of magical tags that let you do all sorts of things. Most web hosts offer PHP support, but if your host does not, consider reading the PHP Links section for resources on finding PHP enabled web hosts.

Let us say you want to save precious bandwidth and develop locally. In this case, you will want to install a web server, such as Apache, and of course PHP. You will most likely want to install a database as well, such as MySQL. You can either install these individually or choose a simpler way. Locate a pre-configured package 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 Linux and Windows. On Linux, you may find rpmfind and PBone helpful for locating RPMs. You may also want to visit apt-get to find packages for Debian.


Your first PHP-enabled page

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

Példa 2-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. Although this is outside the scope of this tutorial, see also the DocumentRoot and ServerName directives in your web server's configuration file (for Apache, this is httpd.conf). 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>

Note that this is not like a CGI script. The file does not need to be executable or special in any way. Think of it as a normal HTML file which happens to have a set of special tags available to you that do a lot of interesting things.

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.

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. 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. If the problems persist, 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 all you want. For more details, read the manual section on basic PHP syntax.

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

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

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

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


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

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

To display this variable, you can simply do:

Példa 2-2. Printing a variable (Array element)

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

A sample output of this script may be:

Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)

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 creating a file that looks like this:

Példa 2-3. Show all predefined variables with phpinfo()

<?php phpinfo(); ?>

When you load up this file in your browser, you will see a page full of information about PHP along with a list of all the variables available to you.

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:

Példa 2-4. 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 any introductory PHP book and read the first couple of chapters, or read the Language Reference part of the manual. You can find a list of PHP books at http://www.php.net/books.php.

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:

Példa 2-5. Mixing both HTML and PHP modes

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

A sample output of this script may be:

<h3>strpos must have returned non-false</h3>
<center><b>You are using Internet Explorer</b></center>

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


Dealing with Forms

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

Példa 2-6. A simple HTML form

<form action="action.php" method="post">
 Your name: <input type="text" name="name" />
 Your age: <input type="text" name="age" />
 <input type="submit" />
</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:

Példa 2-7. Printing data from our form

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

A sample output of this script may be:

Hi Joe. You are 22 years old.

It should be obvious what this does. There is nothing more to it. The $_POST['name'] and $_POST['age'] variables are automatically set for you by PHP. Earlier we used the $_SERVER autoglobal; above we just introduced the $_POST autoglobal 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 autoglobal instead. You may also use the $_REQUEST autoglobal, if you do not care about the source of your request data. It contains the merged information of GET, POST and COOKIE data. Also see the import_request_variables() function.


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/libraries containing code you can reuse. The PHP developers have largely tried to preserve backwards compatibility, so a script written for an older version will run (ideally) without changes in a newer version of PHP. In practice, some changes will usually be needed.

Two of the most important recent changes that affect old code are:

  • The deprecation of the old $HTTP_*_VARS arrays (which need to be indicated as global when used inside a function or method). The following autoglobal arrays were introduced in PHP 4.1.0. They are: $_GET, $_POST, $_COOKIE, $_SERVER, $_FILES, $_ENV, $_REQUEST, and $_SESSION. The older $HTTP_*_VARS arrays, such as $HTTP_POST_VARS, still exist as they have since PHP 3. As of PHP 5.0.0, the long PHP predefined variable arrays may be disabled with the register_long_arrays directive.

  • 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 autoglobal arrays mentioned above. Older scripts, books, and tutorials may rely on this directive being on. If it were on, for example, one could use $id from the URL http://www.example.com/foo.php?id=42. Whether on or off, $_GET['id'] is available.

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


What's next?

With your new knowledge you should be able to understand most of the manual and also the various example scripts available in the example archives. You can also find other examples on the php.net websites in the links section: http://www.php.net/links.php.

To view various slide presentations that show more of what PHP can do, see the PHP Conference Material Sites: http://conf.php.net/ and http://talks.php.net/


3. Fejezet. Telepítés

Általános telepítési szempontok

Mielőtt hozzálátnál a telepítéshez, meg kell tudnod határozni, hogy mire akarod használni a PHP-t. A következő három fő területen használhatod (Mire jó a PHP?):

  • Szerveroldali programozásra

  • Parancssori programok írására

  • Kliens oldali GUI alkalmazások kifejlesztéséhez.

Az első és legszokványosabb használatához három dologra lesz szükséged: magára a PHP-ra, egy webszerverre és egy webböngészőre. Valőszínűleg már rendelkezel egy webböngészővel, és az operációs rendszer telepítésétől függően egy webszerverrel is (Apache Linux alatt vagy IIS Windows alatt). Bérelhetsz tárterületet egy cégtől is, ebben az esetben nem kell semmit magadtól telepítened, csak a PHP szkripteket megírni és feltölteni őket a bérelt webtárhelyedre és nézni a végeredményt a böngészőben. A tárterület bérlésével foglalkozó cégek listája: http://www.php.net/links.php#hosts.

Ha saját magad telepíted a PHP-t, akkor kétféleképpen csatlakoztathatod a kiszolgálóhoz. A PHP-nak rengeteg kiszolgálóhoz van közvetlen modulinterfésze (SAPI). Ezek a szerverek az Apache, Microsoft Internet Information Server, Netscape és iPlanet szerverek. Ezenkívül sok szerver támogatja az ISAPI-t, a Microsoft modulinterfészét mint pl. az OmniHTTPd. Ha PHP-t nem a webszerveredhez modulként telepíteni, mindig lehetőséged van CGI feldolgozóként futtatni. Ez azt jelenti, hogy a webszerver a PHP parancssorból indítható változatát (Windows alatt php.exe) használja a PHP kérések lekezelésére.

Ha érdekelt vagy a PHP-s parancssori programozásban is (pl. automatikus offline képgenerálásra vagy szöveges állományok feldolgozására írt programok), akkor szükséged lesz a parancssorból futtatható változatra is. A részletesebb tájékoztatásért olvasd el a PHP parancssori alkalmazásokhoz. Ebben az esetben nincs szükség sem szerverre sem böngészőre.

A PHP és a PHP-GTK kiterjesztés segítségével kliens oldali GUI alkalmazásokat is fejleszthetsz. Ez teljesen eltérő megközelítés, mint a weboldalak programozása, mivel itt nem HTML kimenetet kell generálni, hanem ablakokat és a bennük levő objektumokat kell kezelni. A PHP-GTK-ról többet is olvashatsz, ha ellátogatsz a honlapjukra. A PHP-GTK nem része a hivatalos PHP disztribuciónak.

Ettől a ponttól ez a fejezet a PHP webszerverhez történő telepítésével foglalkozik, UNIX és Windows alatt - mind modulként mind CGI feldolgozóként.

A forráskód és a futtatható állományok néhány rendszerre (beleértve a Windows-t) megtalálhatóak http://www.php.net/ címen. Ha lehet, akkor valamelyik hozzád legközelebb eső tükörszervert vedd igénybe a letöltésekhez.


Telepítés UNIX rendszerre

Ez a fejezet bemutatja, hogy miként kell feltelepíteni és beállítani a PHP-t UNIX rendszeren. Mielőtt elkezded a telepítést, nézd meg a rendszerednek ás szerverednek megfelelő fejezetet is!

Nélkülözhetetlen előismeretek és szoftverek:

  • Alapvető UNIX ismeretek ("make" és a C fordító használata, ha saját magad szeretnéd végezni a fordítást)

  • Egy ANSI C fordító (ha fordítasz)

  • flex (fordításhoz)

  • bison (fordításhoz)

  • Egy web szerver

  • Bármilyen modul által igényelt elem (mint például a gd vagy pdf könyvtárak)

Számos módja van a PHP telepítésének a UNIX rendszereken, vagy egy fordítási és konfigurálási eljárással, vagy különböző előre-csomagolt megoldások használatával. Az első mód jóval bonyolultabb, így a dokumentáció inkább erre a területre fekteti a hangsúlyt.

Az alapvető konfigurálási folyamatot a configure számára átadott parancssori paraméterek szabályozzák. Ez a fejezet körvonalazza a leggyakoribb lehetőségeket, de számos más paraméter is rendelkezésre áll. Lásd a Configure opciók teljes listáját részletesebb információkért. Számos módja van a PHP telepítésének:


Apache modul (Gyors referencia)

A PHP-t számos különböző módon lehet fordítani, de az egyik legkedveltebb forma az Apache modulként való fordítás. A következőkben egy gyors módszert mutatunk be erre.

Példa 3-1. Gyors telepítési utasítások PHP 4-hez (Apache modul verzió)

1.  gunzip apache_1.3.x.tar.gz
2.  tar xvf apache_1.3.x.tar
3.  gunzip php-x.x.x.tar.gz
4.  tar xvf php-x.x.x.tar
5.  cd apache_1.3.x
6.  ./configure --prefix=/www
7.  cd ../php-x.x.x
8.  ./configure --with-mysql --with-apache=../apache_1.3.x --enable-track-vars
9.  make
10. make install
11. cd ../apache_1.3.x
12. ./configure --activate-module=src/modules/php4/libphp4.a
13. make
14. make install

  Ehelyett a lépés helyett talán jobb, ha a httpd futtatható állományát
  a meglévőre rámásolod. Győződj meg róla, hogy előtte leállítottad
  a szervert!

15. cd ../php-x.x.x
16. cp php.ini-dist /usr/local/lib/php.ini
17. Szerkeszd a httpd.conf vagy srm.conf fájlt és add hozzá:
      AddType application/x-httpd-php .php

18. Használd a szokásos módszert az Apache szerver újraindítására.
    (Le kell állítanod és újra kell indítanod a szervert, nem csak
    újratölteni egy HUP vagy USR1 jellel.)

Fordítás

Ha a PHP-t sikeresen konfiguráltad, készen állsz a fordításra. A make parancs elvégzi ezt a feladatot. Ha nem sikerül a fordítás, és nem tudod kideríteni, miért, olvasd el a Problémák című részt.


Telepítés UNIX/Linux rendszerre

Ez a fejezet a PHP Linux rendszerre történő telepítésének dokumentációját tartalmazza.


Csomagok használata

Számos Linux disztribúció valamilyen csomag támogatással rendelkezik, (például rpm). Ez sokat tud segíteni egy általános telepítés elvégzésében, de ha más funkciókra is vágysz (például biztonságos szerver funkciókra, vagy más adatbázis támogatására), előfordulhat, hogy mégis magadnak kell fordítanod a PHP-t és/vagy a szervert. Ha nem vagy tapasztalt az önálló fordításban, megéri utánanézni, hogy elkészítette-e már valaki más azt a csomagot, ami a kívánt funkciókkal rendelkezik.


Telepítés UNIX/HP-UX rendszerre

Ez a fejezet a PHP HP-UX rendszerre történő telepítésének dokumentációját tartalmazza.

Példa 3-2. Telepítési útmutató a HP-UX 10-hez

Forrás: paul_mckay@clearwater-it.co.uk
Dátum: 04-Jan-2001 09:49
(Ezek a tippek a PHP v4.0.4 és Apache v1.3.9 verziókra vonatkoznak)

Tehát szeretnéd telepíteni a PHP-t és az Apache szervert
egy HP-UX 10.20-at futtató gépen?

1. Szükséged lesz a gzip-re. Töltsd le a
http://hpux.connect.org.uk/ftp/hpux/Gnu/gzip-1.2.4a/gzip-1.2.4a-sd-10.20.depot.Z
címről, tömörítsd ki, és telepítsd swinstall-al.

2. Szükséged lesz a gcc-re. Töltsd le a
http://gatekeep.cs.utah.edu/ftp/hpux/Gnu/gcc-2.95.2/gcc-2.95.2-sd-10.20.depot.gz
címről, tömörítsd ki (most már gzip-el), és telepítsd swinstall-al.

3. Szükséged lesz a GNU binutils-ra. Töltsd le a
http://hpux.connect.org.uk/ftp/hpux/Gnu/binutils-2.9.1/binutils-2.9.1-sd-10.20.depot.gz
címről, tömörítsd ki, és telepítsd swinstall-al.

4. Szükséged lesz a bison-ra. Töltsd le a
http://hpux.connect.org.uk/ftp/hpux/Gnu/bison-1.28/bison-1.28-sd-10.20.depot.gz
címről, és telepítsd az eddigiek szerint.

5. Szükséged lesz a flex-re. Ennek sajnos csak a forráskódját
tudod letölteni az egyik http://www.gnu.org tükörkiszolgálóról.
A <filename>non-gnu</filename> könyvtárban találod az ftp helyen. Töltsd le az
állományt, tömörítsd ki, és a tar -xvf paranccsal megkapod
a szükséges fájlokat. Lépj be a létrejött flex könyvtárba, és
hajsd futtasd a következőket sorban egymás után: ./configure,
make, make install.

Ha hibaüzeneteket kapsz, feltehetően az a probléma, hogy gcc nincs
a PATH-ban, tehát add hozzá a PATH-hoz.

Most pedig jönnek a nehezebb dolgok.

6. Töltsd le a PHP és Apache forráskódokat.

7. Alkalmazd rájuk a gunzip és tar -xvf parancsokat.

Módosítanod kell pár állományt, hogy helyesen leforduljanak.

8. Először a configure nevű fájl szorul némi szerkesztésre, mivel
úgy tűnik nem tudja követni, hogy HP-UX gépen vagyunk.
Lesz még egy jobb módszer ennek a megoldására, de addig is
egy jól működő javítás a
    lt_target=hpux10.20
beillesztése a configure szkript 47286-adik soránál.

9. A következő lépésben az Apache GuessOS fájl szorul
javításra. Az apache_1.3.9/src/helpers fájlban írd át a
89. sort. Ez a jelenlegi tartalma:
    "echo "hp${HPUXMACH}-hpux${HPUXVER}"; exit 0"
Erre kell átirni:
    "echo "hp${HPUXMACH}-hp-hpux${HPUXVER}"; exit 0"

10. Megosztott modulként (SO) nem telepíthető a PHP HP-UX
rendszeren, ezért statikusan bele kell fordítanod a szerverbe.
Ehhez kövesd az Apache oldalon található utasításokat.

11. A PHP és Apache most már sikeresen lefordult, de az Apache
nem fog elindulni. Létre kell hoznod egy új felhasználót
az Apache számára, például www vagy apache néven. Utána
a 252-253-ik sort kell módosítanod az Apache conf/httpd.conf
állományban, tehát ehelyett a két sor helyett:
    User nobody
    Group nogroup
valami hasonlód lesz:
    User www
    Group sys

Ez azért szükséges, mivel az Apache nem futtatható
a nobody nevű felhasználóval HP-UX alatt.

Most már az Apache és a PHP is sikeresen működik.

Remélem ez az útmutató segített,
Paul Mckay.

Telepítés Unix/Solaris rendszerre

Ez a fejezet a PHP Solaris rendszerre történő telepítésének dokumentációját tartalmazza.


Szükséges programok

A Solaris telepítések gyakran nem tartalmaznak C fordítót, és a kapcsolódó eszközöket. A szükséges programok:

  • gcc (javasolt, más C fordító is jó lehet)

  • make

  • flex

  • bison

  • m4

  • autoconf

  • automake

  • perl

  • gzip

  • tar

Természetesen szükséged lehet további szoftverek telepítésére (és esetleg fordítására), ha plusz funkciókat szeretnél elérni (például Oracle vagy MySQL adatbázisok).


Csomagok használata

Egyszerűsítheted a Solaris telepítési eljárást, ha a pkgadd-et használod a szükséges komponensek nagyrészének telepítésénél.


Telepítés Unix/OpenBSD rendszerre

Ez a fejezet bemutatja, hogy miként kell telepíteni és beállítani a PHP-t OpenBSD rendszeren.


Port-ok használata

Ez az ajánlott telepítési módszer OpenBSD-n, mivel így az üzemeltetők a legfrissebb biztonsági és hiba-javításokat képesek alkalmazni majd rá. Ahhoz, hogy használhasd ezt az eljárást, bizonyosodj meg, hogy megvan a legújabb port tree. Ezután találd ki, mely "flavor"-eket kívánod telepíteni, és add ki a make install parancsot. Itt van egy példa, hogyan is kell ezt csinálni:

Példa 3-3. OpenBSD Port telepítési példa

$ cd /usr/ports/www/php4
    $ make show VARNAME=FLAVORS
     (milyen flavor-t akarsz a listából)
    $ env FLAVOR="imap gettext ldap mysql gd" make install
    $ /usr/local/sbin/php4-enable

Package-ek használata

Léteznek előre lefordított csomagok az általad használt OpenBSD verziókhoz is. Ezek az operációs rendszerrel járó Apache verziókkal vannak összeillesztve. Mégis mivel a beállítható lehetőségek (flavors) száma nagy ehhez a porthoz, talán egyszerűbb a port tree használatával újat fordítani a forrásból. Olvasd el, hogy milyen csomagok elérhetők, man oldalak: packages(7)


Telepítés Mac OS X rendszerre

Ez a fejezet a PHP Mac OS X rendszerre történő telepítésének dokumentációját tartalmazza.


Csomagok használata

Rendelkezésre áll néhány előre-csomagolt és előre-fordított PHP változat a Mac OS X rendszerekre. Ez sokat tud segíteni egy általános telepítés elvégzésében, de ha más funkciókra is vágysz (például biztonságos szerver funkciókra, vagy más adatbázis támogatására), előfordulhat, hogy mégis magadnak kell fordítanod a PHP-t és/vagy a szervert. Ha nem vagy tapasztalt az önálló fordításban, megéri utánanézni, hogy elkészítette-e már valaki más azt a csomagot, ami a kívánt funkciókkal rendelkezik.


Fordítás OS X szerveren

Két - némiképp különböző - verziója érhető el a Mac OS X-nek, a kliens és szerver változat. A következők az OS X szerverre vonatkoznak.

Példa 3-4. Mac OS X szerver telepítés

1. Töltsd le az Apache és PHP legfrissebb változatait
2. Tömörítsd ki ezeket, és futtasd a configure programot az Apache-ra:
    ./configure --exec-prefix=/usr \
    --localstatedir=/var \
    --mandir=/usr/share/man \
    --libexecdir=/System/Library/Apache/Modules \
    --iconsdir=/System/Library/Apache/Icons \
    --includedir=/System/Library/Frameworks/Apache.framework/Versions/1.3/Headers \
    --enable-shared=max \
    --enable-module=most \
    --target=apache

4. Esetleg hozzáadhatod még a következő sort:
    setenv OPTIM=-O2
    Ha szerenéd, ha a fordító némi optimalizálást végezne.

5. Lépj be a PHP 4 forrás könyvtárába, és futtasd a configure programot:
    ./configure --prefix=/usr \
    --sysconfdir=/etc \
    --localstatedir=/var \
    --mandir=/usr/share/man \
    --with-xml \
    --with-apache=/src/apache_1.3.12

    Ha bármilyen más kiterjesztést szeretnél (MySQL, GD, stb.),
    szerepeltesd a megfelelő paramétereket itt. A
    --with-apache paraméternek az Apache forráskönyvtárát
    add meg, például "/src/apache_1.3.12".
6. make
7. make install
    Ez létre fog hozni egy könyvtárat az Apache forráskönyvtárában
    az src/modules/php4 alatt.

8. Most újra futtatnod kell a configure-t az Apache-ra,
   hogy beépítsd a PHP 4-et:
    ./configure --exec-prefix=/usr \
    --localstatedir=/var \
    --mandir=/usr/share/man \
    --libexecdir=/System/Library/Apache/Modules \
    --iconsdir=/System/Library/Apache/Icons \
    --includedir=/System/Library/Frameworks/Apache.framework/Versions/1.3/Headers \
    --enable-shared=max \
    --enable-module=most \
    --target=apache \
    --activate-module=src/modules/php4/libphp4.a

    Itt kaphatsz egy üzenetet, ami azt állítja, hogy a libmodphp4.a
    elvault. Ha ez történik, menj az src/modules/php4 könyvtárba,
    az Apache forráskönyvtár alatt, és hajtsd végre ezt:

    ranlib libmodphp4.a

    Aztáb lépj vissza az Apache forráskönyvtár gyökerébe, és
    ismét futtasd az előző configure parancssort. Ez aktualizálja
    a link táblát.

9. make

10. make install

11. Másold, és nevezd át a php.ini-dist állományt a "bin"
    könyvtárba a PHP 4 forráskönvytárból:
    cp php.ini-dist /usr/local/bin/php.ini

    vagy (ha nincs local könyvtárad)

    cp php.ini-dist /usr/bin/php.ini

Fordítás MacOS X kliensre

Ezeket a tippeket Marc Liyanage adta szívesen közre.

A PHP Apache webszerver modulja a Mac OS X része. Ez a verzió a MySQL és PostgreSQL adatbázis-kezelők támogatását is tartalmazza.

Megjegyés: Légy körültekintő az alábbiakban, mert tönkreteheted az Apache szerveredet!

Telepítéshez az alábbiakat kell tenni:

  • 1. Nyiss egy terminál ablakot

  • 2. Írd be "wget http://www.diax.ch/users/liyanage/software/macosx/libphp4.so.gz", és várd meg, amíg letöltődik

  • 3. Írd be "gunzip libphp4.so.gz"

  • 4. Írd be "sudo apxs -i -a -n php4 libphp4.so"

Most írd be, hogy "sudo open -a TextEdit /etc/httpd/httpd.conf" TextEdit megnyitja a webszerver konfigurációs fájlját. Keresd meg a következő két sort a fájl vége felé (használd a Find parancsot):
#AddType application/x-httpd-php .php
   #AddType application/x-httpd-php-source .phps
Töröld ki a két hashmark-ot(#), és ezután mentsd el a fájlt, lépj ki a TextEdit-ből.

Végül írd be: "sudo apachectl graceful" , hogy újrainduljon a webszerver.

Mostantól a PHP-nak futni kell. Ezt ellenőrizheted, ha a "Sites" könyvtáradba bemásolod a "test.php" fájlt, amiben nincs más csak ez a sor: <?php phpinfo() ?>.

Most nyisd meg a 127.0.0.1/~a_te_userneved/test.php címen levő oldalt a webböngésződben. A PHP modulok információs táblázatait kell látnod ezen az oldalon.


Configure opciók teljes listája

Megjegyzés: Ezek a paraméterek csak csak fordításidőben használhatóak. Ha egy lefordított PHP konfigurációján szeretnél változtatni, nézd meg a Konfiguráció című részt.

A továbbiakban egy teljes lista következik a PHP 3 és PHP 4 configure szkriptek által támogatott paraméterekről, amik UNIX-szerű operációs rendszereken használhatóak. A jelöléseknek megfelelően néhány a csak a PHP 3-ban elérhető, néhány csak PHP 4-ben, vannak ami mindkettőben. Sok paraméter neve megváltozott a PHP 3 és a PHP 4 között, miközben továbbra is ugyanazt a funkciót valósítják meg. Ezek kereszthivatkozásokkal vannak ellátva, ezért ha gondod akad a PHP 3 paraméterek átvételével, itt ellenőrizd, hogy megmaradtak-e a paraméterek nevei.


Adatbázisok

--enable-dba=shared

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: A DBA megosztott modulként való beépítése

--enable-dbx

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: Beépíti a DBX támogatást

--enable-dbase

PHP 3: Ez az opció nem áll rendelkezésre; használd helyette a --with-dbase paramétert!

PHP 4: Engedélyezi a beépített dbase támogatást. Semmilyen külső könyvtár nem szükséges hozzá.

--with-dbase

PHP 3: Engedélyezi a beépített dbase támogatást. Semmilyen külső könyvtár nem szükséges hozzá.

PHP 4: Ez az opció nem áll rendelkezésre; használd helyette az --enable-dbase paramétert!

--with-db2[=DIR]

PHP 3, PHP 4: Beépíti a Berkeley DB2 támogatást.

--with-db3[=DIR]

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: Beépíti a Berkeley DB3 támogatást.

--with-dbm[=DIR]

PHP 3, PHP 4: Engedélyezi a DBM támogatást.

--enable-filepro

PHP 3: Ez az opció nem áll rendelkezésre; használd helyette a --with-filepro paramétert!

PHP 4: Engedélyezi a beépített csak olvasásra képes filePro támogatást. Semmilyen külső könyvtár nem szükséges hozzá.

--with-filepro

PHP 3: Engedélyezi a beépített csak olvasásra képes filePro támogatást. Semmilyen külső könyvtár nem szükséges hozzá.

PHP 4: Ez az opció nem áll rendelkezésre; használd helyette az --enable-filepro paramétert!

--with-fbsql[=DIR]

PHP 3: nem elérhető.

PHP 4: engedélyezi a FrontBase SQL támogatást. DIR a FrontBase kiinduló telepítési könyvtára, alapértelmezésben a szokásos Frontbase telepítési könyvtár. A szokásos Frontbase telepítési könyvtárak operációs rendszerenként változnak: Solaris: /opt/FrontBase, WinNT: \usr\FrontBase, Linux: /usr/frontbase, Mac OSX: /Library/FrontBase.

--with-gdbm[=DIR]

PHP 3, PHP 4: Beépíti a GDBM támogatást.

--with-hyperwave

PHP 3, PHP 4: Beépíti a Hyperwave támogatást.

--with-informix[=DIR]

PHP 3, PHP 4: Beépíti az Informix támogatást. A DIR az Informix alap telepítési könyvtára, és nincs alapbeállítása.

--with-ingres[=DIR]

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: Beépíti az Ingres II támogatást. A DIR az Ingres könyvtára (alapbeállításban /II/ingres).

--with-interbase[=DIR]

PHP 3, PHP 4: Beépíti az InterBase támogatást. A DIR az InterBase alap telepítési könyvtára, alapbeállításban /usr/interbase.

Interbase függvények

Interbase honlap

--with-ldap[=DIR]

PHP 3: Beépíti az LDAP támogatást. A DIR az LDAP alap telepítési könyvtára. Alapbeállításban /usr és /usr/local

PHP 4: Beépíti az LDAP support. A DIR az LDAP alap telepítési könyvtára.

Ez biztosítja az LDAP (Lightweight Directory Access Protocol) támogatást. Paramétere az LDAP alap telepítési könyvtára, alapbeállításban /usr/local/ldap.

Az LDAP-ről részletesebb információ található az RFC1777-ben és az RFC1778-ban.

--with-msql[=DIR]

PHP 3, PHP 4: Engedélyezi az mSQL támogatást. Paramétere az mSQL telepítési könyvtára, alapbeállításban /usr/local/Hughes. Ez az alap könyvtára az mSQL 2.0 disztribúciónak. A configure automatikusan detektálja, hogy milyen mSQL verziót használsz, és a PHP támogatja mind az 1.0-ás mind a 2.0-ás mSQL-t, de ha ha a PHP-t az 1.0-ás mSQL támogatással fordítod, csak 1.0-ás mSQL adatbázisokat tudsz majd elérni, és fordítva.

Lásd még az mSQL beállítási lehetőségeket a konfigurációs fájlban.

mSQL honlap

--with-mysql[=DIR]

PHP 3: Beépíti a MySQL támogatást. A DIR a MySQL alap telepítési könyvtára, alapbeállításban számos gyakori helyen keres MySQL fájlokat keresve.

PHP 4: Beépíti a MySQL támogatást. A DIR a MySQL alap könyvtára. Ha nem adod meg, a beépített MySQL könyvtár kerül felhasználásra. Ez az opció alapbeállításban be van kapcsolva.

Lásd még a MySQL beállítási lehetőségeket a konfigurációs fájlban.

MySQL home page

--with-ndbm[=DIR]

PHP 3, PHP 4: Beépíti az NDBM támogatást.

--with-ovrimos

PHP 3, PHP 4: Bekapcsolja az Ovrimos támogatást.

--with-oci8[=DIR]

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: Beépíti az Oracle-oci8 támogatást. Alapbeállításban a DIR az ORACLE_HOME értéke.

--with-oracle[=DIR]

PHP 3: Beépíti az Oracle adatbázis támogatását. A DIR az Oracle könyvtára, alapbeállításban az $ORACLE_HOME értéke.

PHP 4: Beépíti az Oracle-oci7 támogatást. Alapbeállításban a DIR az ORACLE_HOME értéke.

Beépíti az Oracle támogatást. Oracle 7.0 és 7.3 közötti verziókkal tesztelve. A paraméter az ORACLE_HOME könyvtár. Nem kell megadnod ezt a paramétert, ha az Oracle környezeted be van állítva.

Oracle honlap

--with-pgsql[=DIR]

PHP 3: Beépíti a PostgresSQL támogatást. A DIR a PostgresSQL alap telepítési könyvtára, alapbeállításban /usr/local/pgsql.

PHP 4: Beépíti a PostgreSQL támogatást. A DIR a PostgreSQL alap telepítési könyvtára, alapbeállításban /usr/local/pgsql. Állítsd a DIR értékét shared-re, ha külső PHP modulként szeretnéd lefordítani, vagy állítsd shared,DIR-re, ha külső modulként fordítod, és megadod a könyvtárat.

Lásd a Postgres beállítási lehetőségeket a konfigurációs fájlban.

PostgreSQL honlap

--with-sybase-ct[=DIR]

PHP 3, PHP 4: Beépíti a Sybase-CT támogatást. A DIR a Sybase könyvtára, alapbeállításban /home/sybase.

Lásd még a Sybase-CT beállítási lehetőségeket a konfigurációs fájlban.

--with-sybase[=DIR]

PHP 3, PHP 4: Beépíti a Sybase-DB támogatást. A DIR a Sybase könyvtára, alapbeállításban /home/sybase.

Lásd még a Sybase beállítási lehetőségeket a konfigurációs fájlban.

Sybase home page

--disable-unified-odbc

PHP 3: Kikapcsolja a unified ODBC támogatást. Csak akkor van értelme, ha az iODBC, Adabas, Solid, Velocis vagy egy saját ODBC felület engedélyezett.

PHP 4: Ez az opció nem áll rendelkezésre a PHP 4-ben.

A Unified ODBC modul, egy szokásos felület az ODBC-alapú megoldásokkal dolgozó adatbázisokhoz, mint a Solid, az IBM DB2 és az Adabas D. Szintén működőképes normál ODBC könyvtárak esetén. Teszteltük iODBC, Solid, Adabas D, IBM DB2 és Sybase SQL Anywhere adatbázisokkal. Elvárja, hogy egy (és csak egy) engedélyezett ezek közül a modulok közül, vagy a Velocis modul engedélyezett, esetleg egy saját ODBC könyvtár. Ez az opció csak akkor használható, ha az alábbiak közül egy paraméter már meg van adva: --with-iodbc, --with-solid, --with-ibm-db2, --with-adabas, --with-velocis, vagy --with-custom-odbc.

--with-velocis[=DIR]

PHP 3, PHP 4: Beépíti a Velocis támogatást. A DIR a Velocis alap telepítési könyvtára, alapbeállításban /usr/local/velocis.

Velocis honlap


E-üzlet

--with-ccvs[=DIR]

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: Beépíti a CCVS támogatást. Add meg a CCVS telepítési könyvtárat a DIR paraméterben!

--with-cybermut[=DIR]

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: Beépíti a Cybermut támogatást. A DIR paraméter a Cybermut SDK könyvtára, ahol a libcm-mac.a és cm-mac.h állományok találhatóak.

--with-mck[=DIR]

PHP 3: Beépíti a Cybercash MCK támogatást. A DIR a cybercash mck könyvtára, ami alapbeéllításban /usr/src/mck-3.2.0.3-linux. Segítségért az extra/cyberlib-et nézd meg.

PHP 4: Ez az opció nem áll rendelkezésre; használd helyette a --with-cybercash paramétert!

--with-cybercash[=DIR]

PHP 3: Ez az opció nem áll rendelkezésre; használd helyette a --with-mck paramétert!

PHP 4: Beépíti a CyberCash támogatást. A DIR a CyberCash MCK telepítési könyvtára.

--with-pfpro[=DIR]

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: Beépíti a Verisign Payflow Pro támogatást.


Grafika

--enable-freetype-4bit-antialias-hack

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: Beépíti a FreeType2 támogatást (kísérleti jellegű).

--with-gd[=DIR]

PHP 3: Beépíti a GD támogatást (a DIR a GD telepítési könyvtára).

PHP 4: Beépíti a GD támogatást (a DIR a GD telepítési könyvtára). Állítsd a DIR értékét shared-re, ha külső PHP modulként szeretnéd lefordítani, vagy állítsd shared,DIR-re, ha külső modulként fordítod, és megadod a könyvtárat.

--without-gd

PHP 3, PHP 4: Kikapcsolja a GD támogatást.

--with-imagick[=DIR]

PHP 3: Beépíti az ImageMagick támogatást. A DIR a telepítési könyvtár, ha elhagyod, a PHP megpróbálja megtalálni. [kísérleti jellegű]

PHP 4: Ez az opció nem áll rendelkezésre a PHP 4-ben.

--with-jpeg-dir[=DIR]

PHP 3: A jpeg könyvtár a pdflib 2.0-hoz.

PHP 4: A jpeg könyvtár a pdflib 3.x-hez.

--with-png-dir[=DIR]

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: A png konyvtár a pdflib 3.x-hez.

--enable-t1lib

PHP 3: Engedélyezi a t1lib támogatást.

PHP 4: Ez az opció nem áll rendelkezésre; használd helyette a --with-t1lib paramétert!

--with-t1lib[=DIR]

PHP 3: Ez az opció nem áll rendelkezésre; használd helyette az --enable-t1lib paramétert!

PHP 4: Beépíti a T1lib támogatást.

--with-tiff-dir[=DIR]

PHP 3: A tiff könyvtár a pdflib 2.0-hoz.

PHP 4: A tiff könyvtár a pdflib 3.x-hez.

--with-ttf[=DIR]

PHP 3, PHP 4: Beépíti a FreeType támogatást.

--with-xpm-dir[=DIR]

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: Az xpm könyvtár a gd-1.8+-hoz.


Máshova nem sorolható

Ezek besorolásra kerülnek a jövőben további kategóriákba, értelemszerűen.

--with-gmp

PHP 3, PHP 4 : Beépíti a GMP támogatást.

--disable-bcmath

PHP 3: Fordítás BC tetszőleges pontosságú matematikai függvények nélkül. Ezek a függvények lehetőséget adnak olyan nagy számok kezelésére is, amik kiesnek az egész és lebegőpontos számok értelmezési tartományából. Lásd a BCMath tetszőleges pontosságú matematikai függvények című részt.

PHP 4: Ez az opció nem áll rendelkezésre, mivel a bcmath nem fordul be automatikusan; használd az --enable-bcmath paramétert a bekapcsoláshoz!

--disable-display-source

PHP 3: Forráskódmegjelenítési támogatás kikapcsolása.

PHP 4: Ez az opció nem áll rendelkezésre a PHP 4-ben.

--disable-libtool-lock

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: Lock-olás letiltása (gondot okozhat párhuzamos futásnál).

--disable-pear

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: A PEAR telepítésének kikapcsolása.

--disable-pic

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: A PIC kikapcsolása a megosztott modulokra.

--disable-posix

PHP 3: Ez az opció nem áll rendelkezésre; használd helyette a --without-posix paramétert!

PHP 4: A POSIX-szerű funkciók kikapcsolása.

--enable-pcntl

PHP 3: nem használható PHP 3-ban.

PHP 4: Engedélyezi a processz vezérlő függvényeket. (fork, waitpid, signal, stb.)

--disable-rpath

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: Addícionális futásidejű path átadás kikapcsolása.

--disable-session

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: A session támogatás kikapcsolása.

--enable-bcmath

PHP 3: Ez az opció nem áll rendelkezésre, mivel a bcmath automatikusan befordul; használd a --disable-bcmath paramétert a kikapcsoláshoz.

PHP 4: A BC stílusú tetszőleges pontosságú matematikai függvények engedélyezése. Olvasd el a README-BCMATH fájlt további útmutatáshoz. Ezek a függvények lehetőséget adnak olyan nagy számok kezelésére is, amik kiesnek az egész és lebegőpontos számok értelmezési tartományából. Lásd a BCMath tetszőleges pontosságú matematikai függvények című részt.

--enable-c9x-inline

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: Engedélyezi a C9x-inline semantics funkciót.

--enable-calendar

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: Engedélyezi a naptárkonvertálások támogatását.

--enable-debug

PHP 3, PHP 4: Debug szimbólumok engedélyezése.

--enable-debugger

PHP 3: Távoli debug funkciók befordítása.

PHP 4: Ez az opció nem áll rendelkezésre a PHP 4-ben.

--enable-discard-path

PHP 3, PHP 4: Ha ez engedélyezett, a PHP CGI állomány biztonságosan a web könyvtáron kívül helyezhető, és nem fogja tudni senki megkerülni a .htaccess biztonságot.

--enable-dmalloc

PHP 3, PHP 4: A dmalloc engedélyezése.

--enable-exif

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: Az exif támogatás engedélyezése.

--enable-experimental-zts

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: Ez feltehetően működésképtelenné teszi a PHP-det.

--enable-fast-install[=PKGS]

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: Gyors telepítésre optimalizálás [alapbeállítása yes]

--enable-force-cgi-redirect

PHP 3, PHP 4: A szerveren belüli átirányítások biztonsági ellenőrzésének bekapcsolása. Ezt kapcsold be, ha CGI módú futtatható fájlt készítesz Apache szerverrel.

--enable-inline-optimization

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: Ha sok memóriád van, és gcc-t használsz, érdemes ezt kipróbálnod.

--enable-libgcc

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: Engedélyezi a libgcc explicit linkelést.

--enable-maintainer-mode

PHP 3, PHP 4: Engedélyez olyan make szabályokat és függőségeket, amik többnyire nem hasznosak (sőt néha problematikusak) az átlagos telepítő számára.

--enable-mbstr-enc-trans

PHP 4: engedélyezi a http bemeneti karakterek automatikus felismerését és multi-byte-os karakterkódolásra fordítását.

Figyelem

Ez a kapcsoló csak PHP 4.0.6 vagy magasabb verziótól érhető el.

--enable-mbstring

PHP 4: engedélyezi a multi-byte karakterkódoláshoz kapcsolodó függvényeket.

Figyelem

Ez a kapcsoló csak PHP 4.0.6 vagy magasabb verziótól érhető el.

--enable-memory-limit

PHP 3, PHP 4: Memórialimit támogatás engedélyezése (alapbeállításban ez nincs bekapcsolva).

--enable-safe-mode

PHP 3, PHP 4: Safe mode engedélyezése alapbeállításban.

--enable-satellite

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: CORBA támogatás engedélyezése Satellite-on keresztül (szükséges hozzá ORBit).

--enable-shared[=PKGS]

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: Megosztott modulok készítése [alapbeállítása yes]

--enable-sigchild

PHP 3, PHP 4: A PHP saját SIGCHLD kezelőjének engedélyezése.

--enable-static[=PKGS]

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: Statikus modulok készítése [alapbeállítása yes]

--enable-sysvsem

PHP 3, PHP 4: Engedélyezi a System V szemafor támogatást.

--enable-sysvshm

PHP 3, PHP 4: Engedélyezi a System V megosztott memória támogatást.

--enable-trans-sid

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: Engedélyezi az automatikus session id továbbítást.

--with-cdb[=DIR]

PHP 3, PHP 4: Beépíti a CDB támogatást.

--with-config-file-path=PATH

PHP 3: Beállítja a könyvtárat, ahol a php3.ini fájl keresendő. Alapbeállításban /usr/local/lib

PHP 4: Beállítja a könyvtárat, ahol a php.ini fájl keresendő. Alapbeállításban /usr/local/lib.

--with-cpdflib[=DIR]

PHP 3: Beépíti a ClibPDF támogatást. A DIR a ClibPDF telepítési könyvtára, alapbeállításban /usr/local.

PHP 4: Beépíti a cpdflib támogatást (szükséges hozzá cpdflib >= 2). A DIR a cpdfllib telepítési könyvtára, alapbeállításban /usr.

--with-exec-dir[=DIR]

PHP 3, PHP 4: Csak ebben a könyvtárvban engedélyezi a futtatást safe mode esetén. Alapbeállításban /usr/local/php/bin.

--with-fdftk[=DIR]

PHP 3, PHP 4: Beépíti az fdftk támogatást. A DIR az fdftk telepítési könyvtára, alapbeállításban /usr/local.

--with-gnu-ld

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: A C fordító GNU ld-t használ [alapbeállítása no]

--with-icap[=DIR]

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: Beépíti az ICAP támogatást.

--with-imap[=DIR]

PHP 3, PHP 4: Beépíti az IMAP támogatást. A DIR az IMAP include és c-client.a könyvtára.

--with-imsp[=DIR]

PHP 3: Beépíti az IMSP támogatást (a DIR az IMSP's include és libimsp.a könyvtára).

PHP 4: Ez az opció nem áll rendelkezésre a PHP 4-ben.

--with-java[=DIR]

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: Beépíti a Java támogatást. A DIR a JDK telepítési könyvtára. Ez csak megosztott PHP modulként fordítható.

--with-kerberos[=DIR]

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: A Kerberos támogatás beépítése az IMAP-be.

--with-mcal[=DIR]

PHP 3, PHP 4: Beépíti az MCAL támogatást.

--with-mcrypt[=DIR]

PHP 3, PHP 4: Beépíti az mcrypt támogatást. A DIR az mcrypt telepítési könyvtára.

--with-mhash[=DIR]

PHP 3, PHP 4: Az mhash támogatás beépítése. A DIR az mhash telepítési könyvtára.

--with-mm[=DIR]

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: Beépíti az mm támogatást a session tárolásra.

--with-mod_charset

PHP 3, PHP 4: Engedélyezi a transzfer táblákat a mod_charset-hez (Rus Apache).

--with-pdflib[=DIR]

PHP 3: Beépíti a pdflib támogatást (0.6-os és 2.0-s verzióval tesztelve). A DIR a pdflib telepítési könyvtára, alapbeállításban /usr/local.

PHP 4: Beépíti a pdflib 3.x/4.x támogatást. A DIR a pdflib telepítési könyvtára, alapbeállításban /usr/local.

PHP 4 és PDFlib 3.x/4.x megköveteli, hogy legyen JPEG és TIFF könyvtárak a rendszeredben. Amikor PDFlib támogatással fordítasz, használd a --with-jpeg-dir és --with-tiff-dir konfigurációs beállításokat. A --with-png-dir és a --with-zlib-dir beállításokkal pedig megadhatod, hogy a PDFlib támogatás PNG és Zlib támogatással együtt épüljön fel.

--enable-shared-pdflib

PHP 3, PHP 4: a pdflib mint shared library-t aktivizálja.

--with-readline[=DIR]

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: Beépíti a readline támogatást. A DIR a readline telepítési könyvtára.

--with-regex=TYPE

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: Regex könyvtár típusa: system, apache vagy php

--with-servlet[=DIR]

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: Beépíti a servlet támogatást. A DIR a JSDK telepítési könyvtára. Ez az SAPI elvárja, hogy a Java modul megosztott formában legyen feltelepítve.

--with-ming

PHP 3: nem elérhető PHP 3-ban

PHP 4: Beépíti a Ming féle Flash 4 támogatást.

--with-swf[=DIR]

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: Beépíti az swf támogatást.

--with-system-regex

PHP 3: A beépített regex könyvtár kikapcsolása.

PHP 4: (megszüntetve) A rendszer regex könyvtárának használata.

--with-tsrm-pth[=pth-config]

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: A GNU Pth használata.

--with-tsrm-pthreads

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: POSIX thread-ek használata (alapbeállítás)

--with-x

PHP 3: Az X Window System használata.

PHP 4: Ez az opció nem áll rendelkezésre a PHP 4-ben.

--with-bz2[=DIR]

PHP 4: Beépíti a bzip2 támogatást. A DIR paraméter a bzip2 telepítési könyvtára.

--with-zlib-dir[=DIR]

PHP 3: A zlib könyvtár a pdflib 2.0-hoz, vagy a zlib támogatás beépítése.

PHP 4: A zlib könyvtár a pdflib 3.x-hez, vagy a zlib támogatás beépítése.

--with-zlib[=DIR]

PHP 3, PHP 4: A zlib támogatás beépítése (szükséges a zlib >= 1.0.9). A DIR a zlib telepítési könyvtára, alapbeállításban /usr.

--with-zip[=DIR]

PHP 4: Beépíti a zip támogatást (a szükséges zziplib verziószám >= 0.10.6). A DIR a zziplib telepítési könyvtára, alapbeállításban /usr/local.

A legfrissebb zziplib verziót a http://zziplib.sourceforge.net/ címről tudod letölteni.

--without-pcre-regex

PHP 3: A Perl kompatibilis reguláris kifejezések kikapcsolása.

PHP 4: A Perl kompatibilis reguláris kifejezések kikapcsolása. Használd a --with-pcre-regex=DIR opciót, hogy megadd a PCRE include és library fájlok elérési útját, ha nem a beépített konyvtárat használod.

--without-posix

PHP 3: A POSIX funkciók kikapcsolása.

PHP 4: Ez az opció nem áll rendelkezésre; használd helyette a --disable-posix paramétert!

--enable-overload

PHP 3: nem elérhető PHP 3-ban

PHP 4: Engedélyezi objektum tulajdonságok és metódusok túlterhelését (overloading support).


Hálózati

--with-curl[=DIR]

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: Beépíti a CURL támogatást.

--enable-ftp

PHP 3: Ez az opció nem áll rendelkezésre; használd helyette a --with-ftp paramétert!

PHP 4: Engedélyezi az FTP támogatást.

--with-ftp

PHP 3: Engedélyezi az FTP támogatást.

PHP 4: Ez az opció nem áll rendelkezésre; használd helyette az --enable-ftp paramétert!

--disable-url-fopen-wrapper

PHP 3, PHP 4: Az URL-felismerő fopen komponensek kikapcsolása.

Figyelem

Ez a beállítási lehetőség csak a 4.0.3-as és előbbi PHP verziókban található meg. A későbbiekben az allow_url_fopen INI paraméter szabályozza ezt a működést. Ezért nem kell fordításidőben dönteni erről a fukcióról.

--with-mod-dav=DIR

PHP 3, PHP 4: Beépíti a DAV támogatást az Apache mod_dav segítségéve. A DIR a mod_dav telepítési könyvtára (Csak Apache modul verzióban!)

--with-openssl[=DIR]

PHP 3, PHP 4: Beépíti az SNMP OpenSSL támogatását.

--with-snmp[=DIR]

PHP 3, PHP 4: Beépíti az SNMP támogatást. A DIR az SNMP telepítési könyvtára, alapbeállításban számos tipikus helyen keresi a configure. Állítsd a DIR értékét shared-re, ha külső PHP modulként szeretnéd lefordítani, vagy állítsd shared,DIR-re, ha külső modulként fordítod, és megadod a könyvtárat.

--enable-ucd-snmp-hack

PHP 3, PHP 4: Engedélyezi az UCD SNMP hack-et.

--enable-sockets

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: Engedélyezi a socket támogatást.

--with-yaz[=DIR]

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: Beépíti a YAZ támogatást (ANSI/NISO Z39.50). A DIR a YAZ bin telepítési könyvtára.

--enable-yp

PHP 3: Ez az opció nem áll rendelkezésre; használd helyette a --with-yp paramétert!

PHP 4: Beépíti az YP támogatást.

--with-yp

PHP 3: Beépíti az YP támogatást.

PHP 4: Ez az opció nem áll rendelkezésre; használd helyette az --enable-yp paramétert!

--with-mnogosearch

PHP 3, PHP 4: Beépíti az mnoGoSearch támogatást.


PHP viselkedését szabályozó

--enable-magic-quotes

PHP 3, PHP 4: Engedélyezi alapbeállításban a magic quotes szolgáltatást.

--disable-short-tags

PHP 3, PHP 4: Kikapcsolja alapbeállításban a rövid <? kezdő HTML tag-et.

--enable-track-vars

PHP 3: Engedélyezi a GET/POST/Cookie változók követését (asszociatív tömbök előállítását).

PHP 4: Ez az opció nem áll rendelkezésre a PHP 4-ben; a PHP 4.0.2-es, verziótól kezdve a track_vars szolgáltatás mindig be van kapcsolva.


Szerver

--with-aolserver-src=DIR

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: Az AOLserver forrásának könyvtárát.

--with-aolserver=DIR

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: A telepített AOLserver könyvtárát.

--with-apache[=DIR]

PHP 3, PHP 4: Apache modul fordítása. A DIR a felső-szintű Apache könyvtár, alapbeállításban /usr/local/etc/httpd.

--with-apxs[=FILE]

PHP 3, PHP 4: Megosztott Apache modul fordítása. A FILE az Apache apxs elérési útja, opcionális; alapbeállításban apxs.

--enable-versioning

PHP 3: A Solaris 2.x és a Linux által nyújtott versioning és scoping szolgáltatások használata.

PHP 4: Csak a szükséges szimbólumok exportálása. Lásd az INSTALL fájlt további információkért.

--with-caudium[=DIR]

PHP 3: nem elérhető PHP 3-ban

PHP 4: PHP-t Pike modulként építi fel a Caudium webszerveréhez. DIR a Caudium alapkönyvtára. Ha nincs megadva könyvtár, akkor a $prefix/caudium/server -t fogja használni, ahol a prefix a --prefix kapcsolóval szabályozható, ez alapértelmezés szerint a /usr/local.

--with-fhttpd[=DIR]

PHP 3, PHP 4: fhttpd modul fordítása. A DIR az fhttpd forrás könyvtára, alapbeállításban /usr/local/src/fhttpd.

--with-nsapi=DIR

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: A telepített Netscape könyvtára.

--with-phttpd=DIR

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4:

--with-pi3web=DIR

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: A PHP fordítása a Pi3Web szerver moduljaként.

--with-roxen=DIR

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: A PHP Pike modulként való fordítása. A DIR a Roxen könyvtára, általában /usr/local/roxen/server.

--enable-roxen-zts

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: A Roxen fordítása Zend Thread Safety kóddal.

--with-thttpd=SRCDIR

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4:

--with-zeus=DIR

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: A PHP fordítása Zeus ISAPI modulként.


Szöveg és nyelv

--with-aspell[=DIR]

PHP 3, PHP 4: Beépíti az ASPELL támogatást.

--with-gettext[=DIR]

PHP 3, PHP 4: Beépíti a GNU gettext támogatást. A DIR a gettext telepítési könyvtára, alapbeállításban /usr/local.

--with-iconv[=DIR]

PHP 3: nem elérhető PHP 3-ban.

PHP 4: Beépíti az iconv támogatást.

--with-pspell[=DIR]

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: Beépíti a PSPELL támogatást.

--with-recode[=DIR]

PHP 3: Include GNU recode support.

PHP 4: Beépíti a recode támogatást. A DIR a recode telepítési könyvtára.

--enable-shmop

PHP 3, PHP 4 : shmop támogatás aktivizálása.


XML

--with-dom[=DIR]

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: Beépíti a DOM támogatást (szükséges libxml >= 2.0). A DIR a libxml telepítési könyvtára, alapbeállításban /usr

--enable-sablot-errors-descriptive

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: Engedélyezi a leíró jellegű hibaüzeneteket.

--with-sablot[=DIR]

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: Beépíti a Sablotron támogatást.

--enable-wddx

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban.

PHP 4: Beépíti a WDDX támogatást.

--disable-xml

PHP 3: Ez az opció nem áll rendelkezésre a PHP 3-ban, mivel az XML funkciók nem kerülnek beépítésre alapbeállításban. Használd helyette a --with-xml paramétert a bekapcsoláshoz!

PHP 4: Kikapcsolja a beépített expat könyvtár XML támogatását.

--with-xml

PHP 3: Beépíti az XML támogatást.

PHP 4: Ez az opció nem áll rendelkezésre a PHP 4-ben, mivel az XML funkciók befordításra kerülnek alapbeállításban. Használd helyette a --disable-xml paramétert, hogy kikapcsold!


Telepítés Windows rendszerekre

Ez a fejezet a Windows 95/98/Me és a Windows NT/2000/XP rendszerekre történő telepítésekre vonatkozik. A PHP nem működik 16 bites környezetben mint például a Windows 3.1. Bizonyos esetekben a támogatott Windows környezetekre Win32 néven hivatkozunk.

A PHP Windows-ra telepítésének két fő módja van: vagy a kézi vagy a InstallShield telepítővarázslóval történő.

Ha van Microsoft Visual Studio telepítve a rendszereden, akkor megpróbálhatod a PHP-t az eredeti forrásból lefordítani.

Amint sikerült a PHP-t telepítened a Windows-odra, különböző kiterjesztéseket is betölthetsz további funkcionalitások eléréséhez.


Windows InstallShield telepítés

A Windows PHP telepítőprogram letölthető a http://www.php.net/ címről, ez a PHP CGI változatát telepíti is beállítja az IIS, PWS és Xitami szervereket is (ha ilyet használsz). Azt is vedd figyelembe, hogy az InstallShield telepítőprogrammal nagyon könnyű életre kelteni a PHP-t, de ez nagyon sok szempontból korlátozott változat, például a kiterjesztések automatikus telepítését nem végzi el.

Először telepítsd a választott szervert a gépedre, és ellenőrizd, hogy jól működik-e.

Futtassd a telepítő exe fájlt, és kövesd a varázsló által adott utasításokat. Kétféle telepítés közül választhatsz - a standard telepítés jól használható alapbeállításokat ad, az advanced kérdéseket tesz fel (, amelyekre tudni kell válaszolni :) .

A telepítés varázslója elég információt gyűjt ahhoz, hogy elvégezhesse a php.ini fájl beállítását és konfigurálja a szervert a PHP számára. IIS esetén, vagy NT Workstation alatt PWS használatakor az összes ponton fellelhető script map beállítást megmutatja, és kiválaszthatod, hogy mely pontokra kerüljön be a PHP támogatás.

Mikor a telepítés befejeződött, a varázsló informál arról, hogy szükséges-e a rendszer, ill. a szerver újraindítása, vagy rögtön elkezdheted a munkát a PHP-vel.

Figyelem

Légy tekintettel arra, hogy a PHP ezen telepítési módja nem biztonságos. Ha biztonságos PHP-ra vágysz, akkor jobban teszed, ha a kézikönyv további fejezeteit is elolvasod, és minden beállítást körültekintően elvégzel. Ez az automatikus telepítő egy azonnal használható PHP-t varázsol a gépedre, de nem online szerverekre szánták.


Kézi telepítés lépései

Ez a fejezet segít a PHP kézi telepítésében és Windows-os webszerverek konfigurálásában. A zippelt bináris disztribuciót kell letölteni ehhez a http://www.php.net/ címről. Ezt az útmutatót eredetileg Bob Silva készítette. Az eredeti verzió angolul megtalálható a http://www.umesd.k12.or.us/php/win32install.html.

Ez a leírás a következő szerverek manuális PHP telepítését fedi le:

  • Personal Web Server (friss verzió javasolt)

  • Internet Information Server 3 vagy 4

  • Apache 1.3.x

  • Omni HTTPd 2.0b1 vagy újabb

  • Oreilly Website Pro

  • Xitami

  • Netscape Enterprise Server, iPlanet

A Windows-os PHP4 disztribúciók kétféle formában kaphatók - CGI futtató (php.exe) és számos SAPI modulként (például php4isapi.dll). Az utóbbi elég új a PHP 4-ben, és jelentős teljesítményjavulást és néhány új lehetőséget biztosít az előzőhöz képest.

Figyelem

Mindazonáltal, figyelj arra, hogy a SAPI modulok NEM tekinthetők még kész minőségűnek. Különösen az ISAPI modul használatakor valószínűleg súlyos megbízhatósági problémákkal fogsz találkozni főleg Win2K-nál régebbi környezetekben. Tanúja lehetsz számos 500-as kódú szerver hibának és néhány más gyenge modultól is szenvedhetsz. Figyelmeztettünk!

Ennek az az oka, hogy a SAPI modulokban a PHP újdonsült "szál-biztos" (thread-safe) változata fut, amelyet még nem teszteltek és nyúztak eleget ahhoz, hogy teljesen stabilnak nyilvánítsák, és tartalmaz néhány ismert hibát is. Másrészről, néhányan nagyon jó eredményekről számoltak be a SAPI modulok használata kapcsán, még akkor is ha, ha jelen pillanatban nem tudunk arról, hogy bárki is üzemelő webhelyén ezeket használná. Röviden: ha abszolút stabilitás kell, akkor a CGI változat stabilitása és a SAPI modulok teljesítménybeli különbsége közt kell döntened.

Ha Windows 95 alatt akarod használni valamelyik SAPI modult, akkor győződj meg arról, hogy letöltötted a DCOM frissítést a Microsoft DCOM oldaláról. ISAPI modulokhoz, egy ISAPI 4.0-képes Web szerverre lesz szükséged (IIS 4.0, PWS 4.0 és IIS 5.0 alatt tesztelve). IIS 3.0 NEM használható. Elképzelhető, hogy le kell töltened és telepítened a Windows NT 4.0 Option Pack with IIS 4.0-t, ha natív PHP támogatást akarsz.

A következő lépéseket minden telepítés esetén a szerver specifikus beállítások előtt kell végrehajtani.

  • Tömörítsd ki a disztribúciós fájlt egy tetszőleges könyvtárba. A c:\php\ pl. jó választás.

  • Biztosítanod kell, hogy a PHP az általa használandó DLL-eket meg is találja. Hogy milyen DLL-ekre vonatkozik ez, az függ attól, hogy a milyen webszervert használsz és, hogy azon a PHP modulként vagy CGIüként fog futni. A php4ts.dll minden esetben szükséges. Ha szerver modulként (pl. Apache vagy ISAPI) használod, akkor a sapi alkönyvtárból a megfelelő DLL kell. Hogy ezek a DLL-ek elérhetőek legyenek, bemásolhatod őket a rendszerkönyvtárba (pl. winnt/system32 vagy windows/system), vagy rakd egy könyvtárba a fő PHP állománnyal (pl. php.exe, php4apache.dll).

    A PHP bináris, a SAPI modulok és néhány kiterjesztés használata külső DLL-ektől is függ. Bizonyosodj meg róla, hogy ezek a Windows PATH egyik könyvtárában vannak. A legjobb, ha ezeket mind a rendszer könyvtárba másolod, ami általában:

    c:\windows\system ;Windows 9x/Me esetén
    c:\winnt\system32 ;Windows NT/2000/XP esetén

    A másolandó fájlok:

    'php4ts.dll', ha már létezik, írd felül
    A disztribúció 'dlls' könyvtárának fájlai. Ha már a rendszeredben ezek installálva vannak, akkor csakis akkor írd felül azokat, ha valami nem elvártnak megfelelően működik. Mielőtt felülírnád a fájlokat, jó, ha csinálsz róluk biztonsági másolatot vagy átmásolod egy másik könyvtárba őket.

    Töltsd le a legfrissebb, a saját platformodnak megfelelő Microsoft Data Access Components (MDAC) csomago(ka)t, különösen ha Microsoft Windows 9x/NT4-t használsz. MDAC elérhető a http://www.microsoft.com/data/ címen.

  • Másold be a kiválasztott ini fájlt (ld lejjebb) Windows 9x/Me esetén a '%WINDOWS%' könyvtárba vagy Windows NT/2000/XP esetén a '%SYSTEMROOT%' könyvtárba, és nevezd át php.ini-re. A '%WINDOWS%' vagy '%SYSTEMROOT%' könyvtárak: typically:

    c:\windows ; Windows 9x/Me esetén
    c:\winnt vagy c:\winnt40 ; NT/2000/XP szerverek esetén

    Két ini fájl került bele a zip-be: php.ini-dist és php.ini-optimized. Azt tanácsoljuk, hogy a php.ini-optimized-t használd, mert azokban az alapértékek úgy kerültek meghatározásra, hogy minél jobb teljesítménnyel és nagyobb védelemben fussanak a programjaid. A legjobb, ha áttanulmányozod az egész ini beállítások fejezetet, és magad határozod meg az összes bejegyzést. Ha a legnagyobb biztonságot szeretnéd eléni, akkor ez a járandó út, bár a PHP ezekkel php.ini-kben megadott alapbeállításokkal is ragyogóan működik.

  • Szerkeszd át a saját 'php.ini' fájlodat:

    • Az 'extension_dir' bejegyzést át kell írni, hogy az arra a könyvtárra mutasson, ahol a 'php_*.dll' fájlok vannak, pl.: 'c:\php\extensions'.

    • Ha OmniHTTPd használsz, akkor a következő lépést hagyd ki. Állítsd be a 'doc_root'-ot, hogy az a webszervered document_root könyvtárára mutasson, például c:\apache\htdocs vagy c:\webroot

    • Válaszd ki, mely kiterjesztéseket töltse be a PHP induláskor. Nézd át a Windows kiterjesztések c. szakaszt, hogy melyeket kell telepíteni és melyek jönnek együtt a PHP disztribúcióval. Először érdemes tesztelni, hogy működik-e a PHP mindenféle kiterjesztés engedélyezése nélkül is.

    • PWS és IIS alatt, beállíthatod a browscap.ini fájlt, hogy az Windows 9x/Me esetén mutasson a 'c:\windows\system\inetsrv\browscap.ini'-re és NT/2000/XP Server esetén 'c:\winnt\system32\inetsrv\browscap.ini'-re.

    • Figyelj, hogy a Windows-os disztribúció mibs könyvtárában SNMP támogatáshoz szükséges fájlok vannak. Ezt a könyvtárat a DRIVE:\usr\mibs-be másold át (DRIVE az a meghajtó, ahová a PHP-t telepítetted.)


Fordítás forrásból

Mielőtt belevágunk, érdemes megválaszolni azt a kérdést, hogy: "Miért olyan nehéz lefordítani Windows alatt?". Két indokra vezethető vissza:

  1. A Windows (még) nem rendelkezik fejlesztők olyan nagy lélekszámú csapatával, akik szabadon szeretnék megosztani egymás közt forrásaikat. Ennek közvetlen következménye, hogy az ilyen fejlesztésekhez szükséges, elengedhetetlen infrastruktúrális beruházások még nem történtek. Nagyjából a hozzáférhető eszközök mindegyikét Unix alól "hozták át", ezért nem kell meglepődni, ha ez az örökség időnként nagyon szembeötlő.

  2. Az itt következő uasítások legtöbbje "csináld és felejtsd el" jellegű, ezért dőlj hátra, és próbáld meg a lehető leghűségesebben követni azokat.


Előkészületek

Mielőtt elkezded, le kell töltened...

  • Kezdőknek, Cygwin toolkit-et a legközelebbi cygwin tüköroldalról. A nagyon sok közkedvelt GNU segédprogramot tartalmaz, amelyek szükségesek a PHP létrehozásához.

  • A maradék eszközöket töltsd le a PHP oldaláról: http://www.php.net/extra/win32build.zip.

  • A PHP által használt DNS név-feloldó forrását is szerezd be a http://www.php.net/extra/bindlib_w32.zip címről. Ez a win32build.zip könyvtárbeli resolv.lib helyett kell.

  • Ha még nincs zip-et kicsomagoló segédprogramod, akkor szükséged lesz egyre. Egy ingyenes: InfoZip.

Végül kell, ugye, maga a PHP 4 forrása. A legutolsó fejlesztői változatra a szert tehetsz anonim CVS-t használva. Ha a snapshot-ot vagy source tarolt változatokat töltöd le, akkor azokat nemcsak untar-olni és ungzip-elni kell, de minden szimpla soremelést CR + LF -re kell cserélned a *.dsp és *.dsw fájlokban, mielőtt hozzálátnál használni őket a Microsoft Visual C++ -ban.

Megjegyzés: Rakd a Zend és TSRM könyvtárakat a php4 könyvtáron belülre, hogy a létrehozási lépések során megtalálja ezeket a fordító.


Az egész összerakása

  • Kövesd az általad választott unzip kitömörítő program telepítési lépéseit.

  • Indítsd el a setup.exe-t, és kövesd az ott leírtakat. Ha c:\cygnus útvonaltól eltérő helyre akarod telepíteni, akkor a be kell állítani a Cygwin környezeti változót arra a könyvtárra. Windows 95/98 esetén a környezeti változó beállítása történhet az autoexec.bat fájlban is, Windows NT esetén pedig, a My Computer => Control Panel => System párbeszédablakban válaszd ki az Environment nevű panelt.

    Figyelem

    Csinálj egy ideiglenes könyvtárat a Cygwin-nek, máskülönben sok parancs (különösen a bison) sikertelen lesz. Windows 95/98 esetén mkdir C:\TMP, Windows NT esetén mkdir %SystemDrive%\tmp.

  • Tömörítsd ki a win32build.zip fájlt egy könyvtárba.

  • Indítsd el a Microsoft Visual C++ -t, és válaszd ki a menüből a Tools => Options pontot. A párbeszédablakban válaszd ki a Directories panelt. Sorjában a legördülő listából válaszd ki az Executables, az Includes és Library files pontokat és győződj meg róla, hogy a hozzájuk tartozó listákban szerepel-e a cygwin\bin, win32build\include illetve win32build\lib. (A listához hozzáadni úgy kell, hogy a lista végén lévő üres sorra állsz, és elkezdesz gépelni.) Egy jellegzetes listabejegyzések valahogy így mutatnak:

    • c:\cygnus\bin

    • c:\php-win32build\include

    • c:\php-win32build\lib

    Nyomd le OK gombot, és lépj ki a Visual C++ -ból.

  • Csinálj egy másik könyvtárat, ahová kitömöríted a bindlib_w32.zip-et. El kell döntened, hogy hibakereső szimbólumokkal (debug symbol) (bindlib - Win32 Debug) vagy anélkül (bindlib - Win32 Release) akarod fordítani a PHP-t. Állítsd be a megfelelő konfigurációt:

    • GUI -t használóknak: indítsd el a VC++ -t, nyisd meg a bindlib munkaterületetet (File => Open Workspace és válaszd ki a bindlib-et). Ezután: Build=>Set Active Configuration, és válaszd ki a kívánt konfigurációt, és végül: Build=>Rebuild All.

    • Parancssoros módban győződj meg arról, hogy a szükséges C++ környezeti változók legyenek beállítva vagy vcvars.bat le lett-e futtatva, és aztán add ki valamelyik alábbi parancsot:

      • msdev bindlib.dsp /MAKE "bindlib - Win32 Debug"

      • msdev bindlib.dsp /MAKE "bindlib - Win32 Release"

    • Ezen a ponton vagy a Debug vagy a Release alkönyvtárban kell, hogy legyen egy használható resolv.lib. Másold ezt rá a win32build\lib könyvtárban található ugyanilyen nevű fájlra.


Fordítás

A kezdésként legjobb egy önálló/CGI verziót fordítani.

  • GUI -t használóknak: indítsd el a VC++ -t, nyisd meg a php4ts munkaterületetet (File => Open Workspace és válaszd ki a php4ts-t). Ezután: Build=>Set Active Configuration, és válaszd ki a kívánt konfigurációt, és végül: Build=>Rebuild All.

  • Parancssoros módban győződj meg arról, hogy a szükséges C++ környezeti változók legyenek beállítva vagy vcvars.bat le lett-e futtatva, és aztán add ki valamelyik alábbi parancsot:

    • msdev php4ts.dsp /MAKE "php4ts - Win32 Debug_TS"

    • msdev php4ts.dsp /MAKE "php4ts - Win32 Release_TS"

    • Ennél a pontnál a Debug_TS vagy a Release_TS alkönyvtárban kell lennie egy használható php.exe fájlnak.

Ismételed meg a fenti lépéseket a php4isapi.dsp-re, amely a sapi\isapi könyvtárban található, ha a PHP-t Microsoft IIS -en akarod használni.


Windows-os kiterjesztések teleőítése

A webszerver és a PHP telepítése után valószínűleg néhány kiterjesztést is telepíteni akarsz. A következő táblázat az elérhető kiterjesztések zömét megtalálod. Megadhatod, hogy mely kiterjesztések töltődjenek be a PHP indulásakor, ha kitörlöd a megjegyzést jelentő pontosvesszőt (;) a 'extension=php_*.dll' mintájú sorok elejéről a php.ini-ben. A szkriptjeidben is betöltheted dinamikusan őket a dl() segítségével.

A PHP 4 kiterjesztések DLL-jei mind 'php_' taggal kezdődnek ( és 'php3_' a PHP 3-éi). Ezáltal megelőzhető a PHP kiterjesztések és az általuk támogatott könyvtárak közti összevisszaság.

Megjegyzés: PHP 4.0.6-ban BCMath, Calendar, COM, FTP, MySQL, ODBC, PCRE, Session, WDDX és XML támogatás be van építve. Semmilyen kiegészítő kiterjesztést nem kell ezek használatához betölteni. Nézd meg a disztribúcióval jövő README.txt vagy install.txt fájlokban a beépített kiterjesztések listáját!

Megjegyzés: Néhány kiterjesztés további DLL-eket igényel a működésükhez. Néhány ezek közül a disztribúciós csomag része, a 'dlls' könyvtárban találod meg ezeket, de van néhány - pl. Oracle (php_oci8.dll) -, amelyhez szükségesek nincsenek a csomagban.

A csomagolt DLL-eket másold a 'dlls' könyvtárból valamilyen, a Windows PATH részét alkotó könyvtárba, a biztonságos helyek:

c:\windows\system ; Windows 9x/Me esetén
c:\winnt\system32 ; Windows NT/2000/XP esetén.

Ha már a rendszeredben ezek installálva vannak, akkor csakis akkor írd felül azokat, ha valami nem az elvártnak megfelelően működik. Mielőtt felülírnád a fájlokat, jó, ha csinálsz róluk biztonsági másolatot vagy átmásolod egy másik könyvtárba őket.

Táblázat 3-1. PHP kiterjesztések Windows alatt

KiterjesztésLeírásMegjegyzés
php_bz2.dllbzip2 tömörítő függvényeknincs
php_calendar.dllNaptár átváltási függvényekPHP 4.0.3 óta beépített
php_cpdf.dllClibPDF függvényeknincs
php3_crypt.dllCrypt függvények-
php_ctype.dllctype féle függvényeknincs
php_curl.dllCURL, Client URL library függvényekszükséges: libeay32.dll, ssleay32.dll (része a disztribúciónak)
php_cybercash.dllCybercash payment függvényeknincs
php_db.dllDBM függvényekellenjavallt, DBA-t használd helyette (php_dba.dll)
php_dba.dllDBA: (dbm jellegű) adatbázis absztrakciós réteg függvényeinincs
php_dbase.dlldBase függvényeknincs
php3_dbm.dllBerkeley DB2 eljáráskönyvtár-
php_domxml.dllDOM XML függvényekszükséges: libxml2.dll (része a disztribúciónak)
php_dotnet.dll.NET függvényeknincs
php_exif.dllEXIF fejlécek olvasása JPEG-bőlnincs
php_fbsql.dllFrontBase függvényeknincs
php_fdf.dllFDF: Forms Data Format függvények.szükséges: fdftk.dll (része a disztribúciónak)
php_filepro.dllfilePro függvényekcsak olvasható hozzáféréssel
php_ftp.dllFTP függvényekPHP 4.0.3 óta beépített
php_gd.dllGD eljáráskönyvtár képkezelő függvényeinincs
php_gettext.dllGettext függvényekszükséges: gnu_gettext.dll (része a disztribúciónak)
php_hyperwave.dllHyperWave függvényeknincs
php_iconv.dllICONV characterset conversionszükséges: iconv-1.3.dll (része a disztribúciónak)
php_ifx.dllInformix függvényekszükséges: Informix eljáráskönyvtárak
php_iisfunc.dllIIS kezelési függvényeknincs
php_imap.dllIMAP POP3 és NNTP függvényekPHP 3: php3_imap4r1.dll
php_ingres.dllIngres II függvényekszükséges: Ingres II libraries
php_interbase.dllInterBase függvényekszükséges: gds32.dll (része a disztribúciónak)
php_java.dllJava extensionszükséges: jvm.dll (része a disztribúciónak)
php_ldap.dllLDAP függvényekszükséges: libsasl.dll (része a disztribúciónak)
php_mhash.dllMhash Functionsnincs
php_ming.dllMing függvények for Flashnincs
php_msql.dllmSQL függvényekszükséges: msql.dll (része a disztribúciónak)
php3_msql1.dllmSQL 1 client-
php3_msql2.dllmSQL 2 client-
php_mssql.dllMSSQL függvényekszükséges: ntwdblib.dll (része a disztribúciónak)
php3_mysql.dllMySQL függvényekPHP 4 óta beépített
php3_nsmail.dllNetscape levelező függvények-
php3_oci73.dllOracle függvények-
php_oci8.dllOracle 8 függvényekszükséges: Oracle 8 kliens eljáráskönyvtárak
php_openssl.dllOpenSSL függvényekszükséges: libeay32.dll (része a disztribúciónak)
php_oracle.dllOracle függvényekszükséges: Oracle 7 client kliens eljáráskönyvtárak
php_pdf.dllPDF függvényeknincs
php_pgsql.dllPostgreSQL függvényeknincs
php_printer.dllPrinter függvényeknincs
php_sablot.dllXSLT függvényekszükséges: sablot.dll (része a disztribúciónak)
php_snmp.dllSNMP get and walk függvényekcsak NT -n!
php_sybase_ct.dllSybase függvényekszükséges: Sybase kliens eljáráskönyvtárak
php_yaz.dllYAZ függvényeknincs
php_zlib.dllZLib tömörítő függvényeknincs


Szerverek - Apache

Ez a fejezet a PHP Apache szerverre telepítésével foglalkozik, mind a Unix, mind a Windows változatokkal.


A PHP telepítése UNIX-on futó Apache-hoz

Az alábbi 8. sor configure opcióihoz a Configure opciók teljes listájából választhatsz továbbiakat.

Példa 3-5. Gyors telepítési utasítások PHP 4-hez (Apache modul verzió)

1.  gunzip apache_1.3.x.tar.gz
2.  tar xvf apache_1.3.x.tar
3.  gunzip php-x.x.x.tar.gz
4.  tar xvf php-x.x.x.tar
5.  cd apache_1.3.x
6.  ./configure --prefix=/www
7.  cd ../php-x.x.x
8.  ./configure --with-mysql --with-apache=../apache_1.3.x --enable-track-vars
9.  make
10. make install
11. cd ../apache_1.3.x
12. PHP 3 esetén: ./configure --activate-module=src/modules/php3/libphp3.a
    PHP 4 esetén: ./configure --activate-module=src/modules/php4/libphp4.a
13. make
14. make install

  Ehelyett a lépés helyett talán jobb, ha a httpd futtatható állományát
  a meglévőre rámásolod. Győződj meg róla, hogy előtte leállítottad
  a szervert!

15. cd ../php-x.x.x
16. PHP 3 esetén: cp php3.ini-dist /usr/local/lib/php3.ini
    PHP 4 esetén: cp php.ini-dist /usr/local/lib/php.ini

  Szerkeszheted az .ini állományt, beállítva az opciókat.
  Ha máshova szeretnéd tenni ezt a fájlt, add meg a
  --with-config-file-path=/eleresi/ut paramétert a 8. lépésben.

17. Szerkeszd a httpd.conf vagy srm.conf fájlt és add hozzá:

     PHP 3 esetén:   AddType application/x-httpd-php3 .php3
     PHP 4 esetén:   AddType application/x-httpd-php .php

  Itt bármilyen kiterjesztést választhatsz. A .php csak a
  mi javaslatunk. Akár a  .html kiterjesztést is megadhatod.

18. Használd a szokásos módszert az Apache szerver újraindítására.
    (Le kell állítanod és újra kell indítanod a szervert, nem csak
    újratölteni egy HUP vagy USR1 jellel.)

Az Apache telepítésétől és a Unix változattól függően, sok módja lehet a szerver leállításának és újraindításának. Itt néhány jellemző utasítást adunk közre, hogyan kell újraindítani a kiszolgálót, de ezek eltérhetnek apache/unix telepítéstől függően. Az /ahol/van/-t cseréld ki arra a könyvtárra, ahol ezek a programok vannak:

1. különféle Linux és SysV változatok esetén:
/etc/rc.d/init.d/httpd restart

2. apachectl szkripttel:
/ahol/van/apachectl stop
/ahol/van/apachectl start

3. httpdctl és httpsdctl (OpenSSL), hasonlóan az apachectl-hez:
/ahol/van/httpsdctl stop
/ahol/van/httpsdctl start

4. mod_ssl vagy más SSL kiszolgáló használatakor esetleg a kézi megoldás:
    a leállításra és újraindításra:

/ahol/van/apachectl stop
/ahol/van/apachectl startssl

Az apachectl és http(s)dctl állományok elérési útvonala gyakran eltérő. Ha tudsz használni locate vagy whereis vagy which parancsokat, akkor azokkal megkerestetheted ezeket a szervert irányító programokat.

A PHP Apache szerverrel történő fordításának néhány példája:

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

Ez létre fog hozni egy libphp4.so megosztott modult, amit az Apache szerverbe egy LoadModule sorral lehet betölteni a httpd.conf fájlban. A PostgreSQL támogatás ebben az esetben beépített a libphp4.so modulba.

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

Ez szintén egy libphp4.so megosztott modult hoz létre az Apache számára, de egy pgsql.so modult is generál, amit később a PHP-be kell tölteni a php.ini extension direktívájával, vagy egy szkriptben a dl() függvénnyel.

./configure --with-apache=/az/apache/forras/eleresi/utja --with-pgsql

Ez létre fog hozni egy libmodphp4.a modult, egy mod_php4.c-t, és néhány kapcsolódó fájlt, és bemásolja az Apache forrás fába a src/modules/php4 könyvtárba. Ezután az Apache fordítása az --activate-module=src/modules/php4/libphp4.a opcióval történik, és az Apache fordító rendszer elő fog állítani egy libphp4.a fájlt, és statikusan befordítja a httpd bináris állományba. A PostgreSQL támogatás közvetlenül a httpd futattható állomány része, tehát a végső eredmény egy egyedülálló httpd fájl, ami minden Apache és PHP funkciót tartalmaz.

./configure --with-apache=/az/apache/forras/eleresi/utja --with-pgsql=shared

Majdnem megegyezik az előzővel, azonban a PostgreSQL támogatás nem közvetlenül a httpd futtatható állományba épül be, hanem létrejön egy pgsql.so megosztott modul, és ezt később a PHP-be töltheted a php.ini extension beállítással, vagy közvetlenül a dl() függvénnyel egy PHP szkriptben.

Amikor eldöntöd, hogy melyik fordítási módszert választod, vedd számba mindeegyik lehetőség előnyeit és hátrányait is. A különálló objektumként való fordításnak megvan az az előnye, hogy lehetőséged van az Apache-ot külön lefordítani, és nem kell mindig újrafordítani, amikor lecseréled a PHP-t. Az Apache-ba építés (statikus módszer) előnye, hogy a PHP gyorsabban fog betöltődni és futni. További információkért lásd az Apache DSO támogatásról szóló oldalát.


PHP telepítése Windows-on futó Apache alá

Két módja van a PHP Windows-on futó Apache 1.3.x alá telepítésének. Az egyik a CGI kezelőként futtatható php.exe, a másik az Apache modulként használandó dll. Mindkét esetben le kell állítanod az Apache-t, és az srm.conf vagy a httpd.conf fájlokat át kell szerkesztened, hogy Apache együttműködjön a PHP-val.

Kevés változata van a PHP beállításának Apache szerver alá, az alábbi verzió elég egyszerű a kezdők számára is. Nézz utána a további konfigurációs lehetőségeknek az Apache dokumentációdban.

Ha kicsomagoltad a PHP disztribúciót a c:\php\ könyvtárba a Kézi telepítés lépései fejezetnek megfelelően, akkor a következő sorokat kell beírnod az Apache konfigurációs fájlába, hogy CGI kezelőként futtassa PHP-t:

  • ScriptAlias /php/ "c:/php/"

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

  • Action application/x-httpd-php "/php/php.exe"

A második sorban már szerepel a httpd.conf-ban, csak ki van kommentezve. Miután átírtad a konfigurációs fájlt, ne felejtsd el, újraindítani a szervert, például Apache service-ként futtatásakor a NET STOP APACHE után egy NET START APACHE paranccsal, vagy használhatod a szokványos shortcut-okat.

Ha Apache modulként akarod használni a PHP-t, akkor a php4ts.dll-t másold a windows/system-be - Windows 9x/Me eseén vagy a winnt/system32 könyvtárba - Windows NT/2000/XP esetén (felülírva a régit). Ezután a következő két sort kell az Apache konfigurációs fájlába írni:

  • LoadModule php4_module c:/php/sapi/php4apache.dll

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

Megjegyzés: Apache 1.3.22 for Windows kezdő konfigurációs fájla (httpd.conf-dist-win) alapértelmezésben tartalmaz egy ClearModuleList direktívát. Ha ez a direktíva be van kapcsolva, akkor az AddModule mod_php4.c sort az AddModule listába kell tenni, mert máskülönben PHP nem lesz Apache modulként regisztrálva.

Ahhoz, hogy használhasd a szintaxis kiemelést, egyszerűen készíts egy PHP szkript fájlt és illeszd be ezt a kódot: <?php show_source ("eredeti_php_szkript.php"); ?>. Értelemszerűen helyettesítsd az eredeti_php_script.php részt a megmutatni kivánt forráskódot tartalmazó fájlal. (Ez az egyetlen módja ennek, mivel Windows-on nincs a .phps-hez hasonló lehetőség.)

Megjegyzés: Windows-os Apache alatt minden fordított perjel (backslash) helyett szimpla perjelet kell használni egy elérési út meghatározásakor, pl. "c:\konyvtar\file.kit" helyett "c:/konyvtar/file.kit".


Szerverek - CGI/parancssori verzió

Alapbeállításban a PHP CGI programként fordul le. Ez létrehoz egy parancssorból használható értelmezőt, ami CGI feldolgozásra vagy nem webbel kapcsolatos PHP programozásra is használható. Ha egy olyan webszervert futtatsz, amelyhez a PHP modul szintű támogatással rendelkezik, akkor jobb teljesítmény eléréséhez használd inkább azt a módszert. A CGI verzió azonban lehetővé teszi az Apache-ot használóknak, hogy más-más PHP oldalakat más-más user-id-kkel futtassanak. Olvasd el a biztonságról szóló fejezetet, ha CGI-ként szeretnéd használni a PHP-t.


Tesztelés

Ha CGI programként fordítottad le a PHP-t, tesztelheted az eredményt azzal, hogy beírod make test. Mindig jól jön, ha leteszteled, mert így rögtön észlelhetsz olyan problémákat, amik esetleg csak később bukkantak volna fel.


Szintmérés (benchmarking)

Ha CGI programként fordítottad le a PHP 3-at, tesztelheted a sebességét azzal, hogy beírod make bench. Ha a "safe mode" be van kapcsolva, talán nem fog jól lefutni a benchmark, a megengedett 30 másodperc alatt. Ez azért van, mert a set_time_limit() nem használható safe mode-ban. Használd a max_execution_time konfigurációs beállítást, hogy megadhasd ezt az időt a szkriptjeidnek. A make bench nem veszi figyelembe a konfigurációs fájlt.

Megjegyzés: A make bench csak PHP 3-ban érhető el!


Szerverek - fhttpd

Ahhoz, hogy fhttpd modulként állítsd be a PHP-t, válaszolj "yes"-el a "Build as an fhttpd module?" kérdésre (ez a --with-fhttpd=DIR opció a configure-ban) és add meg az fhttpd könyvtárát. Ez alapbeállításban /usr/local/src/fhttpd. Ha fhttpd-t használsz, a PHP felépítése modulként jobb teljesítményt fog nyújtani, több beavatkozási lehetőséget és távoli futtatást biztosít.


Szerverek - Caudium

PHP 4-et Pike modulként építheted be a Caudium webszerveréhez, a PHP 3 nem támogatja ezt. Az alábbi egyszerű utasításokat követve lehet telepíteni a PHP 4-et Caudium alá.

Példa 3-6. Caudium telepítési utasítások

1.  Győződj meg arról, hogy a PHP 4 telepítése előtt már telepítve lett a Caudium.
    A PHP 4 helyes működéséhez a Pike 7.0.268 vagy ennél újabb verziójára lesz
    szükséged. A példa kedvéért feltételezzük, hogy a Caudium a /opt/caudium/server/
    könyvtárban van.
2.  Lépj át php-x.y.z könyvtárba (x.y.z a PHP verziószáma).
3.  ./configure --with-caudium=/opt/caudium/server
4.  make
5.  make install
6.  Indítsd újra a Caudium szervert, ha jelenleg fut.
7.  Lépj be a grafikus konfigurációs felületre és ott válaszd ki azt a "virtual
    server" pontot, amelyhez a PHP 4 támogatást akarsz adni.
8.  Kattints az "Add Module"-ra és keresd meg és utána add hozzá a "PHP 4
    Script Support" modult.
9.  Ha a dokumentáció azt mondja, hogy 'PHP 4 interpreter isn't available',
    akkor nézd meg, biztosan újraindítottad a szervert. Ha már ellenőrizted
    az /opt/caudium/logs/debug/default.1 fájlt mindenféle <filename>PHP4.so</filename>
    -val összefüggő hiba kapcsán, akkor nézd meg azt is, hogy a
    <filename>caudium/server/lib/[pike-verzio]/PHP4.so</filename> létezik-e.

10. Állítsd be a PHP Script Support modult, ha szükséges.

Természetesen számos kiterjesztéssel együtt fordíthatod le a Caudium szerverhez is a PHP 4-t, a kimerítő felsorolásért a teljes konfigurációs beállítások listáját olvasd el.

Megjegyzés: Ha MySQL témogatást is szeretnél, akkor figyelj arra, hogy a normál MySQL kliens kódot használd, máskülönben összeütközések léphetnek fel, ha a Pike is rendelkezik MySQL támogatással. Ezt a MySQL telepítési könyvtárának (install directory) megadásával teheted meg: --with-mysql.


Szerverek - IIS/PWS

Ez a fejezet az IIS szerverekre vonatkozó PHP telepítési útmutatókat tartalmazza, mind az IIS3, mind az IIS4 verziókhoz.


Windows 9x/NT/2000 és PWS/IIS 3

Ezen szervereken a konfigurálás a megadott REG fájl segítségével javasolt (pws-php4cgi.reg). Szerkesztheted ezt a fájlt, hogy a kiterjesztések és a PHP könyvtárait megadd. Vagy követheted az alábbi lépéseket, hogy elkészítsd ezt saját kezűleg.

Figyelem

Az alábbi lépések a windows registry-ben való közvetlen szerkesztést igénylik. Egyetlen hiba használhatatlanná teheti a rendszeredet! Mindenképpen készíts egy biztonsági másolatot, mielőtt bármi mást tennél. A PHP Team nem vállal felelősséget semmilyen kárért!

  • Futtasd a Regedit-et.

  • Keresd meg a HKEY_LOCAL_MACHINE /System /CurrentControlSet /Services /W3Svc /Parameters /ScriptMap pontot.

  • Az Edit menüben válaszd ki a New->String Value pontot.

  • Írd be a fájl kiterjesztést, amit használni szeretnél, pl. .php

  • Klikkelj kétszer az új szövegen és írd be a php.exe elérési útját, pl. c:\php\php.exe %s %s. A %s %s NAGYON fontos, enélkül a PHP nem fog működni.

  • Ismételd ezeket a lépéseket az összes kiterjesztésre, amit használni szeretnél.

A következő lépések nem befolyásolják a web szerver üzembehelyezését, és csak akkor van rá szükség, ha a php szkriptjeidet parancssorból is szeretnéd futtatni - pl. c:\myscripts\test.php) - vagy a fájlböngészőben duplakattintásra elindítani azokat. Ugord át ezeket a lépéseket, ha azt akarod, hogy duplakattintásra inkább a szövegszerkesztődbe töltődjenek be a PHP szkriptek.

  • Keresd meg a HKEY_CLASSES_ROOT pontot.

  • Az Edit menüben válaszd a New->Key pontot.

  • Nevezd el az új kulcsot az előzőekben megadott kiterjesztés nevére, pl. .php

  • Válaszd ki az új kulcsot, aztán a jobb oldalon kattints kétszer a "default value" soron, és írd be, hogy phpfile.

  • Ismételd az utóbbi lépést az összes kiterjesztésre, amit az előző részben beállítottál.

  • Most hozz létre ismét egy új kulcsot (New->Key) a HKEY_CLASSES_ROOT alatt, és nevezd el phpfile-nak.

  • Válaszd ki az új phpfile kulcsot, aztán a jobb oldalon kattints kétszer a "default value" soron, és írd be, hogy PHP Script.

  • Kattints jobbgombbal a phpfile kulcson és válaszd ki a New->Key pontot. Nevezd az új kulcsot Shell-nek.

  • Kattints jobbgombbal a Shell kulcson és válaszd ki a New->Key pontot. Nevezd az új kulcsot open-nek.

  • Kattints jobbgombbal az open kulcson és válaszd ki a New->Key pontot. Nevezd az új kulcsot command-nak.

  • Válaszd ki az új command kulcsot, aztán a jobb oldalon kattints kétszer a "default value" soron, és írd be, a php.exe elérési útját, pl. c:\php\php.exe -q %1. Ne felejtsd el a %1-et!).

  • Lépj ki a Regedit-ből.

  • Ha Windows alatt PWS szervert használsz, indítsd újra a gépet, hogy újratöltse a rendszer a registry-t.

PWS és IIS 3 használók így már rendelkeznek egy teljesen funkcionális rendszerrel. IIS 3 használóknak ajánlható Steven Genusa ötletes script map konfiguráló eszköze.


Windows és 4-es vagy újabb PWS

Kétféle módon lehet a PHP-t 4-es vagy újabb verziójú PWS-hez installálni: ez egyik a CGI bináris, a másik az ISAPI modul dll használata.

Ha a CGI változat mellett döntesz, akkor:

  • Szerkeszd át a csatolt pws-php4cgi.reg fájlt (sapi könyvtár), hogy abban a php.exe-re hivatkozás az installációnak megfelelő legyen. A perjeleket meg kell előzze egy maásik visszaperjel, pl.: [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\w3svc\parameters\Script Map] ".php"="c:\\php\\php.exe"

  • A PWS Manager-ben, egy jobbegérgomb kattintás arra a könyvtárra, amelyhez PHP támogatást szeretnél rendelni, és válaszd ki a Properties menüpontot. Jelöld be az 'Execute' négyzetet, és nyomd meg az OK-t.

Ha ISAPI modulként akarod használni, akkor:

  • Szerkeszd át a csatolt pws-php4isapi.reg fájlt (sapi könyvtár), hogy abban a php4isapi.dll-re hivatkozás az installációnak megfelelő legyen. A perjeleket meg kell előzze egy maásik visszaperjel, pl.: [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\w3svc\parameters\Script Map] ".php"="c:\\php\\sapi\\php4isapi.dll"

  • A PWS Manager-ben, egy jobbegérgomb kattintás arra a könyvtárra, amelyhez PHP támogatást szeretnél rendelni, és válaszd ki a Properties menüpontot. Jelöld be az 'Execute' négyzetet, és nyomd meg az OK-t.


Windows NT/2000 és IIS 4

A PHP telepítése IIS 4-el felszerelt Windows NT/2000 szerverre a következőképpen történik:

  • Az Internet Service Manager-ben (MMC) válaszd a Web Site kezdő könyvtárát.

  • Nyisd meg a könyvtár Properties ablakát a jobb klikkre lenyíló menüből, és ott válaszd a Home Directory, Virtual Directory, vagy Directory fület.

  • Kattints a Configuration gombra, majd az App Mappings fülre.

  • Kattints az Add gombra, és az Executable box-ban írd be, hogy c:\php-eleresi-ut\php.exe %s %s. A %s %s MINDENFÉLEKÉPPEN szerepeljen, ha azt szeretnéd, hogy működjön a PHP.

  • Az Extension box-ban, írd be a kiterjesztést, amit használni szeretnél a PHP szkriptjeidhez. Meg kell ismételned az 4-5 lépéseket minden kiterjesztésre, amit be szeretnél állítani. (.php és .phtml a szokásosak.)

  • Állítsd be a megfelelő biztonságot az Internet Service Manager-ben. Ha az NT szerveren NTFS-t használsz adj futtatási jogokat I_USR_-nek arra a könyvtárra, ami a php.exe fájlt tartalmazza.


Szerverek - Netscape és iPlanet Enterprise

Ez a fejezet a PHP Netscape és iPlanet szerverekhez történő telepítéséről a felvilágosítást és néhány jó tanácsot, mind Sun Solaris és Windows platformokon.

PHP Netscape Enterprise Serverhez történő telepítéséről még többet olvashatsz a http://benoit.noss.free.fr/php/install-php4.html címen.


PHP telepítése Netscape-hez Sun Solaris-on

NES vagy iPlanet szerverekhez a PHP telepítésekor a megfelelő telepítési könyvtárat (install directory) kell megadni: --with-nsapi = DIR beállítás. Az alapértelmezés szerinti könyvtár általában a /opt/netscape/suitespot/. Lehetőleg olvasd el a /php-xxx-version/sapi/nsapi/nsapi-readme.txt fájlt is!

Példa 3-7. PHP telepítési példa Netscape-hez Sun Solaris-on

Sun Solaris 2.6-on futó Netscape Enterprise Server 3.6 telepítési utasítások
bhager@invacare.com -től

1. A következő csomagokat telepítsd a www.sunfreeware.com vagy más download oldalról:

    flex-2_5_4a-sol26-sparc-local
    gcc-2_95_2-sol26-sparc-local
    gzip-1.2.4-sol26-sparc-local
    perl-5_005_03-sol26-sparc-local
    bison-1_25-sol26-sparc-local
    make-3_76_1-sol26-sparc-local
    m4-1_4-sol26-sparc-local
    autoconf-2.13
    automake-1.4
    mysql-3.23.24-beta (ha mysql kell támogatás)
    tar-1.13 (GNU tar)

2. Győződj meg, hogy a PATH tartalmazza a helyes könyvtárakat tartalmazza:
    PATH=.:/usr/local/bin:/usr/sbin:/usr/bin:/usr/ccs/bin
    export PATH

3. gunzip php-x.x.x.tar.gz (ha .gz disztribúcióval van dolgod, egyébként ugorj a 4-re)
4. tar xvf php-x.x.x.tar
5. cd ../php-x.x.x

6. A következő lépések előtt, győződj meg arról, hogy a Netscape szerver
   a /opt/netscape/suitespot/ könyvtárba lett telepítve. Ha nem, akkor a helyes
   útvonalat kell megadni:
   ./configure --with-mysql=/usr/local/mysql --with-nsapi=/opt/netscape/suitespot/ --enable-track-vars --enable-libgcc
7. make
8. make install
Az alaprendszer telepítése után olvasd el a megfelelő readme fájlokat, ha esetleg néhány további konfigurálási lépést kell tenned.

Elsősorban az LD_LIBRARY_PATH környezeti változóhoz kell néhány könyvtárat megadni, hogy a Netscape megtalálja a megosztott könyvtárcsomagokat (shared library). Ezt legegyszerűbb a Netscape-et indító szkriptben elhelyezni . Az indító szkript gyakran a /utvonal/a/szerverhez/https-servername/start könyvtárban található.

A konfigurációs fájlt is át kell írni, ami a /utvonal/a/szerverhez/https-servername/config/ könyvtárban található.

Példa 3-8. Netscape Enterprise beállítási példa

Netscape Enterprise beállítási útmutató
Configuration Instructions for Netscape Enterprise Server
bhager@invacare.com -től

1. Vedd fel a következő sort a mime.types-ba:
    type=magnus-internal/x-httpd-php exts=php

2. Vedd fel a következő sort a obj.conf-ba, shlib függ az operációs rendszertől
    Unix alatt valami ehhez hasonló:
    /opt/netscape/suitespot/bin/libphp4.so.

    A következő sort a mime types init után kell beírni:
    Init fn="load-modules" funcs="php4_init,php4_close,php4_execute,php4_auth_trans" shlib="/php4/nsapiPHP4.dll"
    Init fn=php4_init errorString="Failed to initialize PHP!"

    <object name="default">
    .
    .
    .
    .#NOTE a következő sornak minden 'ObjectType' után és minden 'AddLog' sor után kell állnia
    Service fn="php4_execute" type="magnus-internal/x-httpd-php"
    .
    .
    </Object>


    <Object name="x-httpd-php">
    ObjectType fn="force-type" type="magnus-internal/x-httpd-php"
    Service fn=php4_execute
    </Object>


    Hitelesítési (Authentication) beállítások

    PHP autentikáció nem használható együtt más autentikációval. Minden hitelesítés a saját
    PHP szkriptedhez kerül!!! A PHP hitelesítést a teljes szerverre a következő sor állítja
    be:

    <Object name="default">
    AuthTrans fn=php4_auth_trans
    .
    .
    .
    .
    </Object>

    A PHP hitelesítést csak egy könyvtárra:

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

Ha Netscape Enterprise 4.x -et használsz, akkor a következőket kell tenned:

Példa 3-9. Netscape Enterprise 4.x beállítási példa

A következő sorokat a mime types init után kell beírni, minden más az
előző példában leírthoz hasonló:
Graeme Hoose (GraemeHoose@BrightStation.com)

Init fn="load-modules" shlib="/path/to/server4/bin/libphp4.so" funcs="php4_init,php4_close,php4_execute,php4_auth_trans"
Init fn="php4_init" LateInit="yes"

PHP telepítése Netscape-hez Windows-on

To Install PHP as CGI (for Netscape Enterprise Server, iPlanet, perhaps Fastrack), do the following:

  • Másold be a php4ts.dll fájlt a systemroot könyvtárba - abba a könyvtárba, ahová a Windows-t installáltad.

  • Parancssorból hozd létre a fájl hozzárendelést, ehhez a következő két sort kell begépelni:
    assoc .php=PHPScript
    ftype PHPScript=c:\php\php.exe %1 %*

  • A Netscape Enterprise Administration Server-ben hozz létre egy üres shellcgi könyvtárat és töröld ki azon nyomban. (Ezzel a lépéssel 5 nagyon fontos sor adódik az obj.conf fájlhoz, amivel lehetővé válik, hogy a webszerver shellcgi szkripteket kezeljen.)

  • A Netscape Enterprise Administration Server szakaszban hozz létre egy új mime type bejegyzést (Category: type, Content-Type: magnus-internal/shellcgi, File Suffix:php).

  • Tedd meg ezt minden olyan web server példányra, amelyhez PHP támogatást akarsz adni!

A PHP CGI futtatóként való telepítéséről részletesebb leírásért lásd: http://benoit.noss.free.fr/php/install-php.html

PHP NSAPI-ként való installálásához (Netscape Enterprise Server-hez, iPlanet-hez, esetleg Fastrack-hez) a következőket kell tenni:

  • Másold be a php4ts.dll fájlt a systemroot könyvtárba - abba a könyvtárba, ahová a Windows-t installáltad.

  • Parancssorból hozd létre a fájl hozzárendelést, ehhez a következő két sort kell begépelni:
    assoc .php=PHPScript
    ftype PHPScript=c:\php\php.exe %1 %*

  • A Netscape Enterprise Administration Server szakaszban hozz létre egy új mime type bejegyzést (Category: type, Content-Type: magnus-internal/x-httpd-php, File Suffix:php).

  • Állítsd le a webszervert és szerkeszd át a obj.conf fájlt. Az Init szakasz végén helyezd el a következő két sort: (feltétlenül a mime type init rész után)
    Init fn="load-modules" funcs="php4_init,php4_close,php4_execute,php4_auth_trans" shlib="c:/php/sapi/php4nsapi.dll"
    Init fn="php4_init" errorString="Failed to initialise PHP!"

  • Az <Object name="default"> szakaszban feltétlenül helyezd el a következő sort az összes 'ObjectType' után és még az összes 'AddLog' sor előtt:
    Service fn="php4_execute" type="magnus-internal/x-httpd-php"

  • A fájl végén hozz létre egy új, x-httpd-php nevű object-et. Ehhez a következő sorok beírása szükségeltetik:
    <Object name="x-httpd-php">
    ObjectType fn="force-type" type="magnus-internal/x-httpd-php"
    Service fn=php4_execute
    </Object>

  • Indítsd újra a szervert és engedélyezd a változatatásokat!

  • Tedd meg ezt minden olyan web server példányra, amelyhez PHP támogatást akarsz adni!

A PHP NSAPI szűrőkénti használatának részletesebb leírásért lásd: http://benoit.noss.free.fr/php/install-php4.html


Szerverek - OmniHTTPd

Ez a fejezet az OmniHTTPd szerverre történő telepítési útmutatókat tartalmazza.


Windows-os Omni HTTPd 2.0b1 vagy újabb verzió

A következő lépéseket kell megtenni, hogy a PHP működjön OmniHTTPd-vel. Ez a CGI futtató telepítésének lépései.Az OmniHTTPd támogatja a SAPI-t, de néhány teszt alapján nem tűnik túl stabilnak OmniHTTPd ISAPI modul.

  • 1. lépés: Telepítsd fel a gépedre az OmniHTTPd szervert

  • 2. lépés: Jobb gombbal klikkelj az OmniHTTPd ikonon a tálcán és válaszd ki az előbukkanó menüből a Properties pontot.

  • 3. lépés: Kattints a Web Server Global Settings gombra.

  • 4. lépés: Az "External" fül kiválasztása után írd be, hogy virtual = .php | actual = c:\php-eleresi-ut\php.exe, és nyomd meg az Add gombot!

  • 5. lépés: A Mime fül kiválasztása után írd be: virtual = wwwserver/stdcgi | actual = .php, és nyomd meg az Add gombot!

  • 6 lépés: Kattints az OK-ra.

Ismételd a 2-6. lépéseket minden kiterjesztésre, amit a PHP-hez szeretnél használni.

Megjegyzés: Néhány OmniHTTPd csomag már beépített PHP támogatással jön. A telepítés elején lehet választani, hogy saját PHP telepítést akarsz a 'PHP component' kijelölés törlésével. Azt javasoljuk, hogy mindig a legfrissebb PHP binárisokat használd. Néhány OmniHTTPd a PHP 4 beta változatával kerül forgalomba, ezért nem ajánlatos a beépítettet választani. Ha a szerveren már fut a gépen, akkor a 4. és 5. lépésben a 'Replace' gombot kell használni az új, helyes adatok megadásához.


Szerverek - Oreilly Website Pro

Ebben a fejezetben az Oreilly Website Pro szerverhez történő telepítést tárgyaljuk.


Windows-os Oreilly Website Pro 2.5 és nagyobb verziók

Ez a lista a PHP CGI feldolgozóként ill. ISAPI modulként történő telepítésének lépéseit tartalmazza a Windows-os Oreilly Website Pro szerverekhez.

  • Szerkeszd át a Server Properties-t és and válaszd ki a "Mapping" panelt!

  • A List-ből válaszd ki a "Associations" pontot és írd be a kívánt fájlkiterjesztéseket (.php) és a CGI php.exe-hez vezető útvonalat - pl. c:\php\php.exe -, vagy az ISAPI DLL fájlt - pl. c:\php\sapi\php4isapi.dll.

  • Válaszd ki a "Content Types" pontot és vedd fel ide is ugyanazokat a fájlkiterjesztéseket - .php megadva a content-type-ot is. Ha a CGI változatot használod, akkor 'wwwserver/shellcgi'-t kell beírni, míg ISAPI modul esetén 'wwwserver/isapi'-t. (Mindkét esetben idézőjelek nélkül.)


Szerverek - Xitami

Ebben a fejezetben az Xitami szerverhez történő telepítést tárgyaljuk.


Xitami for Windows

Ez a lista a PHP CGI feldolgozó telepítésének lépéseit írja le a Windows-os Xitami szerverekhez.

  • Bizonyosodj meg, hogy fut a webszerver! Menj a Xitami adminisztrációs oldalára - általában http://127.0.0.1/admin -, és válaszd ki a 'Configuration' pontot!

  • Menj a Filters pontra, és add meg a File extensions mezőben milyen kiterjesztésű fájlokat rendelsz a PHP-hoz - pl.: .php.

  • A 'Filter command or script' mezőbe írd be a php állományhoz vezető útvonalat és a fájl nevét - pl. c:\php\php.exe.

  • Nyomd le a 'Save' ikont!


Más szerverekre fordítás

A PHP-t nagyon sok webszerverhez lehet telepíteni. Nézd meg a Szerverrel kapcsolatos beállítások c. fejezetben a szerverekhez kötödő konfigurációs beállítások teljes listáját! A CGI feldolgozó majdnem az összes, CGI szabványt támogató webszerverrel kompatibilis.


Problémák?

Olvasd el a FAQ-ot

Néhány probléma bizony gyakran előfordul. A leggyakrabban előforduló gondok és válaszok a PHP FAQ-ban olvashatóak, melynek címe: http://www.php.net/manual/faq.php


Egyéb problémák

Ha még mindig elakadsz, talán valaki a PHP telepítési levelezési listán tud segíteni. Jól teszed, ha először megnézed az archívumot, hátha már valaki megválaszolt egy hasonló kérdést. Az archívum elérhető a support oldalon a http://www.php.net/ címen. Az angol PHP telepítési levelezőlistára való feliratkozáshoz küldj egy üres levelet a php-install-subscribe@lists.php.net. címre. A levelezőlista címe: php-install@lists.php.net. A magyar PHP levelezőlistára való feliratkozáshoz küldj egy subscribe témamegjelöléssel rendelkező levelet a wl-phplista-request@gimli.externet.hu. címre. A levelezőlista címe: wl-phplista@gimli.externet.hu.

Ha segítséget szeretnél kapni valamelyik levelezőlistán, légy szíves próbálj meg precíz lenni, és minden fontos részletet adj meg a környezetről (operációs rendszer neve, PHP verziószám, web szerver neve, miként használod a PHP-t - CGI vagy szerver modulként, stb.). Ezenkívül adj meg elég PHP kódot, hogy a többiek reprodukálni és tesztelni tudják a problémát.


Bug jelentések

Ha úgy gondolod, hogy programhibát találtál a PHP feldolgozóban, légy szíves jelentsd a fejlesztőknek (angolul). Lehet, hogy a PHP fejlesztői semmit sem sejtenek felőle, és ha te nem jelented be, előfordulhat, hogy nem lesz kijavítva. Hibákat a bug-követő rendszeren regisztrálhatsz, melynek címe: http://bugs.php.net/.


4. Fejezet. Runtime Configuration

The configuration file

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

The default location of php.ini is a compile time option (see the FAQ entry), but can be changed for the CGI and CLI version with the -c command line switch, see the chapter about using PHP from the command line. You can also use the environment variable PHPRC for an additional path to search for a php.ini file.

Megjegyzés: 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.

Not every PHP directive is documented below. For a list of all directives, please read your well commented php.ini file. You may want to view the latest php.ini here from CVS.

Megjegyzés: The default value for the PHP directive register_globals changed from on to off in PHP 4.2.0.

Példa 4-1. php.ini example

; any text on a line after an unquoted semicolon (;) is ignored
[php] ; section markers (text within square brackets) are also ignored
; Boolean values can be set to either:
;    true, on, yes
; or false, off, no, none
register_globals = off
magic_quotes_gpc = 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"


How to change configuration settings

Running PHP as 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)

With PHP 4.0, 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 table found within the ini_set() documentation.

Megjegyzés: With PHP 3.0, there are Apache directives that correspond to each configuration setting in the php3.ini name, except the name is prefixed by "php3_".

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.

Megjegyzés: 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 virtualhost directives. 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 virtualhost directives.

Példa 4-2. Apache configuration example

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

Figyelem

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 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 PHP configuration directive and the string value. PHP constants in the values would not be parsed.


Other interfaces to PHP

Regardless of the interface to PHP you can change certain values at runtime of your scripts through ini_set(). The following table provides an overview at which level a directive can be set/changed.

Táblázat 4-1. Definition of PHP_INI_* constants

ConstantValueMeaning
PHP_INI_USER1Entry can be set in user scripts
PHP_INI_PERDIR2 Entry can be set in php.ini, .htaccess or httpd.conf
PHP_INI_SYSTEM4 Entry can be set in php.ini or httpd.conf
PHP_INI_ALL7Entry can be set anywhere

You can view the settings of the configuration values in the output of phpinfo(). You can also access the values of individual configuration directives using ini_get() or get_cfg_var().


Miscellaneous configuration directives

This is not a complete list of PHP directives. Directives are listed in their appropriate locations so for example information on session directives is located in the sessions chapter.


Httpd Options

Táblázat 4-2. Httpd Options

NameDefaultChangeable
async_send"0"PHP_INI_ALL


Language Options

Táblázat 4-3. Language and Misc Configuration Options

NameDefaultChangeable
short_open_tagOnPHP_INI_SYSTEM|PHP_INI_PERDIR
asp_tagsOffPHP_INI_SYSTEM|PHP_INI_PERDIR
precision"14"PHP_INI_ALL
y2k_complianceOffPHP_INI_ALL
allow_call_time_pass_referenceOnPHP_INI_SYSTEM|PHP_INI_PERDIR
expose_phpOnPHP_INI_SYSTEM

Here's a short explanation of the configuration directives.

short_open_tag boolean

Tells whether the short form (<? ?>) of PHP's open tag should be allowed. If you want to use PHP in combination with XML, you can disable this option in order to use <?xml ?> inline. Otherwise, you can print it with PHP, for example: <?php echo '<?xml version="1.0"'; ?>. Also if disabled, you must use the long form of the PHP open tag (<?php ?>).

Megjegyzés: This directive also affects the shorthand <?=, which is identical to <? echo. Use of this shortcut requires short_open_tag to be on.

asp_tags boolean

Enables the use of ASP-like <% %> tags in addition to the usual <?php ?> tags. This includes the variable-value printing shorthand of <%= $value %>. For more information, see Escaping from HTML.

Megjegyzés: Support for ASP-style tags was added in 3.0.4.

precision integer

The number of significant digits displayed in floating point numbers.

y2k_compliance boolean

Enforce year 2000 compliance (will cause problems with non-compliant browsers)

allow_call_time_pass_reference boolean

Whether to enable the ability to force arguments to be passed by reference at function call time. This method is deprecated and is likely to be unsupported in future versions of PHP/Zend. The encouraged method of specifying which arguments should be passed by reference is in the function declaration. You're encouraged to try and turn this option Off and make sure your scripts work properly with it in order to ensure they will work with future versions of the language (you will receive a warning each time you use this feature, and the argument will be passed by value instead of by reference).

See also References Explained.

expose_php boolean

Decides whether PHP may expose the fact that it is installed on the server (e.g. by adding its signature to the Web server header). It is no security threat in any way, but it makes it possible to determine whether you use PHP on your server or not.


Resource Limits

Táblázat 4-4. Resource Limits

NameDefaultChangeable
memory_limit"8M"PHP_INI_ALL

Here's a short explanation of the configuration directives.

memory_limit integer

This sets the maximum amount of memory in bytes that a script is allowed to allocate. This helps prevent poorly written scripts for eating up all available memory on a server. In order to use this directive you must have enabled it at compile time. So, your configure line would have included: --enable-memory-limit. Note that you have to set it to -1 if you don't want any limit for your memory.

As of PHP 4.3.2, and when memory_limit is enabled, the PHP function memory_get_usage() is made available.

See also: max_execution_time.


Data Handling

Táblázat 4-5. Data Handling Configuration Options

NameDefaultChangeable
track-vars"On"PHP_INI_??
arg_separator.output"&"PHP_INI_ALL
arg_separator.input"&"PHP_INI_SYSTEM|PHP_INI_PERDIR
variables_order"EGPCS"PHP_INI_ALL
register_globals"Off"PHP_INI_PERDIR|PHP_INI_SYSTEM
register_argc_argv"On"PHP_INI_PERDIR|PHP_INI_SYSTEM
register_long_arrays"On"PHP_INI_PERDIR|PHP_INI_SYSTEM
post_max_size"8M"PHP_INI_SYSTEM|PHP_INI_PERDIR
gpc_order"GPC"PHP_INI_ALL
auto_prepend_file""PHP_INI_SYSTEM|PHP_INI_PERDIR
auto_append_file""PHP_INI_SYSTEM|PHP_INI_PERDIR
default_mimetype"text/html"PHP_INI_ALL
default_charset"iso-8859-1"PHP_INI_ALL
always_populate_raw_post_data"0"PHP_INI_SYSTEM|PHP_INI_PERDIR
allow_webdav_methods"0"PHP_INI_SYSTEM|PHP_INI_PERDIR

Here's a short explanation of the configuration directives.

track_vars boolean

If enabled, then Environment, GET, POST, Cookie, and Server variables can be found in the global associative arrays $_ENV, $_GET, $_POST, $_COOKIE, and $_SERVER.

Note that as of PHP 4.0.3, track_vars is always turned on.

arg_separator.output string

The separator used in PHP generated URLs to separate arguments.

arg_separator.input string

List of separator(s) used by PHP to parse input URLs into variables.

Megjegyzés: Every character in this directive is considered as separator!

variables_order string

Set the order of the EGPCS (Environment, GET, POST, Cookie, Server) variable parsing. The default setting of this directive is "EGPCS". Setting this to "GP", for example, will cause PHP to completely ignore environment variables, cookies and server variables, and to overwrite any GET method variables with POST-method variables of the same name.

See also register_globals.

register_globals boolean

Tells whether or not to register the EGPCS (Environment, GET, POST, Cookie, Server) variables as global variables. For example; if register_globals = on, the URL http://www.example.com/test.php?id=3 will produce $id. Or, $DOCUMENT_ROOT from $_SERVER['DOCUMENT_ROOT']. You may want to turn this off if you don't want to clutter your scripts' global scope with user data. As of PHP 4.2.0, this directive defaults to off. It's preferred to go through PHP Predefined Variables instead, such as the superglobals: $_ENV, $_GET, $_POST, $_COOKIE, and $_SERVER. Please read the security chapter on Using register_globals for related information.

Please note that register_globals cannot be set at runtime (ini_set()). Although, you can use .htaccess if your host allows it as described above. An example .htaccess entry: php_flag register_globals on.

Megjegyzés: register_globals is affected by the variables_order directive.

register_argc_argv boolean

Tells PHP whether to declare the argv & argc variables (that would contain the GET information).

See also command line. Also, this directive became available in PHP 4.0.0 and was always "on" before that.

register_long_arrays boolean

Tells PHP whether or not to register the deprecated long $HTTP_*_VARS type predefined variables. When On (default), long predefined PHP variables like $HTTP_GET_VARS will be defined. If you're not using them, it's recommended to turn them off, for performance reasons. Instead, use the superglobal arrays, like $_GET.

This directive became available in PHP 5.0.0.

post_max_size integer

Sets max size of post data allowed. This setting also affects file upload. To upload large files, this value must be larger than upload_max_filesize.

If memory limit is enabled by your configure script, memory_limit also affects file uploading. Generally speaking, memory_limit should be larger than post_max_size.

gpc_order string

Set the order of GET/POST/COOKIE variable parsing. The default setting of this directive is "GPC". Setting this to "GP", for example, will cause PHP to completely ignore cookies and to overwrite any GET method variables with POST-method variables of the same name.

Megjegyzés: This option is not available in PHP 4. Use variables_order instead.

auto_prepend_file string

Specifies the name of a file that is automatically parsed before the main file. The file is included as if it was called with the include() function, so include_path is used.

The special value none disables auto-prepending.

auto_append_file string

Specifies the name of a file that is automatically parsed after the main file. The file is included as if it was called with the include() function, so include_path is used.

The special value none disables auto-appending.

Megjegyzés: If the script is terminated with exit(), auto-append will not occur.

default_mimetype string

default_charset string

As of 4.0b4, PHP always outputs a character encoding by default in the Content-type: header. To disable sending of the charset, simply set it to be empty.

always_populate_raw_post_data boolean

Always populate the $HTTP_RAW_POST_DATA variable.

allow_webdav_methods boolean

Allow handling of WebDAV http requests within PHP scripts (eg. PROPFIND, PROPPATCH, MOVE, COPY, etc..) If you want to get the post data of those requests, you have to set always_populate_raw_post_data as well.

See also: magic_quotes_gpc, magic-quotes-runtime, and magic_quotes_sybase.


Paths and Directories

Táblázat 4-6. Paths and Directories Configuration Options

NameDefaultChangeable
include_pathPHP_INCLUDE_PATHPHP_INI_ALL
doc_rootPHP_INCLUDE_PATHPHP_INI_SYSTEM
user_dirNULLPHP_INI_SYSTEM
extension_dirPHP_EXTENSION_DIRPHP_INI_SYSTEM
cgi.fix_pathinfo"0"PHP_INI_SYSTEM
cgi.force_redirect"1"PHP_INI_SYSTEM
cgi.redirect_status_env""PHP_INI_SYSTEM
fastcgi.impersonate"0"PHP_INI_SYSTEM
cgi.rfc2616_headers"0"PHP_INI_SYSTEM

Here's a short explanation of the configuration directives.

include_path string

Specifies a list of directories where the require(), include() and fopen_with_path() functions look for files. The format is like the system's PATH environment variable: a list of directories separated with a colon in Unix or semicolon in Windows.

Példa 4-3. Unix include_path

include_path=".:/php/includes"

Példa 4-4. Windows include_path

include_path=".;c:\php\includes"

Using a . in the include path allows for relative includes as it means the current directory.

doc_root string

PHP's "root directory" on the server. Only used if non-empty. If PHP is configured with safe mode, no files outside this directory are served. If PHP was not compiled with FORCE_REDIRECT, you SHOULD set doc_root if you are running PHP as a CGI under any web server (other than IIS) The alternative is to use the cgi.force_redirect configuration below.

user_dir string

The base name of the directory used on a user's home directory for PHP files, for example public_html.

extension_dir string

In what directory PHP should look for dynamically loadable extensions. See also: enable_dl, and dl().

extension string

Which dynamically loadable extensions to load when PHP starts up.

cgi.fix_pathinfo boolean

Provides real PATH_INFO/PATH_TRANSLATED support for CGI. PHP's previous behaviour was to set PATH_TRANSLATED to SCRIPT_FILENAME, and to not grok what PATH_INFO is. For more information on PATH_INFO, see the cgi specs. Setting this to 1 will cause PHP CGI to fix it's paths to conform to the spec. A setting of zero causes PHP to behave as before. Default is zero. You should fix your scripts to use SCRIPT_FILENAME rather than PATH_TRANSLATED.

cgi.force_redirect boolean

cgi.force_redirect is necessary to provide security running PHP as a CGI under most web servers. Left undefined, PHP turns this on by default. You can turn it off AT YOUR OWN RISK.

Megjegyzés: Windows Users: You CAN safely turn this off for IIS, in fact, you MUST. To get OmniHTTPD or Xitami to work you MUST turn it off.

cgi.redirect_status_env string

If cgi.force_redirect is turned on, and you are not running under Apache or Netscape (iPlanet) web servers, you MAY need to set an environment variable name that PHP will look for to know it is OK to continue execution.

Megjegyzés: Setting this variable MAY cause security issues, KNOW WHAT YOU ARE DOING FIRST.

fastcgi.impersonate string

FastCGI under IIS (on WINNT based OS) supports the ability to impersonate security tokens of the calling client. This allows IIS to define the security context that the request runs under. mod_fastcgi under Apache does not currently support this feature (03/17/2002) Set to 1 if running under IIS. Default is zero.

cgi.rfc2616_headers int

Tells PHP what type of headers to use when sending HTTP response code. If it's set 0, PHP sends a Status: header that is supported by Apache and other web servers. When this option is set to 1, PHP will send RFC 2616 compliant headers. Leave it set to 0 unless you know what you're doing.


File Uploads

Táblázat 4-7. File Uploads Configuration Options

NameDefaultChangeable
file_uploads"1"PHP_INI_SYSTEM
upload_tmp_dirNULLPHP_INI_SYSTEM
upload_max_filesize"2M"PHP_INI_SYSTEM|PHP_INI_PERDIR

Here's a short explanation of the configuration directives.

file_uploads boolean

Whether or not to allow HTTP file uploads. See also the upload_max_filesize, upload_tmp_dir, and post_max_size directives.

upload_tmp_dir string

The temporary directory used for storing files when doing file upload. Must be writable by whatever user PHP is running as. If not specified PHP will use the system's default.

upload_max_filesize integer

The maximum size of an uploaded file.


General SQL

Táblázat 4-8. General SQL Configuration Options

NameDefaultChangeable
sql.safe_mode"0"PHP_INI_SYSTEM

Here's a short explanation of the configuration directives.

sql.safe_mode boolean


Debugger Configuration Directives

Figyelem

Only PHP 3 implements a default debugger, for more information see E Függelék.

debugger.host string

DNS name or IP address of host used by the debugger.

debugger.port string

Port number used by the debugger.

debugger.enabled boolean

Whether the debugger is enabled.


5. Fejezet. Alapvető szintaxis

Escape szekvencia HTML-ben

Amikor a PHP feldolgoz egy fájlt, akkor egyszerűen a kimenetre másol minden karaktert, amíg nem találkozik valamelyik speciális jelöléssel (lásd alább!), amelyet PHP kódrészlet kezdeteként értelmez. Ekkor a PHP futtatni kezdi a zárójelölésig található összes kódot. Ezzel a működési elvvel lehet könnyen HTML oldalakba elhelyezni PHP kódot, mivel mindent, ami a PHP nyitó- és zárójelölésein kívül esik, teljes mértékben békénhagy, és csak ezeken belüli tartalmat értelmezi programkódként.

Négyféle jelöléssel lehet az állomány bizonyos részeit PHP kódként megjelölni. Ezek közül csak kettő használható bármilyen esetben: <?php. . .?> and <script language="php">. . .</script> a másik kettő ki és bekapcsolható a php.ini konfigurációs fájlban. Bár a rövid vagy az ASP-stílusú formák kényelmesnek tűnnek, egyszersmind kevésbé hordozhatók, mint a hosszabb változatok. Emellett, ha XML vagy XHTML fájlokba kell PHP kódot illeszteni, azt csak <?php. . .?> alakkal lehet - igazodva az XML ajánláshoz.

Példa 5-1. A PHP-módba kerülés lehetőségei

1.  <?php echo("Ha XHTML vagy XML dokumentumokat is akarsz szolgáltatni," .
               "biztos szeretni fogod ezt\n"); ?>

2.  <? echo ("Ez a legegyszerűbb, egy SGML processing utasítás\n"); ?>
    <?= $valtozo; # Ez egy rövidítése a "<? echo ..?>"-nak ?>

3.  <script language="php">
        echo ("Néhány szerkesztő (ilyen pl. a FrontPage) nem" .
              "szereti a processing utasításokat");
    </script>

4.  <% echo ("Használhatsz ASP-stílusú tag-eket"); %>
    <%= $valtozo; # Ez egy rövidítése a "<% echo ..%>"-nak %>

Az első lehetőség a leginkább javasolt, mivel ezzel XML-konform dokumentumokban , mint például XHTML, is lehet PHP kódokat elhelyezni.

A második forma nem mindig használható, csak akkor, ha a rövid nyitó jelölések engedélyezve vannak. Engedélyezhetjük - PHP 3-ban - short_tags() függvényhívással, a short_open_tag beállítással a PHP konfigurációs fájlban, vagy a PHP fordításánál a configure program --enable-short-tags opciójával. Annak ellenére ha alapértelmezés szerint engedélyezve van is, a rövid nyitójelölések használata ellenjavallt

A negyedik mód csak akkor elérhető, ha az ASP-stílusú jelölés is engedélyezve van az asp_tags konfigurációs beállítással.

Megjegyzés: Az ASP-stílusú tagek a 3.0.4. verziótól használhatóak

Megjegyzés: A rövid nyitójelölések használata kerülendő újrafelhasználandó, széles körű terjesztésre szánt könyvtárak vagy programok fejlesztésekor, illetve olyan alkalmazások megírásakor, amelyek üzemeltetése felett a program írójának nincs ellenőrzése, Ennek oka, hogy a rövid nyitójelölések nem minden konfigurációban használhatók, így csökkenti a hordozhatóságot. Hordozható, újrafelhasználható komponensek esetén ne használd a rövid nyitójelöléseket!

A lezárójelölés magában foglalja a jelölést közvetlenül követő újsort karaktert, ha van ilyen, emellett a PHP blokk utolsó sorát lezáró pontosvesszőt (;).

A PHP a következő struktúrák használatát is megengedi:

Példa 5-2. HTML blokkok feltételhez kötése

<?php if ($igazez) { ?>
<strong>Igaz a változó tartalma</strong>
<?php } else { ?>
<strong>Hamis a változó tartalma</strong>
<?php } ?>
Ez a várakozásoknak megfelelően működik, mivel a PHP ?> lezáró jelölést követően mindent átmásol a kimenetre, amíg egy újabb nyitó jelöléssel. A fenti példa természtesen mondvacsinált, de nagy méretű szövegblokkok kiíratásakor hatékonyabbnak bizonyulhat ideiglenesen elhagyni a PHP módot, mint mindezt a szöveget echo(), print() vagy ehhez hasonló függvényekkel kiíratni.


Utasítások elválasztása

Az utasítások - a C és a perl nyelvhez hasonlóan - pontosvesszővel végződnek.

A záró tag (?>) szintén feltételezi az utasítás végét, tehát az alábbiak egyenértékűek:

<?php
    echo "Ez egy teszt";
?>

<?php echo "Ez egy teszt" ?>


Megjegyzések - kommentek

A PHP támogatja a 'C', 'C++' és Unix shell-szerű megjegyzéseket. Például:

<?php
    echo "Ez egy teszt"; // Ez egy egysoros c++ szerű megjegyzés
    /* Ez egy többsoros megjegyzés
       Még egy sor megjegyzés */
    echo "Ez egy másik teszt";
    echo "Ez az utolsó teszt"; # Ez egy shell-szerű megjegyzés
?>

Az "egysoros" megjegyzések valójában csak a sor végéig, vagy az aktuális PHP kód végéig tartanak, attól függően, hogy melyik van előbb.

<h1>Ez egy <?php# echo "egyszerű";?> példa.</h1>
<p>A fenti fejléc kiírja 'Ez egy egyszerű példa'.

Figyelj rá, hogy ne ágyazd egymásba a 'C'-stílusú megjegyzéseket, ami akkor történhet, ha egy hosszú programblokkot kikommentezel.

<?php
 /*
    echo "Ez egy teszt"; /* Ebből a megjegyzésből baj lesz */
 */
?>

Az egysoros megjegyzések csak a sor végéig vagy az aktuális PHP kódblokk végéig tart attól függően, melyik van előbb. Ez azt jelenti, hogy a // ?> sorban a ?> után álló HTML utasítások kiírásra kerülnek, a ?> zárójelölés visszaállítja a HTML módot, és ezt a // nem tudja befolyásolni.


6. Fejezet. Típusok

Bevezető

A PHP nyolc primitív típust támogat.

A négy skalár típus:

A két összetett típus:

Végül két speciális típus:

Megjegyzés: Ebben a kézikönyvben gyakran találkozhatsz mixed paraméterekkel is. Ez a kvázi-típus csak a dokumentációkban létezik, annak jelölésére szolgál, hogy többféle lehetőség adott arra a paraméterre abban az esetben.

A változó típusát rendszerint nem a programozó adja meg [persze van beleszólása...], hanem a PHP futási időben határozza meg a változó környezetétől függően.

Megjegyzés: Ha egy kifejezés értékére és/vagy típusára vagy kiváncsi, akkor használd a var_dump() függvényt.

Ha csak a típusára van szükség könnyen olvasható formában, akkor a gettype()-ot kell alkalmazni. Típusellenőrzésre viszont ne ezt, hanem az is_type függvényeket kell használni a programokban.

Ha egy változó típusát egy adott típusra kell konvertálnunk, castolhatjuk a változót, vagy alkalmazzuk rá a settype() függvényt.

A változó különbözőképp viselkedhet bizonyos helyzetekben, attól függően, hogy az adott pillanatban milyen típusú. Bővebb leírásért lásd még a Bűvészkedés a típusokkal című részt!


Logikai adattípus

Ez a legegyszerűbb típus. Egy boolean igazságértéket fejez ki. Lehet vagy TRUE (igaz), vagy FALSE (hamis).

Megjegyzés: A logikai adattípus a PHP 4-esben került bevezetésre.


Szintaxis

Egy logikai érték megadásához használhatod a TRUE vagy FALSE szavakat, szükség szerint. Egyik jelentése sem függ a kis- és nagybetűs írásmódtól.

$igaz = True; // a logikai igaz értéket adjuk az $igaz változónak

Tipikus valamilyen operátor használatakor kapsz boolean típusú értéket, amit egy vezérlési szerkezetben fel tudsz használni.

if ($akcio == "verzio_kiirasa") { // a == operátor boolean értékkel tér vissza
    echo "Ez az 1.23-as változat";
}

// ez nem szükséges
if ($elvalaszto_kiirasa == TRUE) {
    echo "<hr>\n";
}

// mivel egyszerűen ez is működik
if ($elvalaszto_kiirasa) {
    echo "<hr>\n";
}


Logikai értékké alakítás

Ha kifejezetten boolean típusúvá szeretnél alakítani egy értéket, használd a (bool) vagy a (boolean) típusátalakítást. A legtöbb esetben azonban nem kell ezt alkalmaznod, mivel az érték automatikusan átalakul, ha egy operátor, függvény, vagy vezérlési szerkezet boolean típusú argumentumot vár.

Lásd még a Bűvészkedés a típusokkal című részt.

Amikor boolean típusúvá kell alakítani egy értéket, az alábbiak FALSE értéket adnak:

Minden más érték TRUE lesz (beleértve bármilyen resource (eőforrás) típusú értéket).

Figyelem

A -1 is TRUE lesz, mint minden más nem nulla (akár negatív, akár pozitív) szám!


Egész számok

Egy integer a következő halmaz része: Z = {..., -2, -1, 0, 1, 2, ...}.

Lásd még a Tetszőleges pontosságú egészek és a Lebegőpontos számok című részeket.


Szintaxis

Az egészek megadhatók decimális (10 alapú), hexadecimális (16 alapú) vagy oktális (8 alapú) számként, opcionális előjellel (- vagy +).

Ha az oktális formát választod, a számot egy 0 (nulla) jeggyel kell kezdened, ha a hexadecimálisat, akkor 0x-el.

Példa 6-1. Egész értékek

$a = 1234; # decimális szám
$a = -123; # negatív szám
$a = 0123; # oktális szám (megegyezik a 83 decimális számmal)
$a = 0x1A; # hexadecimális szám (megegyezik a 26 decimális számmal)
Az egészek maximális mérete operációs rendszertől függ, az átlagos érték a két milliárd (32 bites előjeles egész).


Egészek értelmezési határának túllépése

Az integer típus értelmezési tartományán kívül eső egész értékek float típussá alakulnak. Ha valamely művelet eredménye kívül esik a integer értelmezési tartományán, akkor az eredmény automatikusan float típusúvá konvertálódik.

$nagy_szam =  2147483647;
var_dump($nagy_szam);
// kimenete: int(2147483647)
$nagyobb_szam =  2147483648;
var_dump($nagyobb_szam);
// kimenete: float(2147483648)

// ez működik hexadecimálisan megadott egészekre is:
var_dump( 0x80000000 );
// kimenete: float(2147483648)

$millio = 1000000;
$nagy_szam =  50000 * $millio;
var_dump($nagy_szam);
// kimenete: float(50000000000)

Figyelem

Sajnálatosan meg kell említenünk, hogy a PHP 4.0.6-ban ez az átalakítás nem működött mindig pontosan negatív számok használatakor, például: ha a -50000 * $millio műveletet eredménye: -429496728. Ha mindkét operandus pozitív, nincs semmi probléma.

Ezt a hiba ki lett javítva a PHP 4.1.0-ben.

PHP-ben nincs egész osztás. Az 1/2 művelet a 0.5 float (lebegépontos) értéket eredményezi.

var_dump( 25/7 );
// output: float(3.5714285714286)


Egész értékké alakítás

Ha kifejezetten integer típusúvá szeretnél alakítani egy értéket, használd az (int) vagy az (integer) típusátalakítást. A legtöbb esetben azonban nem kell ezt alkalmaznod, mivel az érték automatikusan átalakul, ha egy operátor, függvény, vagy vezérlési szerkezet integer típusú argumentumot vár.

Lásd még a Bűvészkedés a típusokkal című részt.


Átalakításboolean (logikai) értékekről

A FALSE (hamis) érték a 0 (nulla) egész számmá alakul, a TRUE (igaz) érték az 1 (egy) egész számot adja.


Átalakítás lebegőpontos értékekről

Lebegépontos számok egész értékké alakításakor a szám tört része elvész, azaz lefelé kerekítés történik.

Ha a lebegőpontos szám az egész tartományon kívül esik (általában +/- 2.15e+9 = 2^31), az eredmény nem definiált, mivel a lebegőpontos szám nem rendelkezik elég precizitással, hogy pontos egész eredményt kapj. Sem warning, sem notice szintű hiba nem lép fel ebben az esetben!

Figyelem

Soha ne alakíts egy ismeretlen törtszámot integer típusúvá, mivel ez időnként nem várt eredményekhez vezethet.

echo (int) ( (0.1+0.7) * 10 ); // kiírja, hogy 7!

Lásd a a lebegőpontos számok pontotsságának problémái című részt.


Átalakítás karakterláncokról

Lásd a String átalakítás című részt.


Átalakítás más típusokról

Figyelem

Az egésszé alakítás viselkedése más típusokra nem definiált. Jelenleg ezek az átalakítások megegyeznek azzal, mintha először logikai, majd utána egész értékké alakítottad volna a kiindulási értéket. Erre a viselkedeésre azonban nem szabad építeni, mivel minden figyelmeztetés nélkül megváltozhat.


Lebegőpontos számok

A lebegőpontos számok ("float", "valós szám") az alábbi szintaxisok bármelyikével hozhatóak létre:
$a = 1.234; $a = 1.2e3; $a = 7E-10;
A lebegőpontos számok mérete platformfüggő, de a maximális érték körülbelül 1.8e308, durván 14 tizedesjegy pontossággal (64 bites IEEE formátum).

Lebegőpontos számok pontossága

Elég gyakran előfordul, hogy egyszerű decimális törtek, mint a 0.1 és a 0.7 nem konvertálhatóak pontosan bináris megfelelőikre kis veszteség nélkül. Ez zavaró eredményekhez vezethet, például floor((0.1+0.7)*10) tipikusan 7 értékkel tér vissza, az elvárt 8 helyett, a belső ábrázolás miatt, ami valójában 7.9999999999....

Ez azzal a ténnyel van kapcsolatban, hogy lehetetlen megjeleníteni néhány törtet véges számú decimálisan számjeggyel. Például 1/3 decimálisan 0.3333333. . . értékké válik.

Ezért soha ne bízz meg a törtszámok eredményeiben az utolsó jegyig, és soha se hasoníts össze két lebegőpontos számot pontos egyenlőségre. Ha nagyobb pontosságú számokra van szükséges, használd a tetszőleges pontosságú matematikai függvényeket vagy a gmp függvényeket.


Stringek

A string karakterek sorozata. PHP-ben egy karakter pontosan egy bytenak felel meg, így 256 különböző karakter lehetséges. Ez azt is jelenti, hogy a PHP-nek jelenleg nincs beépített Unicode támogatása.

Megjegyzés: Nem okozhat problémát a stringek körében, hogy túl hosszúvá válnak. Semmiféle korlát nem létezik a PHP által kezelt stringek méretére, ezért nem kell tartani a hosszú stringektől.


Szintaxis

A stringeket háromféleképpen lehet létrehozni.


String létrehozása aposztróffal

A legkönnyebben úgy adhatunk meg egy egyszerű stringet, hogy aposztrófok (' karakterek) közé tesszük.

Ha a stringben egy aposztófot szeretnél elhelyezni, és azzal nem a string végét szeretnéd jelezni, más nyelvekhez hasonlóan egy visszaperjel karaktert kell alkalmaznod az aposztóf előtt (\). Ha egy aposztróf, vagy a string vége előtt el szeretnél helyezni egy visszaperjelet, meg kell dupláznod azt. Figyelj arra, hogy ha bármilyen más karakter elé teszel visszaperjelet, a visszaperjel meg fog jelenni a stringben. Emiatt gyakran nincs szükség magának a visszaperjelnek a duplázására.

Megjegyzés: PHP 3 használatakor azonban egy E_NOTICE szintű figyelmeztetést kapsz, ha ezt kihasználod.

Megjegyzés: A többi móddal ellentétben a változók értékei nem helyettesítődnek be, ha aposztrófos stingben változókra hivatkozol.

echo 'Egyszerű string';
echo 'A stringekbe újsor karaktereket is építhetsz,
ilyen formában.';
echo 'Arnold egyszer azt mondta: "I\'ll be back"';
// kimenete: ... "I'll be back"
echo 'Are you sure you want to delete C:\\*.*?';
// kimenete: ... delete C:\*.*?
echo 'Are you sure you want to delete C:\*.*?';
// kimenete: ... delete C:\*.*?
echo 'Ezen a ponton próbálok beépíteni \n egy újsort';
// kimenet: ... beépíteni \n egy újsort


String létrehozása idézőjellel

Ha egy stringet idézőjelek (") közé helyezünk, a PHP több speciális jelölés feldolgozására lesz képes:

Táblázat 6-1. Speciális jelölések idézőjeles stringben

jelölésjelentése
\nújsor (LF vagy 0x0A (10) ASCII kódú karakter)
\rkocsivissza (CR vagy 0x0D (13) ASCII kódú karakter)
\tvízszintes tabulátor (HT vagy 0x09 (9) ASCII kódú karakter)
\\visszaperjel
\$dollárjel
\"idézőjel
\[0-7]{1,3} egy karaktersorozat, ami oktális számokra illeszkedik
\x[0-9A-Fa-f]{1,2} egy karaktersorozat, ami hexadecimális számokra illeszkedik

Ha bármilyen más karakter elé visszaperjelet írsz, ebben az esetben is ki fog íródni a visszaperjel.

A legfontosabb előnye az idézőjeles stringeknek az, hogy a változók behelyettesítésre kerülnek. Lásd a változók behelyettesítése című részt további részletekért.


String létrehozása heredoc szintaxissal

Egy másfajta módszer a stringek megadására a heredoc szintaxis ("<<<"). [ez itt megint nem elírás, kedves unix-shell programozó!] A <<< jelzés után egy azonosítót kell megadni, majd a stringet, és végül az azonosítót mégegyszer, ezzel zárva le a stringet.

A lezáró azonosítónak mindenképpen a sor legelső karakterén kell kezdődnie. Ugyancsak figyelni kell arra, hogy ez az azonosító is az általános PHP elemek elnevezési korlátai alá tartozik: csak alfanumerikus karaktereket és aláhúzást tartalmazhat, és nem kezdődhet számjegy karakterrel.

Figyelem

Nagyon fontos, hogy odafigyelj arra, hogy a lezáró azonosítót tartalmazó sor ne tartalmazzon semmi mást, csupán esetleg egy idézőjel (;) karaktert. Ez még pontosabban azt is jelenti, hogy az azonosító nem lehet beljebb kezdve, és nem szabad semmilyen szóköz vagy tabulátor karaktert sem elhelyezni a pontosvessző előtt vagy után.

Feltehetően a legkellemetlenebb korlátozás az, hogy még egy kocsivissza (\r) karakter sem lehet a sor végén, csak egy újsor (\n) szerepelhet. Mivel a Microsoft Windows a \r\n sorozatot használja a sorok végének jelzésére, a heredoc nem fog működni, ha olyan szerkesztőben készíted a programod, ami ezt a sorvég jelzést használja. A legtöbb fejlesztőeszköz azonban lehetőséget ad UNIX sorvégjelzéssel ellátott állományok mentésére.

A heredoc az idézőjeles stringekhez hasonlóan működik, az idézőjelek nélkül. Ez azt jelenti, hogy nem kell visszaperjellel jelülni az idézőjeleket a szövegben, de a fenti speciális jelölések használhatóak. A változók értékei behelyettesítődnek, de az idézőjeles karaktersorozatokhoz hasonlóan gondosan kell ügyelni a komplex változó hivatkozások megadására.

Példa 6-2. "Heredoc" string példa [VAS: Vége A Stringnek de helyette lehet bármi]

<?php
$str = <<<VAS
Példa egy stringre, amely
több sorban van, és heredoc
szintaxisú
VAS;

/* Komplexebb példa, változókkal. */
class ize
{
    var $ize;
    var $valami;

    function ize()
    {
        $this->ize = 'Valami';
        $this->valami = array('elso', 'masodik', 'harmadik');
    }
}

$ize = new ize();
$nev = 'Béla';

echo <<<VAS
A nevem "$nev". Kiírok egy értéket: $ize->ize.
Most kiírok egy tömbelemet: {$ize->valami[1]}.
Ez nagy 'A' kell, hogy legyen: \x41
VAS;
?>

Megjegyzés: A heredoc a PHP 4-esben került a nyelvbe.


Változók behelyettesítése

Ha egy stringet idézőjelek között, vagy heredoc szintaxissal adsz meg, a jelölt változók értékei behelyettesítésre kerülnek.

Kétféleképpen lehet megadni egy változót, az egyszerű és a komplex formátummal. Az egyszerű forma a leggyakoribb és legkényelmesebb. Lehetőséget ad egy skalár, tömb érték vagy egy objektum tulajdonság beillesztésére.

A komplex szintaxis a PHP 4-es változatában került a nyelvbe, és a jelölésben használatos kapcsos zárójelekről ismerhető fel.


Egyszerű szintaxis

Ha dollár ($) jelet talál a PHP egy stringben, mohón megkeresi az összes ezt követő azonosítóban is használható karaktert, hogy egy érvényes változónevet alkosson. Használj kapcsos zárójeleket, ha pontosan meg szeretnéd határozni, meddig tart egy változó.

$ingatlan = 'ház';
echo "kertes $ingatlan kerítéssel"; // működik, szóköz nem lehet változónévben
echo "páros $ingatlanszám"; // nem működik, az 's' és további karakterek lehetnek változónévben
echo "páros ${ingatlan}szám"; // működik, mert pontosan meg van adva a név

Hasonlóképpen meg lehet adni tömbindexet vagy objektum tulajdonságot is. A tömbindexek esetében a záró szögletes zárójel (]) jelöli az index végét, az objektum tulajdonságoknál az egyszerű skalárok szabályai érvényesek, habár objektum tulajdonágok esetén nem használható a fenti trükk.

$gyumolcsok = array( 'eper' => 'piros' , 'alma' => 'zöld' );
echo "Az alma $gyumolcsok[alma]."; // ez másképpen használandó karaktersorozatokon kívül. 
// Lásd az $ize[valami] karakterláncon kívüli problémáját

echo "A négyzet $negyzet->szelesseg méter széles.";

echo "A négyzet $negyzet->szelesseg00 centiméter széles."; // nem működik
// A megoldás érdekében lásd a komplex szintaxis szakaszt!

Bármely ennél komplexebb helyettesítéshez a komplex szintaxis használatos.


Komplex (kapcsos zárójeles) szintaxis

Ezt nem azért nevezzük komplexnek, mert a szintaxis komplex, hanem azért, mert így komplex kifejezések helyettesítésére nyílik lehetőség :).

Gyakorltilag bármilyen változó érték behelyettesíthető ezzel a szintaxissal. Egyszerűen úgy kell megadni az értéket adó kifejezést, mintha a stringen kívül dolgoznál vele, és utána { és } jelek közé kell zárni. Mivel a '{' jel megadására nincs speciális jelölés, ez a forma csak akkor fog működni, ha a { után közvetlenül egy $ jel található. (Használhatod a "{\$" vagy "\{$" jelöléseket, ha a stringben a "{$" sorozatot szeretnéd beilleszteni, és nem változóhelyettesítést adsz meg). Néhány példa, ami tisztázhatja a félreértéseket:

$oriasi = 'fantasztikus';
echo "Ez { $oriasi}"; // nem működik, kiírja, hogy : Ez { fantasztikus}
echo "Ez {$oriasi}";  // működik, kiírja, hogy: Ez fantasztikus
echo "Ez a négyzet {$negyzet->szelesseg}00 centiméter széles.";
echo "Működik: {$tomb[4][3]}";
echo "Hibás: {$tomb[ize][3]}"; 
   // ennek ugyanaz az oka, mint ami miatt
   // a $ize[valami] hibás egy stringen kívül

echo "Ebben a formában már helyes: {$tomb['ize'][3]}";
echo "Akár ezt is írhatod: {$obj->ertekek[3]-&gt;nev}";
echo "Ez a $nev nevű változó értéke: {${$nev}}";


String karaktereinek elérése

A string karaktereire nullától számozott indexekkel lehet hivatkozni, a string neve után megadott kapcsos zárójelek között.

Megjegyzés: Kompatibilitási okokból a tömböknél használatos szögletes zárójelek is alkalmazhatóak a karakterek eléréséhez. Ez a tömb jelzés azonban nem javasolt a PHP 4-esben.

Példa 6-3. Néhány string példa

<?php
/* String hozzárendelése */
$str = "Ez egy string";

/* Hozzáfűzés */
$str = $str . " több szöveggel";

/* Hozzáfűzés egy más módja újsor karakterrel a végén */
$str .= " és egy újsor a végére.\n";

/* Ez a string végülis ilyen lesz: '<p>Szám: 9</p>' */
$num = 9;
$str = "<p>Szám: $num</p>";

/* Ez meg: '<p>Szám: $num</p>' */
$num = 9;
$str = '<p>Szám: $num</p>';

/* A string első karaktere kerül first-be  */
$str = 'Ez egy teszt.';
$first = $str{0};

/* Most meg az utolsó */
$str = 'Ez még mindig egy teszt';
$last = $str{strlen($str)-1};
?>


Hasznos függvények

Stringeket a '.' (pont) stringösszefűző operátorral tudsz összefűzni. A '+' (összeadás) operátor nem alkalmas erre a feladatra. Lásd a String operátorok című részt további információkért.

Számos hasznos függvény létezik stringek manipulálásához.

Lásd a string függvények című részt általános függvényekért, a reguláris kifejezés függvényeket fejlett kereséshez és cserékhez (két formában: Perl és POSIX kiterjesztett).

Külön függvények léteznek URL stringekhez, és stringek kódolásához/dekódolásához (mcrypt és mhash kódolások).

Végül ha ezek között sem találod, amit keresel, lásd a karakter típus függvényeket.


String konverziók

Amikor egy string számként értékelődik ki, az eredmény típusa a következőképp kerül meghatározásra.

A string lebegőpontosként értékelődik ki, ha a '.', 'e', vagy 'E' karakterek bármelyikét tartalmazza. Egyébként egészként értékelődik ki.

Az érték meghatározása a string első karakterei alapján történik. Ha a string érvényes számmal kezdődik, ez az érték kerül felhasználásra. Máskülönben az érték 0 lesz [nulla, nem nagy O betű]. Érvényes számnak tekintendő, amelynek opcionális előjelét egy vagy több számjegy követi (melyben lehet egy tizedespont), végül lehet exponense. Az exponens egy 'e' vagy 'E' karakter, melyet egy vagy több szám követ.

$foo = 1 + "10.5";                // $foo most float (11.5)
$foo = 1 + "-1.3e3";              // $foo most float (-1299)
$foo = 1 + "bob-1.3e3";           // $foo most integer (1)
$foo = 1 + "bob3";                // $foo most integer (1)
$foo = 1 + "10 Kicsi Pingvin";    // $foo most integer (11)
$foo = 4 + "10.2 Kicsi Pingvinke" // $foo most integer (14)
$foo = "10.0 disznó " + 1;        // $foo most integer (11)
$foo = "10.0 disznó " + 0.5;      // $foo most float (10.5) [szóval 10 disznó, meg egy féldisznó]

Ha többet szeretnél megtudni erről a konverzióról, akkor nézd meg a Unix manualt strtod(3). [=RTFM]

Ha szeretnéd kipróbálni valamelyik fejezetbeli példát, elmásolhatod innen a példákat és beszúrhatod az alábbi sort, hogy lásd mi is történik.

[Ahhoz nem árt azért előbb érteni a beszúrt sort. A beszúrandó string elején a "\" azért van, hogy a $foo helyére NE a foo változó értéke kerüljön, hanem a \$ hatására a $ karakter íródjon ki, majd a foo karaktersor, egy egyenlőségjel, és utána a $foo változó értéke. Az első "\" hatására ugyanis a köv. karakter ("$") elveszti különleges jelentését, és kimásolódik a kimenetre, majd jön a "foo=" szöveg, ez is úgy, ahogy van a kimenetre kerül, a fordító nem is találkozott változóval, amit be kellene helyettesíteni. Aztán jön a $foo, ezt már felismeri a fordító, és a változó értékét írja ki]:

echo "\$foo==$foo; típusa " . gettype ($foo) . "<br />\n";


Tömbök

A PHP tömbjei rendezett leképezéseket valósítanak meg. A leképezés értékeket rendel kulcsokhoz. Ez a típus sokféleképpen használható, mint egy hagyományos tömb, egy lista (vektor), hash tábla, szótár, kollekció, halmaz, sor, és mások. Mivel egy újabb PHP tömb szerepelhet értékként, könnyen szimulálhatsz fákat.

Az említett struktúrák leírása ezen kézikönyv kereteibe nem fér bele, de legalább egy példát mutatunk mindegyikre. További információkért külső forrásokat kell igénybe venned erről az igen széles témáról.


Szintaxis

Tömb létrehozása az array() nyelvi elemmel

Egy array (tömb) típusú változót az array() nyelvi elemmel tudsz létrehozni, amely számos vesszővel elválasztott kulcs => érték párt vár.

Egy kulcs vagy egy nemnegatív integer (egész szám) vagy egy string. Ha a kulcs egy szabványos formában megadott nemnegatív egész szám (integer), az a megfelelő módon kerül értelmezésre. Konkrétabban pl. a '8' a 8 egész szám lesz, míg a '08' a '08' string.

Az érték bármi lehet.

Ha nem adsz meg egy kulcsot, a PHP veszi az egész indexek közül a legnagyobbat, és ennél egyel nagyobb indexű elemet hoz létre. Az egészek lehetnek negatívak is, de ez igaz a negatív indexekre is. Ha például a legnagyobb index -6, akkor az következő, új index -5. Ha még nincs egész értékkel megadott index, az új kulcs 0 (nulla) lesz. Ha olyan kulcsot adsz meg, ami már a tömb eleme, a korábbi elem felülíródik.

A logikai true érték integer típusúvá alakítva a 1 indexnek felel meg. A false integer típusúvá alakítva a 0 indexnek felel meg. A NULL üres stringgé konvertálódik, amit kulcsként használva létrehoz egy üres string kulcsú bejegyzést a tömbben, de ez nem azonos az üres szögletes zárójelek használatával ([] -- új elemet fűz a tömb végéhez).

Tömbök és objektumok nem használhatók kulcsként. Ha ez mégis megtörténik, akkor figyelmeztetést kapunk: Illegal offset type.

array( [kulcs =>] érték
     , ...
     )
// a kulcs vagy egy string vagy egy nemnegatív integer (egész szám)
// az érték bármi lehet


Létrehozás/módosítás a szögletes zárójeles formával

Meglévő tömbök is módosíthatóak konkrét elemek megadásával.

Ezt úgy tudod megtenni, hogy a tömb neve után szögletes zárójelekben megadod a kulcsot, amit módosítani szeretnél. Ha elhagyod a kulcsot, és csak egy üres szögletes zárójel párt ("[]") adsz meg a változó neve után, a tömb végére illeszthetsz elemet.
$tomb[kulcs] = érték;
$tomb[] = érték;
// a kulcs vagy egy string vagy egy nemnegatív integer (egész szám)
// az érték bármi lehet
Ha a $tomb nem létezik, ezzel létrejön. Tehát ez egy újabb alternatíva tömbök létrehozására. Ha módosítani szeretnél egy elemet, rendelj hozzá új értéket. Ha meg szeretnél szüntetni egy kulcs/érték párt, használd az unset() függvényt.


Hasznos függvények

Jónéhámy függvény létezik a tömbökkel való munka megkönnyítésére. Lásd a tömb függvények című részt.

Megjegyzés: Az unset() függvénnyel lehet egy értéket a tömbből törölni. Figyelj arra, hogy a tömb nem lesz újraindexelve!

$a = array( 1 => 'egy', 2 => 'kettő', 3 => 'három' );
  unset( $a[2] );
  /* ennek eredményeképpen $a így fog kinézni:
     $a = array( 1=>'egy', 3=>'három');
     és NEM így:
     $a = array( 1 => 'egy', 2 => 'három');
  */

A foreach vezérlési szerkezet kifejezetten a tömbök számára jött létre. Egy egyszerű módszert ad tömbökön való végiglépkedésre.


Mit tehetünk, és mit nem a tömbökkel

Miért nem jó az $ize[bigyo] forma?

Minden string típusú kulcsot idézőjelek vagy aposztrófok közé kell tenni tömbbeli elemre történő hivatkozásnál, például: $ize['bigyo'] és nem $ize[bigyo]. Vajon miért nem jó $ize[bigyo] alak? Talán láttad ezt a szintaxist régi PHP programokban:

$ize[bigyo] = 'ellenség';
echo $ize[bigyo];
// stb.

Ez hibás, és mégis működik. Akkor mégis miért nem jó? Azért, mert a bigyo itt valójában egy nem definiált állandót jelöl, és nem a 'bigyo' sztringet (figyelj az aposztrófokra). A későbbi PHP verziókban már előfodulhatnak olyan előre definiált állandók, amelyeknek ugyanaz lesz a neve, mint ami a saját kódodban sztringként szerepel. Azért működik, mert ezeket a nem definiált állandókat a PHP a nevükkel azonos tartalmú sztringgé konvertálja. A szintaxis részben is már olvasható volt, hogy a szögletes zárójelek ('[' és ']') között egy kifejezésnek kell állnia. Ez azt jelenti, hogy írhatsz ehhez hasonló dolgokat is:

echo $tomb[ ize(true) ];

Ez a példa bemutatja, hogyan használhatsz függvény visszatérési értéket tömbindexként. A PHP úgyszintén ismeri a konstansokat. Bizonyára hallottál már az E_* konstansokról.

$hiba_leiras[E_ERROR]   = "Fatális hiba történt";
$hiba_leiras[E_WARNING] = "A PHP figyelmeztetést adott";
$hiba_leiras[E_NOTICE]  = "Informális megjegyzés";

Figyeld meg, hogy az E_ERROR egy érvényes azonosító, mint a valami az előző példában. De a legutóbbi példa ugyanaz, mintha ezt írnánk:

$hiba_leiras[1] = "Fatális hiba történt";
$hiba_leiras[2] = "A PHP figyelmeztetést adott";
$hiba_leiras[8] = "Informális megjegyzés";

mivel az E_ERROR konstans értéke 1, stb.


De miért nem jó ez?

Valamikor a jövőben a PHP fejlesztői hozzáadhatnak egy új konstanst vagy kulcsszót a nyelvhez, és akkor bajba kerülsz. Például jelenleg sem használhatóak az empty és default szavak, mivel ezek speciális kulcsszavak.

Ha ezek az érvek nem győznek meg: ez a szintaxis egyszerűen nem javasolt, és bármikor megszűnhet működni.

Megjegyzés: Ha az error_reporting beállítást E_ALL értékre állítod be, látni fogod, hogy a PHP figyelmeztetéseket generál, valahányszor olyan indexre történik hivatkozás, ami nem definiált. (Add az error_reporting(E_ALL); sort a programod elejéhez).

Megjegyzés: Idézőjeles stringekben, egy másik szintaxis érvényes. Lásd a változók behelyettesítése című részt további részletekért.


Példák

A tömb típus a PHP-ben nagyon sokoldalú, ezért összegyűjtöttünk néhány példát, hogy megmutassuk a tömbök erejét.

// ez
$a = array( 'szín' => 'piros',
            'íz'   => 'édes',
            'alak' => 'kerek',
            'név'  => 'alma',
                      4        // 0 lesz a kulcsa
          );

// teljesen megyezik ezzel
$a['szín'] = 'piros';
$a['íz']   = 'édes';
$a['alak'] = 'kerek';
$a['név']  = 'alma';
$a[]       = 4;        // 0 lesz a kulcsa

$b[] = 'a';
$b[] = 'b';
$b[] = 'c';
// a következő tömböt adja: array( 0 => 'a' , 1 => 'b' , 2 => 'c' )
// vagy egyszerűen: array('a', 'b', 'c')

Példa 6-4. Az array() használata

// Tömb, mint tulajdonság hozzárendelés
$map = array( 'verzió'     => 4
            , 'rendszer'   => 'Linux'
            , 'nyelv'      => 'angol'
            , 'short_tags' => true
            );

// szigorúan számokat tartalmazó tömb
$tomb = array( 7
             , 8
             , 0
             , 156
             , -10
             );
// ez ugyanaz, mint array ( 0 => 7, 1 => 8, ...)

$valtogatas = array(         10 // 0. indexű/kulcsú
                  , 5    =>  6
                  , 3    =>  7
                  , 'a'  =>  4
                  ,         11 // kulcsa 6 (a legnagyobb egész kulcs 5 volt)
                  , '8'  =>  2 // kulcsa 8 (egész!)
                  , '02' => 77 // kulcsa '02'
                  , 0    => 12 // a 10 értéket felülírjuk 12-vel
                  );

// üres tömb
$ures = array();

Példa 6-5. Kollekció

$szinek = array('piros','kék','zöld','sárga');

foreach ( $szinek as $szin ) {
    echo "Szereted a(z) $szin színt?\n";
}

/* kimenete:
Szereted a(z) piros színt?
Szereted a(z) kék színt?
Szereted a(z) zöld színt?
Szereted a(z) sárga színt?
*/

Figyelj arra, hogy jelenleg közvetlenül nem lehet módosítani a tömb elemeinek értékét ezzel a ciklussal. A problémát a következőképpen tudod megkerülni:

Példa 6-6. Kollekció

foreach ( $szinek as $kulcs => $szin )
{
    // nem működik (nem módosítja a tömböt):
    //$szin = strtoupper($szin);

    // működik (módosítja a tömböt):
    $szinek[$kulcs] = strtoupper($szin);
}
print_r($szinek);

/* kimenete:
Array
(
    [0] => PIROS
    [1] => KÉK
    [2] => ZÖLD
    [3] => SÁRGA
)
*/

Ebben a példában egy egytől számozott tömböt készítünk.

Példa 6-7. Egytől kezdődő index

$elsonegyed  = array(1 => 'Január', 'Február', 'Március');
print_r($elsonegyed);

/* kimenete:
Array
(
    [1] => 'Január'
    [2] => 'Február'
    [3] => 'Március'
)
*/

Példa 6-8. Felöltés valós adatokkal

// egy tömb felöltése a <link linkend="ref.dir">könyvtárban</link> található filenevekkel
$konyvtar = opendir('.');
while ($filenev = readdir($konyvtar)) {
    $filenevek[] = $filenev;
}
closedir($konyvtar);

A tömbök rendezettek. A sorrendet számos függvénnyel megváltoztathatod. Lásd a tömb függvények című részt további információkért.

Példa 6-9. Tömbök rendezése

sort($filenevek);
print_r($filenevek);

Mivel a tömb egy értéke bármi lehet, értékként akár egy másik tömböt is megadhatsz. Ilyen formában készíthetsz rekurzív vagy többdimenziós tömböket.

Példa 6-10. Rekurzív és többdimenziós tömbök

$gyumolcsok = array ( "gyümölcsök"  => array ( "a" => "narancs"
                                     , "b" => "banán"
                                     , "c" => "alma"
                                     )
                , "számok" => array (  1
                                     , 2
                                     , 3
                                     , 4
                                     , 5
                                     , 6
                                     )
                , "lyukak"   => array (     "első"
                                     , 5 => "második"
                                     ,      "harmadik"
                                     )
                );

Objektumok

Objektumok létrehozása

Egy objektum létrehozására a new operátor való, amely az adott objektumtípus egy példányát hivatott létrehozni [mivel lehet, hogy hivatkozni akarunk rá, rendszerint másolni szoktuk az objektumot (ill. a címét) egy változóba]

<?php
class semmi #egy objektumosztály létrehozása, semmi az osztály neve
{
    function do_semmi ()
    {
        echo "Csinálom a semmit.";
    }
}

$bar = new semmi;  #$bar most egy semmi típusú objektum
$bar->do_semmi();  #a $bar objektum do_semmi()
                   #metódusát (függvényét) hívja
?>

Alaposabb információkért nézd meg az Osztályok és objektumok című részt.


Erőforrások

Az erőforrás egy olyan speciális változó, ami egy külső erőforrásra tartalmaz referenciát. Az erőforrásokat speciális függvények hozzák létre és használják. Lásd az ide tartozó függeléket a különböző erőforrás típusokhoz tartozó függvények listájával.

Megjegyzés: Az erőforrás típus a PHP 4-ben került a nyelvbe.


Erőforrások felszabadítása

A PHP 4-es Zend Egine-jében bevezetett hivatkozás-számlálási technika következtében a használatlan erőforrásokat automatikusan detektálja a PHP (mint a Java). Ebben az esetben minden erőforrás által használt összes más erőforrás felszabadításra kerül a szemétgyűjtő algoritmusban. Emiatt ritkán szükséges, hogy felszabadítsuk a foglalt memóríát valamilyen free_result jellegű függvénnyel.

Megjegyzés: Az állandó adatbázis kapcsolatok speciálisak abban az értelemben, hogy nem szűnnek meg a szemétgyűjtés során. Lásd még az állandó kapcsolatok című részt.


NULL

A speciális NULL érték jelzi, hogy egy változó nem tartalmaz értéket. A NULL a NULL egyetlen lehetséges értéke.

Megjegyzés: A NULL típus a PHP 4-ben került bevezetésre.

Egy változó NULL-nak tekintendő, ha

  • a NULL állandó értéke lett hozzárendelve.

  • ha még semmilyen érték nem lett hozzárendelve.

  • ha az unset() függvény törölte.


Szintaxis

Csak egy értéket vehet fel a NULL típus, ami a kisbetűs és nagybetűs írásmódra nem érzékeny NULL kulcsszó.

$valtozo = NULL;

Lásd még: is_null() és unset()!


Bűvészkedés a típusokkal

A PHP nem követeli meg (nem támogatja) az explicit típusdefiníciót a változók deklalárásakor; egy változó típusát a környezet határozza meg, amiben a változót használjuk. Vagyis ha egy stringet rendelünk var-hoz, akkor var string lesz. Ha ezután egy egészet rendelünk hozzá, var egész lesz.

Egy példa a PHP automatikus típuskonverziójára az összeadás '+' operátora. Ha bármely operandusa lebegőpontos, akkor mindegyik operandusból lebegőpontos lesz, és az eredmény is az lesz. Máskülönben, ha az operandusok egészek, az eredmény is egész lesz. Figyeljünk azonban arra, hogy az operandusok típusát NEM változtatja meg; csupán a kiértékelés módját határozza meg.

$foo = "0";                  // $foo egy string (ASCII 48)
$foo += 2;                   // $foo most egész (2)
$foo = $foo + 1.3;           // $foo most lebegőpontos (3.3)
$foo = 5 + "10 Kis Pingvin"; // $foo egész (15)
$foo = 5 + "10 Kismalac";    // $foo egész (15)

Ha az utolsó két példa furcsának tűnik, nézd meg a String konverziókat.

Ha egy változót adott típussal szeretnél használni egy kifejezésben, nézd meg a Típus konverziókat. Ha a változó típusát akarod megváltoztatni, használd a settype() függvényt.

Ha az ebben a fejezetben található példákat ki szeretnéd próbálni, használd a var_dump() függvényt a típusok és értékek kiírására.

Megjegyzés: Egy tömb típusának automatikus konverziója jelenleg nem definiált.

$a = 1;      // $a egész
$a[0] = "f"; // $a tömb lesz, $a[0]-ba "f" kerül

A fenti példából ugyan tisztán látszik, hogy $a-ból tömb lesz, aminek az első eleme 'f', de mi a helyzet ezzel:

$a = "1";    // $a egy string
$a[0] = "f"; // Mi van a string offsettel? Mi történik?

Mivel a PHP támogatja, hogy a stringet, mint karakterek tömbjét kezeljük, és "beleindexeljünk" a fenti példa problémához vezet: $a-ból most tömb legyen, aminek az eleme "f", vagy a string első karaktere legyen "f"?

Emiatt, a PHP 3.0.12 és PHP 4.0b3-RC4 verzióiban az automatikus típuskonverzió eredménye nem definiált. A megoldáson már dolgoznak.


Típuskonverziók

PHP-ben a típuskonverzió úgy működik, mint C-ben: a kívánt típus nevét zárójelbe írjuk az elé a változó elé, amelyet cast-olni (konvertálni) akarunk.

$foo = 10;            // $foo egész
$bar = (float) $foo;  // $bar lebegőpontos

A megengedett típusok:

  • (int), (integer) - egésszé konvertál

  • (bool), (boolean) - logikai értékké konvertál

  • (real), (double), (float) - lebegőpontos számmá konvertál

  • (string) - stringgé konvertál

  • (array) - tömbbé konvertál

  • (object) - objektummá konvertál

Megjegyzés: Ahelyett, hogy egy változót stringgé alakítasz, egyszerűen idézőjelbe is teheted, hogy ezt a hatást elérd.

Megjegyzés: szóközök és tabulátorok megengedettek a string belsejében, tehát az alábbiak ugyanazt csinálják:

$foo = (int) $bar;
$foo = ( int ) $bar;

Nem mindig tiszta, hogy mi történik, ha típusok közt cast-olunk [implicit cast]. További információkért lásd az alábbi fejezeteket:

Amikor egy tömböt stringgé alakítasz, az eredmény az Array szó lesz. Hasonlóan, ha objektumot stringgé alakítasz, az Object szót kapod.

Ha skalárból, vagy stringből tömbbé szeretnénk konvertálni, a változó az első eleme lesz a tömbnek:

$var = 'szia';
$arr = (array) $var;
echo $arr[0]; // kiírja 'szia'

Ha egy skalárt vagy stringet objektummá akarjuk konvertálni, a változó az objektum egy attribútuma lesz; az attribútum neve 'scalar' lesz:

$var = 'szia';
$obj = (object) $var;
echo $obj->scalar; // kiírja, hogy 'szia'


7. Fejezet. Változók

Alapok

PHP-ban a változókat egy dollárjel utáni változónév jelöli. A változónevek érzékenyek kis- és nagybetűk különbözőségére.

A változónevekre a PHP más jelzőivel azonos szabályok vonatkoznak. Egy érvényes változónév betűvel vagy aláhúzással kezdődik, amit tetszőleges számú betű, szám vagy aláhúzás követ. Reguláris kifejezéssel kifejezve ez a következőt jelenti: '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'

Megjegyzés: Ebben az esetben egy betű lehet az angol abc egy betűje a-z-ig és A-Z-ig, valamint a 127-től 255-ig terjedő (0x7f-0xff) ASCII kódú karakterek.

$var = "Géza";
$Var = "János";
echo "$var, $Var";           // kiírja, hogy "Géza, János"

$4site        = 'ez nem jó'; // nem érvényes, mert számmal kezdődik
$_4site       = 'ez ok';     // érvényes, aláhúzással kezdődik
$täyte        = 'mansikka';  // érvényes, az 'ä' az ASCII 228-as karaktere
$tükörfúrógép = "árvíztűrő"; // érvényes, ellenőrizheted egy ASCII táblában

PHP 3-ban a változókhoz mindig értékek tartoznak. Vagyis ha egy kifejezést rendelünk egy változóhoz, az eredeti kifejezés egészének értéke másolódik a célváltozóba. Ez azt jelenti, hogy ha például egy változó értékét egy másikhoz rendeljük, egyikük megváltozása sincs hatással a másikra. Nézd át Kifejezések c. fejezetet, ahol az ilyen jellegű hozzárendelésekről több információ található.

PHP 4-ben lehetőség van egy másik hozzárendelési módra: változó referencia szerinti hozzárendelésére. Ez azt jelenti, hogy az új változó egyszerűen hivatkozik (más szóval "alias lesz", vagy "rá mutat") az eredetire. Az új változón végzett változtatások az eredetit is érintik és fordítva. Ez azt is jelenti, hogy nem történik másolás; ekképpen a hozzárendelés gyorsabban történik meg. Igaz ugyan, hogy ez a sebességnövekedés csak "feszes" ciklusokban vagy nagy tömböknél ill. objektumok átadásakor jelentkezik.

Referencia szerinti értékadáshoz egyszerűen & jelet kell az átadandó változó neve elé írni. Az alábbi kód - például - kiírja kétszer, hogy 'Nevem Bob':

<?php
$ize = 'Bob';              // 'Bob' hozzárendelése $ize-hoz
$bigyo = &$ize;            // Hivatkozás $ize-ra $bigyo-ban.
$bigyo = "Nevem $bigyo";   // $bigyo megváltoztatása...
echo $ize;                 // $ize is megváltozott
echo $bigyo;
?>

Fontos megjegyezni, hogy csak megnevezett változókra lehet referenciát létrehozni.

<?php
$ize = 25;
$bigyo = &$ize;      // Ez egy érvényes hozzárendelés.
$bigyo = &(24 * 7);  // Érvénytelen referencia egy névtelen kifejezésre.

function test()
{
   return 25;
}

$bigyo = &test();    // Érvénytelen.
?>


Előre definiált változók

A PHP egy számos előre definiált változót biztosít az bármely futó szkript számára. Sokat ezek közül nem lehet teljes pontossságal dokumentálni, mert függnek a a futtató szervertől, a használt verziótól, a konfigurálástól, és más gyéb tényezőktől. Néhány ilyen változó nem elérhető, ha a PHP parancssorból fut.

E tényezők ellenére az alábbi listában azok az előre definiált változók vannak felsorolva, amelyek a PHP 3 tipikus installálásakor elérhetők az Apache 1.3.6-ot használva.

Az összes előre definiált változó kilistázható, és sok más hasznos információt is közöl a phpinfo().

Megjegyzés: Ez a lista nem teljes, nem is ez a célja. Ez csak egy útmutató arról, hogy milyen típusú előre definiált változók lehetnek.


Apache változók

Ezek a változók az Apache webszerver változói. Ha másik szerveren fut a PHP, nincs rá garancia, hogy ugyanezek a változók akkor is rendelkezésre állnak: némelyik hiányozhat, esetleg itt nem szereplőket is biztosíthat a szerver. Számos a CGI 1.1 specifikációban dokumentált változókra biztosan lehet alapozni.

Figyelni kell arra, hogy ha a PHP parancssorból (command line) használva a változók töredékének van csak értelme, ha egyáltalán definiáltak ilyen esetben.

$GATEWAY_INTERFACE

A server CGI specifikációjának verziója. Pl.: 'CGI/1.1'.

$SERVER_NAME

A gazdagép (host) neve, ami alatt a szkript fut. Ha a szkript virtuális host-on fut, a virtuális host neve.

$SERVER_SOFTWARE

Serverazonosító sztring, amely a kérésekre (request) adott válasz (response) fejlécében (header) szerepel.

$SERVER_PROTOCOL

Az oldal lekéréséhez használt protokoll neve és verziója pl. 'HTTP/1.0'

$REQUEST_METHOD

Az oldal eléréséhez használt kérési forma, pl.: 'GET', 'HEAD', 'POST', 'PUT'.

$QUERY_STRING

Keresési kérdés, az oldalt meghívó URL-ben a ? után szereplő rész, ha létezik.

$DOCUMENT_ROOT

A www dokumentumok főkönyvtára, amely alatt a jelenlegi szkript fut. Ez a szerver konfigurációs fájljában meghatározott érték.

$HTTP_ACCEPT

Az aktuális kérés Accept: HTTP fejlécének tartalma, ha van ilyen. Ebben adja meg a böngésző, hogy milyen formátumokat képes fogadni.

$HTTP_ACCEPT_CHARSET

Az aktuális kérés Accept-Charset: HTTP fejlécének tartalma, ha van ilyen. pl. 'iso-8859-1,*,utf-8'.

$HTTP_ACCEPT_ENCODING

Az aktuális kérés Accept-Encoding: HTTP fejlécének tartalma, ha van ilyen. pl. 'gzip'.

$HTTP_ACCEPT_LANGUAGE

Az aktuális kérés Accept-Language: HTTP fejlécének tartalma, ha van ilyen. pl. 'en'.

$HTTP_CONNECTION

Az aktuális kérés Connection: HTTP fejlécének tartalma, ha van ilyen. pl. 'Keep-Alive'.

$HTTP_HOST

Az aktuális kérés Host: HTTP fejlécének tartalma, ha éppen van ilyen.

$HTTP_REFERER

Annak az oldalnak az URL címe, ahonnan ide került a látogató. Ezt a látogató böngészőprogramja állítja be, de ezt nem minden böngésző és nem mindig teszi meg.

$HTTP_USER_AGENT

Az aktuális User_Agent: HTTP fejlécének tartalma, ha van ilyen. Ez a string, amely meghatározza az oldal megtekintéséhez használt böngészőt, pl. Mozilla/4.5 [en] (X11; U; Linux 2.2.9 i586). Sok más mellett ezt az értéket a fel lehet használni arra, hogy a get_browser() fügvénnyel az aktuális böngésző képességeinek megfelelően lehessen kialakítani az oldal megjelenését.

$REMOTE_ADDR

Az az IP cím, ahonnan a látogató az oldalt lekérte.

$REMOTE_PORT

A látogató gépén a webszerverrel való kommunikációhoz használt port száma.

$SCRIPT_FILENAME

A PHP szkript abszolút elérési útja a szerver gépen.

$SERVER_ADMIN

A SERVER_ADMIN a kiszolgáló konfigurációs fájl direktíva értéke (Apache alatt). Ha a szkript egy virtuális host-on fut, akkor ez a virtuális host-hoz rendelt érték.

$SERVER_PORT

A kiszolgálógépen a kiszolgáló kommunikációjában használt port száma. Alapértelmezés szerint ez a '80', de például SSL-t használva ez a biztonságos HTTP portnak a száma lesz.

$SERVER_SIGNATURE

A kiszolgáló verziószámát és a virtuális host-ot tartalmazó sztring, ha engedélyezett. Ez a szöveg jelenik meg minden szerver által generált oldal alján.

$PATH_INFO

Hasonló értéket tartalmaz, mint a SCRIPT_NAME, de CGI verzió esetén ez jobb lehet az önhivatkozó kérdőívek készítésekor, mert egyes szervereken a SCRIPT_NAME tartalmazza a PHP bináris meghívási útvonalát is.

$PATH_TRANSLATED

A szkript a fájlrendszer szerinti (nem a document root-hoz viszonyított!) elérési útja. Ezt a kiszolgáló a virtuális->valós átalakítás után határozza meg.

$SCRIPT_NAME

Az aktuális szkript elérési útja, ahogy az az URL-ben megjelenik. Hasznos a saját magukra mutató oldalakhoz.

$REQUEST_URI

Az az URI, amellyel az oldalt lekérték. pl. '/index.html'.


Környezeti változók

A PHP globális változói közé kerülnek a PHP feldolgozót futtató környezet változói. Számos változót a shell szolgáltat, ami alatt a PHP fut. Mivel más-más rendszerek más-más shell-eket használnak, ezért egy pontos lista összeállítása lehetetlen. A használt shell dokumentációjában nézz utána az előre definiált környezeti változóknak!

Más környezeti változók - beleértve a CGI változókat is - attól függően kerülnek be, hogy a PHP szerver modulként fut vagy CGI feldolgozóként.


PHP változók

Ezeket a PHP maga állítja elő. A $HTTP_*_VARS változók csak akkor állnak rendelkezésre, ha a track_vars be van kapcsolva. Ha engedélyezted ezt a beállítást, ezek a változók mindig létrejönnek, még ha üresek is. Ez nem engedi a rosszindulatú felhasználóknak, hogy meghamasítsák a változókat.

Megjegyzés: A PHP 4.0.3 verziótól kezdve a track_vars mindig be van kapcsolva, függetlenül a konfigurációs fájl beállításától.

Megjegyzés: Az új szuper globális (Superglobals) változók 4.1.0 verziótól használhatók. További részletekért lásd a 4.1.0 verzió bejelentését Ezek a $_GET, $_POST, $_ENV, $_SERVER, $_COOKIE, $_REQUEST $_FILES és a $_SESSION tömbök, amelyek fesztelen megfogalmazásban szuper globális jelzővel illetik, mivel minden esetben használhatók tekintet nélkül az aktuális érvényességi körre. Emiatt a régi, nekik megfelelő $HTTP_*_VARS tömbök használata már nem javasolt.

Ha a register_globals be van kapcsolva, ezek a változók globális változókként is létrejönnek, függetlenül a $HTTP_*_VARS tömböktől. Nézd meg idevonatkozó részletes információkért a biztonságról szóló Globálisan is elérhető változók (Register Globals) használata c. fejezetet!

$argv

A szkriptnek átadott argumentumok tömbje. Ha a szkript parancssor alól futtatjuk, ez egy C-szerű hozzáférést biztosít a parancssor argumentumokhoz. Ha GET metódussal hívjuk, az URL kérdőjel utáni részét (query string) tartalmazza.

$argc

A parancssori argumentumok számát tartalmazza (ha parancssorból futtatjuk).

$PHP_SELF

A most futó szkriptfájl neve, a document root-hoz képest relatív alakban. Ha a PHP parancssorból fut, ez a változó nem elérhető. Ez a változó a kérés útvonal információját is tartalmazza, ha az létezik, azaz a $PHP_SELF a "http://example.com/test.php/foo.bar" címre a következőt fogja adni: "/test.php/foo.bar"

$HTTP_COOKIE_VARS

HTTP cookie-kat (sütiket) tartalmazó asszociatív tömb.

$_COOKIE

HTTP cookie-kat (sütiket) tartalmazó asszociatív tömb, amely minden hatókörben elérhető. PHP 4.1.0-ban került a nyelvbe.

$HTTP_GET_VARS

HTTP GET metódussal által szolgáltatott adatokat tartalmazó asszociatív tömb.

$_GET

HTTP GET metódussal által szolgáltatott adatokat tartalmazó asszociatív tömb, amely minden hatókörben elérhető. PHP 4.1.0-ban került a nyelvbe.

$HTTP_POST_VARS

HTTP POST metódussal által szolgáltatott adatokat tartalmazó asszociatív tömb.

$_POST

HTTP POST metódussal által szolgáltatott adatokat tartalmazó asszociatív tömb, amely minden hatókörben elérhető. PHP 4.1.0-ban került a nyelvbe.

$HTTP_POST_FILES

A HTTP POST metódussal feltöltött fájlokról tartalmaz információkat, asszociatív tömb. Lásd a POST metódusú feltöltések című részt további információkért a $HTTP_POST_FILES tartalmát és szerkezetét illetően. PHP 4.0.0-ban került a nyelvbe.

$_FILES

A HTTP POST metódussal feltöltött fájlokról tartalmaz információkat, asszociatív tömb. Lásd a POST metódusú feltöltések című részt további információkért a $_POST tartalmát és szerkezetét illetően. Minden hatókörben elérhető. PHP 4.1.0-ban került a nyelvbe.

$HTTP_ENV_VARS

A szülő/futtató környezet aktuális változóit tartalmazó asszociatív tömb.

$_ENV

A szülő/futtató környezet aktuális változóit tartalmazó asszociatív tömb, amely minden hatókörben elérhető. PHP 4.1.0-ban került a nyelvbe.

$HTTP_SERVER_VARS

A HTTP szervertől érkező változókkal feltöltött asszociatív tömb. Ezek a változók megfelelnek a fent említett Apache változóknak.

$_SERVER

A HTTP szervertől érkező változókkal feltöltött asszociatív tömb, amely minden hatókörben elérhető. PHP 4.1.0-ban került a nyelvbe.

$HTTP_SESSION_VARS

Az aktuális szkripthez tartozó session változókat tartalmazó asszociatív tömb.

$_SESSION

Az aktuális szkripthez tartozó session változókat tartalmazó asszociatív tömb, amely minden hatókörben elérhető. A _SESSION tömbben új bejegyzések létrehozásával automatikusan regisztrálhatók értékek, mint a session_register() segítségével. PHP 4.1.0-ban került a nyelvbe.

$_REQUEST

A GET, POST és Cookie változókból összeállított asszociatív tömb. Más szóval, bármilyen a felhasználótól ügyféltől érkező adatot tartalmaz, ami biztonsági szempontból nem megbízható. Minden hatókörben elérhető. PHP 4.1.0-ban került a nyelvbe.


Változók hatásköre

[Ezt a fejezetet érdemes elolvasni, még akkor is, ha profi vagy valamilyen programozási nyelvben, mert a PHP tartogat egy-két érdekes meglepetést...]

A változó hatásköre az a környezet, amelyben a változó definiált. A legtöbb esetben minden PHP változónak egyetlen hatásköre van. Ez az egyetlen hatáskör kiterjed az include és a require segítségével használt fájlokra is. Például:

$a = 1;
include "b.inc";

Itt az $a változó elérhető lesz az beillesztett b.inc szkriptben is. A felhasználói függvényekkel a lokális függvényhatáskör kerül bevezetésre. Alapértelmezés szerint minden, függvényen belül használt változó ebbe a lokális függvényhatáskörbe tartozik, például:

$a = 1; /* globális hatáskör */

function Test ()
{
    echo $a; /* egy helyi változót vár */
}

Test();

Ez a szkript nem fog semmilyen kimenetet sem eredményezni, mivel az echo kifejezés az $a változónak egy helyi - függvényen belüli - változatára utal, és ebben a hatáskörben ehhez nem rendeltek értéket. Ez valamelyest különbözik a C nyelv filozófiájától, ahol a globális változók automatikusan elérhetők bármely függvényből, feltéve ha a függvényben újra nem definiáltad azt a változót. Ez problémák forrása lehet, ha az ember véletlenül megváltoztat egy globális változót. A PHP-ben a globális változókat global kulcsszóval kell deklarálni a függvényekben, például:

$a = 1;
$b = 2;

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

    $b = $a + $b;
}

Ossszead();
echo $b;

A fenti szkript kiírja, hogy "3". $a és $b global-ként való deklarálásával minden utalás ezekre a változókra a globális változót fogja érinteni. Nincs megkötve, hány globális változót kezelhet egy függvény.

Globális változók elérésének másik módja a PHP által definiált speciális $GLOBALS tömb használata. Az előbbi példával egyenértékű megoldás:

$a = 1;
$b = 2;

function Osszead()
{
    $GLOBALS["b"] = $GLOBALS["a"] + $GLOBALS["b"];
}

Osszead();
echo $b;

A $GLOBALS asszociatív tömb, ahol a globális változó neve jelenti a kulcsot, és a változó értéke a tömbelem értéke.

A változók hatáskörének másik fontos lehetősége a static (statikus) változó. A statikus változó csak lokális hatáskörben él - egy függvényen belül, de két függvényhívás közt nem veszti el az értékét, a változó hatásköréből való kilépés esetén is megmarad az értéke:

function Test()
{
    $a = 0;
    echo $a;
    $a++;
}

Ez nagyon haszontalan függvény, mivel nem csinál mást, mint minden meghívásakor $a-t 0-ra állítja, aztán kiírja a 0-t. Az $a++ teljesen felesleges, mert amint vége a függvény futásának az $a változó megszűnik. Ahhoz, hogy ebből értelmes számlálófüggvény legyen - megmaradjon a számláló értéke -, az $a változót statikusnak kell deklarálni:

function Test()
{
    static $a = 0;
    echo $a;
    $a++;
}

Most már valahányszor meghívódik a Test() függvény, kiírja $a értékét, majd azt megnöveli eggyel.

A statikus változókat a rekurzív függvények megvalósításában is felhasználhatjuk. Rekurzívnak nevezzük azt a függvényt, amely saját magát hívja meg. Ezt természetesen feltételhez kell kötni, nehogy végtelen rekurzióba kerüljön a vezérlés és meghatározatlan időre a függvényen belül csapdába esik. Mindig meg kell bizonyosodni arról, hogy megfelelő feltétel rendelkezésre áll a rekurzió befejezéséhez. A következő függvény rekurzívan elszámol 10-ig a statikus $count változó segítségével: [A static kulcsszó nagyon fontos!]

function Test()
{
    static $count = 0;

    $count++;
    echo $count;
    if ($count < 10) {
        Test ();
    }
    $count--;
}


Változó változók

Néha kényelmes változó változók használata. Ez olyan változó jelent, amelynek a nevét dinamikusan lehet beállítani. A normál változót így adunk értéket:

$a = "hello";

A változó változó veszi egy változó értékét, amelyet egy másik változó értékének tekinti. A fenti példában a hello, egy változó neveként használható, a $a elé még egy $-t írva.

$$a = "világ";

Ekkor már két változó van a PHP szimbólumtáblájában: $a, amelynek tartalma "hello", és $hello, amelynek a tartalma "világ". Ennélfogva a következő programsor:

echo "$a ${$a}";

pontosan ugyanazt csinálja, mintha ezt írtuk volna:

echo "$a $hello";

Mindkettő kiírja, hogy: hello világ.

Annak érdekében, hogy változó változókat tömbökkel együtt is használhassuk, fel kell oldani a következő kétértelműséget. A $$a[1] kifejezés kiértékelésekor a feldolgozónak tudnia kell, hogy ez a $a[1] értékét tekintse a hivatkozott változó neveként, vagy $$a-t - és ekkor és ennek a tömbnek 1. indexű elemére történt a hivatkozás. Az első esetben ${$a[1]}, míg a másodikban ${$a}[1] írandó.


Változók a PHP-n kívülről

HTML űrlapok (GET és POST)

Egy HTML űrlap (form) elküldésével az űrlap összes beviteli mezőjének értéke automatikusan elérhetővé válik a szkript számára a PHP segítségével. Ha a track_vars szolgáltatás be van kapcsolva, ezek a változók a $HTTP_POST_VARS, $HTTP_GET_VARS, és/vagy $HTTP_POST_FILES, asszociatív tömbökben foglalnak helyet a változók forrásának megfelelően.

További információkért ezekről a változókról olvasd el az Előre definiált változók című részt.

Példa 7-1. Egyszerű űrlap változó példája

<form action="foo.php" method="post">
    Name: <input type="text" name="usernev"><br>
    <input type="submit">
</form>

Ha elküldjük a fenti űrlapot, akkor a PHP létrehozza a $HTTP_POST_VARS['usernev'] változót. Ha a register_globals beállítás aktív, akkor ez a változó elérhető lesz $usernev globális változóként is.

Megjegyzés: A magic_quotes_gpc konfigurációs beállítás hatással van a GET, POST és COOKIE metódusokkal kapott értékekre. Bekapcsolva a (Ez a "PHP", biz'a!) szövegből automágikusan (Ez a \"PHP\", biz\'a!) lesz, hogy megkönnyítse az adatbázisba írást. Lásd még: addslashes(), stripslashes() és magic_quotes_sybase!

A PHP megérti és kezeli a tömbökbe rendezett űrlapváltozókat. (Lásd related faq!) Hasznos lehet csoportosítani az összetartozó változókat, vagy az olyan űrlapelemeket, ahol több lehetőség közül nem csak egy választható.

Példa 7-2. Összetettebb űrlapváltozók

<form action="array.php" method="post">
    Név: <input type="text" name="szemelyes[nev]"><br>
    Email: <input type="text" name="szemelyes[email]"><br>
    Sör: <br>
    <select multiple name="ital[]">
        <option value="warthog">Warthog
        <option value="guinness">Guinness
        <option value="stuttgarter">Stuttgarter Schwabenbräu
        </select>
    <input type="submit">
</form>

PHP 3-ban ilyen módon csak egydimenziós tömbök hozhatók létre, míg PHP 4-ben nincs ilyen korlátozás.


IMAGE SUBMIT változónevek

Az űrlap elküldésekor megoldható, hogy gomb helyett képet használunk ilyesféle jelölés segítségével:

<input type="image" src="image.gif" name="elkuld">

Ha a felhasználó a képre kattint, a kiszolgálóra a következő két változó jut el: elkuld_x-et és elkuld_y-t. Ezek tartalmazzák a kattintás képen belüli koordinátáit. A tapasztaltabbak biztos megjegyeznék, hogy a változónevek nem aláhúzást, hanem pontot tartalmaznak, de a PHP a pontot automatikusan aláhúzássá konvertálja.


HTTP sütik (cookie)

A PHP támogatja a Netscape specifikációja által definiált HTTP sütiket. A süti olyan mechanizmus, amely a távoli böngészőn tesz lehetővé adattárolást, és így lehetővé teszi a visszatérő felhasználók azonosítását. A sütiket a setcookie() függvénnyel lehet beállítani. A sütik a HTTP fejléc részei, így a SetCookie függvényt bármilyen kimenet generálása előtt kell meghívni. Ugyanezt a megkötést kell betartani a header() függvénnyel. Bármilyen süti, amelyet a klienstől érkezik, automatikusan egy PHP változóba kerül, úgy, mint a GET és a POST metódus adatai.

Ha több adatot akarsz rendelni egy sütihez, egyszerűen rakj []-t a cookie neve után. Például:

setcookie("EnSutim[]", "tesztelem", time()+3600);

Vigyázz, mert a süti felülírja az előző azonos nevű sütit, hacsak nem különbözik a path vagy a domain. Így pl. egy bevásárlókocsi megírásakor jó egy számlálót is elhelyezni, hogy elkerüljük a problémát.

Példa 7-3. SetCookie Példa

$Szamlalo++;
setcookie("Szamlalo", $Szamlalo, time()+3600);
setcookie("Kocsi[$Szamlalo]", $elem, time()+3600);

Környezeti változók

A PHP automatikusan létrehozza az elérhető környezeti változókat, mint egyszerű PHP változókat.

echo $HOME;  /* Megmutatja a HOME környezeti változót, ha van. */

Mivel az információ ami a GET, POST és Cookie mechanizmuson keresztül jön, mind automatikusan PHP változókat generál, ezért néha jobb, ha direkt a környezeti változókból olvassuk ki, hogy tudjuk, valójában melyik változatból olvasunk. A getenv() függvényt lehet erre használni. A környezeti változókat be is lehet állítani a putenv() függvénnyel.


Pontok a bejövő változónevekben

Általában a PHP nem változtatja meg a változók neveit, amikor a szkript megkapja őket. A pont viszont nem érvényes karakter egy PHP változóneven belül. Az ok megértéséért nézd a:
$varname.ext;  /* érvénytelen változónév */
Most az elemző lát egy $varname nevű változót, amelyet stringösszefűző operátor (.) követ, majd egy csupasz sztring: az ext - idézőjel nélküli string, amely nem egyezik semmilyen ismert vagy lefoglalt kulcsszóval. Ez nyilván nem a kívánt eredményt adná.

Emiatt fontos, hogy PHP automatikusan helyettesíti a pontokat aláhúzásjellel.


Változótípusok meghatározása

Mivel a PHP határozza meg a változók típusát és konvertálja őket (általában) szükség szerint, nem mindig nyilvánvaló, hogy milyen típusú egy pillanatban egy adott változó. A PHP-nek számos függvénye van, amelyek egy változó típusát hivatottak eldönteni. Ezek: gettype(), is_long(), is_double(), is_string(), is_array(), és is_object().


8. Fejezet. Állandók

Az állandó egy skalár érték azonosítója (neve). Mint ahogy az elnevezése is mutatja, a program futása során nem változik/hat meg az értéke. Ez alól csak a 'mágikus' __FILE__ és __LINE__ állandók tűnhetnek kivételeknek, ám ezek valójában nem állandók. Az állandók alapesetben érzékenyek a kis- és nagybetűs irásmódra. Megállapodás szerint általában csupa nagybetűs neveket használunk az állandók neveiként.

Az állandók neveire a PHP más jelzőivel azonos szabályok vonatkoznak. Egy érvényes állandó-név betűvel vagy aláhúzással kezdődik, amit tetszőleges számú betű, szám vagy aláhúzás követ. Reguláris kifejezéssel kifejezve ez a következőt jelenti: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*

Megjegyzés: Ebben az esetben egy betű lehet az angol abc egy betűje a-z-ig és A-Z-ig, valamint a 127-től 255-ig terjedő (0x7f-0xff) ASCII kódú karakterek.

Az állandók bárhonnan elérhetőek -- az aktuális érvényességi körtől (scope) függetlenül bárhol használhatók.


Szintakszis

A define() függvénnyel lehet állandót létrehozni, amelynek definiálása után később nem lehet törölni vagy megváltoztatni az értékét.

Csak skaláris adat (boolean, integer, float vagy string típusú) lehet egy konstans tartalma.

A konstans értékére a nevének megadásával lehet hivatkozni. A változókkal ellentétben nem szabad $ jelet tenned a konstand neve elé. Használható még a constant() függvényt is, ha például a konstans nevét egy változó adja. A get_defined_constants() függvénnyel lehet a definiált konstansok listáját megkapni.

Megjegyzés: A konstansok és a (globális) változók különböző névtérben vannak. Ez azt jelenti, hogy a TRUE és a $TRUE két különböző dolgot jelent.

Ha egy definiálatlan konstanst próbálsz meg használni, a PHP a konstans nevét veszi karaktersorozatként értékül. Ilyen esetekben egy notice szintű hiba keletkezik. A defined() függvény segítségével vizsgálható a konstans létezése.

A következők a fontosabb különbségek a változókhoz képest:

  • Az állandók nevét nem kell dollár jellel $ kezdeni.

  • Az állandók akárhol definiálhatók, és akárhonnan elérhetők, a változók környezeti korlátozásaitól függetlenül.

  • Az állandók nem módosíthatóak, és nem törölhetőek, miután egyszer létrehozták azokat.

  • Az állandók csak skaláris értékeket tartalmazhatnak.

Példa 8-1. Konstansok definiálása

<?php
define("KONSTANS", "Helló világ!");
echo KONSTANS; // kiírja, hogy "Helló világ!"
echo Konstans; // kiírja, hogy "Konstans" és hibát eredményez
?>


Előre definiált állandók

PHP számos előredefiniált állandót biztosít a szkriptek futtatása során. Ezek többnyire a különböző kiterjesztések által meghatározott állandók, és csak akkor léteznek, ha az adott kiterjesztés is elérhető/használható akár dinamikusan betöltve vagy előre befordítva.

Az előre definiált állandók listája itt olvasható.


9. Fejezet. Kifejezések

A kifejezések a PHP legfontosabb építőkövei. A PHP-ban majdnem minden, amit leírsz, egy kifejezés. A lehető legegyszerűbb és mégis pontos definíciója a kifejezésnek: "mindaz, amelynek értéke van".

A kifejezések legalapvetőbb formái az állandók és a változók. Az "$a = 5" az '5'-öt az $a változóhoz rendeli. Az '5'-nek nyilván 5 az értéke, vagyis más szavakkal az '5' olyan kifejezés, melynek értéke 5 (itt az '5' egy egész típusú állandó).

Ez után a hozzárendelés után $a értéke 5 kell legyen, sőt, $b = $a esetén az eredménynek azonosnak kell lennie azzal, mint $b = 5 esetén. Másképp megfogalmazva az $a olyan kifejezés, amelynek értéke 5. Ha minden jól megy, pontosan ez fog történni.

Kissé bonyolultabb példák a kifejezésekre a függvények. Például tekintsük az alábbi függvényt:

function ize()
{
    return 5;
}

Megelőlegezzük ,hogy nem idegen Tőled a függvények koncepciója - ha nem így lenne, akkor olvasd el a függvényekről szóló fejezetet. Amint az elvárható, a $c = foo() lényegében azonos $c = 5 beírásával. A függvények olyan kifejezések, amelyeknek az értéke a visszatérési értékük. Mivel foo() 5-tel tér vissza, a 'foo()' kifejezés értéke 5. Általában a függvények nem arra használatosak, hogy egy bedrótozott számmal térjenek vissza, hanem valamilyen számolt származtatott értékkel.

Természetesen a változóknak a PHP-ben nem kell egésznek lenniük, és nagyon gyakran nem is azok. A PHP három féle skalártípust támogat: egész, lebegőpontos és sztring értékeket (skalárnak az számít, amit nem lehet kisebb darabokra bontani, eltérően - például - a tömböktől). A PHP két nem skalár típust is támogat: a tömb és objektum típust. Mindegyikükhöz lehet értéket rendelni, és mindegyikük lehet egy függvény visszatérési értéke.

Eddig a PHP/FI 2 használói nem találkoztak semmi különössel. Mindamellett a PHP továbbfejleszti a kifejezés fogalmát, ahogy azt sok hasonló nyelv teszi. A PHP egy kifejezés-orientált nyelv, abból a szempontból, hogy majdnem minden kifejezés. Tekintsük a példát, amivel eddig foglalkoztunk: '$a = 5'. Látható, hogy két értéket szerepel benne: az egész konstans '5' és $a értéke, amelyet az 5 értékkel frissítettünk. Az igazság azonban az, hogy még egy érték is van a kifejezésben, a magáé a hozzárendelésé. A hozzárendelés maga kiértékeli az átadandó értéket, ebben az esetben az 5-öt. Ez azt jelenti gyakorlatilag, hogy a '$a=5', a hatásától eltekintve egy kifejezés, amelynek az értéke 5. Ha ezért olyasmit írunk, hogy '$b=($a=5)', akkor az olyasmi, mintha '$a=5; $b=5;'-t írtunk volna (a pontosvessző jelöli az állítás végét). Mivel a hozzárendelés jobbról balra történik, ez írható zárójelek nélkül is: '$b=$a=5'.

A kifejezés-orientáltság másik jó példája az elő- és utónövekményes operátor. A PHP/FI 2 használóinak és sok más nyelvet használónak ismerős lehet a változó++ és változó-- jelölés. Ezek az növelő és csökkentő operátorok. A PHP/FI 2-ben a '$a++'-nek nincs értéke (mert nem kifejezés), és ezért nem is lehet semmihez hozzárendelni, vagy valamire használni. A PHP kiterjesztette az inkrementálás/dekrementálás lehetőségeit azzal, hogy ezeket is kifejezésekké alakította, mint ahogyan a C nyelvben is megtették. A PHP-ben a C nyelvhez hasonlóan kétféle növekményes operátor van: elő- és utó(növekményes). Mindkettő megnöveli a változó értékét, tehát a változó szempontjából nézve nincs különbség, a kifejezés értékében annál inkább. A '++$változó' formájú előnövekményes a megnövelt értéket adja vissza. (A PHP először növeli a változót, majd kiértékeli, innen jön az 'elő'). A '$változó++' alakú utónövekményes a változó eredeti értéket adja. (A PHP először kiértékeli, aztán növeli a változót, innen jön az 'utó'). [A csökkentő operátorokkal értelemszerűen ugyanez a helyzet.]

A kifejezések egy gyakori típusai az összehasonlító kifejezések. Ezek a kifejezések 0-t vagy 1-et adnak, annak megfelelően, hogy hamisak (FALSE), vagy igazak (TRUE) (ebben a sorrendben). A PHP támogatja a > (nagyobb), >= (nagyobb, vagy egyenlő), == (egyenlő), != (nem egyenlő), < (kisebb) és a <= (kisebb, vagy egyenlő) operátorokat. Ezeket a kifejezéseket általában feltételes kifejezésekben szokták használni. Ilyen pl. az if kifejezés.

Az utolsó példa, amivel itt foglalkozunk, a kombinált hozzárendelés-operátor kifejezés. Már tudhatod, hogy ha $a-t eggyel szeretnéd megnövelni, akkor egyszerűen írhatod, hogy '$a++' vagy '++$a'. Mi van akkor, hogy ha nem eggyel, hanem 3-mal kell megnövelni? Lehet háromszor egymás után írni, hogy '$a++', de ez nem valami hatékony és üdvözítő megoldás. Sokkal jobb gyakorlat az '$a=$a+3' használata. Ez kiértékeli az $a + 3-at, és hozzárendeli az $a-hoz, amelynek az lesz a végső eredménye, hogy $a értéke megnő hárommal. A PHP-ben - több más C-szerű nyelvhaz hasonlóan - ennél rövidebb formában is megadható: '$a+=3'. Ez pontosan azt jelenti, hogy "vedd $a értékét, és adjál hozzá hármat, és írd vissza az eredményt $a-ba". Amellett, hogy rövidebb és érthetőbb, még gyorsabb is. '$a+=3' értéke, mint egy normál értékadásé a hozzárendelt érték. Ez persze NEM 3, hanem $a + 3 (hiszen ezt az értéket rendeltük $a-hoz). Az összes többi kétoperandusú operátort lehet ilyenformán hozzárendelő-operátorként használni, például '$a-=5' (kivon 5-öt $a-ból), '$b*=7' (megszorozza $b-t 7-tel), stb.

Létezik még egy kifejezés, amely elég különösnek tűnhet, hacsak nem láttad már más nyelvekben: a háromoperandusú feltételes operátor:

$elso ? $masodik : $harmadik

Értéke: ha az első kifejezés értéke TRUE(nem nulla), akkor a második részkifejezés, egyébként a harmadik részkifejezés. Egy segítő példa:

$b = $todo == 'növel' ? $a+5 : $a-5; // $b $a+5 lesz, ha $todo értéke 'növel'
                                     // egyébként $b $a-5 lesz

Ez megegyezik az alábbi kóddal:

if ($todo == 'növel') $b = $a+5 else $b = $a-5;

Az alábbi példa segíthet az elő- és utónövekményes illetve csökkentő operátorok és kifejezéseik jobb megértésében:

function duplaz($i)
{
    return $i*2;
}

$b = $a = 5;        /*ötöt rendelünk $a és $b változókhoz */

$c = $a++;          /* utónövekményes, $c 5 lesz, mert
                       először $a kiértékelődik, csak aztán nő */

$e = $d = ++$b;     /* előnövekményes, $b növelt értéke (6)
                       adódik tovább $d-nek és $e-nek */

                    /* itt $d és $e hat */

$f = duplaz($d++);  /* $d kétszeresének hozzárendelése MIELŐTT
                       inkrementálódik, 2*6 = 12 lesz $f */

$g = duplaz(++$e);   /* $e kétszeresének hozzárendelése MIUTÁN
                        inkrementálódik 2*7=14 lesz $g */

$h = $g += 10;       /* először $g 10-zel nő, így 24 lesz az értéke,
                        ez adódik tovább $h-nak, az is 24 lesz*/

A fejezet elején azt ígértük, hogy leírjuk a különböző utasítás-típusokat, és ígéretnek megfelelően a kifejezések lehetnek állítások. Nem minden kifejezés állítás azonban, mert utasítás, amely illeszkedik 'kif' ';' mintára, vagyis a pontosvesszővel folytatodó kifejezés. A '$b=$a=5;'-ben $a=5 érvényes kifejezés, de nem érvényes utasítás önmagában. A teljes '$b=$a=5;' már igen.

Még egy említésre méltó dolog a kifejezések igaz értéke. Sok esetben főleg feltételes elágazásokban és ciklusokban, nem igazán érdekes, hogy a kifejezésnek mi az értéke, csak az, hogy igaz (TRUE) vagy hamis (FALSE). A TRUE és FALSE konstansok (nevük nem függ a kis- és nagybetűs írásmódtól) a PHP két lehetséges logikai értékei. Amikor szükséges, a kifejezések automatikusan logikai értékké alakulnak. Lásd a típuskonverziókról szóló fejezetet további részletekért.

A PHP a kifejezések egy teljes és hatékony megvalósítását biztosítja, és teljes dokumentációja meghaladja e kézikönyv kereteit. A fenti példák rávilágítanak, hogy mi is az a kifejezés, és hogyan kell létrehozni hasznos kifejezéseket. A kézikönyv hátralevő részében az expr alatt egy érvényes PHP kifejezést értünk.


10. Fejezet. Operátorok


Operátorok precedenciája

Az operátorok precedenciája azt határozza meg, hogy milyen "szorosan" köt össze két kifejezést. Például az 1 + 5 * 3 kifejezésben, a kifejezés értéke 16, és nem 18, mert a szorzás operátorának, a ("*")-nak nagyobb precedenciája van, mint az összeadásénak ("+"). Zárójelek segítségével tetszőleges precedenciát lehet felállítani egy kifejezésen belül, ha szükséges. Például a (1 + 5) * 3 eredménye 18 lesz.

[Az asszociativitás talán megér egy kis magyarázatot. Ez azt határozza meg, hogy az adott szinten levő operátorok egymás utáni, zárójel nélküli használatát hogyan értelmezi a fordító. Egy példán keresztül talán érthetőbbé válik: 1-2+3 értelmezhető (1-2)+3-nak (= 2), vagy 1-(2+3)-nak (= -4). Az előbbi kiértékelés, amely balról jobbra asszociatív, a helyes ebben az esetben. A második kiértékelés pedig jobbról balra asszociatív - ilyen lenne például a hatványozás, amely nincs a nyelvben implementálva (erre szolgál pow()). Ha a ** lenne a hatványozás, akkor a 2**3**2 helyesen 2 a 9-en = 512 lenne. Vannak nem köthető (nem asszociatív) operátorok is, ilyenek az összehasonlító operátorok. A PHP-ban tehát nem értelmes a 2<$x<4 kifejezés.]

Az alábbi táblázat az operátorokat precedenciájuk szerint növekvő sorrendben tartalmazza.

Táblázat 10-1. Operátorok precedenciája

asszociativitásoperátorok
balról jobbra,
balról jobbraor
balról jobbraxor
balról jobbraand
jobbról balraprint
balról jobbra= += -= *= /= .= %= &= |= ^= ~= <<= >>=
balról jobbra? :
balról jobbra||
balról jobbra&&
balról jobbra|
balról jobbra^
balról jobbra&
nem köthető== != === !==
nem köthető< <= > >=
balról jobbra<< >>
balról jobbra+ - .
balról jobbra* / %
jobbról balra! ~ ++ -- (int) (float) (string) (array) (object) @
jobbról balra[]
nem köthetőnew


Aritmetikai operátorok

Emlékszel az elemi aritmetikára a suliból? Ezek pont úgy működnek, mint ott.

Táblázat 10-2. Aritmetikai operátorok

PéldaNévEredmény
$a + $bÖsszeadás$a és $b összege
$a - $bKivonás$a és $b különbsége
$a * $bSzorzás$a és $b szorzata
$a / $bOsztás$a és $b hányadosa
$a % $bModulus$a / $b maradéka

Az osztás operátor ("/") mindig lebegőpontos számot ad eredményül, mégha mindkét operandus egész típusú vagy egész típusúvá alakított string.


Hozzárendelő operátorok

Az alapvető hozzárendelő operátor az "=". Elsőre azt hihetnénk, hogy ez az "egyenlő valamivel" jele. Valójában azt jelenti, hogy a bal oldali operandus [ami az egyenlőségjel bal oldalán áll] a jobb oldali kifejezést kapja értékül.

A hozzárendelő kifejezés értéke a bal oldalhoz rendelt érték. Vagyis a "$a = 3" értéke 3. Ez lehetőséget ad néhány trükkös dologra:

$a = ($b = 4) + 5; // $a most 9, és $b 4

Az alapvető hozzárendelő operátoron felül vannak ún. "kombinált" operátorok is az összes kétoperandusú aritmetikai és sztring operátorok számára, amelyek lehetővé teszik, hogy használjunk egy változót egy kifejezésben, majd rögtön be is állítsuk a változót a kifejezés értékére. Például:

$a = 3;
$a += 5; // $a-t 8-ra állítja, mintha  $a = $a + 5;-öt írtunk volna
$b = "Csecs ";
$b .= "Emő"; // $b "Csecs Emő" lesz, egyenértékű párja: $b = $b . "Emő";

A hozzárendelés az eredeti változót az újba másolja érték szerint, így az egyiken elvégzett változtatások a másikat nem érintik. Ezt fontos tudni, például egy sokszor végrehajtott ciklus belsejében nagy tömbök másolásakor. A PHP 4 támogatja a $var =&$othervar; szintaxisú referencia szerinti érték hozzárendelést is, de ez PHP 3-ban nem működik. A 'referencia szerinti értékhozzárendelés' azt jelenti, hogy mindkét változó ugyanarra az adatra fog mutatni, és nem történik meg a változó értékének lemásolása. További információkat a referenciákról a Referenciák részletesen című fejezetben olvashatsz.


Bitorientált operátorok

A bitorientált operátorok teszik lehetővé, hogy egész típusú számokon belül bizonyos biteket beállítsunk, vagy lefedjünk (maszkolás). Ha viszont az opertáron mindkét oldalán sztring típusú változó áll, akkor a bitorientált operátorok a sztringek karakterein dolgoznak úgy, hogy a karakterek ASCII kódjain végzik el a műveletet, és az eredményül adódó számot ASCII kóddal megadott karakternek értelmezi.

<?php
    echo 12 ^ 9; // '5' -öt ír ki

    echo "12" ^ "9"; // kiírja a visszaperjel karaktert (ASCII #8), mert
                     // ('1' (ASCII #49)) ^ ('9' (ASCII #57)) =  (ASCII #8)

    echo "hallo" ^ "hello"; // eredmény: #0 #4 #0 #0 #0
                            // 'a' ^ 'e' = #4
?>

Táblázat 10-3. Bitorientált operátorok

PéldaNévEredmény
$a & $bÉsOtt lesz '1' az eredményben, ahol $a és $b mindegyikében az a bit '1'-es. Minden más biten '0'.
$a | $bVagyOtt lesz '1' az eredményben, ahol $a és $b közül legalább az egyik azon a bitje '1'-es. Minden más biten '0'.
$a ^ $bKizáró vagyOtt lesz '1' az eredményben, ahol $a és $b közül csakis pontosan az egyikben '1' állt. Minden más biten '0'. [Más közelítésben ott lesz '1' az eredményben, ahol különböző bitek álltak $a-ban és $b-ben; megint más közelítésben $a azon bitjei invertálódnak, amely helyeken $b-ben '1' áll]
~ $aNem$a összes bitjét invertálja
$a << $bEltolás balra$a bitjeit $b számú bittel balra tolja (minden bitnyi eltolás 2-vel való szorzást jelent [amíg el nem fogynak a bitek, utolsó helyen előjelbit van ?!])
$a >> $bEltolás jobbra$a bitjeit $b számú bittel jobbra tolja (minden bitnyi eltolás 2-vel való egész-osztást jelent. [Vigyázz, negatív számot inkább ne tolj jobbra!])

Összehasonlító operátorok

Az összehasonlító operátorok, mint nevük is sugallja, két érték összehasonlítására szolgálnak.

Táblázat 10-4. Összehasonlító operátorok

PéldaNévEredmény
$a == $bEgyenlőIgaz (TRUE), ha $a és $b értéke egyenlő
$a === $bAzonosIgaz (TRUE), ha $a és $b értéke egyenlő, és azonos típusúak (csak PHP 4)
$a != $bNem egyenlőIgaz (TRUE), ha $a és $b értékei különbözők
$a <> $bNem egyenlőIgaz (TRUE), ha $a és $b értékei különbözők
$a !== $bNem azonosIgaz (TRUE), ha $a és $b értékei vagy típusai különbözők (csak PHP 4)
$a < $bKisebb mintIgaz (TRUE), ha $a szigorúan kisebb, mint $b
$a > $bNagyobb mintIgaz (TRUE), ha $a szigorúan nagyobb, mint $b
$a <= $bKisebb, vagy egyenlőIgaz (TRUE), ha $a kisebb, vagy egyenlő, mint $b
$a >= $bNagyobb, vagy egyenlőIgaz (TRUE), ha $a nagyobb, vagy egyenlő, mint $b

A feltételes "?:" (ternális) operátor úgyanúgy működik, mint C-ben és sok más nyelvben.

(kif1) ? (kif2) : (kif3);

A kifejezés kif2-t értékeli ki, ha kif1 igaznak bizonyul (TRUE), és kif3-at, ha kif1 hamis (FALSE).


Hibakezelő operátorok

A PHP egy hibakezelő operátort támogat, az at jelet (@ - kukac). PHP kifejezés elé írva a kifejezés által esetlegesen generált hibaüzenete(ke)t figyelmen kívül hagyja a rendszer.

Ha a track_errors szolgáltatás be van kapcsolva, bármilyen a kifejezés által generált hibaüzenet a $php_errormsg globális változóba kerül tárolásra. Ez a változó minden hiba esetén felülíródik, ezért használható információk kinyerése érdekében a kifejezést követően ezt minél hamarabb ellenőrizni kell.

<?php
/* Szándékos állomány megnyitási hiba */
$file = @file ('nem_letezo_allomany') or
    die ("Nem lehet megnyitni, a hiba: '$php_errormsg'");

// bármilyen kifejezésre működik, nem csak függvényekre
$ertek = @$tomb[$kulcs];
// nem ad notice szintű hibát, ha a $kulcs kulcs nem létezik
?>

Megjegyzés: A @ operátor csak kifejezésekre működik. Egyszerű ökölszabályként alkalmazandó, ha valaminek az értelmezett az értéke, akkor az elé a @ operátor is oda tehető. Ekképpen például használható változók, függvények és include() hívások, állandók neve előtt és sok más esetben. Nem használható azonban függvény és osztály definíciók vagy nyelvi szerkezetek (mint például if és foreach utasítások) előtt.

Lásd még: error_reporting()!

Figyelem

Jelenleg a "@" hibakezelő operátor kikapcsolja azon kritikus hibák jelentését is, amelyek megszakítják a szkript futását. Más problémák mellett, ha függvényből érkező hibaüzenetek elnyelésére használod a "@" jelet, le fog állni a szkript futása, ha nem létezik a megadott függvény vagy elírtad annak nevét.


Végrehajtó operátorok

A PHP-ban létezik egy program-végrehajtó operátor: a visszaidézőjel [aki tudja az igazi nevét, ne rejtse véka alá!] (``). Ezek nem szimpla idézőjelek! A PHP megpróbálja a sztring tartalmát parancssorból futtatandó utasításként végrehajtani, amelynek a kimenete lesz az operátor értéke. Ez nem egyszerűen a kimenetre kerül, hanem hozzárendelhető egy változóhoz.

[Az alábbi kis példa az aktuális könyvtár tartalmát (hosszú lista, rejtett fájlok is) formázva írja ki (fix szélességű betűket használva, újsor karaktereket tiszteletben tartva)]

$output = `ls -al`;
echo "<pre>$output</pre>";

Megjegyzés: A végrehajtó operatár nem használható, ha a safe mode be van kapcsolva.

Lásd még: escapeshellcmd(), exec(), passthru(), popen(), shell_exec() és system()!


Növelő/csökkentő operátorok

A PHP támogatja a C-szerű ún. elő- és utónövekményes ill. csökkentő operátorokat.

Táblázat 10-5. Növelő/csökkentő operátorok

PéldaNévHatás
++$aelőnövekményesNöveli $a-t eggyel, majd visszaadja $a értékét
$a++utónövekményesVisszaadja $a értékét, majd növeli $a-t eggyel
--$aelőcsökkentőCsökkenti $a-t eggyel, majd visszaadja $a értékét
$a--utócsökkentőVisszaadja $a értékét, majd csökkenti $a-t eggyel

Itt egy egyszerű példaprogram:

<?php
echo "<h3>Utónövekményes</h3>";
$a = 5;
echo "5-nek kell lennie: " . $a++ . "<br />\n";
echo "6-nak kell lennie: " . $a . "<br />\n";

echo "<h3>Előnövekményes</h3>";
$a = 5;
echo "6-nak kell lennie: " . ++$a . "<br />\n";
echo "6-nak kell lennie: " . $a . "<br />\n";

echo "<h3>Előcsökkentő</h3>";
$a = 5;
echo "5-nek kell lennie: " . $a-- . "<br />\n";
echo "4-nek kell lennie: " . $a . "<br />\n";

echo "<h3>Utócsökkentő</h3>";
$a = 5;
echo "4-nek kell lennie: " . --$a . "<br />\n";
echo "4-nek kell lennie: " . $a . "<br />\n";
?>


Logikai operátorok

Táblázat 10-6. Logikai operátorok

PéldaNévEredmény
$a and $bÉsPontosan akkor igaz (TRUE), ha mind $a mind $b igazak (TRUE).
$a or $bVagyPontosan akkor igaz (TRUE), ha $a és $b között van igaz (TRUE).
$a xor $bKizáró vagyPontosan akkor igaz (TRUE), ha $a és $b közül pontosan egy igaz (TRUE).
! $aTagadásPontosan akkor igaz (TRUE), ha $a nem igaz (TRUE).
$a && $bÉsPontosan akkor igaz (TRUE), ha mind $a mind $b igaz (TRUE).
$a || $bVagyPontosan akkor igaz (TRUE), ha $a és $b között van igaz (TRUE).

Az "és" és a "vagy" operátorok két variációjára a magyarázat az operátorok precedenciájában van. (Lásd: Operátorok Precedenciája.)


String operátorok

Két string operátor van. Az egyik az összefűzés operátor ('.'), amely bal és jobb oldali operandusának összefűzöttjével tér vissza. A második az összefűző-hozzárendelő operátor ('.='), amely hozzáfűzi a jobb oldalon szereplő szöveges értéket a bal oldali operandus végéhez. Olvasd el a Hozzárendelő operátorok című részt!

$a = "Para ";
$b = $a . "Zita"; // most $b értéke "Para Zita"

$a = "Dárdarázó ";
$a .= "Vilmos"; // most $a értéke "Dárdarázó Vilmos"


Tömb operátorok

Jelenleg a + az egyetlen tömb-operátor PHP-ban. A jobboldali tömböt a baloldalihoz fűzi úgy, hogy az ismétlődő indexen levő elem nem írja felül az eredeti elemet.

$a = array("a" => "alma", "b" => "banán");
$b = array("a" =>"körte", "b" => "áfonya", "c" => "cseresznye");

$c = $a + $b;

var_dump($c);
array(3) {
  ["a"]=>
  string(5) "alma"
  ["b"]=>
  string(6) "banán"
  ["c"]=>
  string(6) "cseresznye"
}


11. Fejezet. Vezérlési szerkezetek

Az összes PHP szkript utasítások sorozatából áll. Az utasítás lehet hozzárendelő utasítás, függvényhívás, ciklus, feltételes utasítás, vagy üres utasítás. Az utasítások általában pontosvesszővel végződnek. Ezenkívül az utasításokat csoportosítani lehet; utasításblokkba foglalhatók kapcsos zárójelek segítségével. Az utasításblokkok maguk is utasítások. A különféle utasítástípusokat ebben a fejezetben tárgyaljuk.


if

Az if szerkezet az egyik legfontosabb szerkezete a legtöbb nyelvnek - így a PHP-nek is. A PHP a C-ben megismerthez hasonló if szerkezettel bír:

if (kifejezés)
    utasítás

Amint a kifejezésekről szóló fejezetben szerepel, a kifejezés logikai értéke értékelődik ki. Ha kifejezés TRUE, akkor a PHP végrehajtja az utasítást; ha FALSE, akkkor figyelmen kívül hagyja. Arról, hogy mely értékek tekinthetők FALSE-nak, a Logikai értékké alakítás c. fejezetben olvashatsz.

Az alábbi példa kiírja, hogy a nagyobb, mint b, ha $a nagyobb, mint $b:

if ($a > $b)
    print "a nagyobb, mint b";

Gyakran sok utasítást kell feltételhez kötve végrehajtani. Természetesen nem kell minden utasításhoz külön if-et írni. Az utasításokat utasításblokkba lehet összefogni. Az alábbi kód például kiírja, hogy a nagyobb, mint b ha $a nagyobb, mint $b, és utána hozzárendeli $a értékét $b-hez:

if ($a > $b) {
    print "a nagyobb, mint b";
    $b = $a;
}

A feltételes utasítások vég nélkül további if utasításokba ágyazhatók, amely a program különböző részeinek feltételes végrehajtását igen hatékonnyá teszi.


else

Gyakori, hogy egy bizonyos feltétel teljesülése esetén valamilyen utasítást kell végrehajtani, és valamilyen másik utasítást, ha nem teljesül a feltétel. Erre való az else. Az else kibővíti az if utasítást, hogy akkor hajtson végre utasítást, amikor az if kifejezés FALSE-ként értékelődik ki. Az alábbi kód például kiírja, hogy a nagyobb, mint b ha $a $b-nél nagyobb, egyébként az a NEM nagyobb, mint b üzenetet írja ki:

if ($a > $b) {
    print "a nagyobb, mint b";
} else {
    print "a NEM nagyobb, mint b";
}

Az else utasítás csak akkor hajtódik végre, ha az if kifejezés és az összes elseif kifejezés is FALSE értékű. Az elseif -ről most olvashatsz.


elseif

Az elseif, amint azt a neve is sugallja, az if és az else kombinációja. [perlesek figyelem, itt elseif-nek hívják!!!] Az else-hez hasonlóan az if utasítást terjeszti ki, hogy különböző utasításokat hajtson végre abban az esetben, ha az eredeti if kifejezés értéke FALSE lenne. Azonban az else-sel ellentétben csak akkor hajtra végre az alternatív kódrészt, ha az elseif kifejezés TRUE. Az alábbi kód például - $a értékétől függően - üdvözli Menő Manót, és Víz Eleket, vagy kiírja, hogy ismeretlen:

if ($a == "Menő Manó") {
   print "Szervusz Menő Manó! Rég láttalak!";
} elseif ($a == 'Víz Elek') { #szimpla idézőjel is használható
   print "Üdv Víz Elek!";
} else {
   print "Szervusz, idegen. Hát téged mi szél hozott ide?";
}

Egy if kifejezést több elseif követhet. Az első olyan elseif kifejezés hajtódik végre (ha van), amely értéke TRUE. A PHP-ban az 'else if' is (különírva) használható és ugyanúgy fog viselkedni, mint az 'elseif' (egybeírva). A szintaktikai jelentés 'kicsit' eltérő (ha ismered a C-t, nos ez pont úgy működik) de végülis ugyanaz lesz a végeredmény.

Az elseif ág csak akkor hajtódik végre, ha az őt megelőző if kifejezés, és az összes köztes elseif kifejezések FALSE értékűek, de az adott elseif kifejezése TRUE.


Vezérlési szerkezetek alternatív szintaxisa

A PHP bizonyos vezérlési szerkezeteihez egy alternatív szintaxist is nyújt; név szerint: az if, while, for, foreach, és switch számára. Minden esetben az alternatív szintaxisnál a nyitó kapcsos zárójel helyett kettőspontot (:) kell írni, a záró zárójel helyett pedig a vezérlési szerkezetnek megfelelő endif;, endwhile;, endfor;, endforeach;, vagy endswitch; utasításokat értelemszerűen.

<?php if ($a == 5): ?>
A most éppen 5.
<?php endif; ?>

A fenti példában az "A most éppen 5." egy alternatív szintaxisú if kifejezésbe van ágyazva. A HTML rész csak akkor íródik ki, ha $a egyenlő 5-tel.

Az alternatív szintaxis az else-re és az elseif-re is alkalmazható. Az alábbi példa egy if szerkezet, amiben van elseif és else is alternatív formában:

if ($a == 0.5):
   print "a most fél.";
   print "De vajon kitől?";
elseif ($a == 8):
   print "Nekem nyolc, hogy mennyi az a.";
   print "Úgyis megváltoztatom az értékét.";
   $a++;
else:
   print "Ez így nem vicces, hogy a se nem fél, se nem nyolc";
endif;

Lásd még a while, for, és if szerkezeteket további példák reményében!


while

A while ciklusok a PHP legegyszerűbb ciklusai. Éppen úgy viselkednek, mint a C nyelvbeli megfelelőik. A while általános szintaxisa:

while (kifejezés) utasítás

A while utasítás jelentése egyszerű. Azt mondja a PHP-nek, hogy mindaddig ismételje az utasítás(ok) végrehajtását, amíg a while kifejezés TRUE. Iterációnak nevezzük azt, amikor a PHP egyszer végrehajtja az utasítást/utasításblokkot egy ciklus részeként. A kifejezés értéke a ciklus kezdetekor értékelődik ki, tehát még ha az utasításblokk belsejében hamissá is válik a feltétel, a blokk végrehajtása akkor sem áll meg, csak az iteráció végén [feltéve ha közben megint meg nem változik a feltétel]. Amikor a while kifejezés értéke már az első vizsgálatkor FALSE, akkor az utasítás(blokk) egyszer sem kerül végrehajtásra.

Az if szerkezethez hasonlóan több utasítást csoportosítani lehet a while ciklusban kapcsos zárójelekkel, vagy az alternatív szintaxis használatával:

while (kifejezés): utasítás ... endwhile;

Az alábbi példák ugyanazt csinálják - 1-től 10-ig kiírják a számokat:

/* 1. variáció */

$i = 1;
while ($i <= 10) {
    print $i++;  /* a kiírt érték $i, csak
                    utána növelünk
                    (post-inkrementáció) */
}

/* 2. variáció */

$i = 1;
while ($i <= 10):
    print $i;
    $i++;
endwhile;


do..while

A do..while ciklusok nagyon hasonlóak a while ciklusokhoz, a különbség mindössze annyi, hogy a kifejezés igaz volta itt az iteráció végén értékelődik ki, és nem az elején. A fő különbség a hagyományos while ciklushoz képest, hogy a do..while ciklus első iterációja garantáltan lefut (a kifejezés igazságértékét csak az iteráció végén ellenőrzi), amely nem garantált a hagyományos while ciklusnál (itt a kifejezés igazságértéke az iteráció kezdetén kerül kiértékelésre, ha értéke kezdetben FALSE, akkor a ciklus végrehajtása azonnal befejeződik).

Csak egy szintaxisa van a do..while ciklusnak:

$i = 0;
do {
   print $i;
} while ($i>0);

A fenti ciklus pontosan egyszer fut le, mert az első iteráció után, amikor a kifejezés igazságértéke vizsgálatra kerül, kiderül, hogy FALSE ($i nem nagyobb, mint 0) és a ciklus végrehajtása befejeződik.

Haladó C programozók már bizonyára jártasak a do..while ciklus másfajta használatában. Például utasításblokk közepén ki lehet lépni a blokkból, ha az utasításblokkot do..while(0), közé tesszük, és break utasítást használunk. A következő kódrészlet ezt szemlélteti:

do {
    if ($i < 5) {
        print "i nem elég nagy";
        break;
    }
    $i *= $factor;
    if ($i < $minimum_limit) {
        break;
    }
    print" i most jó";

     ...i feldolgozása...

} while(0);

Ne aggódj, ha ezt nem azonnal vagy egyáltalán értetted meg. Lehet szkripteket - sőt hatékony szkripteket - írni ennek a lehetőségnek a használata nélkül is.


for

A for cilus a legbonyolultabb ciklus a PHP-ben. Éppen úgy viselkedik, mint a C nyelvbeli párja (–> C-ben értőknek tovább gomb). A for ciklus szintaxisa:

for (kif1; kif2; kif3) utasítás

[A fenti for szerkezettel megegyező az alábbi, remélhetőleg már ismerős kifejezés:

kif1;
while (kif2) {
  utasítás;
  kif3;
}

Remélem így már érthetőbb lesz az alábbi magyarázat].

Az első kifejezés (kif1) a ciklus kezdetén egyszer kerül végrehajtásra.

Minden iteráció elején kif2 kiértékelődik. Ha értéke TRUE, akkor a ciklus folytatódik, és az utasításra kerül a vezérlés. Ha értéke FALSE, akkor a ciklus véget ér.

Minden iteráció végén kif3 is végrehajtásra kerül.

Bármelyik kifejezést el lehet hagyni. Ha kif2 üres, az azt jelenti, hogy a ciklus a végtelenségig fut [hacsak nem jön a jó tündér break utasítás képében...] (A PHP implicit TRUE-nak feltételezi az üres kif2-t, mint a C.) Ez nem annyira haszontalan, mint elsőre amennyire elsőnek tűnik, hiszen gyakran fejezheted be a ciklust egy feltételes kifejezésbe ágyazott break kifejezéssel a for feltétel kifejezésének kiértékelése helyett.

Nézd az alábbi példákat, mindegyikük kiírja a számokat 1-től 10-ig:

/* téma */

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

/* 1. variáció */

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

/* 2. variáció */

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

/* 3. variáció - Coda :-) */

for ($i = 1; $i <= 10; print $i, $i++);

Természetesen "a téma" a legbarátságosabb (vagy esetleg a 3. variáció). Sok helyen hasznos azonban, hogy üres kifejezés is írható for ciklusba...

A PHP a for ciklus esetén is megengedi az alternatív szintaxishasználatát:

for (kif1; kif2; kif3): utasítás; ...; endfor;

Más nyelvekben létezik az ún. foreach szerkezet tömbök vagy hash-ek bejárására. A PHP 3-ban nincs ilyen, de a PHP 4-ben implementálták (lásd: foreach). PHP 3-ban a while, a list() és az each() szerkezeteket használhatod erre a célra. Nézd meg ezeknek a dokumentációját alkalmazási példákért.


foreach

A PHP 4-ben (nem a PHP 3-ban!) a Perlhez és más nyelvekhez hasonlóan létezik az ún. foreach szerkezet is. Ez jól használható eszközt ad a tömbökön végzett iterációkhoz. Ha más típusú vagy inicializálatlan változóra nem lehet használni, azokra hibát jelez. Két szintaxisa létezik, a második egy apró, de hasznos kiegészítéssel nyújt többet az elsőhöz képest.

foreach(tömb_kifejezés as $ertek) utasítás
foreach(tömb_kifejezés as $kulcs => $ertek) utasítás

Az első forma végigmegy a tömb_kifejezés szolgáltatta tömbön. Minden alkalommal az aktuális elem értéke a $ertek változóba kerül, és a belső tömb mutató növelésre kerül. (A következő alkalommal tehát a soron következő elemet fogja venni).

A második forma ugyanezt végzi el, de az aktuális elem kulcsa a $kulcs változóba kerül.

Megjegyzés: Amikor a foreach indul, a belső tömb mutató az első elemre áll. Ez azt jelenti, hogy nem kell meghívni a reset() függvényt egy foreach ciklus előtt.

Megjegyzés: Szintén fontos megjegyezni, hogy a foreach függvény a megadott tömb egy másolatával dolgozik, nem magával a tömbbel, ezért az each()-el ellentétben az eredeti tömb mutatója nem változik meg, és a tömbön végzett módosítások sem kerülnek be az eredeti tömbbe.

Megjegyzés: A foreach nem támogatja a @ hiba-elnyelő operátor használatát!

Talán már tudod, hogy az alábbi példák egyenértékűek:

reset ($tomb);
while (list(, $ertek) = each ($tomb)) {
    echo "Érték: $ertek<br>\n";
}

foreach ($tomb as $ertek) {
    echo "Érték: $ertek<br>\n";
}

Az alábbiak is azonos eredményt szolgáltatnak:

reset ($tomb);
while (list($kulcs, $ertek) = each ($tomb)) {
    echo "Kulcs: $kulcs, Érték: $ertek<br>\n";
}

foreach ($tomb as $kulcs => $ertek) {
    echo "Kulcs: $kulcs, Érték: $ertek<br>\n";
}

Néhány további felhasználási példa:

/* első foreach példa: csak érték */

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

foreach ($tomb as $ertek) {
   print "Az aktuális értéke \$tomb-nek: $ertek.\n";
}

/* második foreach példa: érték (a kulcs csak illusztráció) */

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

$i = 0; /* csak pedagógiai okokból :) */

foreach ($tomb as $ertek) {
    print "\$tomb[$i] => $ertek.\n";
    $i++;
}

/* harmadik foreach példa: kulcs és érték */

$a = array (
    "egy" => 1,
    "kettő" => 2,
    "három" => 3,
    "tizenhét" => 17
);

foreach ($tomb as $kulcs => $ertek) {
    print "\$tomb[$kulcs] => $ertek.\n";
}

/* negyedik foreach példa: többdimenziós tömb */

$tomb[0][0] = "a";
$tomb[0][1] = "b";
$tomb[1][0] = "y";
$tomb[1][1] = "z";

foreach ($tomb as $belsotomb) {
    foreach ($belsotomb as $ertek) {
        print "$ertek\n";
    }
}

/* ötödik foreach példa: dinamikus tömbök */

foreach(array(1, 2, 3, 4, 5) as $ertek) {
    print "$ertek\n";
}


break

A break azonnal kilép az aktuális for, foreach, while, do..while ciklusból vagy switch szerkezetből.

A break elfogad egy elhagyható szám paramétert, amely megadja, hogy hány egymásba ágyazott struktúrából kell egyszerre 'kiugrani'.

$tomb = array ('egy', 'kettő', 'három', 'négy', 'stop', 'öt');
while (list (, $ertek) = each ($tomb)) {
    if ($ertek == 'stop') {
        break;    /* írhattál volna ide 'break 1;'-et is */
    }
    echo "$ertek<br>\n";
}

/* Az elhagyható paraméter használata */

$i = 0;
while (++$i) {
    switch ($i) {
    case 5:
        echo "5 esetén<br>\n";
        break 1;  /* csak a switch-ből lép ki */
    case 10:
        echo "10 esetén kilépés<br>\n";
        break 2;  /* a switch és a while befejezése */
    default:
        break;
    }
}


continue

A continue ciklusok belsejében használható arra, hogy átugorjuk az aktuális iteráció hátralevő részét, és a végrehajtást a következő iterációval folytassuk.

A continue elfogad egy elhagyható szám paramétert, amely megadja, hogy hány egymásba ágyazott struktúrának a hátralévő részét kell átugrani.

while (list ($kulcs, $ertek) = each ($tomb)) {
    if (!($kulcs % 2)) { // a páros indexűek kihagyása
        continue;
    }
    valami_paratlan_dolog ($ertek);
}

$i = 0;
while ($i++ < 5) {
    echo "Külső while<br>\n";
    while (1) {
        echo "&nbsp;&nbsp;Középső while<br>\n";
        while (1) {
            echo "&nbsp;&nbsp;Belső while<br>\n";
            continue 3;
        }
        echo "Ezt soha nem fogja kiírni.<br>\n";
    }
    echo "Ezt sem...<br>\n";
}


switch

A switch kifejezés hasonló egy sereg IF kifejezéshez, ahol a kifejezésekben ugyanaz szerepel. [Pont olyan, mint a C-ben, C-s gyakorlattal rendelkezőknek Tovább gomb]. Gyakori, hogy ugyanazt a változót (vagy kifejezést) kell összehasonlítani több különböző értékkel, és más-más kódot végrehajtani a változó (kifejezés) értékétől függően. Pontosan erre való a switch.

Az alábbi két példa két különböző módon írja ki ugyanazt, az egyik egy sor if kifejezést használ, a másik pedig a switch-et:

if ($i == 0) {
    print "i most 0";
}
if ($i == 1) {
    print "i most 1";
}
if ($i == 2) {
    print "i most 2";
}

switch ($i) {
    case 0:
        print "i most 0";
        break;
    case 1:
        print "i most 1";
        break;
    case 2:
        print "i most 2";
        break;
}

A hibák elkerülése végett fontos megérteni, hogy hogyan kerül végrehajtásra a switch szerkezet. A switch vagyis utasításról utasításra hajtódik végre. Nem hajtódik végre semmilyen utasítás, csak akkor, ha egy olyan case kifejezést talál a PHP, amely egyezik a switch kifejezés értékével. Ezután a PHP addig folytatja az utasítások végrehajtását, amíg el nem éri a switch blokk végét, vagy nem találkozik egy break utasítással. FONTOS! Ha nem nincs break egy case-hez tartozó utasítás(sorozat) végén, akkor a PHP végrehajtja a soron következő case-hez tartozó utasításokat is! Például:

switch ($i) {
    case 0:
        print "i most 0";
    case 1:
        print "i most 1";
    case 2:
        print "i most 2";
}

Itt, ha $i értéke 0, akkor a PHP az összes kiíró utasítást végrehajtja! Ha $i értéke 1, akkor a PHP az utolsó két print-et hajtja végre, és csak ha $i értéke 2, akkor kapod a 'kívánt' eredményt (csak az 'i most 2' íródik ki). Tehát nagyon fontos nem elfelejteni a break utasítást (bár bizonyos körülmények között lehet, hogy pont ennek elhagyása a szándékos).

A switch kifejezésben a feltétel csak egyszer értékelődik ki és a kapott eredmény lesz összehasonlítva a case kifejezések mindegyikével. Ha elseif kifejezéseket használsz, a kifejezések újra és újra kiértékelődnek. [és újra és újra be kell gépelni. Ez nem csak fárasztó, de hiba forrása is lehet.] Ha a kifejezés bonyolult, vagy egy ciklus belsejében van, a switch a gyorsabb.

Egy eset (case) utasításlistája üres is lehet, így a vezérlés a következő case-címkére adódik.

switch ($i) {
    case 0:
    case 1:
    case 2:
        print "i 3-nál kisebb, de nem negatív";
        break;
    case 3:
        print "i pont 3";
}

Egy különleges eset a default [alapértelmezett] címke. Ez a címke bármivel egyezik, amivel a korábbi case elemek nem egyeztek. Ennek kell az utolsó elemnek lennie. Például:

switch ($i) {
    case 0:
        print "i most 0";
        break;
    case 1:
        print "i most 1";
        break;
    case 2:
        print "i most 2";
        break;
    default:
        print "i se nem 0, se nem 1, se nem 2";
}

A case kifejezés tetszőleges kifejezés, aminek egyszerű a típusa, vagyis egész vagy lebegőpontos szám, vagy string. Tömbök és objektumok itt nem használhatók, csakis egy-egy elemük ill. változójuk egyszerű típusként.

Az alternatív szintaxis működik a switch-ekkel is. Bővebb információért lásd: Vezérlési szerkezetek alternatív szintaxisa.

switch ($i):
    case 0:
        print "i most 0";
        break;
    case 1:
        print "i most 1";
        break;
    case 2:
        print "i most 2";
        break;
    default:
        print "i se nem 0, se nem 1, se nem 2";
endswitch;


declare

A declare egy kódblokk számára adott futtatási direktívák beállítását teszi lehetővé. A declare szintaxisa hasonló a vezérlési szerkezetekéhez:

declare (direktíva) utasítás

A direktíva rész a declare blokk működését szabályozza. Jelenleg csak egy direktíva használható, a ticks. (Lásd lejjebb a ticks részleteit)

A declare blokk utasítás része mindig egyszer fut le. Az, hogy miképp, és milyen mellékhatásokkal, a direktíva részben megadottaktól függ.


Tick-ek

A tick egy olyan esemény, amely minden N db alacsony szintű utasítás végrehajtásakor bekövetkezik a declare blokkban. Az N értéket a ticks=N szintaxissal kell megadni a declare blokk direktíva részében.

Az egyes tick-ekre bekövetkező esemény(ek) a register_tick_function() függvénnyel állítható(ak) be. Lásd az alábbi példát. Akár több esemény is bekövetkezhet egy tick-re.

Példa 11-1. A PHP kód egy részének időmérése

<?php
// Ez a függvény megjegyzi a hívása időpontjait
function idopontok ($visszaadni = FALSE)
{

    static $idopontok;

    // Visszaadja a $profile tartalmát, és törli
    if ($visszaadni) {
        $idok = $idopontok;
        unset ($idopontok);
        return ($idok);
    }

    $idopontok[] = microtime();
}

// A tick kezelő beállítása
register_tick_function("idopontok");

// Beállítjuk az első időpontot a declare előtt
idopontok();

// A kódblokk futtatása, minden második utasítás egy tick
declare (ticks = 2) {
    for ($x = 1; $x < 50; ++$x) {
        echo similar_text (md5($x), md5($x*$x)), "<br />";
    }
}

// Az időmérő függvény adatainak kiírása
print_r (idopontok(TRUE));
?>
A fenti példa a declare blokkban lévő PHP kód sebességét méri, rögzítve minden második alacsonyszintű utasítás végrehajátásának időpontját. Ez az információ alkalmas lehet arra, hogy megtaláld a lassan futó részeket a kódodban. Ezt a hatást másképp is el lehet érni, de tick-eket használva sokkal kényelmesebb és könnyebben megvalósítható megoldást kapsz.

A tick-ek kiválóan alkalmasak hibakeresésre, egyszerű multitasking megvalósítására, háttérben futattott I/O-ra, és sok más feladatra.

Lásd még a register_tick_function() és az unregister_tick_function() függvényeket.


return

A return() utasítás függvényen belül használva azonnal befejezi a folyó függvény futását, és a paramétereként megadott érték szolgáltatja a függvény visszatérési értékét. A return() az eval() függvénnyel futatott kód vagy a szkript futását is leállítja.

A globális érvényességi körben használva a folyó szkript futását szakítja meg. Ha ez a szkript az include() vagy a require() hatására lett futtatva, akkor a vezérlés visszaadódik arra a fájlra, ahol ezek az utasítások szerepelnek, valamint include() esetén a return() paramétere lesz az include() utasítás visszatérési értéke. Ha a return() a fő szkriptben lett kiadva, akkor befejeződik a szkript futása. Ha ez a auto_prepend_file vagy auto_append_file konfigurációs beállításban szereplő fájlok valamelyikében történik (lásd: konfigurációs fájl) akkor, (csak) ezeknek a futása fejeződik be.

További magyarázatért lásd Visszatérési értékek c. fejezetet!

Megjegyzés: Mivel a return() nyelvi szerkezet és nem függvény, a paraméterét körülvevő zárójelek elhagyhatók. Valójában az a megszokottabb, hogy nem is használják, bár ez egyáltalán nem számít.


require()

A require() beilleszti és feldolgozza a megadott fájlt. Ennek részletes mikéntjéről, lásd include()!

A require() és az include() megegyezik egymással a hibakezelését leszámítva. Az include() nem fatális hibát, figyelmeztetést generál, a require() viszont fatális hibát jelez. Másszóval, ahol az igényelt fájl nemlétekor a futást meg kell szakítani, ajánlott a require(). Az include() nem így viselkedik, a hibától függetlenül a szkript futtatása folytatódik. Bizonyosodj meg, hogy a include_path helyesen van beállítva!

Példa 11-2. Egyszerű require() példák

<?php

require 'prepend.php';

require $valamifajl;

require ('valamifajl.txt');

?>

Lásd az include() oldalát még több példáért!

Megjegyzés: PHP 4.0.2 előtt, a következők szerint működött. A require() mindig beolvasta a kívánt fájlt, még ha az a require()-t tartalmazó sorra soha nem is került vezérlés. A feltételes szerkezetek nem befolyásolták a működését. Mégis, ha a require()-t tartalmazó sorra nem került vezérlés a megadott fájlban lévő kód nem futott le. Ehhez hasonlóan, a ciklusok sem befolyásolták a működését. Habár a fájlban szereplő kód függött az azt körülölelő ciklustól, a require() maga csak egyszer történt meg.

Figyelem

A PHP Windows rendszeren futó verziója a 4.3.0-ásnál régebbi változataiban nem támogatja a távoli állomány elérést e függvény használatakor, még akkor sem, ha az allow_url_fopen engedélyezett.

Lásd még: include(), require_once(), include_once(), eval(), file(), readfile(), virtual() és include_path!


include()

Az include() beilleszti és feldolgozza a megadott fájlt.

Az alábbiak igazak a require()-ra is. A require() és az include() megegyezik egymással a hibakezelését leszámítva. Az include() nem fatális hibát, figyelmeztetést generál, a require() viszont fatális hibát jelez. Magyarán, ahol az igényelt fájl nemlétekor a futást meg kell szakítani, ajánlott a require(). Az include() nem így viselkedik, a hibától függetlenül a szkript futtatása folytatódik. Bizonyosodj meg, hogy a include_path helyesen van beállítva!

A fájl beillesztése során a megadott fájl örökli az include() helyén érvényes változó hatáskört. Bármely változó, amely azon a ponton elérhető, elérhető a beillesztett fájlban is.

Példa 11-3. Egyszerű include() példa

valtozok.php
<?php

$szin     = 'zöld';
$gyumolcs = 'alma';

?>

teszt.php
<?php

echo "Egy $szin $gyumolcs"; // Egy

include 'valtozok.php';

echo "egy $szin $gyumolcs"; // Egy zöld alma

?>

Függvény belsejében a megadott fájlban szereplő kód úgy fog viselkedni, mintha az magában a függvényben szerepelt volna. Ez azt jelenti, hogy a fájl örökli a változók érvényességi körét.

Példa 11-4. Függvényen belüli beillesztés

<?php

function ize()
{
global $szin;

    include 'valtozok.php';

    echo "Egy $szin $gyumolcs";
}

/* valtozok.php az ize() függvény hatóköréébe esik, *
 * így a $gyumolcs nem elérhető a főggvényen kívül. *
 * A $szin igen, mivel globálisnak lett deklarálva. */

ize();                      // Egy zöld alma
echo "Egy $szin $gyumolcs"; // Egy zöld

?>

Ha egy fájlt beillesztünk az include()-dal vagy require()-ral, akkor a célfájl elején az elemző kilép a PHP módból HTML módba, majd visszaáll PHP módba a fájl végén. Ennek okán bármely beillesztendő fájlban levő PHP kódot közre kell fogni egy érvényes PHP kezdő- és zárójelöléssel.

Ha az include()-dal hívott fájl HTTP-n keresztül érkezik az "fopen wrapper"-ek használatával, és a célszerver PHP kódként feldolgozza a fájlt, akkor átadhatsz változókat a hívott fájlnak HTTP GET lekérési formában. Ez nem teljesen ugyanaz, mintha a include()-dal hívott fájl örökölné a helyi változókat, mivel a szkript valójában a távoli szerveren fut le, és a futási eredmény kerül beépítésre a helyi szkriptbe.

Figyelem

A PHP Windows rendszeren futó verziója a 4.3.0-ásnál régebbi változataiban nem támogatja a távoli állomány elérést e függvény használatakor, még akkor sem, ha az allow_url_fopen engedélyezett.

Példa 11-5. include() HTTP-n keresztül

/* Ezek a példák feltételezik, hogy a szerver be van állítva a .php      *
 * fájlok feldolgozására és nincs beállítva a .txt fájlok feldolgozására *
 * A 'működik' azt jelenti, hogy az $ize és $bigyo változók elérhetőek   *
 * a hívott fájlban.                                                     */

// Nem működik: a file.txt nem kerül feldolgozásra
include ("http://szerver/file.txt?ize=1&bigyo=2");

// Nem működik: egy 'file.php?ize=1&bigyo=2' nevű fájlt keres a helyi gépen
include ("file.php?ize=1&bigyo=2");

// Működik
include ("http://szerver/file.php?ize=1&bigyo=2");

$ize = 1;
$bigyo = 2;
include ("file.txt");  /* Működik */
incluie ("file.php");  /* Működik */
A kapcsolodó információkért lásd még: Távoli fájlok elérése, fopen() és file()

Mivel az include() és a require() különleges nyelvi elem, kapcsos zárójelekkel kell közrefogni, ha egy feltételes utasításon belül szerepel.

Példa 11-6. include() feltételes blokkon belül

/*Ez NEM JÓ, és nem a várt eredményt adja */

if ($feltetel)
    include($file);
else
    include($other);

/* Ez a HELYES */

if ($feltetel) {
    include($file);
} else {
    include($other);
}

return utasítást lehet elhelyezni egy include()-olt fájlban annak érdekében, hogy a kiértékelés ott befejeződjön, és visszaadjon egy értéket a hívó szkriptnek. A visszatérési értéket ugyanúgy használhatod, mint egy közönséges függvénynél.

Megjegyzés: PHP 3, a return nem jelenhet meg függvény blokkon kívül máshol, amely esetben a függvénybő ltörténő visszatérést jelöli.

Példa 11-7. Az include() és a return() utasítás

return.php
<?php

$var = 'PHP';

return $var;

?>

noreturn.php
<?php

$var = 'PHP';

?>

testreturns.php
<?php

$ize = include 'return.php';

echo $ize; // kiírja: 'PHP'

$bigyo = include 'noreturn.php';

echo $bigyo; // kiírja: 1

?>

$bigyo értéke 1, mert a beillesztés sikeres volt. Figyeld meg a különbséget a két fenti példa között. Az első a return() segítségével visszaadott egy értéket, a második nem. Létezik még néhány egyéb módja is változók beemelésének a fopen(), file() segítségével, vagy include() és Kimenet szabályzó függvények együttes használatával.

Lásd még: require(), require_once(), include_once(), readfile() és virtual()!


require_once()

Az require_once() beilleszt és feldolgoz fájlokat a program futása közben. Ez hasonló az require() működéséhez, azzal a fontos különbséggel, hogy ha a már egyszer beillesztésre került kódot a PHP nem próbálja meg ismét betölteni.

A require_once() használatos azokban az esetekben, amikor ugyanaz a fájl esetleg többször kerülhet beillesztésre a szkript futása során, de biztosítani kell, hogy ez ténylegesen csak egyszer történjen meg, így megelőzve a függvények újradefiniálását, változók értékének átállítását, stb.

További példákhoz az require_once() és include_once() használatához nézd meg a PEAR kódot, ami a legfrissebb PHP disztribúciókban megtalálható.

Megjegyzés: A require_once() PHP 4.0.1pl2 verzióban került a nyelvbe.

Megjegyzés: Különös figyelemmel kell lenni arra, hogy hogyan viselkedik a a require_once() és a include_once() olyan operációs rendszereken, ahol az állománynevek nem nagybetűérzékenyek (mint pl. Windows)

Példa 11-8. require_once() nagybetűérzékeny

require_once("a.php"); // a.php kerül beillesztésre
require_once("A.php"); // ismét a.php kerül beillesztésre pl. Windows-on!

Figyelem

A PHP Windows rendszeren futó verziója a 4.3.0-ásnál régebbi változataiban nem támogatja a távoli állomány elérést e függvény használatakor, még akkor sem, ha az allow_url_fopen engedélyezett.

Lásd még: include(), require(), include_once(), get_required_files(), get_included_files(), readfile() és virtual()!


include_once()

Az include_once() beilleszt és feldolgoz fájlokat a program futása közben. Ez hasonló az include() működéséhez, azzal a fontos különbséggel, hogy ha a már egyszer beillesztésre került kódot a PHP nem próbálja meg ismét betölteni.

Az include_once() használatos azokban az esetekben, amikor ugyanaz a fájl esetleg többször kerülhet beillesztésre a szkript futása során, de biztosítani kell, hogy ez ténylegesen csak egyszer történjen meg, így megelőzve a függvények újradefiniálását, változók értékének átállítását, stb.

További példákhoz az require_once() és include_once() használatához nézd meg a PEAR kódot, ami a legfrissebb PHP disztribúciókban megtalálható.

Megjegyzés: Az include_once() PHP 4.0.1pl2 verzióban került a nyelvbe.

Megjegyzés: Különös figyelemmel kell lenni arra, hogy hogyan viselkedik a a require_once() és a include_once() olyan operációs rendszereken, ahol az állománynevek nem nagybetűérzékenyek (mint pl. Windows)

Példa 11-9. require_once() nagybetűérzékeny

require_once("a.php"); // a.php kerül beillesztésre
require_once("A.php"); // ismét a.php kerül beillesztésre pl. Windows-on!

Figyelem

A PHP Windows rendszeren futó verziója a 4.3.0-ásnál régebbi változataiban nem támogatja a távoli állomány elérést e függvény használatakor, még akkor sem, ha az allow_url_fopen engedélyezett.

Lásd még: include(), require(), require_once(), get_required_files(), get_included_files(), readfile() és virtual()!


12. Fejezet. Függvények

Felhasználó által definiált függvények

Függvényeket a következő szintaxis szerint definiálhatod:

function foo ($arg_1, $arg_2, ..., $arg_n)
{
    echo "Példa függvény.\n";
    return $retval;
}

Bármely érvényes PHP kód megjelenhet egy függvényen belül, akár még más függvény vagy osztály definíciók is.

PHP 3-ban a függvényeket definiálni kell, mielőtt hivatkozás történik rájuk (függvényhívás előtt). PHP 4-ben nincs ez a megkötés.

A PHP nem támogatja a függvények polimorfizmusát (többalakúságát), a függvényekdefiníciókat nem lehet megszüntetni vagy újradefiniálni egy már definiált függvényeket.

A PHP 3 nem támogatja a változó számú függvényargumentumokat, bár az argumentumok kezdőértéke támogatott. Lásd az Argumentumok kezdőértéke című részt bővebb információért. A PHP 4 mindkettő lehetőséget támogatja. Lásd a Változó számú függvényargumentumok című részt és a func_num_args(), func_get_arg() és a func_get_args() függvényeket részletesebb leírásért.


Függvényargumentumok

Az információ a függvényekhez az argumentumlistán keresztül jut el, ami egy vesszővel határolt változó és/vagy konstanslista.

A PHP támogatja az érték szerinti (ez az alapértelmezett) referenciakénti paraméterátadást is, és az argumentumok kezdőértékét. A változó hosszúságú argumentumlisták csak a PHP 4-ben jelentek meg. Lásd a változó hosszúságú argumentumlistákat és a func_num_args(), func_get_arg() és a func_get_args() függvényeket részletesebb leírásért. PHP 3-ban hasonló hatás érhető el a függvénynek tömb típusú változó paraméterként történő átadásával:

function tombot_kezel($input)
{
    echo "$input[0] + $input[1] = ", $input[0]+$input[1];
}


Referencia szerinti argumentumfeltöltés

Alapértelmezésben a függvény paraméterei érték szerint adódnak át (vagyis ha megváltoztatod a változót a függvényen belül, annak a függvényen kívülre nincs hatása). Ha szeretnéd megengedni, hogy a függvény módosítsa az átadott paramétereket, referencia szerint kell átadni azokat.

Ha egy függvényargumentum mindig referencia szerint kell átadni, akkor a függvénydefinícióban az argumentum neve elé egy & jelet kell írni.

function fgv_extrakkal(&$string)
{
    $string .= 'és a szükséges plusssz.';
}
$str = 'Ez egy karakterfüzér, ';
fgv_extrakkal($str);
echo $str;    // kiírja, hogy 'Ez egy karakterfüzér, és a szükséges plusssz.'


Argumentumok kezdőértékei

Bármely függvény skalár-argumentumainak megadhatsz kezdőértéket a C++ szintaxisnak megfelelően:

function kavet_csinal ($tipus = "cappucino")
{
    return "Csinálok egy pohár " . $tipus . "t.\n";
}
echo kavet_csinal ();
echo kavet_csinal ("espresso");

A fenti kód kimenete:
Csinálok egy pohár cappucinot.
Csinálok egy pohár espressot.

A kezdőértéknek konstans kifejezésnek kell lennie, nem lehet pl. változó vagy objektum.

Figyelj arra, hogy a kezdőértékkel rendelkező argumentumok más argumentumoktól jobbra helyezkedjenek el; különben a dolgok nem úgy mennek majd, ahogy azt várnád [hanem úgy, ahogy írtad :)]. Lásd a következő kódot:

function joghurtot_keszit ($type = "acidophilus", $flavour)
{
    return "Készítek egy köcsög $flavour ízű $type-t.\n";
}

echo joghurtot_keszit ("eper");   // nem úgy működik, mint szeretnéd !?!?

A fenti példa kimenete:
Warning: Missing argument 2 in call to joghurtot_keszit() in
/usr/local/etc/httpd/htdocs/phptest/functest.php on line 41
Készítek egy köcsög ízű eper-t.

Most hasonlítsd össze az alábbival:

function joghurtot_keszit ($flavour, $type = "acidophilus")
{
    return "Készítek egy köcsög $flavour ízű $type-ot.\n";
}

echo joghurtot_keszit ("eper");   // ez már jó

A fenti példa kimenete:
Készítek egy eper ízű acidophilus-t.

Megjegyzés: [Azért vannak kiskapuk... Az argumentumokat adjuk át egy asszociatív tömbben! Az alapértékeket pedig egy másik tömbben. Ezután vegyük végig az alapértékeket tartalmazó tömb elemeit. Ha nem definiáltak a kapott tömbben, akkor írjuk felül az alapértékeket tartalmazó tömb megfelelő elemével. Így bármelyik argumentum elhagyható, sőt még annyit is nyerünk a dolgon, hogy nem kell megjegyeznünk a paraméterek sorrendjét. (forrás: egy bő lére eresztett amerikai PHP 3 könyv)]


Változó hosszúságú argumentumlista

A PHP 4 támogatja a változó hosszúságú argumentumlistát a felhasználók által definiált függvényekben. Valóban nagyon egyszerű kezelni ezt a func_num_args(), func_get_arg() és a func_get_args() függvényekkel.

Semmilyen különleges szintakszist nem igényel és az argumentumlista lehet explicit módon adott és viselkedhet úgy is, mint egy normál függvény.


Visszatérési értékek

Az elhagyható return állítást használva adhatnak vissza értéket a függvények. Bármely típus visszaadható, beleértve a listákat és az objektumokat is. A függvény végrehajtása azonnal befejeződik, és a vezérlés visszakerül a függvényhívás utáni pozícióba. További részletes információkért lásd: return()!

function negyzete ($num)
{
    return $num * $num;
}
echo negyzete (4);   // kiírja '16'.

Megjegyzés: [Ha nincs return, az utolsó kifejezés értékével tér viszsza a függvény]

Több értéket nem tud visszaadni a függvény, de hasonló hatás érhető el ezen többszörös értékek listába szervezésével.

function kis_szamok()
{
    return array (0, 1, 2);
}
list ($nulla, $egy, $ketto) = kis_szamok();

Ha a függvénynek referenciával kell visszatérnie, akkor az & referencia operátort kell alkalmaznod a függvény deklarásákor és a a visszatérési érték megadásakor is.

function &referenciat_ad_vissza()
{
    return &$valtozo;
}

$hivatkozas = &referenciat_ad_vissza();

További információkért lásd a Referenciák fejezetet!


old_function

Az old_function kifejezés lehetővé teszi függvény deklarálását a PHP/FI2 szintakszisnak megfelelően (kivéve persze, hogy a 'function'-t ki kell cserélned 'old_function'-ra)

Ez egy ellenjavallt tulajdonság, és csak a PHP/FI2->PHP 3 konverter használhatja.

Figyelem

Az old_function segítségével deklarált függvényeket nem hívhatod a PHP belső részéből. Több minden mellett ez azt jelenti, hogy nem használhatod olyan függvényekben, mint az usort(), array_walk(), és a register_shutdown_function(). Ez a korlátozás megkerülhető egy olyan keretfüggvény megírásával (normál PHP 3 formában), amely meghívja az old_function-t.


Függvényváltozók

A PHP lehetővé teszi a függvényváltozók használatát. Ha egy változónevet kerek zárójelek követnek, akkor a PHP megkeresi a változó értékével azonos nevű függvényt, és megpróbálja azt végrehajtani. Ezt többek között visszahívandó (callback) függvények vagy függvénytáblák implementálására használható.

A függvényváltozók nem fognak működni az olyan nyelvi elemekkel, mint például az echo(), unset(), isset(), empty() vagy include() és print().

Példa 12-1. Függvényváltozó példa

<?php
function ize()
{
    echo "Az ize()-ben<br>\n";
}

function bigyo($param = '')
{
    echo "A bigyo()-ban; az argumentum:'$param'.<br>\n";
}

$func = 'ize';
$func();
$func = 'bigyo';
$func('Stex van Boeven');
?>

Lásd még a változó változókat és a function_exists() függvényt.


13. Fejezet. Osztályok, objektumok

class

Az osztály (objektumtípus) változók és rajtuk műveletet végző függvények [metódusok] együttese. Osztályt az alábbi szintakszis szerint lehet definiálni:

<?php
class Kosar
{
    var $dolgok;  // A kosárban levő dolgok
   
    // berak a kosárba $db darabot az $sorsz indexű dologból
 
    function berak ($sorsz, $db)
    {
        $this->dolgok[$sorsz] += $db;
    }
   
    // kivesz a kosárból $db darabot az $sorsz indexű dologból
 
    function kivesz ($sorsz, $db)
    {
        if ($this->items[$sorsz] > $db) {
            $this->items[$sorsz] -= $db;
            return true;
        } else {
            return false;
        }   
    }
}
?>

Ez definiál egy Kosar nevű osztályt, ami a kosárban levő áruk asszociatív tömbjéből áll, és definiál 2 funkciót hozzá, hogy bele lehessen rakni, illetve kivenni a kosárból.

Figyelem

Az alábbi figyelmeztetések a PHP 4-es verziójára érvényesek.

Az stdClass név le van foglalva, mivel belsőleg a Zend motor használja. Emiatt nem lehet egy stdClass nevű osztályod PHP-ben.

A __sleep és __wakeup nevek speciálisak a PHP osztályokban. Nem szabad ezeket a neveket használni a metódusokhoz, hacsak nem a hozzájuk tartozó speciális funkcionalitást szeretnéd felülírni. Lásd az alábbi részletes leírást.

A PHP számára lefoglalt az összes __ karakterekkel kezdődő metódusnév, mint speciális név. Nem szabad __ karakterekkel kezdődő metódusnevet adni, hacsak nem a dokumentált funkciókat szeretnéd használni.

Megjegyzés: PHP 4-ben csak állandó értékű var inicializáló értékek megengedettek. Ha nem állandó értéket szeretnél beállítani, írnod kell egy inicializáló metódust, ami automatikusan meghívódik, amikor egy objektumpéldány létrejön az osztályból. Az ilyen metódusokat hívjuk konstruktoroknak (lásd lentebb).

/* Egyik alábbi értékadás sem működik PHP 4-ben */
class Kosar
{
    var $mai_datum = date("Y. m. d.");
    var $nev = $csaladi_nev;
    var $tulajdonos = 'Ferenc ' . 'János';
    var $termekek = array("Videó", "TV");
}

/* Így kell a fenti beállításokat elérni */
class Kosar
{
    var $mai_datum;
    var $nev;
    var $tulajdonos;
    var $termekek;

    function Kosar()
    {
        $this->mai_nap = date("Y. m. d.");
        $this->nev = $GLOBALS['csaladi_nev'];
        /* stb. . . */
    }
}
?>

Az osztályok típusok, vagyis az aktuális változók tervrajzai. A kívánt típusú változót a new operátorral hozhatod létre.

$kosar = new Kosar;
$kosar->berak("10", 1);

$masik_kosar = new Kosar;  
$masik_kosar->berak("0815", 3);

Ez létrehozza a Kosar objektumosztály $kosar és $masik_kosar nevű objektumpéldányait. A $kosar objektum berak() függvényét meghívtuk, hogy a 10-es számú árucikkből rakjon 1 darabot a kosárba. Három darab 0815 számú ternék került a $masik_kosar nevű kosárba.

Mind a $kosar, mind a $masik_kosar objektumoknak megvannak a berak() és kivesz() metódusai, és tulajdonságai. Ezek azonban egymástól független metódusok és tulajdonságok. Az objektumokról hasonlóan gondolkozhatsz, mint a könyvtárakról az állományrendszerben. Lehetséges, hogy két különböző OLVASSEL.TXT állományod van, ha ezek két különböző könyvtárban vannak. Úgy mint a könytáraknál, ahol meg kell adnod a teljes elérési utat, hogy egy állományra szeretnél hivatkozni a gyökérkönyvtárban, a teljes metódusnevet meg kell adnod, hogy meg tudd azt hívni. A PHP nyelvben a gyökérkönyvtár analógiája a globális környezet, és az elérési út elválasztója a ->. Ezért a $kosar->dolgok név és a $masik_kosar->dolgok név két különböző változót ad meg. Figyeld meg, hogy a változót $kosar->dolgok néven kell elérni, és nem $kosar->$dolgok néven, azaz a PHP változók neveiben csak egy dollárjelet kell tenned.

// helyes, egy dollárjel
$kosar->dolgok = array("10" => 1);

// helytelen, mivel a $kosar->$dolgok értelme $kosar->""
$kosar->$dolgok = array("10" => 1);

// helyes, de lehetséges, hogy nem a megcélzott eredmény
// $kosar->$valtozo értelme $kosar->dolgok
$valtozo = 'dolgok;
$kosar->$valtozo = array("10" => 1);

Egy osztály definiálásakor nem tudhatod, milyen néven lesz majd elérhető az objektumod a PHP programban: a Kosar osztály készítése idején nem volt ismert, hogy később $kosar vagy $masik_kosar néven nevezzük-e majd az objektumpéldányt. Ezért nem írhatod a Kosar osztályban, hogy $kosar->dolgok. De hogy el tudjad érni az osztály saját metódusait és tulajdonságait az objektumpéldány(ok) nevétől függetlenül, használhatod a $this kvázi-változót, amit 'a sajátom' vagy 'az aktuális objektumpéldány' értelemben alkalmazhatsz. Ezért a '$this->dolgok[$sorsz] += $db' úgy olvasható, hogy 'adj $db darab $sorsz sorszámú terméket a saját dolgok tömbömhöz', vagy 'adj $db darab $sorsz sorszámú terméket az aktuális objektumpéldány dolgok tömbjéhez'.

Megjegyzés: Van pár hasznos függvény az osztályok és objektumok kezeléséhez. Lásd az Osztály és objektum függvények című részt.


extends

Gyakori, hogy szeretnél olyan osztályokat kialakítani, amelyek egy már meglévő osztályhoz hasonló tulajdonságokkal és metódusokkal rendelkeznek. Tulajdonképpen jó gyakorlat egy általános osztályt definiálni, amit minden projektedben használhatsz, és ezt az osztályt alakítani az egyes projektek igényeinek megfelelően. Ennek a megvalósítása érdekében az osztályok lehetnek más osztályok kiterjesztései. A kiterjesztett, vagy származtatott osztály minden tulajdonággal és metódussal rendelkezik, ami a kiindulási osztályban megvolt (ezt nevezzük öröklésnek, bár senki sem hal meg a folyamat során). Amit hozzáadsz a kiindulási osztályhoz, azt nevezzük kiterjesztésnek. Nem lehetséges megcsonkítani egy osztályt, azaz megszüntetni egy metódust, vagy tulajdonságot. Egy leszármazott osztály mindig pontosan egy alaposztálytól függ, azaz egyidejűéleg többszörös leszármaztatás nem támogatott. A kiterjesztés kulcsszava az 'extends'.

class Gazdas_Kosar extends Kosar
{
    var $tulaj;

    function tulajdonosa ($nev)
    {
        $this->tulaj = $nev;
    }
}

Ez definiál egy Gazdas_Kosar nevű osztályt, ami a Kosar összes változójával és metódusával rendelkezik, és van egy saját változója, a $tulaj, no meg egy saját metódusa, a tulajdonosa(). A gazdás kosarat a hagyományos módon hozhatod létre, és a kosár tulajdonosát is be tudod állítani, le tudod kérdezni [ebben az esetben favágó módszerrel]. A gazdás kosarakon továbbra is lehet használni a Kosar függvényeit:

$gkosar = new Gazdas_Kosar;  // Gazdás kosár létrehozása
$gkosar->tulajdonosa ("Namilesz Teosztasz"); // a tulaj beállítása
print $gkosar->tulaj;        // a tulajdonos neve
$gkosar->break ("10", 1);    // (Kosar-ból öröklött funkcionalitás)

Ezt "szülő-gyermek" kapcsolatnak is hívják. Egy osztály akkor válik szülőosztállyá, ha más osztály létrehozásakor ezt veszik alapul az extends kulcsszó használatával. Ezzel a kiterjesztéssel definiált osztályt hívjuk gyermek-osztálynak -- ebben a kapcsolatban. Ugyanis ezek után ez a gyermekosztály is lehet más osztályok szülőosztálya, ha belőle is származtatnak egy osztályt.

Megjegyzés: Az osztálydefinicióknak a további felhasználásuk előtt rendelkezésre kell állniuk! Ha a Gazdas_Kosar-ra van szükség a Kosar kiterjesztéseként, akkor előbb a Kosar osztályt kell definiálni. Ha egy újabb osztályt származtatunk Sarga_Gazdas_Kosar néven a Gazdas_Kosar osztályból, akkor a Gazdas_Kosar osztálydefiniciónak előbb kell szerepelnie. Röviden, az osztálydefiniciók sorrendje nagyon fontos. Az osztálydefiníciókat hierarchia legfelső szintjén álló osztállyal kell kezdeni, azzal, amelyik minden más osztálynak az ősének számít (szülő vagy nagy-, déd-, ük-, szépszülő).


Konstruktor

Figyelem

A PHP 3 és PHP 4 konstruktorok különbözőképpen működnek. A PHP 4 megvalósítása erősen javasolt.

A konstruktorok az osztályok olyan metódusai, amelyek automatikusan meghívásra kerülnek egy új objektumpéldány new kulcsszóval történő létrehozása során. A PHP 3-ban egy metódus akkor tekinthető konstruktornak, ha a neve megyezik az osztály nevével. A PHP 4-ben egy metódus akkor lesz kostruktorrá, hogy a neve megegyezik annak az osztálynak a nevével, ahol deifiniálták. A különbség hajszálnyi, de kritikus (lásd lentebb).

// A PHP 3 és PHP 4 verziókban is működik
class Auto_Kosar extends Kosar
{
    function Auto_Kosar ()
    {
        $this->berak ("10", 1);
    }
}

Ez egy olyan Auto_Kosar nevű osztályt [objektumtípust] hoz létre, mint a Kosar, csak rendelkezik egy konstruktorral, amely inicializálja a kosarat 1 darab "10"-es áruval, valahányszor a new operátorral hozzuk létre az objektumot. [de csak akkor!!!] A konstruktoroknak is lehet átadni paramétereket, és ezek lehetnek elhagyhatók is, amely még hasznosabbá teszi őket. Ha paraméterek nélkül is használható osztályt szeretnél, állíts be minden paraméternek alapértéket.

// A PHP 3 és PHP 4 verziókban is működik
class Konstruktoros_Kosar extends Kosar
{
    function Konstruktoros_Kosar ($sorsz = "10", $db = 1)
    {
        $this->berak ($sorsz, $db);
    }
}
 
// Mindig ugyanazt az uncsi dolgot veszi...
 
$kiindulo_kosar = new Konstruktoros_Kosar;
 
// Igazi vásárlás
 
$masik_kosar = new Konstruktoros_kosar ("20", 17);

Az @ operátor használatával elnémíthatók a konstruktorban fellépő hibák, használata ilyen esetben: @new.

Figyelem

A PHP 3-ban a leszármazott osztályokra és konstrukrotokra számos korlátozás van. Az alábbi példákat érdemes alaposan áttekinteni, hogy megértsd ezeket a korlátozásokat.

class A
{ 
    function A()
    { 
        echo "Én vagyok az A osztály konstruktora.<br>\n"; 
    } 
} 
    
class B extends A
{
    function C()
    {
        echo "Én egy metódus vagyok.<br>\n";
    }
}

// PHP 3-ban semmilyen konstruktor sem kerül meghívásra
$b = new B;

PHP 3-ban semmilyen konstruktor sem kerül meghívásra a fenti példában. A PHP 3 szabálya a következő: 'A konstruktor egy metódus, aminek ugyanaz a neve, mint az osztálynak'. Az osztály neve B, és nincs B() nevű metódus a B osztályban. Semmi sem történik.

Ez a PHP 4-ben ki van javítva egy másik szabály bevezetésével: Ha az osztályban nincs konstruktor, a szülő osztály konstruktora hívódik meg, ha létezik. A fenti példa kimenete 'Én vagyok az A osztály konstruktora.<br>' lett volna PHP 4-ben.

class A
{
    function A()
    {
        echo "Én vagyok az A osztály konstruktora.<br>\n";
    }

    function B()
    {
        echo "Én egy B nevű metódus vagyok az A osztályban.<br>\n";
        echo "Nem vagyok A konstruktora.<br>\n";
    }
}

class B extends A
{
    function C()
    {
        echo "Én egy metódus vagyok.<br>\n";
    }
}

// Ez meghívja B()-t, mint konstruktort
$b = new B;

A PHP 3-ban az A osztály B() metódusa hirtelen konstruktorrá válik a B osztályban, habár ez soha sem volt cél. A PHP 3 szabálya: 'A konstruktor egy metódus, aminek ugyanaz a neve, mint az osztálynak'. A PHP 3 nem foglalkozik azzal, hogy a metódus a B osztályban van-e definiálva, vagy öröklés útján áll rendelkezésre.

Ez a PHP 4-ben ki van javítva egy másik szabály bevezetésével: 'A konstruktor egy metódus, aminek ugyanaz a neve, mint az osztálynak, ahol deifiniálták'. Ezért a PHP 4-ben a B osztálynak nincs saját konstruktora, így a szülő osztály kostruktora hívódik meg, kiírva, hogy 'Én vagyok az A osztály konstruktora.<br>'.

Figyelem

Sem a PHP 3, sem a PHP 4 nem hívja meg a szülő osztály konstruktorát automatikusan egy leszármazott osztály definiált konstruktorából. A te feladatod, hogy meghívd a szülő konstruktorát, ha szükséges.

Megjegyzés: Nem léteznek destruktorok sem a PHP 3 sem a PHP 4 verzióiban. Bár használhatod a register_shutdown_function() függvényt a destruktorok legtöbb viselkedésének eléréséhez.

A destruktor olyan metódus, ami automatikusan meghívódik, amikor egy objektum megszűnik, akár az unset() meghívásával, akár a környezete megszűnése miatt. PHP-ben nincsenek destruktorok.


::

Figyelem

Az alábbiak csak PHP 4-ben érvényesek.

Időnként hasznos az ősosztályok metódusaira vagy tulajdonságaira hivatkozni, vagy olyan osztálymetódusokat meghívni, amelyek nem példányosított objektumokhoz tartoznak. A :: operátor erre használható.

class A
{
    function pelda()
    {
        echo "Én az eredeti A::pelda() metódus vagyok.<br>\n";
    }
}

class B extends A
{
    function pelda()
    {
        echo "Én a felüldefiniáló B::pelda() metódus vagyok.<br>\n";
        A::example();
    }
}

// nincs semmilyen objektum az A osztályból
// ez azonban ki fogja írni:
//   Én az eredeti A::pelda() metódus vagyok.<br>
A::pelda();

// B egy objektuát hozzuk létre
$b = new B;

// ez ki fogja írni:
//   Én a felüldefiniáló B::pelda() metódus vagyok.<br>
//   Én az eredeti A::pelda() metódus vagyok.<br>
$b->pelda();

A fenti példa meghívja az A osztály pelda() metódusát, habár nincs konkrét példányunk az A osztályból, tehát ezt nem írhatnánk le az $a->pelda()-hoz hasonlóan. Ehelyett a pelda() egy 'osztálymetódusként' viselkedik, azaz az osztály egy függvényeként, és nem egy példány metódusaként.

Osztálymetódusok léteznek, de osztálytulajdonságok (változók) nem. Mivel a hívás pillanatában semmilyen objektum nem létezik, egy osztálymetódus nem használhat objektum változókat, és egyáltalán nem használhatja a $this speciális referenciát. Egy objektummetódus azonban természetesen dolgozhat globális változókkal és lokális változókkal is.

A fenti példa a B osztályban felüldefiniálja a pelda() metódust. Az A osztálytól örökölt eredeti definíció eltűnik, és többé nem érhető el, hacsak nem az A osztályban megvalósított pelda() függvényre hivatkozol közvetlenül, a :: operátor segítségével. Ennek eléréséhez A::pelda()-t kell használni (ebben az esetben írhatnál parent::pelda()-t is, ahogy az a következő szakaszban olvasható).

Ebben a környezetben van aktuálisan használt objektum, és ennek lehetnek objektum változói (tulajdonságai). Ekképpen ha egy objektummetóduson belül használod ezt az operátort, akkor alkalmazhatod a $this-t, és felhasználhatod az objektum tulajdonságait.


parent

Gyakran van szükség arra, hogy a szülő tulajdonságaira vagy metódusaira hivatkozzunk leszármazott osztályokban. Ez különösen igaz, ha a leszármazott osztály egy finomítása, vagy specializálása az alaposztálynak.

Ahelyett, hogy a szülő osztály nevét megadd minden ilyen meghíváskor (mint a hogy a :: operátor példája mutatta), használhatod a parent speciális nevet, ami tulajdonképpen a szülő osztály nevét jelenti, amit az extends kulcsszónál megadtál. Ennek a speciális névnek a használatával elkerülöd a szülő osztály nevének ismétlődését. Ha a megvalósítás során a leszármazási fát meg kell változtatni, csak egy helyen, az extends kulcsszónál kell átírnod a nevet.

class A
{
    function pelda()
    {
        echo "Én A::pelda() vagyok egyszerű funkcióval.<br>\n";
    }
}

class B extends A
{
    function pelda()
    {
        echo "Én B::pelda() vagyok több funkcióval.<br>\n";
        parent::pelda();
    }
}

$b = new B;

// Ez a B::pelda() metódust hívja, ami az A::pelda()-t hívja
$b->pelda();


Objektumok szerializációja, objektumok session-ökben

Megjegyzés: A PHP 3-ban az objektumok elveszítik az osztály-hozzárendelésüket a szerializációs, és deszerializációs folyamat során. Az eredmény objektum típusú, de nem tartozik semelyik osztályhoz, és nincs egy metódusa sem, tehát eléggé használhatatlan (csupán egy tömb, furcsa szintakszissal).

Figyelem

A következő információk csak a PHP 4-es változatára érvényesek.

A serialize() egy karaktersorozatot ad vissza, ami az átadott érték byte-sorozatban megadott megfelelője. Az unserialize() visszaalakít egy ilyen karaktersorozatot az eredeti értékké. A szerializációs folyamat során egy objektum átadásával elmenthetjük az objektum minden tulajdonságát (változóját). A függvények nem kerülnek elmentésre, csak az osztály neve.

Ahhoz, hogy az unserialize() segítségével vissza lehessen állítani egy objektumot, az objektum osztályának (típusának) már definiálva kell lennie. Ez a következőket jelenti egy példán keresztül megvilágítva. Ha az elso.php oldalon az A osztályú $a objektumot szerializálod, akkor kapsz egy olyan karaktersorozatot, amely az A osztályra hivatkozik, és tartalmazza az összes $a-ban lévő változó (tulajdonság) értékét. Ha ezt a karaktersorozatot a masodik.php oldalon objektummá szeretnéd alakítani, újra létrehozva az A osztályú $a nevű objektumot, akkor az A osztály definíciójának rendelkezésre kell állnia a masodik.php oldalon is. Ez úgy érhető el, hogy az A osztály definícióját egy külső állományban tárolod, és ezt alkalmazod mind az elso.php, mind a masodik.php oldalon.

aosztaly.inc:
  class A 
  {
      var $egy = 1;
    
      function egyet_mutat()
      {
          echo $this->egy;
      }
  }
  
elso.php:
  include("aosztaly.inc");
  
  $a = new A;
  $s = serialize($a);
  // tároljuk az $s-t valahol, ahol masodik.php megtalálja
  $fp = fopen("tarolas", "w");
  fputs($fp, $s);
  fclose($fp);

masodik.php:
  // ez szükséges, hogy a deszerializáció rendben menjen
  include("aosztaly.inc");

  $s = implode("", @file("tarolas"));
  $a = unserialize($s);

  // most már használható az egyet_mutat() metódus
  $a->egyet_mutat();

Ha session-öket alkalmazol, és a session_register() függvénnyel regisztálsz objektumokat, ezek az objektumok automatikusan szerializálódnak minden PHP program futása után, és deszerializálódnak minden további programban. Ez egyszerűen azt jelenti, hogy ezek az objektumok akármelyik oldalon feltűnhetnek, miután a session részévé váltak.

Erősen javasolt, hogy minden regisztrált objektum osztály definícióját betöltsd minden oldalon, még akkor is, ha éppen nem használod azokat. Ha ezt nem teszed meg, és egy objektum úgy deszerializálódik, hogy nem áll rendelkezésre az osztály definícója, el fogja veszteni az osztály hozzárendelését, és az stdClass osztály egy példánya lesz, metódusok nélkül, így használhatatlanná válik.

Ezért ha a fenti példában az $a a session részévé válik a session_register("a") meghívásával, akkor be kell töltened az aosztaly.inc külső állományt minden oldalon, nem csak az elso.php és masodik.php programokban.


A speciális __sleep és __wakeup metódusok

A serialize() ellenőrzi, hogy van-e az osztályodnak __sleep nevű metódusa. Ha van, ez lefut a szerializáció előtt. Ez megtisztíthatja az objektumot, és végül egy tömbbel tér vissza, amely tartalmazza az adott objektum ténylegesen szerializálandó tulajdonságainak neveit.

A __sleep célja, hogy bezárjon minden adatbázis kapcsolatot, a várakozó adatokat lementse, és hasonló 'tisztító' jellegű tevékenységeket végezzen. Hasznos lehet akkor is, ha nagyon nagy objektumaid vannak, amelyeket külön szeretnél lementeni.

Ezzel szemben az unserialize() a speciális __wakeup nevű függvényt használja. Ha ez létezik, ez a függvény alkalmazható arra, hogy visszaállítsa az objektum erőforrásait.

A __wakeup célja lehet például, hogy visszaállítson egy adatbázis kapcsolatot, ami a szerializáció során elveszett, és hasonló beállítási feladatokat végezzen.


Referenciák a konstruktorban

Referenciák képzése kontruktorokban problémás helyzetekhez vezethet. Ez a leírás segít a bajok elkerülésében.

class Ize
{
    function Ize($nev)
    {
        // egy referencia létrehozása a globális $globalref változóban
        global $globalref;
        $globalref[] = &$this;
        // a név beállítása a kapott értékre
        $this->nevBeallitas($nev);
        // és kiírás
        $this->nevKiiras();
    }

    function nevKiiras()
    {
        echo "<br>",$this->nev;
    }
	
    function nevBeallitas($nev)
    {
        $this->nev = $nev;
    }
}

Nézzük, hogy van-e különbség az $obj1 és az $obj2 objektum között. Az előbbi a = másoló operátorral készült, az utóbbi a =& referencia operátorral készült.

$obj1 = new Ize('konstruktorban beállított');
$obj1->nevKiiras();
$globalref[0]->nevKiiras();

/* kimenete:
konstruktorban beállított
konstruktorban beállított
konstruktorban beállított */

$obj2 =& new Ize('konstruktorban beállított');
$obj2->nevKiiras();
$globalref[1]->nevKiiras();

/* kimenete:
konstruktorban beállított
konstruktorban beállított
konstruktorban beállított */

Szemmel láthatóan nincs semmi különbség, de valójában egy nagyon fontos különbség van a két forma között: az $obj1 és $globalref[0] _NEM_ referenciák, NEM ugyanaz a két változó. Ez azért történhet így, mert a "new" alapvetően nem referenciával tér vissza, hanem egy másolatot ad.

Megjegyzés: Nincsenek teljesítménybeli problémák a másolatok visszaadásakor, mivel a PHP 4 és újabb verziók referencia számlálást alkalmaznak. Legtöbbször ellenben jobb másolatokkal dolgozni referenciák helyett, mivel a referenciák képzése eltart egy kis ideig, de a másolatok képzése gyakorlatilag nem igényel időt. Ha egyik sem egy nagy tömb, vagy objektum, és a változásokat nem szeretnéd mindegyik példányban egyszerre látni, akkor másolatok használatával jobban jársz.

Hogy bebizonyítsuk, amit fent írtunk, lásd az alábbi kódot:

// Most megváltoztatjuk a nevet. Mit vársz?
// Számíthatsz arra, hogy mind $obj1 és $globalref[0] megváltozik...
$obj1->nevBeallitas('kívülről beállítva');

// mint korábban írtuk, nem ez a helyzet
$obj1->nevKiiras();
$globalref[0]->nevKiiras();

/* kimenet:
konstruktorban beállított
kívülről beállítva */

// lássuk mi a különbség az $obj2 és $globalref[1] esetén
$obj2->nevBeallitas('kívülről beállítva');

// szerencsére ezek nem csak egyenlőek, hanem éppen ugyan az
// a két változó, így $obj2->nev és $globalref[1]->nev ugyanaz
$obj2->nevKiiras();
$globalref[1]->nevKiiras();

/* kimenete:
kívülről beállítva
kívülről beállítva */

Végül még egy utolsó példa, próbáld meg megérteni.

class A
{
    function A($i)
    {
        $this->ertek = $i;
        // próbáld meg kitalálni, miért nem kell itt referencia
        $this->b = new B($this);
    }

    function refLetrehozas()
    {
        $this->c = new B($this);
    }

    function ertekKiiras()
    {
        echo "<br>",get_class($this),' osztály: ',$this->value;
    }
}


class B
{
    function B(&$a)
    {
        $this->a = &$a;
    }

    function ertekKiiras()
    {
        echo "<br>",get_class($this),' osztály: ',$this->a->value;
    }
}

// próbáld meg megérteni, hogy egy egyszerű másolás
// miért okoz nem várt eredményeket a *-al jelölt sorban
$a =& new A(10);
$a->refLetrehozas();

$a->ertekKiiras();
$a->b->ertekKiiras();
$a->c->ertekKiiras();

$a->ertek = 11;

$a->ertekKiiras();
$a->b->ertekKiiras(); // *
$a->c->ertekKiiras();

/*
kimenete:
A osztály: 10
B osztály: 10
B osztály: 10
A osztály: 11
B osztály: 11
B osztály: 11
*/


14. Fejezet. Referenciák

Mik a referenciák

A referenciák lehetőséget adnak PHP-ben azonos változó tartalom elérésére különböző nevek alatt. Ezek szimbólumtábla bejegyzések, nem olyanok, mint a C nyelv mutatói. PHP-ben a változók neve és tartalma két különböző dolog, tehát ugyanaz a tartalom kaphat különböző neveket. A legjobb hasonlat talán a UNIX állománynevek és állományok rendszere. A változóneveket könyvtár bejegyzésekként foghatod fel, a változók tartalmát állományokként. A referenciák olyanok, mint UNIXban a hardlinkek.


Mit lehet referenciákkal tenni

A PHP referenciák lehetőséget adnak arra, hogy egy értékhez két nevet lehessen rendelni. Ez azt jelenti, hogy a következő programban:

<?php
$a =& $b;
?>

az $a és $b nevek ugyanarra az értékre hivatkoznak.

Megjegyzés: Az $a és a $b nevek teljesen egyenrangúak. Nem arról van szó, hogy az $a a $b-re mutat, vagy fordítva, hanem arról, hogy az $a és a $b név ugyanannak az értéknek két elnevezése.

Ugyanez a forma használható az olyan függvényeknél, amelyek referenciát adnak vissza, vagy a new operátor használatakor (a PHP 4.0.4 és későbbi verziókban):

<?php
$obj =& new valamilyen_osztaly();
$ize =& valtozo_kereses ($valami);
?>

Megjegyzés: Ha nem használod az & -t, akkor az osztálypéldány másoláta adódik át. A $this objektumon belüli használatával ugyanazon az objektumpéldányon dolgozol. Ha az értékadás során az & -t elhagyod, akkor az objektumról másolat készül és a $this már ezen a másolaton fog dolgozni. Van, amikor ez nem kívánatos, mivel általában egy példányon szeretnénk dolgozni a jobb memóriahasználat és teljesítmény érdekében.

Az @ operátort nem lehet együtt használni a &new utasítással, amivel el lehetne nyomni a konstruktorban fellépő hibákról történő jelzéseket. Ez a jelenlegi Zend motor egyik korlátja, és ezért fordítási hibát (parse error-t) fog jelezni, ha ilyet talál.

A a referenciákat paraméterátadáskor is lehet használni. Ebben az esetben a meghívott függvény egy lokális változója és a hívó környezet egy változója ugyanazt az értéket fogja képviselni. Például:

<?php
function ize (&$valtozo)
{
    $valtozo++;
}

$a = 5;
ize ($a);
?>

Ez a kód az $a változó értékét 6-ra állítja. Ez azért történik meg, mivel az ize függvényben a $valtozo egy referencia a $a változó értékére. A részletes leírást a referenciakénti paraméterátadás c. fejezetben olvashatod.

A referenciák harmadik felhasználási módja a refencia visszatérési-érték.


Mit nem lehet referenciákkal tenni

Mint korábban írtuk, a referenciák nem mutatók. A következő konstrukció ezért nem a vártnak megfelelően viselkedik:

<?php
function ize (&$valtozo)
{
    $valtozo =& $GLOBALS['valami'];
}
ize($valami);
?>

A foo függvényben a $valtozo változó a $valami értékéhez lesz kötve, de utána ezt megváltoztatjuk a $GLOBALS["valami"] értékére. Nincs lehetőség a referenciák segítségével a $valami más értékhez kötésére a hívó környezetben, mivel a $valami nem áll rendelkezésre az ize függvényben. Ott a $valtozo reprezentálja az értékét, amely csak változó tartalommal bír és nem név-érték kötéssel a hívó szimbólumtáblájában.


Referenciakénti paraméterátadás

A függvényeknek változókat referenciaként is át lehet adni, így a függvény tudja módosítani a hívó környezetben definiált értéket. Ez a következőképpen oldható meg:

<?php
function ize (&$valtozo)
{
    $valtozo++;
}

$a = 5;
ize ($a);
// $a itt 6
?>

Figyeld meg, hogy nincs referencia jelzés a függvényhíváskor, csak a függvény definíciójában. Ez önmagában elég a megfelelő működéshez.

A következők szerepelhetnek referenciakénti paraméterátadásban:

  • Változó, például ize($a)

  • New utasítás, például ize(new osztaly())

  • Egy függvény által visszaadott referencia, például:

    <?php
    function &valami()
    {
        $a = 5;
        return $a;
    }
    ize(valami());
    ?>

    Lásd még a refencia visszatérési-érték leírását.

Minden más kifejezést kerülni kell referencia szerinti paraméterátadáskor, mivel az eredmény határozatlan lesz. A következő példákban a referencia szerinti paraméterátadás hibának minősül:

<?php
function valami() // Figyeld meg, nincs & jel!
{
    $a = 5;
    return $a;
}
ize(valami());

ize($a = 5) // Kifejezés, nem változó
ize(5) // Konstans, nem változó
?>

Ezek a meghatározások a PHP 4.0.4 és későbbi verzióira érvényesek.


Refencia visszatérési-érték

A refencia visszatérési-érték pl. olyan változók megtalálásakor lehet hasznos, amelyekről referenciát kell készíteni. Ha referenciát kell visszaadni visszatérési értékként, akkor használd az alábbi formát:

<?php
function &valtozo_kereses ($param)
{
    ...kód...
    return $megtalalt_valtozo;
}

$ize =& valtozo_kereses ($valami);
$ize->x = 2;
?>

Ebben a példában a valtozo_kereses egy objektumot keres meg, és a megtalált objektum egy tulajdonságát állítjuk át - helyesen. A referenciák használata nélkül a másolatának egy tulajdonságán tettük volna mindezt - hibásan.

Megjegyzés: A paraméter átadással ellentétben, itt a & jelet mindkét helyen meg kell adnod a referenciavisszaadás jelöléséhez. Így nem egy másolatot kapsz, és az $ize változóra nézve referencia hozzárendelés történik, nem pedig érték hozzárendelés (értékmásolás).


Referenciák megszüntetése

Amikor megszüntetsz egy referenciát, csak megszakítod a változónév és az érték közötti kapcsolatot. Ez nem azt jelenti, hogy a váltózó értékét törlöd. Például:

<?php
$a = 1;
$b =& $a;
unset ($a);
?>

nem fogja megszüntetni a $b nevet, csak az $a nevet, így az érték a $b néven továbbra is elérhető.

Ismét érdemes a Unix unlink parancsával és az állományrendszerrel való hasonlatosságra gondolni.


A PHP által használt referenciák

Sok konstrukció a PHP-ben referenciák segítségével valósul meg, azért minden fentebb tárgyalt kérdés ezekre az elemekre is igaz. Néhány olyan konstrukciót, mint a referencia átadást vagy visszatérést már kifejtettünk, más referenciákat használó konstrukciók:


global referenciák

Amikor egy változót a global $valtozo formával globálisként használsz, tulajdonképpen egy referenciát képzel a megfelelő globális változóra,azaz a következő kódnak megfelelő történik:

<?php
$valtozo =& $GLOBALS['valtozo'];
?>

Ez például azt is jelenti, hogy a $valtozo törlése nem fogja törölni a globális változót.


$this

Egy objektum metódusban a $this mindig az aktuális példányra egy referencia.

III. Biztonság

Tartalom
15. Security

15. Fejezet. Security

PHP is a powerful language and the interpreter, whether included in a web server as a module or executed as a separate CGI binary, is able to access files, execute commands and open network connections on the server. These properties make anything run on a web server insecure by default. PHP is designed specifically to be a more secure language for writing CGI programs than Perl or C, and with correct selection of compile-time and runtime configuration options, and proper coding practices, it can give you exactly the combination of freedom and security you need.

As there are many different ways of utilizing PHP, there are many configuration options controlling its behaviour. A large selection of options guarantees you can use PHP for a lot of purposes, but it also means there are combinations of these options and server configurations that result in an insecure setup.

The configuration flexibility of PHP is equally rivalled by the code flexibility. PHP can be used to build complete server applications, with all the power of a shell user, or it can be used for simple server-side includes with little risk in a tightly controlled environment. How you build that environment, and how secure it is, is largely up to the PHP developer.

This chapter starts with some general security advice, explains the different configuration option combinations and the situations they can be safely used, and describes different considerations in coding for different levels of security.


General considerations

A completely secure system is a virtual impossibility, so an approach often used in the security profession is one of balancing risk and usability. If every variable submitted by a user required two forms of biometric validation (such as a retinal scan and a fingerprint), you would have an extremely high level of accountability. It would also take half an hour to fill out a fairly complex form, which would tend to encourage users to find ways of bypassing the security.

The best security is often inobtrusive enough to suit the requirements without the user being prevented from accomplishing their work, or over-burdening the code author with excessive complexity. Indeed, some security attacks are merely exploits of this kind of overly built security, which tends to erode over time.

A phrase worth remembering: A system is only as good as the weakest link in a chain. If all transactions are heavily logged based on time, location, transaction type, etc. but the user is only verified based on a single cookie, the validity of tying the users to the transaction log is severely weakened.

When testing, keep in mind that you will not be able to test all possibilities for even the simplest of pages. The input you may expect will be completely unrelated to the input given by a disgruntled employee, a cracker with months of time on their hands, or a housecat walking across the keyboard. This is why it's best to look at the code from a logical perspective, to discern where unexpected data can be introduced, and then follow how it is modified, reduced, or amplified.

The Internet is filled with people trying to make a name for themselves by breaking your code, crashing your site, posting inappropriate content, and otherwise making your day interesting. It doesn't matter if you have a small or large site, you are a target by simply being online, by having a server that can be connected to. Many cracking programs do not discern by size, they simply trawl massive IP blocks looking for victims. Try not to become one.


Installed as CGI binary

Possible attacks

Using PHP as a CGI binary is an option for setups that for some reason do not wish to integrate PHP as a module into server software (like Apache), or will use PHP with different kinds of CGI wrappers to create safe chroot and setuid environments for scripts. This setup usually involves installing executable PHP binary to the web server cgi-bin directory. CERT advisory CA-96.11 recommends against placing any interpreters into cgi-bin. Even if the PHP binary can be used as a standalone interpreter, PHP is designed to prevent the attacks this setup makes possible:

  • Accessing system files: http://my.host/cgi-bin/php?/etc/passwd

    The query information in a URL after the question mark (?) is passed as command line arguments to the interpreter by the CGI interface. Usually interpreters open and execute the file specified as the first argument on the command line.

    When invoked as a CGI binary, PHP refuses to interpret the command line arguments.

  • Accessing any web document on server: http://my.host/cgi-bin/php/secret/doc.html

    The path information part of the URL after the PHP binary name, /secret/doc.html is conventionally used to specify the name of the file to be opened and interpreted by the CGI program. Usually some web server configuration directives (Apache: Action) are used to redirect requests to documents like http://my.host/secret/script.php to the PHP interpreter. With this setup, the web server first checks the access permissions to the directory /secret, and after that creates the redirected request http://my.host/cgi-bin/php/secret/script.php. Unfortunately, if the request is originally given in this form, no access checks are made by web server for file /secret/script.php, but only for the /cgi-bin/php file. This way any user able to access /cgi-bin/php is able to access any protected document on the web server.

    In PHP, compile-time configuration option --enable-force-cgi-redirect and runtime configuration directives doc_root and user_dir can be used to prevent this attack, if the server document tree has any directories with access restrictions. See below for full the explanation of the different combinations.


Case 1: only public files served

If your server does not have any content that is not restricted by password or ip based access control, there is no need for these configuration options. If your web server does not allow you to do redirects, or the server does not have a way to communicate to the PHP binary that the request is a safely redirected request, you can specify the option --enable-force-cgi-redirect to the configure script. You still have to make sure your PHP scripts do not rely on one or another way of calling the script, neither by directly http://my.host/cgi-bin/php/dir/script.php nor by redirection http://my.host/dir/script.php.

Redirection can be configured in Apache by using AddHandler and Action directives (see below).


Case 2: using --enable-force-cgi-redirect

This compile-time option prevents anyone from calling PHP directly with a URL like http://my.host/cgi-bin/php/secretdir/script.php. Instead, PHP will only parse in this mode if it has gone through a web server redirect rule.

Usually the redirection in the Apache configuration is done with the following directives:

Action php-script /cgi-bin/php
AddHandler php-script .php

This option has only been tested with the Apache web server, and relies on Apache to set the non-standard CGI environment variable REDIRECT_STATUS on redirected requests. If your web server does not support any way of telling if the request is direct or redirected, you cannot use this option and you must use one of the other ways of running the CGI version documented here.


Case 3: setting doc_root or user_dir

To include active content, like scripts and executables, in the web server document directories is sometimes considered an insecure practice. If, because of some configuration mistake, the scripts are not executed but displayed as regular HTML documents, this may result in leakage of intellectual property or security information like passwords. Therefore many sysadmins will prefer setting up another directory structure for scripts that are accessible only through the PHP CGI, and therefore always interpreted and not displayed as such.

Also if the method for making sure the requests are not redirected, as described in the previous section, is not available, it is necessary to set up a script doc_root that is different from web document root.

You can set the PHP script document root by the configuration directive doc_root in the configuration file, or you can set the environment variable PHP_DOCUMENT_ROOT. If it is set, the CGI version of PHP will always construct the file name to open with this doc_root and the path information in the request, so you can be sure no script is executed outside this directory (except for user_dir below).

Another option usable here is user_dir. When user_dir is unset, only thing controlling the opened file name is doc_root. Opening a URL like http://my.host/~user/doc.php does not result in opening a file under users home directory, but a file called ~user/doc.php under doc_root (yes, a directory name starting with a tilde [~]).

If user_dir is set to for example public_php, a request like http://my.host/~user/doc.php will open a file called doc.php under the directory named public_php under the home directory of the user. If the home of the user is /home/user, the file executed is /home/user/public_php/doc.php.

user_dir expansion happens regardless of the doc_root setting, so you can control the document root and user directory access separately.


Case 4: PHP parser outside of web tree

A very secure option is to put the PHP parser binary somewhere outside of the web tree of files. In /usr/local/bin, for example. The only real downside to this option is that you will now have to put a line similar to:

#!/usr/local/bin/php

as the first line of any file containing PHP tags. You will also need to make the file executable. That is, treat it exactly as you would treat any other CGI script written in Perl or sh or any other common scripting language which uses the #! shell-escape mechanism for launching itself.

To get PHP to handle PATH_INFO and PATH_TRANSLATED information correctly with this setup, the PHP parser should be compiled with the --enable-discard-path configure option.


Installed as an Apache module

When PHP is used as an Apache module it inherits Apache's user permissions (typically those of the "nobody" user). This has several impacts on security and authorization. For example, if you are using PHP to access a database, unless that database has built-in access control, you will have to make the database accessible to the "nobody" user. This means a malicious script could access and modify the database, even without a username and password. It's entirely possible that a web spider could stumble across a database administrator's web page, and drop all of your databases. You can protect against this with Apache authorization, or you can design your own access model using LDAP, .htaccess files, etc. and include that code as part of your PHP scripts.

Often, once security is established to the point where the PHP user (in this case, the apache user) has very little risk attached to it, it is discovered that PHP is now prevented from writing any files to user directories. Or perhaps it has been prevented from accessing or changing databases. It has equally been secured from writing good and bad files, or entering good and bad database transactions.

A frequent security mistake made at this point is to allow apache root permissions, or to escalate apache's abilitites in some other way.

Escalating the Apache user's permissions to root is extremely dangerous and may compromise the entire system, so sudo'ing, chroot'ing, or otherwise running as root should not be considered by those who are not security professionals.

There are some simpler solutions. By using open_basedir you can control and restrict what directories are allowed to be used for PHP. You can also set up apache-only areas, to restrict all web based activity to non-user, or non-system, files.


Filesystem Security

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.

Példa 15-1. Poor variable checking leads to....

<?php
// remove a file from the user's home directory
$username = $_POST['user_submitted_name'];
$homedir = "/home/$username";
$file_to_delete = "$userfile";
unlink ("$homedir/$userfile");
echo "$file_to_delete has been deleted!";
?>
Since the username is postable from a user form, they can submit a username and file belonging to someone else, and delete files. 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:

Példa 15-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 = "../etc/";
$homedir = "/home/../etc/";
$file_to_delete = "passwd";
unlink ("/home/../etc/passwd");
echo "/home/../etc/passwd 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:

Példa 15-3. More secure file name checking

<?php
// removes a file from the hard drive that
// the PHP user has access to.
$username = $_SERVER['REMOTE_USER']; // using an authentication mechanisim

$homedir = "/home/$username";

$file_to_delete = basename("$userfile"); // strip paths
unlink ($homedir/$file_to_delete);

$fp = fopen("/home/logging/filedelete.log","+a"); //log the deletion
$logstring = "$username $homedir $file_to_delete";
fputs ($fp, $logstring);
fclose($fp);

echo "$file_to_delete has been deleted!";
?>
However, even this is not without it's 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:

Példa 15-4. More secure file name checking

<?php
$username = $_SERVER['REMOTE_USER']; // using an authentication mechanisim
$homedir = "/home/$username";

if (!ereg('^[^./][^/]*$', $userfile))
     die('bad filename'); //die, do not process

if (!ereg('^[^./][^/]*$', $username))
     die('bad username'); //die, do not process
//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.


Database Security

Nowadays, databases are cardinal components of any web based application by enabling websites to provide varying dynamic content. Since very sensitive or secret information can be stored in a database, you should strongly consider protecting your databases.

To retrieve or to store any information you need to connect to the database, send a legitimate query, fetch the result, and close the connection. Nowadays, the commonly used query language in this interaction is the Structured Query Language (SQL). See how an attacker can tamper with an SQL query.

As you can surmise, PHP cannot protect your database by itself. The following sections aim to be an introduction into the very basics of how to access and manipulate databases within PHP scripts.

Keep in mind this simple rule: defense in depth. The more places you take action to increase the protection of your database, the less probability of an attacker succeeding in exposing or abusing any stored information. Good design of the database schema and the application deals with your greatest fears.


Designing Databases

The first step is always to create the database, unless you want to use one from a third party. When a database is created, it is assigned to an owner, who executed the creation statement. Usually, only the owner (or a superuser) can do anything with the objects in that database, and in order to allow other users to use it, privileges must be granted.

Applications should never connect to the database as its owner or a superuser, because these users can execute any query at will, for example, modifying the schema (e.g. dropping tables) or deleting its entire content.

You may create different database users for every aspect of your application with very limited rights to database objects. The most required privileges should be granted only, and avoid that the same user can interact with the database in different use cases. This means that if intruders gain access to your database using your applications credentials, they can only effect as many changes as your application can.

You are encouraged not to implement all the business logic in the web application (i.e. your script), instead do it in the database schema using views, triggers or rules. If the system evolves, new ports will be intended to open to the database, and you have to re-implement the logic in each separate database client. Over and above, triggers can be used to transparently and automatically handle fields, which often provides insight when debugging problems with your application or tracing back transactions.


Connecting to Database

You may want to estabilish the connections over SSL to encrypt client/server communications for increased security, or you can use ssh to encrypt the network connection between clients and the database server. If either of these is used, then monitoring your traffic and gaining information about your database will be difficult for a would-be attacker.


Encrypted Storage Model

SSL/SSH protects data travelling from the client to the server, SSL/SSH does not protect the persistent data stored in a database. SSL is an on-the-wire protocol.

Once an attacker gains access to your database directly (bypassing the webserver), the stored sensitive data may be exposed or misused, unless the information is protected by the database itself. Encrypting the data is a good way to mitigate this threat, but very few databases offer this type of data encryption.

The easiest way to work around this problem is to first create your own encryption package, and then use it from within your PHP scripts. PHP can assist you in this with several extensions, such as Mcrypt and Mhash, covering a wide variety of encryption algorithms. The script encrypts the data before inserting it into the database, and decrypts it when retrieving. See the references for further examples of how encryption works.

In case of truly hidden data, if its raw representation is not needed (i.e. not be displayed), hashing may also be taken into consideration. The well-known example for the hashing is storing the MD5 hash of a password in a database, instead of the password itself. See also crypt() and md5().

Példa 15-5. Using hashed password field

// storing password hash
$query  = sprintf("INSERT INTO users(name,pwd) VALUES('%s','%s');",
            addslashes($username), md5($password));
$result = pg_exec($connection, $query);

// querying if user submitted the right password
$query = sprintf("SELECT 1 FROM users WHERE name='%s' AND pwd='%s';",
            addslashes($username), md5($password));
$result = pg_exec($connection, $query);

if (pg_numrows($result) > 0) {
    echo "Welcome, $username!";
}
else {
    echo "Authentication failed for $username.";
}

SQL Injection

Many web developers are unaware of how SQL queries can be tampered with, and assume that an SQL query is a trusted command. It means that SQL queries are able to circumvent access controls, thereby bypassing standard authentication and authorization checks, and sometimes SQL queries even may allow access to host operating system level commands.

Direct SQL Command Injection is a technique where an attacker creates or alters existing SQL commands to expose hidden data, or to override valuable ones, or even to execute dangerous system level commands on the database host. This is accomplished by the application taking user input and combining it with static parameters to build a SQL query. The following examples are based on true stories, unfortunately.

Owing to the lack of input validation and connecting to the database on behalf of a superuser or the one who can create users, the attacker may create a superuser in your database.

Példa 15-6. Splitting the result set into pages ... and making superusers (PostgreSQL and MySQL)

$offset = argv[0]; // beware, no input validation!
$query  = "SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET $offset;";
// with PostgreSQL 
$result = pg_exec($conn, $query);
// with MySQL
$result = mysql_query($query);
Normal users click on the 'next', 'prev' links where the $offset is encoded into the URL. The script expects that the incoming $offset is a decimal number. However, what if someone tries to break in by appending a urlencode()'d form of the following to the URL

// in case of PostgreSQL
0;
insert into pg_shadow(usename,usesysid,usesuper,usecatupd,passwd)
    select 'crack', usesysid, 't','t','crack'
    from pg_shadow where usename='postgres';
--

// in case of MySQL
0;
UPDATE user SET Password=PASSWORD('crack') WHERE user='root';
FLUSH PRIVILEGES;

If it happened, then the script would present a superuser access to him. Note that 0; is to supply a valid offset to the original query and to terminate it.

Megjegyzés: It is common technique to force the SQL parser to ignore the rest of the query written by the developer with -- which is the comment sign in SQL.

A feasible way to gain passwords is to circumvent your search result pages. The only thing the attacker needs to do is to see if there are any submitted variables used in SQL statements which are not handled properly. These filters can be set commonly in a preceding form to customize WHERE, ORDER BY, LIMIT and OFFSET clauses in SELECT statements. If your database supports the UNION construct, the attacker may try to append an entire query to the original one to list passwords from an arbitrary table. Using encrypted password fields is strongly encouraged.

Példa 15-7. Listing out articles ... and some passwords (any database server)

$query  = "SELECT id, name, inserted, size FROM products
                  WHERE size = '$size'
                  ORDER BY $order LIMIT $limit, $offset;";
$result = odbc_exec($conn, $query);
The static part of the query can be combined with another SELECT statement which reveals all passwords:

'
union select '1', concat(uname||'-'||passwd) as name, '1971-01-01', '0' from usertable;
--

If this query (playing with the ' and --) were assigned to one of the variables used in $query, the query beast awakened.

SQL UPDATE's are also susceptible to attack. These queries are also threatened by chopping and appending an entirely new query to it. But the attacker might fiddle with the SET clause. In this case some schema information must be possessed to manipulate the query successfully. This can be acquired by examining the form variable names, or just simply brute forcing. There are not so many naming conventions for fields storing passwords or usernames.

Példa 15-8. From resetting a password ... to gaining more privileges (any database server)

$query = "UPDATE usertable SET pwd='$pwd' WHERE uid='$uid';";
But a malicious user sumbits the value ' or uid like'%admin%'; -- to $uid to change the admin's password, or simply sets $pwd to "hehehe', admin='yes', trusted=100 " (with a trailing space) to gain more privileges. Then, the query will be twisted:

// $uid == ' or uid like'%admin%'; --
$query = "UPDATE usertable SET pwd='...' WHERE uid='' or uid like '%admin%'; --";

// $pwd == "hehehe', admin='yes', trusted=100 "
$query = "UPDATE usertable SET pwd='hehehe', admin='yes', trusted=100 WHERE ...;"

A frightening example how operating system level commands can be accessed on some database hosts.

Példa 15-9. Attacking the database hosts operating system (MSSQL Server)

$query  = "SELECT * FROM products WHERE id LIKE '%$prod%'";
$result = mssql_query($query);
If attacker submits the value a%' exec master..xp_cmdshell 'net user test testpass /ADD' -- to $prod, then the $query will be:

$query  = "SELECT * FROM products
                    WHERE id LIKE '%a%'
                    exec master..xp_cmdshell 'net user test testpass /ADD'--";
$result = mssql_query($query);

MSSQL Server executes the SQL statements in the batch including a command to add a new user to the local accounts database. If this application were running as sa and the MSSQLSERVER service is running with sufficient privileges, the attacker would now have an account with which to access this machine.

Megjegyzés: Some of the examples above is tied to a specific database server. This does not mean that a similar attack is impossible against other products. Your database server may be similarly vulnerable in another manner.


Avoiding techniques

You may plead that the attacker must possess a piece of information about the database schema in most examples. You are right, but you never know when and how it can be taken out, and if it happens, your database may be exposed. If you are using an open source, or publicly available database handling package, which may belong to a content management system or forum, the intruders easily produce a copy of a piece of your code. It may be also a security risk if it is a poorly designed one.

These attacks are mainly based on exploiting the code not being written with security in mind. Never trust any kind of input, especially that which comes from the client side, even though it comes from a select box, a hidden input field or a cookie. The first example shows that such a blameless query can cause disasters.

  • Never connect to the database as a superuser or as the database owner. Use always customized users with very limited privileges.

  • Check if the given input has the expected data type. PHP has a wide range of input validating functions, from the simplest ones found in Variable Functions and in Character Type Functions (e.g. is_numeric(), ctype_digit() respectively) and onwards to the Perl compatible Regular Expressions support.

  • If the application waits for numerical input, consider verifying data with is_numeric(), or silently change its type using settype(), or use its numeric representation by sprintf().

    Példa 15-10. A more secure way to compose a query for paging

    settype($offset, 'integer');
    $query = "SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET $offset;";
    
    // please note %d in the format string, using %s would be meaningless
    $query = sprintf("SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET %d;",
                     $offset);

  • Quote each non numeric user input which is passed to the database with addslashes() or addcslashes(). See the first example. As the examples shows, quotes burnt into the static part of the query is not enough, and can be easily cracked.

  • Do not print out any database specific information, especially about the schema, by fair means or foul. See also Error Reporting and Error Handling and Logging Functions.

  • You may use stored procedures and previously defined cursors to abstract data access so that users do not directly access tables or views, but this solution has another impacts.

Besides these, you benefit from logging queries either within your script or by the database itself, if it supports logging. Obviously, the logging is unable to prevent any harmful attempt, but it can be helpful to trace back which application has been circumvented. The log is not useful by itself, but through the information it contains. More detail is generally better than less.


Error Reporting

With PHP security, there are two sides to error reporting. One is beneficial to increasing security, the other is detrimental.

A standard attack tactic involves profiling a system by feeding it improper data, and checking for the kinds, and contexts, of the errors which are returned. This allows the system cracker to probe for information about the server, to determine possible weaknesses. For example, if an attacker had gleaned information about a page based on a prior form submission, they may attempt to override variables, or modify them:

Példa 15-11. Attacking Variables with a custom HTML page

<form method="post" action="attacktarget?username=badfoo&password=badfoo">
<input type="hidden" name="username" value="badfoo" />
<input type="hidden" name="password" value="badfoo" />
</form>

The PHP errors which are normally returned can be quite helpful to a developer who is trying to debug a script, indicating such things as the function or file that failed, the PHP file it failed in, and the line number which the failure occured 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:

Példa 15-12. 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 webserver 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, by using E_NONE, you insulate your code from probing.

Példa 15-13. Finding dangerous variables with E_ALL

<?php
if ($username) {  // Not initialized or checked before usage
    $good_login = 1;
}
if ($good_login == 1) { // If above test fails, not initialized or checked before usage
    readfile ("/highly/sensitive/data/index.html");
}
?>


Using Register Globals

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 (poison) your scripts will 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:

Példa 15-14. 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).

Példa 15-15. 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 outside of PHP.

Példa 15-16. 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 unitialized variables you may turn up error_reporting() to show E_NOTICE level errors.

Superglobals: availability note: Since PHP 4.1.0, superglobal arrays such as $_GET , $_POST, and $_SERVER, etc. have been available. For more information, read the manual section on superglobals


User Submitted Data

The greatest weakness in many PHP programs is not inherent in the language itself, but merely an issue of code not being written with security in mind. For this reason, you should always take the time to consider the implications of a given piece of code, to ascertain the possible damage if an unexpected variable is submitted to it.

Példa 15-17. 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?
fputs ($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).


Hiding PHP

In general, security by obscurity is one of the weakest forms of security. But in some cases, every little bit of extra security is desirable.

A few simple techniques can help to hide PHP, possibly slowing down an attacker who is attempting to discover weaknesses in your system. By setting expose_php = off in your php.ini file, you reduce the amount of information available to them.

Another tactic is to configure web servers such as apache to parse different filetypes through PHP, either with an .htaccess directive, or in the apache configuration file itself. You can then use misleading file extensions:

Példa 15-18. Hiding PHP as another language

# Make PHP code look like other code types
AddType application/x-httpd-php .asp .py .pl
Or obscure it completely:

Példa 15-19. Using unknown types for PHP extensions

# Make PHP code look like unknown types
AddType application/x-httpd-php .bop .foo .133t
Or hide it as HTML code, which has a slight performance hit because all HTML will be parsed through the PHP engine:

Példa 15-20. Using HTML types for PHP extensions

# Make all PHP code look like HTML
AddType application/x-httpd-php .htm .html
For this to work effectively, you must rename your PHP files with the above extensions. While it is a form of security through obscurity, it's a minor preventative measure with few drawbacks.


Keeping Current

PHP, like any other large system, is under constant scrutiny and improvement. Each new version will often include both major and minor changes to enhance and repair security flaws, configuration mishaps, and other issues that will affect the overall security and stability of your system.

Like other system-level scripting languages and programs, the best approach is to update often, and maintain awareness of the latest versions and their changes.


16. Fejezet. HTTP hitelesítés PHP-vel

A HTTP hitelesítési (authentication) funkciók csak akkor elérhetőek PHP-ben, ha az Apache modulként fut, bár régebben a CGI módú használat során is működött ez a funkció, azonban ez a lehetőség már megszűnt. Az Apache modulként futó PHP esetében a header() függvényt kell használni arra, hogy egy "Authentication Required" üzenetet küldjön a kliens böngészőnek, aminek hatására az egy Username/Password bemeneti ablakot nyit meg a felhasználó számára. Ha a látogató kitöltötte a username és password mezőket, az URL, ami a PHP szkriptre mutat, ismét meghívásra kerül, és rendelkezésre állnak a $PHP_AUTH_USER, $PHP_AUTH_PW és a $PHP_AUTH_TYPE változók, amik a felhasználói név, jelszó és azonosítási típus értékeket tartalmazzák értelemszerűen. Jelen pillanatban csupán a "Basic" azonosítási típus támogatott. Lásd még a header() függényvt.

PHP verziókhoz kötödő megjegyzés: Az autoglobális változók, mint pl. $_SERVER, a 4.1.0 verziótól elérhetőek. PHP 3-ban helyette a $HTTP_SERVER_VARS használható.

Egy egyszerű példa PHP szkript, ami kliens azonosítást vált ki:

Példa 16-1. HTTP azonosítási példa

<?php
  if( !isset($_SERVER['PHP_AUTH_USER']) ) {
    header("WWW-Authenticate: Basic realm=\"Azonosítás indoka\"");
    header("HTTP/1.0 401 Unauthorized");
    echo "Ez jelenik meg, ha a Cancel gombot nyomja a felhasználó\n";
    exit;
  } else {
    echo "<p>Helló {$_SERVER['PHP_AUTH_USER']}.</p>";
    echo "<p>A megadott jelszavad: {$_SERVER['PHP_AUTH_PW']}.</p>";
  }
?>

Megjegyzés: Vigyázni kell a HTTP fejlécek írásakor! A maximális kompatibilitás eléréséhez a "Basic" kulcsszót nagy B betűvel kell kezdeni, a "realm" részt mindenképpen idézőjelbe (és nem aposztrófok közé) kell tenni! Végül pontosan egy szóközt hagyj ki a "401" előtt a "HTTP/1.0 401" fejléc sorban.

Egy valós esetben persze nem a $PHP_AUTH_USER és $PHP_AUTH_PW kiírása az elérni kívánt cél, így általában a felhasználói név és jelszó ellenőrzése következik. Természetesen lehetőség van ezt egy adatbázis lekérdezéssel megoldani, vagy egy dbm fájlban utánanézni a szükséges adatoknak.

Figyelj az Internet Explorer böngészők hibáira, ezek nem fogadják el tetszőleges sorrendben a HTTP fejléceket. A tesztek azt mutatják, hogy a WWW-Authenticate elküldése a HTTP/1.0 401 előtt megoldja a problémát.

Mivel a hagyományos HTTP azonosítás során a jelszó rejtett az elért szkript előtt, a PHP nem állítja be a PHP_AUTH változókat ha az adott file-ra a hagyományos azonosítás is engedélyezett, és így nem deríthető ki a user jelszava. Ebben az esetben a REMOTE_USER változó tartalmazza a már azonosított felhasználó nevét, azaz: $_SERVER['REMOTE_USER'].

Beállítási megjegyzés: A PHP az AuthType direktíva megléte alapján dönti el, hogy rajta kívülálló azonosítás történik-e. Figyelj ennek a direktívának az elkerülésére abban a környezetben, ahol a PHP-t szeretnéd használni azonosítások kezelésére (különben minden azonosítási próbálkozás sikertelen lesz).

Vedd észre, hogy ez nem küszöböli ki azt a problémát, hogy más nem azonosítás-köteles URL címeken lévő szkriptek ugyanazon a szerveren megszerezzék a jelszavakat az azonosított URL-ekről.

A Netscape Navigator és Internet Explorer böngészők törölni fogják a böngésző adott oldalhoz tartozó azonosítási tárát (authentication cache), amennyiben egy 401-es szerver üzenetet kapnak. Ez gyakorlatilag kilépteti a user-t, ami azt jelenti, hogy legközelebb ismét meg kell adnia a nevét és jelszavát. Időnként ezt arra használják, hogy lejárati időt rendelve a belépésekhez egy idő után megszüntessék azokat, vagy egy kilépés gombot biztosítsanak.

Példa 16-2. HTTP azonosítási példa, ami új nevet és jelszót kér

<?php
  function azonositas() {
   header( "WWW-Authenticate: Basic realm=\"Azonosítási Rendszer Teszt\"");
   header( "HTTP/1.0 401 Unauthorized");
   echo "Érvényes nevet és jelszót kell megadnod, hogy elérd ezt a szolgáltatást!\n";
   exit;
  }
  if (!isset($_SERVER['PHP_AUTH_USER']) || ($_POST['SeenBefore'] == 1 && $_POST['OldAuth'] == $_SERVER['PHP_AUTH_USER'])) {
   azonositas();
  }
  else {
   echo "<p>Üdv néked, {$_SERVER['PHP_AUTH_USER']}<br>";
   echo "Régebben: {$_REQUEST['OldAuth']}";
   echo "<form action=\"{$_SERVER['PHP_SELF']}\" method=\"post\">\n";
   echo "<input type=\"hidden\" name=\"JartMarItt\" value=\"1\">\n";
   echo "<input type=\"hidden\" name=\"RegiUser\" value=\"{$_SERVER['PHP_AUTH_USER']}\">\n";
   echo "<input type=\"submit\" value=\"Újraazonosítás\">\n";
   echo "</form></p>\n";
  }
?>

A HTTP Basic azonosítási standard nem követeli meg ezt a viselkedést a böngészők részéről, tehát ne építs rá! Lynx-el végzett tesztek azt mutatták, hogy a Lynx nem törli az azonosítási bizonyítványokat a 401-es szerver válasz hatására, tehát egy back és forward lépéssel ismét megnyílik az oldal, feltéve, hogy az azonosítási feltételek nem változtak. Ellenben a felhasználó megnyomhatja a '_' billentyűt, hogy törölje az azonosítási információkat.

Szintén fontos megjegyezni, hogy ez a módszer nem vezet eredményre, ha Microsoft IIS szervert használsz CGI módú PHP-val, az IIS korlátozásai miatt.

Megjegyzés: Ha safe mode be van kapcsolva, akkor a WWW-Authenticate fejléc realm részéhez a szkript UID-ja is hozzáadódik. the header.


17. Fejezet. Sütik (cookie-k)

A PHP támogatja a HTTP cookie-k kezelését. A sütik lehetőséget adnak arra, hogy adatokat tárolj a kliens gépen, így követve vagy azonosítva a visszatérő látogatókat. Sütik beállítására a setcookie() függvénnyel nyílik lehetőség. A sütik részei a HTTP fejlécnek, így a setcookie() függényt azelőtt kell meghívni, mielőtt bármilyen kimenetet küldesz a böngészőnek. Ez a header() függvénnyel megegyező korlátozást jelent. A kimenet szabályozó függvényeket használhatod a kimenet késleltetésére addig, amíg minden sütit és fejlécet elküldtél.

Minden süti, amit a klienstől visszakapsz, automatikusan PHP változóvá válik, pont úgy, mint a GET és a POST kérésekkel érkező adatok, feltéve, hogy a register_globals és variables_order php.ini beállítások ennek megfelelően vannak beállítva. Ha több értéket szeretnél adni egy sütinek, add a szokásos [] végződést a süti nevéhez.

A PHP 4.1.0 és későbbi változataiban a $_COOKIE nevű mindenhonnan látható változó mindig létrejön, tartalmazva a klienstől érkezett sütiket. A $HTTP_COOKIE_VARS a korábbi verziókban használható, ha a track_vars php.ini beállítás be van kapcsolva, bár ez a változó nem látszik mindenhonnan. (A 4.0.3-as változattól felfele ez mindig be van kapcsolva)

Részletesebb információkért, beleértve a böngésző hibákat, lásd a setcookie() függvényt.


18. Fejezet. Fájlfeltöltés kezelése

POST metódusú feltöltések

A PHP alkalmas fájl feltöltést fogadni bármilyen RFC-1867 kompatibilis böngészőtől (mint a Netscape Navigator 3 vagy későbbi és a Microsoft Internet Explorer 3 Microsoft javítással, vagy későbbi IE javítás nélkül). Ez a szolgáltatás egyaránt lehetővé teszi a látogatónak szöveges és bináris fájlok feltöltését. A PHP azonosítási és fájlkezelési képességeivel teljes felügyeletet lehet gyakorolni afelett, hogy ki tölthet fel állományokat, és azokkal mi történjen.

Kapcsolodó konfigurációs megjegyzés: Lásd még: file_uploads, upload_max_filesize, upload_tmp_dir és post_max_size direktívákat a php.ini-ben!

Érdemes megemlíteni, hogy a PHP támogatja a PUT metódust is, amit a Netscape Composer és a W3C Amaya kliensek használnak. Lásd a PUT metódusú feltöltések részt.

Az állomány feltöltési lehetőség egy különleges módon kialakított űrlappal biztosítható, amely nagyjából így néz ki:

Példa 18-1. Állományfeltöltő űrlap

<form enctype="multipart/form-data" action="_URL_" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="1000">
Állpmány elküldése: <input name="userfile" type="file">
<input type="submit" value="OK">
</form>
Az _URL_ a feldolgozást végző PHP fájlra kell, hogy mutasson. A MAX_FILE_SIZE rejtett mező a file típusú input mező előtt kell, hogy szerepeljen, és azt adja meg, hogy mekkora a maximális fájl méret (byte-okban megadva), amit a kliens jogosult feltölteni.

Figyelem

A MAX_FILE_SIZE csak javasolt érték a böngészők számára. Könnyű megkerülni ezt a megadott maximumot. Ezért nem szabad csak arra építeni, hogy a böngésző úgy viselkedik, ahogy azt ebben a példában láttuk. A maximális feltöltési állományméretre vonatkozó PHP beállítások azonban nem kerülhetőek meg.

A feltöltött állományokra vonatkozó változók PHP verziótól függően különböznek egymástól. Az autoglobális $_FILES PHP 4.1.0 óta létezik, a $HTTP_POST_FILES tömb PHP 4.0.0 óta. Ezek a tömbök tartalmazzák az összes feltöltött állomány adatait. Az új verziókban már a $_FILES használata javasolt. Ha a register_globals PHP diretíva be van kapcsolva, akkor a vonatkozó változók a globális névtérben is létrejönnek, és mint globális változók használhatók. Figyelem: A register_globals alapértelmezés szerint biztonsági okokból ki van kapcsolva, PHP 4.2.0 verziójától kezdve.

A $_FILES tartalma a fenti példánk alapján a következő. Megjegyezzük, hogy az alábbi felsorolás arra épít, hogy a az állomány feltölő mező neve userfile, ahogy a fenti példában látható.

$_FILES['userfile']['name']

Az állomány eredeti neve a távoli kliensgépen.

$_FILES['userfile']['type']

A feltöltött állomány MIME típusa, ha a böngésző átadta ezt az információt, pl.: "image/gif".

$_FILES['userfile']['size']

A feltöltött állomány mérete bájtokban.

$_FILES['userfile']['tmp_name']

Annak az ideiglenes állománynak a neve, amely a szerveren tárolja a feltöltött állomány tartalmát.

$_FILES['userfile']['error']

Az állomány feltöltés során keletkezett hiba kódja. Az error elem PHP 4.2.0-tól használható.

Megjegyzés: A PHP 4.1.0 előtti verziókban $_FILES tömb helyett a $HTTP_POST_FILES-t kell használni, amely nem autoglobális változó, mint ahogy $_FILES. A PHP 3 nem biztosítja a $HTTP_POST_FILES változót sem.

Ha register_globals is turned on in php.ini, additional variables are available. For example, $userfile_name will equal $_FILES['userfile']['name'], $userfile_type will equal $_FILES['userfile']['type'], etc. Keep in mind that as of PHP 4.2.0, register_globals defaults to off. It's preferred to not rely on this directive.

Ha a register_globals be van kapcsolva a php.ini fájlban, akkor a következő változók jönnek létre. A $userfile_name megegyezik a $_FILES['userfile']['name'] elemével, $userfile_type a $_FILES['userfile']['type'] elemével, stb. Vedd figyelembe, hogy PHP 4.2.0 verziójától kezdve a register_globals alapértelmezés szerint ki vankapcsolva. Nem ajánlatos erre a direktívára hagyatkozni program írásakor.

Az állományok alapbeállításban a szerver szokásos ideiglenes könyvtárában tárolódnak, ha nem adtál meg mást az upload_tmp_dir beállítással a php.ini fájlban. A szerver alapbeállítású könyvtára megváltoztatható a TMPDIR környezeti változóval abban a környezetben, ahol a PHP fut. PHP szkriptből a putenv()-el való átállítás nem működik. Ez a környezeti változó annak ellenőrzésére is használható, hogy más műveletek is végezhetőek-e a feltöltött állományokon.

Példa 18-2. Fájlfeltöltések ellenőrzése

Az alábbi példák a PHP 4.0.2-nél újabb verzióival működnek. Lásd az is_uploaded_file() és move_uploaded_file() függvényeket.

<?php
// A PHP 4.1.0 előtti verzióiban a $_FILES helyett a $HTTP_POST_FILES használandó
if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
    copy($_FILES['userfile']['tmp_name'], "/a/feltoltott/file/uj/helye");
} else {
    echo "Lehetséges támadás. Fájlnév: " . $HTTP_POST_FILES['userfile']['name'];
}
/* ...vagy... */
move_uploaded_file($_FILES['userfile']['tmp_name'], "/a/feltoltott/file/uj/helye");
?>

A PHP programnak, amely megkapja a feltöltött állományt, gondoskodnia kell arról is, hogy a kívánt műveleteket elvégezze az állománnyal. Például törölheti azt, ha az túl nagy, vagy túl kicsi, figyelembe véve a $_FILES['userfile']['size'] változó értékét, vagy meghatározhatja a $_FILES['userfile']['type'] alapján, hogy ez a fájl megfelel-e egy meghatározott fájltípusnak, és ha nem, törölheti. PHP 4.2.0-től kezdve a $_FILES['userfile']['error'] használható arra, hogy a hibakódoknak megfelelően változzon szkript működését. Bármi is legyen a cél a feltöltött állománnyal, a PHP szkriptnek kell gondoskodnia arról, hogy elmozgassa egy biztonságos helyre, vagy törölje az ideiglenes könyvtárból az adott ideiglenes állományt.

Az ideiglenes állomány törlésre kerül az ideiglenes könyvtárból a kérés végrehajtásának végeztével, ha nem lett elmozgatva vagy átnevezve.


Hibaüzenetek magyarázatai

PHP 4.2.0-tól kezdve PHP az állományhoz tartozó tömbben a megfelelő hibakódot is visszaadja. Ezt a hibakódot a feltöltéskor létrehozott tömb ['error'] eleme tárolja. Másképp megfogalmazva, a hiba a $_FILES['userfile']['error'] hivatkozás értékeként olvasható ki.

UPLOAD_ERR_OK

érték: 0; nincs hiba, a feltöltés sikerült.

UPLOAD_ERR_INI_SIZE

érték: 1; a feltölteni kívánt fájl túl nagy a php.ini-ben megadott upload_max_filesize direktíva által megengedetthez képest.

UPLOAD_ERR_FORM_SIZE

érték: 2; a feltölteni kívánt fájl túl nagy a HTML űrlapban megadott MAX_FILE_SIZE értékhez képest.

UPLOAD_ERR_PARTIAL

érték: 3; az állomány csak részben lett feltöltve.

UPLOAD_ERR_NO_FILE

érték: 4; nem történt állomány-feltöltés.

Megjegyzés: Ezek állandókként is használhatók PHP 4.3.0-tól kezdve.


Tipikus csapdák

A MAX_FILE_SIZE nem tartalmazhat nagyobb értéket, mint az upload_max_filesize beállítás értéke. Az alapbeállítás 2 megabyte.

Ha a memóriakorlát be van állítva, esetleg növelni kell a memory_limit értékét. Gondoskodni kell a memory_limit kellően nagyra állításáról!

Ha a max_execution_time túl kicsire van állítva, a program futása során letelhet az idő. Ezért gondoskodni kell a max_execution_time kellően nagyra állításáról! Az állományok feltöltése nem számít bele a max_execution_time időbe, de egy nagyobb állomány feldolgozása lehetséges, hogy több időt vesz igénybe a program számára.

Ha a post_max_size túl kicsi, nagy állományok nem tölthetőek fel. Gondoskodni kell a post_max_size kellően nagyra állításáról!

Ellenőrizni kell mindig, hogy pontosan mely állományokon végez műveletet a program. A felhasználók esetleg más könyvtárakhoz is hozzáférhetnek...

A CERN httpd szerver úgy tűnik, hogy eldob mindent a klienstől kapott Content-type MIME fejlécben az első szóközt követően. Amíg ez fennáll, a CERN httpd szerver nem fogja támogatni a fájl feltöltéseket.

Köszönhetően a nagyon sokféle állomány elnevezési lehetőségnek, konvenciónak nam garantálható, hogy a különleges nevű (pl. szóközt tartalmazó) állományok feltöltése mindig a megfelelően működik.


Több állomány egyidejű feltöltése

Lehetséges több állomány egyidejű feltöltése is, az input elemek name paramétereinek különbözőre állításával.

Úgyszintén lehetőség van több megegyező nevű űrlap elemmel is több állomány feltöltésére. Ebben az esetben a kapcsolódó információkat tömbökben adja vissza a PHP. Ehhez a hagyományos tömbhivatkozást kell alkalmazni, mint minden más űrlapelemnél:

Megjegyzés: Több állomány egyidejű feltöltése a PHP 3.0.10 óta lehetséges.

Példa 18-3. Több fájl egyidejű feltöltése

<form action="file-feltolt.php" method="post" enctype="multipart/form-data">
  Az alábbi fájlok elküldése:<br>
  <input name="userfile[]" type="file"><br>
  <input name="userfile[]" type="file"><br>
  <input type="submit" value="OK">
</form>

Amikor a fenti űrlap adatai elküldésre kerülnek, a $_FILES['userfile'] $_FILES['userfile']['name'] és $_FILES['userfile']['size'] változók értéket kapnak. A $HTTP_POST_FILES tömbben ugyanezek elérhetőek a PHP 4.1.0 előtti verziókban. Ezek mind számokkal indexelt tömbök a tömbben beküldötteknek megfelelő értékekkel. A PHP 3-ban a $HTTP_POST_VARS használható. Ha a register_globals be van kapcsolva, globális változókat is létrehozásra kerülnek.

Páldául ha a /home/test/review.html és /home/test/xwp.out állományok kerültek feltöltésre, akkor a $_FILES['userfile']['name'][0] tartalma review.html és a $_FILES['userfile']['name'][1] tartalma xwp.out. Hasonló módon a $_FILES['userfile']['size'][0] a review.html fájl méretét tartalmazza, stb.

$_FILES['userfile']['name'][0], $_FILES['userfile']['tmp_name'][0], $_FILES['userfile']['size'][0] és $_FILES['userfile']['type'][0] szintén elérhetőek.


PUT metódusú feltöltések

A PHP támogatja a HTTP PUT metódust is, amit például a Netscape Composer és a W3C Amaya használ. A PUT kérések sokkal egyszerűbbek, mint az eddig tárgyalt feltöltések. A következőképpen néz ki:

PUT /eleresi/ut/filenev.html HTTP/1.1

Ez hagyományosan azt jelenti, hogy a kliens a küldött adatokat az /eleresi/ut/filenev.html fájlba szeretné elmenteni a webgyökér alatt. Az nyilvánvalóan nem lenne jó megoldás az Apache vagy a PHP részéről, ha bárkinek megengedné, hogy felülírja a fájlokat a web könyvtáradban. Éppen ezért a PUT kérések kezeléséhez be kell állítani a webszerver számára, hogy egy PHP szkriptnek küldje az ilyen bemenetet. Apache alatt ezt a Script direktívával teheted meg. Ez elhelyezhető szinte tetszőleges ponton az Apache konfigurációs fájlodban. Egy gyakori hely erre egy <Directory> blokk belseje, vagy esetleg egy <Virtualhost> blokk belseje. Például egy ilyen sor megoldja a feladatot:

Script PUT /put.php

Ez beállítja az Apache számára a PUT kérések kezelésére a put.php-t abban a környezetben, ahol ezt a sort elhelyezted a konfiguráláskor. Ez természetesen feltételezi, hogy a .php kiterjesztést a PHP kezeli és a PHP aktív.

A put.php fájlban aztán valami hasonlót tehetsz:

<?php copy($PHP_UPLOADED_FILE_NAME,$DOCUMENT_ROOT.$REQUEST_URI); ?>

Ez a kérés által meghatározott helyre másolja a küldött fájlt. Valós helyzetben természetesen szükséges valamilyen ellenőrzés, és/vagy felhasználóazonosítás, mielőtt esetleg felülírod egyik fontos fájlodat. A PHP a POST metódushoz hasonlóan egy ideiglenes fájlban tárolja a feltöltött fájlt. Amikor a kérés teljesítése befejeződött, ez az ideiglenes fájl törlődik. Ez azt jelenti, hogy a PUT kéréseket feldolgozó szkriptednek ezt a fájlt el kell mozgatnia máshova, ha meg szeretnéd tartani a feltöltött fájlt. Az ideiglenesen létrehozott fájl elérési útját a fájl nevével a $PHP_PUT_FILENAME váltózó tartalmazza, és a javasolt célt a $REQUEST_URI változó tartalmazza (bár ez lehet más is nem Apache szervereken). Ez a cél az, amit a kliens meghatározott. Neked nem kell feltétlenül ezt a helyet elfogadnod, lehet, hogy neked az a kényelmesebb (és biztonságosabb), hogy a feltöltött fájlokat egy speciális upload könyvtárban tárolod.


19. Fejezet. Távoli állományok kezelése

Amennyiben az allow_url_fopen be van kapcsolva a php.ini-ben, HTTP és FTP URL-eket lehet paraméterként átadni majdnem minden olyan függvénynek, amelyek fájlnevet kér paraméterül, beleértve az include(), include_once(), require() és require_once() utasításokat is. További információkért a használható protokollokkal kapcsolatban nézz el ide: J Függelék.

Megjegyzés: PHP 4.0.3 és régebbi verziókban az ilyen URL-ek értelmezéséhez szükséges a --enable-url-fopen-wrapper beállítás bekapcsolása.

Megjegyzés: A Windows-os, 4.3 előtti változatok PHP nem támogatják a távoli állományelérést a következő függvények esetén: include(), include_once(), require() és require_once(), valamint az imagecreatefromXXX függvények esetén. Ezekről többet: XLI, Képmanipuláló függvények Referencia

Ezt a lehetőséget lehet használni például egy távoli webszerveren lévő fájlt megnyitására, majd a kívánt adatok kigyűjtésére, vagy arra, hogy csak egyszerűen a saját oldalad kinézetével, stílusával tálald.

Példa 19-1. Egy távoli weboldal címsorának megállapítása

<?php
$file = fopen ("http://www.example.com/", "r");
if (!$file) {
    echo "<p>Nem lehet megnyitni a külső file-t!\n";
    exit;
}
while (!feof ($file)) {
  $line = fgets ($file, 1024);
  /* Ez csak akkor jó, ha a cím és a körbezáró tag-ek egy sorban vannak */
  if (eregi ("<title>(.*)</title>", $line, $out)) {
      $title = $out[1];
      break;
  }
}
fclose($file);
?>

Lehetőség van egy FTP szerveren tárolt fájlba írásra is, feltéve, hogy megfelelő jogokkal rendelkező user-ként lépsz be. Ezzel a módszerrel csak új fájlok hozhatók létre, ha már létezik a megadott nevű állomány akkor a fopen() hívása sikertelen lesz. Ha nem 'anonymous' felhasználóként szeretnél belépni, a felhasználói nevet és jelszót az URL részeként kell megadni a alábbi formában: 'ftp://felhasznalo:jelszo@ftp.pelda.hu/eleresi/ut/alma.txt'. (Ugyanezt a módszert használható akkor is, ha olyan állományokat kell elérni HTTP-n keresztül, amelyek a Basic azonosítást igénylik.)

Példa 19-2. Adat tárolása távoli gépen

<?php
$file = fopen ("ftp://ftp.example.com/incoming/outputfile", "w");
if (!$file) {
    echo "<p>Nem lehet megnyitni a külső file-t írásra.\n";
    exit;
}
/* Itt írunk a file-ba */
fputs ($file, "$_SERVER['HTTP_USER_AGENT']\n");
fclose ($file);
?>

Megjegyzés: A fenti példa alapján talán azt hihetnénk, hogy ilyen technikát kell használni például távoli naplózáshoz. Sajnálatos módon azonban ez nem működik, mert a fopen() hívása sikertelen lesz, ha a távoli állomány már létezik. Az ehhez hasonló elosztott, távoli naplózáshoz a syslog() függvény szolgáltatásait kell igénybe venni.


20. Fejezet. Kapcsolatkezelés

Megjegyzés: Az alábbi fejezetek csak a PHP 3.0.7-es és későbbi verzióira vonatkoznak!

A PHP belsőleg nyilvántartja a kapcsolati státuszt. Három lehetséges állapot van:

  • 0 - NORMAL (Normál)

  • 1 - ABORTED (Megszakított)

  • 2 - TIMEOUT (Időtúllépéses)

Amikor egy PHP szkript fut, alapállapotban a NORMAL állapot aktív. Ha a távoli kliens bontja a kapcsolatot, az ABORTED statátusz jelzése lesz aktív. Ez tipikusan akkor áll elő, ha a látogató a STOP gomb-ot használja a böngészőjében. Ha a PHP által felügyelt időkorált kerül túllépésre (lásd a set_time_limit() függvényt), a TIMEOUT állapot válik aktívvá.

Eldöntheted, hogy ha a kliens bontja a kapcsolatot, a szkript is leálljon-e vagy sem. Néha hasznos lehet, ha a szkriptjeid mindig végigfutnak, annak ellenére, hogy a kliens már nem fogadja a kimenetet. Alapbeállításban azonban a szkript is befejezi a futását, ha a kliens bontja a kapcsolatot. Ez a viselkedés az ignore_user_abort php.ini beállítással, valamint az ennek megfelelő "php_value ignore_user_abort" Apache .conf direktívával állítható, vagy az ignore_user_abort() függvénnyel. Ha nem konfigurálod úgy a PHP-t, hogy hagyja figyelmen kívül a kliens kapcsolatbontását, a szkriptjeid le fognak állni ilyen esetekben. Egyetlen kivétel ez alól, ha egy 'shutdown' függvényt definiálsz a register_shutdown_function()-al. Egy ilyen beállítással, ha a látogató lenyomja a STOP gombot, a szkripted következő kimenet-küldési kísérletére a PHP a 'shutdown' függvényt fogja meghívni. A 'shutdown' függvény abban az esetben is meghívásra kerül, ha a szkript normálisan befejezi a futását, tehát ha valami speciálisat szeretnél tenni, amikor a kliens bontja a kapcsolatot, a connection_aborted() függvényt használhatod. Ez igazat fog visszaadni, ha a kapcsolatot a kliens bontotta.

A szkripted a belső időmérés következtében is megállhat. Alapbeállításban egy szkript maximum 30 másodpercig futhat. Ez megváltoztatható a max_execution_time php.ini direktívával, illetve a megfelelő "php_value max_execution_time" Apache .conf beállítással, valamint a set_time_limit() függvénnyel. Amikor ez az idő letelik, a szkript megáll, és ha a fenti esetben említett 'shutdown' függvény definiált, az kerül meghívásra. Az időtúllépés esetét a connection_timeout() függvényel állapíthatod meg. Ez igazat fog visszaadni, ha időtúllépés miatt hívódott meg a 'shutdown'.

Fontos megjegyezni, hogy az ABORTED és TIMEOUT állapotok egyszerre is aktívak lehetnek, ha a PHP-ben a kliens kapcsolatbontásának figyelmen kívül hagyását kérted. A PHP tudni fogja, hogy a kliens már bontotta a kapcsolatot, de a szkript futni fog tovább. Ha ráadásul eléri az időkorlátot, a szkript megáll, és a 'shutdown' függvény hívódik meg (ha beállítottál ilyet). Ezen a ponton azt fogod tapasztalni, hogy mind a connection_timeout(), mind a connection_aborted() igazat ad. Mindkettőt ellenőrizheted, ha a connection_status() függvényt hívod. Ez egy bitmezőt ad vissza, az aktív állapotokkal. Tehát ebben az esetben, mivel mindkét állapot aktív, 3-at fogsz visszakapni.


21. Fejezet. Állandó adatbázis kapcsolatok

Az állandó kapcsolatok SQL adatbázisokkal nem szűnnnek meg, ha a szkripted futása befejeződik. Ha egy állandó kapcsolatot kérsz, a PHP ellenőrzi, hogy van-e már megegyező kapcsolat (ami még az előző kérésekből maradhatott meg), és ha létezik, akkor azt használja. Ha nem talál ilyet, létrehoz egy kapcsolatot. A megegyező kapcsolat azt jelenti, hogy ugyanaz a host és ugyanaz a felhasználói név és jelszó került felhasználásra.

Megjegyzés: Állandó kapcsolatokat nem csak adatbázisok szolgáltathatnak, vannak más ilyen képességű kiterjesztések, mint például az IMAP kiterjesztés.

Ha esetleg nem ismered alaposabban a webszerverek működését, hibás kép alakulhat ki benned az állandó kapcsolatokról. Ezek a kapcsolatok nem alkalmasak arra, hogy felhasználói 'session'-eket nyiss ugyanazon SQL linkkel. Nem adnak lehetőséget hatékony tranzakciók felépítésére. Egészen pontosan, hogy alaposabban tisztázzuk a kérdést, az állandó adatbázis kapcsolatok nem adnak semmilyen plusz lehetőséget, ami nélkülük nem létezne.

Miért?

A válaszhoz meg kell érteni, hogyan működnek együtt a webszerverek a PHP-vel. Ennek három különböző módja lehetséges.

Az első lehetőség, hogy a PHP-t CGI "wrapper"-ként használod. Ha ezt a módszert használod, minden oldal lekérésekor és feldolgozásakor egy új példány fut le a PHP feldolgozóból. Mivel a szkript futtatása után egy ilyen példány leáll, minden erőforrás, amit lefoglalt (beleértve az adatbázis kapcsolatotokat) megszűnik. Ebben az esetben semmit sem érsz azzal, hogy állandó kapcsolatot próbálsz nyitni, ez az állandóság nem valósul meg.

A népszerűbb második forma, amikor a PHP-t modulként futtatod egy több process-es webszerverben. Egy több process-es webszerver tipikusan rendelkezik egy szülő process-el, ami koordinálja a többi kapcsolódó process (a gyermekek) munkáját, amik valójában a weboldalak kiszolgálását végzik. Ha egy kérés érkezik egy klienstől, egy éppen szabad gyermekprocess kapja meg a kiszolgálásra az utasítást. Ez azt jelenti, hogy ha ugyanaz a kliens egy újabb kapcsolatot kezdeményez, esetleg egy másik gyermekprocesshez jut, mint az első alkalommal. Ebben az esetben az állandó adatbázis kapcsolat azt jelenti a számodra, hogy az egyes gyermekprocess-ek csak az első alkalommal kell, hogy létrehozzák a kapcsolatot az adatbázissal, és amennyiben egy későbbi kérés ugyanebben a gyermekprocessben ugyanazt a kapcsoltatot kívánja megnyitni, a létező kapcsolat kerül felhasználásra.

A harmadik módszer, hogy a PHP-t plug-in-ként használod egy 'multithreaded' web szerverben. Ez azt jelenti, hogy az ISAPI, WSAPI, és NSAPI (Windows alatt) formák használhatóak a PHP-vel. Ez a PHP 4.0.0 óta lehetséges, és így a PHP alkalmas plug-in szintű együttműködésre a Netscape FastTrack (iPlanet), a Microsoft Internet Information Server (IIS), és az O'Reilly WebSite Pro szerverekkel, valamint más, a fenti standardokat támogató szerverekkel. Ebben az esetben az állandó adatbázis kapcsolatok működése megegyezik a fent leírt több process-es modellel.

Ha az állandó adatbázis kapcsolatok nem nyújtanak plusz szolgáltatásokat, mégis mire jók?

A válasz igen egyszerű: hatékonyság! Az állandó adatbázis kapcsolatok akkor lehetnek hasznosak, ha nagy a feleslegesen adatbázishoz kapcsolódással eltöltött idő. Az, hogy ez valójában milyen esetben van így, rengeteg faktoron múlik. Például azon, hogy milyen típusú adatbázisról van szó, azonos, vagy különböző gépen van-e, mint a szerver, mennyire terhelt az SQL szerver, stb. Lényegében, ha sok időt vesz igénybe a kapcsolódás, az állandó kapcsolatok jelentős segítséget nyújthatnak neked. Egy gyermekprocess így csak egy alkalommal kell, hogy kapcsolódjon, ahelyett, hogy egy ezt kérő oldal minden feldolgozásakor megtenné. Ez azt is jelenti, hogy minden gyermekprocessnek, meglesz a maga állandó kapcsolata a szerver felé. Például, ha 20 különböző gyermekprocess dolgozott fel egy állandó adatbáziskapcsolatot kérő oldalt, 20 különböző állandó kapcsolatod lesz az SQL szerverhez, egy-egy minden gyermektől.

Fontos megjegyezni azonban, hogy ennek lehetnek hátrányos következményei is, ha az adatbázisszerver korlátozott kapcsolatainak számát az állandó kapcsolatok lefoglalják. Ha az adatbázisszervered egyidejűleg maximálisan 16 kapcsolatot képes kezelni, és egy forgalmas időszakban egyszerre 17 process próbál meg kapcsolódni az adatbázishoz, az egyik képtelen lesz erre... Ha olyan hiba van a programodban (például végetelen ciklus), ami nem hagyja a kapcsolat felbontását, egy csak 16 kapcsolattal bíró adatbázis alaposan le lesz foglalva. Nézz utána az adatbázisszervered dokumentációjában, hogy hogyan tudod lekezelni az elhagyott vagy inaktív kapcsolatokat.

Figyelem

Van még néhány faktor, amit érdemes figyelembe venned, ha állandó adatbázis kapcsolatokat használsz. Egy ilyen probléma, hogy ha tábla lezárást (lock) használsz egy állandó kapcsolaton, és a szkript valamilyen okból nem tudja feloldani a zárat, ezt a kapcsolatot használó további szkriptek nem fognak helyesen működni, és a webszerver vagy adatbázis szerver újraindítására lehet szükség a feloldáshoz. Hasonlóan ha tranzakciókat használsz, a tranzakció blokk tovább folytatódik a következő megegyező kapcsolatot használó szkriptben, ha a tranzakciót indító szkript nem tudja lezárni azt. Ezekben az esetekben a register_shutdown_function() függvényt használhatod, hogy egy egyszerű "takarító" függvényt futtass le a programod végeztével, ami visszavonja a tranzakciókat, és feloldja a tábla zárakat. Jobban teszed azonban, ha úgy kerülöd meg a problémát, hogy nem használsz állandó kapcsolatokat olyan szkriptekben, amik tábla zárakat, vagy tranzakciókat alkalmaznak.

Összefoglalva: az állandó adatbáziskapcsolatokat úgy tervezték, hogy megfeleltethetőek legyenek a hagyományos kapcsolatokkal. Ez azt jelenti, hogy minden esetben lehetőséged van az állandó kapcsolatokat hagyományos kapcsolatokra cserélni, és ez nem fogja megváltoztatni a szkriptjeid működését. Ez a lépés megváltoztathatja a szkripted hatékonyságát, de a viselkedését nem!

Lásd még fbsql_pconnect(), ibase_pconnect(), ifx_pconnect(), imap_popen(), ingres_pconnect(), msql_pconnect(), mssql_pconnect(), mysql_pconnect(), ociplogon(), odbc_pconnect(), ora_plogon(), pfsockopen(), pg_pconnect(), és sybase_pconnect().


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


Security and Safe Mode

Táblázat 22-1. Security and Safe Mode Configuration Directives

NameDefaultChangeable
safe_mode"0"PHP_INI_SYSTEM
safe_mode_gid"0"PHP_INI_SYSTEM
safe_mode_include_dirNULLPHP_INI_SYSTEM
safe_mode_exec_dir""PHP_INI_SYSTEM
safe_mode_allowed_env_varsPHP_PHP_INI_SYSTEM
safe_mode_protected_env_varsLD_LIBRARY_PATHPHP_INI_SYSTEM
open_basedirNULLPHP_INI_SYSTEM
disable_functions""PHP_INI_SYSTEM
disable_classes""PHP_INI_SYSTEM
For further details and definition of the PHP_INI_* constants see ini_set().

Here's a short explanation of the configuration directives.

safe_mode boolean

Whether to enable PHP's safe mode. Read the Security chapter for more information.

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

As of PHP 4.2.0, 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/"

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.

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

Megjegyzés: 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.

open_basedir string

Limit the files that can be opened by PHP to the specified directory-tree, including the file itself. This directive is NOT affected by whether Safe Mode is turned On or Off.

When a script tries to open a file with, for example, fopen() or gzopen(), the location of the file is checked. When the file is outside the specified directory-tree, PHP will refuse to open it. All symbolic links are resolved, so it's not possible to avoid this restriction with a symlink.

The special value . indicates that the directory in which the script is stored will be used as base-directory.

Under Windows, separate the directories with a semicolon. On all other systems, separate the directories with a colon. As an Apache module, open_basedir paths from parent directories are now automatically inherited.

The restriction specified with open_basedir is actually a prefix, not a directory name. This means that "open_basedir = /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: "open_basedir = /dir/incl/"

Megjegyzés: Support for multiple directories was added in 3.0.7.

The default is to allow all files to be opened.

disable_functions string

This directive allows you to disable certain functions for security reasons. It takes on a comma-delimited list of function names. disable_functions is not affected by Safe Mode.

This directive must be set in php.ini For example, you cannot set this in httpd.conf.

disable_classes string

This directive allows you to disable certain classes for security reasons. It takes on a comma-delimited list of class names. disable_classes is not affected by Safe Mode.

This directive must be set in php.ini For example, you cannot set this in httpd.conf.

Availability note: This directive became available in PHP 4.3.2

See also: 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. 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 this 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


Functions restricted/disabled by safe mode

This is a still probably incomplete and possibly incorrect listing of the functions limited by safe mode.

Táblázat 22-2. Safe mode limited functions

FunctionLimitations
dbmopen()Ellenőrzi, hogy az állományok/könyvtárak, amelyekkel dolgozni szeretnél, ugyanazzal a felhasználói azonosítóval (UID) rendelkeznek-e, mint az éppen futó program.
dbase_open()Ellenőrzi, hogy az állományok/könyvtárak, amelyekkel dolgozni szeretnél, ugyanazzal a felhasználói azonosítóval (UID) rendelkeznek-e, mint az éppen futó program.
filepro()Ellenőrzi, hogy az állományok/könyvtárak, amelyekkel dolgozni szeretnél, ugyanazzal a felhasználói azonosítóval (UID) rendelkeznek-e, mint az éppen futó program.
filepro_rowcount()Ellenőrzi, hogy az állományok/könyvtárak, amelyekkel dolgozni szeretnél, ugyanazzal a felhasználói azonosítóval (UID) rendelkeznek-e, mint az éppen futó program.
filepro_retrieve()Ellenőrzi, hogy az állományok/könyvtárak, amelyekkel dolgozni szeretnél, ugyanazzal a felhasználói azonosítóval (UID) rendelkeznek-e, mint az éppen futó program.
ifx_*sql_safe_mode restrictions, (!= safe mode)
ingres_*sql_safe_mode restrictions, (!= safe mode)
mysql_*sql_safe_mode restrictions, (!= safe mode)
pg_lo_import()Ellenőrzi, hogy az állományok/könyvtárak, amelyekkel dolgozni szeretnél, ugyanazzal a felhasználói azonosítóval (UID) rendelkeznek-e, mint az éppen futó program.
posix_mkfifo()Ellenőrzi, hogy a könyvtár, amelyben dolgozni szeretnél, ugyanazzal a felhasználói azonosítóval (UID) rendelkezik-e, mint az éppen futó program.
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()Ellenőrzi, hogy az állományok/könyvtárak, amelyekkel dolgozni szeretnél, ugyanazzal a felhasználói azonosítóval (UID) rendelkeznek-e, mint az éppen futó program.
chdir()Ellenőrzi, hogy a könyvtár, amelyben dolgozni szeretnél, ugyanazzal a felhasználói azonosítóval (UID) rendelkezik-e, mint az éppen futó program.
dl()Ez a függvény nem használható, ha a safe mode be van kapcsolva.
backtick operatorEz a függvény nem használható, ha a safe mode be van kapcsolva.
shell_exec() (functional equivalent of backticks)Ez a függvény nem használható, ha a safe mode be van kapcsolva.
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.
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.
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.
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.
fopen()Ellenőrzi, hogy a könyvtár, amelyben dolgozni szeretnél, ugyanazzal a felhasználói azonosítóval (UID) rendelkezik-e, mint az éppen futó program.
mkdir()Ellenőrzi, hogy a könyvtár, amelyben dolgozni szeretnél, ugyanazzal a felhasználói azonosítóval (UID) rendelkezik-e, mint az éppen futó program.
rmdir()Ellenőrzi, hogy a könyvtár, amelyben dolgozni szeretnél, ugyanazzal a felhasználói azonosítóval (UID) rendelkezik-e, mint az éppen futó program.
rename()Ellenőrzi, hogy az állományok/könyvtárak, amelyekkel dolgozni szeretnél, ugyanazzal a felhasználói azonosítóval (UID) rendelkeznek-e, mint az éppen futó program. Ellenőrzi, hogy a könyvtár, amelyben dolgozni szeretnél, ugyanazzal a felhasználói azonosítóval (UID) rendelkezik-e, mint az éppen futó program.
unlink()Ellenőrzi, hogy az állományok/könyvtárak, amelyekkel dolgozni szeretnél, ugyanazzal a felhasználói azonosítóval (UID) rendelkeznek-e, mint az éppen futó program. Ellenőrzi, hogy a könyvtár, amelyben dolgozni szeretnél, ugyanazzal a felhasználói azonosítóval (UID) rendelkezik-e, mint az éppen futó program.
copy()Ellenőrzi, hogy az állományok/könyvtárak, amelyekkel dolgozni szeretnél, ugyanazzal a felhasználói azonosítóval (UID) rendelkeznek-e, mint az éppen futó program. Ellenőrzi, hogy a könyvtár, amelyben dolgozni szeretnél, ugyanazzal a felhasználói azonosítóval (UID) rendelkezik-e, mint az éppen futó program. (on source and target)
chgrp()Ellenőrzi, hogy az állományok/könyvtárak, amelyekkel dolgozni szeretnél, ugyanazzal a felhasználói azonosítóval (UID) rendelkeznek-e, mint az éppen futó program.
chown()Ellenőrzi, hogy az állományok/könyvtárak, amelyekkel dolgozni szeretnél, ugyanazzal a felhasználói azonosítóval (UID) rendelkeznek-e, mint az éppen futó program.
chmod()Ellenőrzi, hogy az állományok/könyvtárak, amelyekkel dolgozni szeretnél, ugyanazzal a felhasználói azonosítóval (UID) rendelkeznek-e, mint az éppen futó program. In addition, you cannot set the SUID, SGID and sticky bits
touch()Ellenőrzi, hogy az állományok/könyvtárak, amelyekkel dolgozni szeretnél, ugyanazzal a felhasználói azonosítóval (UID) rendelkeznek-e, mint az éppen futó program. Ellenőrzi, hogy a könyvtár, amelyben dolgozni szeretnél, ugyanazzal a felhasználói azonosítóval (UID) rendelkezik-e, mint az éppen futó program.
symlink()Ellenőrzi, hogy az állományok/könyvtárak, amelyekkel dolgozni szeretnél, ugyanazzal a felhasználói azonosítóval (UID) rendelkeznek-e, mint az éppen futó program. Ellenőrzi, hogy a könyvtár, amelyben dolgozni szeretnél, ugyanazzal a felhasználói azonosítóval (UID) rendelkezik-e, mint az éppen futó program. (note: only the target is checked)
link()Ellenőrzi, hogy az állományok/könyvtárak, amelyekkel dolgozni szeretnél, ugyanazzal a felhasználói azonosítóval (UID) rendelkeznek-e, mint az éppen futó program. Ellenőrzi, hogy a könyvtár, amelyben dolgozni szeretnél, ugyanazzal a felhasználói azonosítóval (UID) rendelkezik-e, mint az éppen futó program. (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() Ellenőrzi, hogy az állományok/könyvtárak, amelyekkel dolgozni szeretnél, ugyanazzal a felhasználói azonosítóval (UID) rendelkeznek-e, mint az éppen futó program. Ellenőrzi, hogy a könyvtár, amelyben dolgozni szeretnél, ugyanazzal a felhasználói azonosítóval (UID) rendelkezik-e, mint az éppen futó program. (note: only affected since PHP 4.2.1)
parse_ini_file() Ellenőrzi, hogy az állományok/könyvtárak, amelyekkel dolgozni szeretnél, ugyanazzal a felhasználói azonosítóval (UID) rendelkeznek-e, mint az éppen futó program. Ellenőrzi, hogy a könyvtár, amelyben dolgozni szeretnél, ugyanazzal a felhasználói azonosítóval (UID) rendelkezik-e, mint az éppen futó program. (note: only affected since PHP 4.2.1)
set_time_limit() Has no affect when PHP is running in safe mode.
max_execution_time Has no affect when PHP is running in safe mode.
mail() In safe mode, the fifth parameter is disabled. (note: only affected since PHP 4.2.3)
Any function that uses php4/main/fopen_wrappers.c ??


23. Fejezet. Parancssori programozás a PHP-ben

A 4.3-as verziótól felfelé a PHP támogat egy új SAPI (Server Application Programming Interface) típust, a CLI-t ami a Command Line Interface rövidítése. A nevéből következik, hogy ez a SAPI típus leginkább shell (vagy akár desktop!) alkalmazások fejlesztéséhez használatos a PHP-ben. Van néhány különbség a CLI SAPI és a többi SAPI között, ezek magyarázatára a későbbiekben rátérünk.

A CLI SAPI először a PHP 4.2.0 verziójában jelent meg, de akkor még csak kísérleti jelleggel. Használatához a --enable-cli kapcsolóval kellett indítani a ./configure scriptet installáláskor. A PHP 4.3.0 megjelenésétől megszűnt a kísérleti státusz és a CLI SAPI mindig beépül a php futtatható binárisba. (Windows alatt ez a php.exe)

Lényegesebb különbségek a CLI SAPI és a többi SAPI között:

  • A CGI SAPI-val ellentétben soha nem ír ki fejléceket.

    Habár a CGI SAPI lehetőséget ad a HTTP fejlécek letiltására egy kapcsolóval, de ez nem egyenértékű a CLI SAPI által nyújtott megoldással.

    A CLI alapértelmezetten "csendes" (quiet) módban indul, de a -q kapcsolót megtartották a kompatibilitás érdekében, hogy régebbi CGI szkripteket is problémamentesen lehessen futtatni.

    Nem cseréli fel az aktuális könyvtárat az éppen futó szkript könyvtárára. (A -C kapcsolót azért megtartották a kompatibilitás érdekében)

    Egyszerű, szöveges hibaüzenetek (nincs HTML formázás).

  • Vannak php.ini utasítások, melyeket a CLI SAPI egyszerűen figyelmen kívül hagy, mivel nincs közük a shell környezethez:

    Táblázat 23-1. Figyelmen kívül hagyott php.ini utasítások

    UtasításCLI SAPI default valueMagyarázat
    html_errorsFALSE A shellben lehetetlen elolvasni a hibaüzeneteket, ha azok zavaros HTML elemekkel tarkítva száguldanak át a képernyőn. Emiatt ez az utasítás alapértelmezetten FALSE.
    implicit_flushTRUE Általában azt akarjuk, hogy a print(), echo() és a hasonszőrű függvények mindenképpen írjanak a kimenetre és ne puffereljenek semmit. De használható a output buffering utasítás, ha a kimenet késleltetése vagy manipulálása a cél.
    max_execution_time0 (korlátlan) Minden eshetőségre felkészülve a PHP nem korlátozza a shell szkriptek futásidejét. Ez érthető, hiszen míg egy webes szkript általában pár másodperc alatt lefut, addig a shellprogramok nagyon hosszú ideig futhatnak.
    register_argc_argvTRUE A globális PHP változók $argc (a változók számát adja át a szkriptnek) és a $argv (az aktuális változók tömbje) elválaszthatatlanok a parancssori programok futásától és mindig feltöltődnek a megfelelő értékpárokkal, amikor használod a CLI SAPI-t.

    Megjegyzés: Ezek az utasítások nem adhatók meg a fentiektől különböző értékekkel a konfigurációs php.ini fájlban vagy egyéb saját php.ini-ben (ismert, hogy több php.ini is használható, akár könyvtáranként más). Ez egy korlátozás, mert alapértelmezett értékeik azután aktiválódnak, miután a konfigurációs fájlok lefutottak. Azonban ezek az értékek változhatnak a szkript futása alatt (ami nincs hatással minden említett utasításra, pl. register_argc_argv).

  • Hogy kényelmesebbé tegyék a parancssori programozást, néhány konstanst előre definiáltak:

    Táblázat 23-2. Specifikus CLI konstansok

    konstansokLeírás
    STDIN Egy, már megnyitott streamet (folyamatot) az stdin-re (standard input - bemenet) küld. A stream megnyitásától a következőképpen kímél meg bennünket:
    $stdin = fopen('php://stdin', 'r');
    STDOUT Egy, már megnyitott streamet az stdout-ra (standard output - kimenet) küld. Ez a stream megnyitásától a következőképpen kímél meg bennünket:
    $stdout = fopen('php://stdout', 'w');
    STDERR Egy, már megnyitott streamet az stdout-ra küld (Ez a hibaüzenetek kiíratásáért felelős.) A stream megnyitásától a következőképpen kímél meg bennünket:
    $stderr = fopen('php://stderr', 'w');

    A fentieknek megfelelően nincs szükség arra, hogy pl. megnyiss egy streamet az stderr-ért, hanem egyszerűen csak használd a konstanst a stream forrás helyett:
    php -r 'fwrite(STDERR, "stderr\n");'
    Ezeket a streameket nem kell külön lezárni, automatikusan megteszi ezt a PHP.

  • A CLI SAPI nem cseréli az aktuális könyvtára a futó szkript könyvtárára!

    Szemléletes példa erre a CGI SAPI sajátosságra:
    <?php
        /* Ez a mi kis tesztprogramunk ;) és az aktuális könyvtárat írja ki,
        amiben éppen "tartózkodunk". Neve: test.php */
        echo getcwd(), "\n";
    ?>

    A CGI verzió használatakor a következőkre számíthatunk:
    $ pwd  //Linux/Unix alatt kiírja az aktuális könyvtárat 
    /tmp   //az aktuális könyvtár a /tmp
    
    $ php-cgi -f másik_könyvtár/test.php  
    /tmp/másik_könyvtár
    Ebből tisztán látszik, hogy a PHP lecserélte az aktuális könyvtárat a futtatott szkriptére.

    Ugyanez a CLI SAPI-val:
    $ pwd
    /tmp
    
    $ php -f másik_könyvtár/test.php
    /tmp
    Ez sokkal nagyobb rugalmasságot biztosít a parancssori programok írása során a PHP-ben.

    Megjegyzés: A fenti példában a CGI SAPI ugyanúgy viselkedik, mint a CLI SAPI, ha a -C kapcsolóval indítod a szkriptet a parancssorból.

Az alábbi listát a parancssori opciókról a PHP generálta. Ezt bármikor kilistáztathatod ha a PHP-t a -h kapcsolóval indítod parancssorból:
Usage: php [options] [-f] <file> [args...]
       php [options] -r <code> [args...]
       php [options] [-- args...]
  -s               Display colour syntax highlighted source.
  -w               Display source with stripped comments and whitespace.
  -f <file>        Parse <file>.
  -v               Version number
  -c <path>|<file> Look for php.ini file in this directory
  -a               Run interactively
  -d foo[=bar]     Define INI entry foo with value 'bar'
  -e               Generate extended information for debugger/profiler
  -z <file>        Load Zend extension <file>.
  -l               Syntax check only (lint)
  -m               Show compiled in modules
  -i               PHP information
  -r <code>        Run PHP <code> without using script tags <?..?>
  -h               This help

  args...          Arguments passed to script. Use -- args when first argument 
                   starts with - or script is read from stdin

A CLI SAPI-val háromféleképpen indíthatsz el egy PHP programot:

  1. Hogyan lehet a PHP-vel fájlokat futtatni.

    php my_script.php
    
    php -f my_script.php
    Mindkét módon (használva a -f kapcsolót vagy nem) futtatja a my_script.php nevű szkriptet. Bármit futtathatsz, a PHP szkriteknek nem muszáj .php kiterjesztésűeknek lenniük, bármilyen nevű és kiterjesztésű fájl futtatható.

  2. PHP kód futtatása közvetlenül a parancssorból.

    php -r 'print_r(get_defined_constants());'
    Különösen figyelni kell a shell változók helyettesítésére és az idézőjelekre!

    Megjegyzés: A példát figyelmesen szemlélve észrevehetjük, hogy nincsenek nyitó és záró tagok. Az -r kapcsolóval ezekre nincs szükség. Ha mégis használod őket, az hibához fog vezetni.

  3. PHP kód futtatása a standard inputon (stdin) keresztül.

    Ez a módszer dinamikussá teszi a PHP kód létrehozását és egyből a futtatható binárisba táplálja a kódot, amint a következő (képzeletbeli) példában láthatjuk:
    $ valami_szkript | valami_filter | php | sort -u >eredmeny.txt

A három programfuttatási módszert nem lehet egymással kombinálni.

Mint minden shellprogram, a PHP bináris, így az általad írt PHP szkript képes argumentumokat feldolgozni. Bármennyi argumentumot megadhatsz a szkriptednek, ezek számát nem korlátozza a PHP (A shellben van egy bizonyos határ a megadható argumentumok számát illetően, de az általában bőségesen elég). A szkriptnek átadott argumentumokat a $argv globális tömb tartalmazza. A tömb nulladik eleme mindig a szkript neve. (Ez a - karakterjel abban az esetben, ha a PHP kód az -r kapcsolóval lett indítva a parancssorból.) A másik globális tömb a $argc, ami a $argv tömb elemeinek számát tartalmazza (De ez NEM egyenlő a szkriptnek átadott argumentumok számával!).

Amikor különféle opciókkal akarod futtatni egy szkriptet, az argumentumoknak nem szabad - karakterrel kezdődniük. Ha mégis kiteszed a - jelet, akkor abból könnyen probléma lehet, mert a PHP úgy veszi, mintha a saját opciói közül adnál meg egyet. Hogy ezt elkerüld, használd a -- szeparátort. Ez esetben a PHP az argumentumokat változtatás nélkül továbbítja a szkriptnek.

# Ez nem fogja futtatni a megadott kódot, csak szemléltetésre jó.
$ php -r 'var_dump($argv);' -h
Usage: php [options] [-f] <file> [args...]
[...]

# Ez átadja a szkriptnek a '-h' argumentumot és megakadályozza a PHP-t abban,
# hogy a sajátjának higgye. 
$ php -r 'var_dump($argv);' -- -h
array(2) {
  [0]=>
  string(1) "-"
  [1]=>
  string(2) "-h"
}

Habár, van egy másik módja a PHP paracssori futtatásának. Lehet írni olyan programokat, melyek a #!/usr/bin/php sorral kezdődnek és ezt követi a "normál" PHP kód, a szabványos PHP kezdő-és záró tagokkal (valamint a fájl futtatási paramétereinek a beállításai). Ezzel a módszerrel úgy futtathatjuk programunkat, mint egy normál shell vagy Perl szkriptet:
#!/usr/bin/php
<?php
    var_dump($argv);
?>
Feltéve, hogy ennek a fájlnak test a neve (és az éppen aktuális könyvtárunkban van, Linux alatt), a következőket tehetjük:
$ chmod 755 test
$ ./test -h -- foo
array(4) {
  [0]=>
  string(6) "./test"
  [1]=>
  string(2) "-h"
  [2]=>
  string(2) "--"
  [3]=>
  string(3) "foo"
}
Látható, hogy ebben az esetben semmi problémát nem okozott az, hogy a szkriptnek a - karakterrel adtuk át az argumentumokat.

Táblázat 23-3. Parancssori opciók

OpcióLeírás
-s

Színesben kiemelt forrását írja ki a szkriptnek.

Ez az opció egy saját algoritmust használ a fájl elemzéséhez, amivel HTML kódot generál a forrásból a standard kimenetre. Ez a kód tartalmazza a színes kiemeléshez szükséges és az egyéb formázó tag-eket, a szabványos <code> [...] </code> HTML formában, de nem tartalmazza a HTML fejléceket.

Megjegyzés: Ez az opció nem hazsnálható együtt az -r kapcsolóval.

-w

Kommentek és felesleges sorközök nélkül listázza ki a kódot.

Megjegyzés: Ez az opció nem használható együtt az -r kapcsolóval.

-f

Értelmezi és futtatja az -f kapcsoló után megadott fájlot. Ez a kapcsoló opcionális és el lehet hagyni, ha pusztán a fájlnév elegendő a fájl futtatásához.

-v

Kiírja a PHP, PHP SAPI, és a Zend verziószámát a standard kimenetre, pl:
$ php -v
PHP 4.3.0-dev (cli), Copyright (c) 1997-2002 The PHP Group
Zend Engine v1.2.1, Copyright (c) 1998-2002 Zend Technologies

-c

Ha nem a megszokott helyén van, akkor megadhatjuk ezzel a kapcsolóval, hogy hol a php.ini vagy megadhatunk egy saját INI fájlot (aminek nem muszáj php.ini nevet adni!), pl..:
#ezzel megmondjuk a PHP-nek, hogy a /saját/könyvtárban találja a php.ini-t
$ php -c /saját/könyvtár/ maszek.php

#ez pedig utasítja PHP-t, hogy a /saját/könyvtárban/ levő saját.ini-t
#vegye alapul a maszek.php szkript futtatásakor.
$ php -c /saját/könyvtár/saját.ini maszek.php

-a

Interaktívan futtatja a PHP-t.

-d

Ezzel az opcióval bármilyen konfigurációs utasítást, ami csak a php.ini-ben megtalálható, egy saját értékkel érvényesíthetünk a szkript futásának idejére. Az általános formája a következő:
-d konfigurációs_utasítás[=érték]

Példák:
# Az értéket elhagyva a megadott konfigurációs utasításhoz az "1" értéket
# rendeli.
$ php -d max_execution_time -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(1) "1"

# Ha csak egy szóközt nyomunk az érték helyett, akkor a konfigurációs
# utasításnak az "" értéket adja.
php -d max_execution_time= -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(0) ""

# A konfigurációs utasítás értéke az lesz, amit az egyenlőségjel után írunk: 
$  php -d max_execution_time=20 -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(2) "20"
$  php -d max_execution_time=fogalmamsincsen -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(15) "fogalmamsincsen"

-e

A hibakeresést segíti részletes információk kiírásával.

-z

Betölti a Zend bővítményt. Ha csak a futtatandó szkript nevét adtuk meg utána, akkor a PHP megpróbálja ezt a bővítményt a rendszereden alapértelmezett függvéykönyvtár (library) útvonal alapján betölteni (Ez általában az /etc/ld.so.conf fájlban van definiálva a Linux rendszereken). Ha megadsz egy konkrét útvonalat, akkor a PHP ezt veszi alapul, nem pedig a rendszer általit. Relatív útvonalat is megadhatsz a PHP-nek, hogy az aktuális könyvtárhoz képest hol keresse a bővítményt.

-l

Segítségével kényelmesen elvégezhető a szintaktikai ellenőrzés egy megadott PHP kódon. Ha nincs hiba, a standard kimenetre kiírja, hogy No syntax errors detected in <filename> És a shell visszatérési értéke 0. Hiba esetén a szöveg Errors parsing <filename>, majd kiírja a standard kimenetre a megérdemelt hibaüzenetet és a shell visszatérési értéke 255 lesz.

Ez az opció nem jelzi a végzetes hibákat (mint pl. egy definiálatlan függvény). Használd ezt az -f kapcsolóval együtt, ha végzetes hibákat is akarsz találni. ;)

Megjegyzés: Ez az opció nem használható együtt az -r kapcsolóval.

-m

Eme opció használatával a PHP kilistázza a beépített (és betöltött) PHP és Zend modulokat:
$ php -m
[PHP Modules]
xml
tokenizer
standard
session
posix
pcre
overload
mysql
mbstring
ctype

[Zend Modules]

-i Ez a parancsori opció meghívja a phpinfo() függvényt és kiírja az eredményét. Ha a PHP furcsán viselkedik, ajánlatos kiadni a parancssorban egy php -i-t és figyelmesen elolvasni a hibaüzeneteket a táblázatokban. Készülj fel rá, hogy a kimenet HTML formázott, így a parancssorban szinte olvashatatlan. (Irányítsd át a kimenetet egy HTML fájlba (php -i >phpinfo.html) és nézd meg egy böngészővel.)
-r

Ez az opció teszi lehetővé, hogy PHP parancsokat adjunk ki közvetlenül a parancssorból. A kezdő és a záró PHP tagok (<?php és ?>) NEM KELLENEK és hibához fog vezetni, ha mégis alkalmazod őket.

Megjegyzés: Óvatosan kell bánni ezzel a parancssori PHP futtatási módszerrel, nehogy a változó helyettesítés miatt összeakadjon a shellel.

Példa egy ilyen hibára
$ php -r "$foo = get_defined_constants();"
Command line code(1) : Parse error - parse error, unexpected '='
Itt az a probléma, hogy az sh/bash shell elvégezte a változó helyettesítést mert dupla idézőjeleket " használtunk. Mivel azonban a $foo nem definiált, a shell behelyettesíti egy üres értékre, vagyis az a helyzet, mintha a következő parancsot adtuk volna ki a PHP-nek:
$ php -r " = get_defined_constants();"
Az a helyes megoldás, ha egyszerű idézőjeleket (') használunk. Az ilyen idézőjelek közé írt változókkal nem foglalkozik az sh/bash.
$ php -r '$foo = get_defined_constants(); var_dump($foo);'
array(370) {
  ["E_ERROR"]=>
  int(1)
  ["E_WARNING"]=>
  int(2)
  ["E_PARSE"]=>
  int(4)
  ["E_NOTICE"]=>
  int(8)
  ["E_CORE_ERROR"]=>
  [...]
Ha nem sh/bash, shellt használsz, a hibákat és tapasztalataidat bátran oszd meg velünk egy emailben: phpdoc@lists.php.net. Problémákat okozhat, ha shell változókat akarsz a kódba integrálni vagy blackslahes-eket használni.

-h Ezzel az opcióval lehet információt szerezni az aktuális parancssori opciókról és néhány sornyi magyarázatot hozzájuk.

The PHP executable can be used to run PHP scripts absolutely independent from the web server. If you are on a Unix system, you should add a special first line to your PHP script, and make it executable, so the system will know, what program should run the script. On a Windows platform you can associate php.exe with the double click option of the .php files, or you can make a batch file to run the script through PHP. The first line added to the script to work on Unix won't hurt on Windows, so you can write cross platform programs this way. A simple example of writing a command line PHP program can be found below.

Példa 23-1. Script intended to be run from command line (script.php)

#!/usr/bin/php
<?php

if ($argc != 2 || in_array($argv[1], array('--help', '-help', '-h', '-?'))) {
?>

This is a command line PHP script with one option.

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

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

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

In the script above, we used the special first line to indicate, that this file should be run by PHP. We work with a CLI version here, so there will be no HTTP header printouts. There are two variables you can use while writing command line applications with PHP: $argc and $argv. The first is the number of arguments plus one (the name of the script running). The second is an array containing the arguments, starting with the script name as number zero ($argv[0]).

In the program above we checked if there are less or more than one arguments. Also if the argument was --help, -help, -h or -?, we printed out the help message, printing the script name dynamically. If we received some other argument we echoed that out.

If you would like to run the above script on Unix, you need to make it executable, and simply call it as script.php echothis or script.php -h. On Windows, you can make a batch file for this task:

Példa 23-2. Batch file to run a command line PHP script (script.bat)

@c:\php\php.exe script.php %1 %2 %3 %4

Assuming, you named the above program as script.php, and you have your php.exe in c:\php\php.exe this batch file will run it for you with your added options: script.bat echothis or script.bat -h.

See also the Readline extension documentation for more functions you can use to enhance your command line applications in PHP.

V. Függvény referencia

Tartalom
I. Apache-specifikus függvények
II. Tömbkezelő függvények
III. Aspell függvények [ellenjavallt]
IV. BCMath tetszőleges pontosságú matematikai függvények
V. Bzip2 tömörítési függvények
VI. Naptár függvények
VII. CCVS függvények
VIII. COM támogató függvények Windowshoz
IX. Osztály/Objektum függvények
X. ClibPDF függvények
XI. Crack functions
XII. CURL, Client URL Library Functions
XIII. Cybercash payment függvények
XIV. Cyrus IMAP administration functions
XV. Character type functions
XVI. Database (dbm-style) abstraction layer functions
XVII. Dátummal és időponttal kapcsolatos függvények
XVIII. dBase functions
XIX. DBM Functions [deprecated]
XX. dbx függvények
XXI. DB++ Functions
XXII. Direct IO functions
XXIII. Könyvtárkezelő függvények
XXIV. DOM XML függvények
XXV. .NET functions
XXVI. Error Handling and Logging Functions
XXVII. File alteration monitor functions
XXVIII. FrontBase Functions
XXIX. filePro függvények
XXX. Filesystem functions
XXXI. Forms Data Format functions
XXXII. FriBiDi functions
XXXIII. FTP functions
XXXIV. Függvénykezelő függvények
XXXV. GNU Gettext
XXXVI. GMP functions
XXXVII. HTTP functions
XXXVIII. Hyperwave functions
XXXIX. Hyperwave API functions
XL. iconv functions
XLI. Képmanipuláló függvények
XLII. IMAP, POP3 and NNTP functions
XLIII. Informix functions
XLIV. InterBase functions
XLV. Ingres II functions
XLVI. IRC Gateway Functions
XLVII. PHP / Java Integration
XLVIII. LDAP functions
XLIX. LZF Functions
L. Mail függvények
LI. mailparse functions
LII. Matematikai függvények
LIII. Multi-Byte String Functions
LIV. MCAL functions
LV. Mcrypt Encryption Functions
LVI. MCVE Payment Functions
LVII. Mhash függvények
LVIII. Mimetype Functions
LIX. Microsoft SQL Server functions
LX. Ming függvénykönyvtár Flash mozik előállításához
LXI. Miscellaneous functions
LXII. mnoGoSearch Functions
LXIII. mSQL functions
LXIV. MySQL függvények
LXV. Improved MySQL Extension
LXVI. Mohawk Software session handler functions
LXVII. muscat functions
LXVIII. Hálózatkezelési Függvények
LXIX. Ncurses terminal screen control functions
LXX. Lotus Notes functions
LXXI. NSAPI-specific Functions
LXXII. Unified ODBC functions
LXXIII. Object Aggregation/Composition Functions
LXXIV. Oracle 8 függvények
LXXV. OpenSSL functions
LXXVI. Oracle függvények
LXXVII. Ovrimos SQL functions
LXXVIII. Kimenet Szabályozó Függvények
LXXIX. Object property and method call overloading
LXXX. PDF functions
LXXXI. Verisign Payflow Pro functions
LXXXII. PHP Options&Information
LXXXIII. POSIX functions
LXXXIV. PostgreSQL függvények
LXXXV. Process Control Functions
LXXXVI. Programfuttató függvények
LXXXVII. Printer functions
LXXXVIII. Pspell Functions
LXXXIX. GNU Readline
XC. GNU Recode függvények
XCI. Reguláris kifejezések függvényei (Perl kompatibilis)
XCII. qtdom functions
XCIII. Regular Expression Functions (POSIX Extended)
XCIV. Semaphore, Shared Memory and IPC Functions
XCV. SESAM database functions
XCVI. Munkamenet kezelő függvények
XCVII. Shared Memory Functions
XCVIII. SimpleXML functions
XCIX. SQLite
C. Shockwave Flash functions
CI. SNMP functions
CII. Socket functions
CIII. Stream functions
CIV. String functions
CV. Sybase functions
CVI. Tidy Functions
CVII. Tokenizer functions
CVIII. URL függvények
CIX. Változókkal kapcsolatos függvények
CX. vpopmail függvények
CXI. W32api functions
CXII. WDDX függvények
CXIII. XML értelmező függvények
CXIV. XML-RPC functions
CXV. XSLT függvények
CXVI. YAZ functions
CXVII. YP/NIS Functions
CXVIII. Zip Fájl függvények (csak olvasáshoz)
CXIX. Zlib Compression Functions

I. Apache-specifikus függvények

Ezek a függvények csak akkor használhatók, ha a PHP Apache modulként fut.

Tartalom
apache_child_terminate -- terminálja az Apache processzt a kérés után
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 --  Végrehajt egy részleges kérést a meghatározott URI-re és visszatér ennek összes információjával
apache_note -- Apache kérés megjegyzéseket kér és állít be
apache_request_headers -- visszaadja az összes HTTP-kérés fejlécet
apache_response_headers -- visszadja az összes HTTP válasz fejlécet
apache_setenv -- Apache subprocess_env változóit állítja be
ascii2ebcdic -- Átalakít egy stringet ASCII-ből EBCDIC-be
ebcdic2ascii -- Átalakít egy stringet EBCDIC-ből ASCII-be
getallheaders -- visszaadja az összes HTTP-kérés fejlécet
virtual -- Végrehajt egy Apache allekérést

apache_child_terminate

(PHP 4 >= 4.0.5)

apache_child_terminate -- terminálja az Apache processzt a kérés után

Leírás

bool apache_child_terminate ( void )

Az apache_child_terminate() feljegyzi megszüntetésre az aktuális PHP kérést futtató Apache processzt, azaz miután a PHP szkript futása befejeződött, az Apache megkísérli ezt a processzt bezárni. Ezt pl. sok memóriát fogyasztó processzek leállításra lehet használni, mivel ez memória csak belsőleg szabadul fel általában, és az operációs rendszer szintjén nem jelenik meg.

Megjegyzés: Ennek a lehetőségnek a használatát befolyásolja a child_terminate a php.ini-ben, amelynek kezdőértéke off alapértelmezés szerint.

Ez a lehetőség nem használható az Apache többszálú verzióban, így Win32-es platformon futó változataira sem.

Lásd még: exit()!

apache_get_modules

(PHP 4 >= 4.3.2)

apache_get_modules --  Get a list of loaded Apache modules

Description

array apache_get_modules ( void )

This function returns an array with the loaded Apache modules.

Példa 1. apache_get_modules() example

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

The above example will output something similar to:

Array
(
    [0] => core
    [1] => http_core
    [2] => mod_so
    [3] => sapi_apache2
    [4] => mod_mime
    [5] => mod_rewrite
)

apache_get_version

(PHP 4 >= 4.3.2)

apache_get_version --  Fetch Apache version

Description

string apache_get_version ( void )

apache_get_version() returns the version of Apache as string, or FALSE on failure.

Példa 1. apache_get_version() example

<?php
$version = apache_get_version();
echo "$version \n <br />";
?>

The printout of the above program will look similar to:

Apache/1.3.29 (Unix) PHP/4.3.4

See also phpinfo().

apache_getenv

(PHP 4 >= 4.3.0)

apache_getenv --  Get an Apache subprocess_env variable

Description

string apache_getenv ( string variable [, bool walk_to_top])

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

apache_lookup_uri

(PHP 3>= 3.0.4, PHP 4 )

apache_lookup_uri --  Végrehajt egy részleges kérést a meghatározott URI-re és visszatér ennek összes információjával

Leírás

object apache_lookup_uri ( string filename)

Végrehajt egy részleges kérést a meghatározott URI-re és visszatér ennek összes információjával. Elég messze elmegy ahhoz, hogy megszerezze az összes információt az adott forrásról és visszaadja ezeket egy osztályban. A visszaadott osztály tulajdonságai:

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

Megjegyzés: Az apache_lookup_uri() csak akkor működik, ha a PHP Apache modulként van telepítve.

apache_note

(PHP 3>= 3.0.2, PHP 4 )

apache_note -- Apache kérés megjegyzéseket kér és állít be

Leírás

string apache_note ( string note_name [, string note_value])

Az apache_note() egy Apache-specifikus függvény amely egy kérésben értékeket kér le és állít be a notes táblában. Ha egy argumentummal hívod, akkor az aktuális note_name megjegyzés értékével tér vissza. Ha két argumentummal hívod, akkor beállítja a note_name értékét note_value-ra, és a note_name korábbi értékével tér vissza.

apache_request_headers

(PHP 4 >= 4.3.0)

apache_request_headers -- visszaadja az összes HTTP-kérés fejlécet

Leírás

array apache_request_headers ( void )

apache_request_headers() függvény az aktuális kérés összes HTTP fejlécével tér vissza, amit asszociatív tömbben ad vissza. Ez csak akkor használható, ha a PHP Apache modulként fut.

Megjegyzés: PHP 4.3.0-t megelőzően az apache_request_headers() neve getallheaders() volt. PHP 4.3.0-tól kezdve a getallheaders() csak álnévként szolgál a apache_request_headers() függvényhez.

Ez a példa kijelzi az aktuális kéréshez tartozó összes fejlécsort.

Példa 1. apache_request_headers() példa

<?php
$fejlecek = apache_request_headers();

foreach ($fejlecek as $fejlec => $ertek) {
    echo "$fejlec: $ertek <br />\n";
}
?>

Megjegyzés: A környezetből olvasva is lekérhetőek a tipikus CGI változók, és e módszer mindenképpen működik, függetlenül attól, hogy a PHP Apache modulként működik vagy sem. A phpinfo() használatával meg lehet tekinteni az ezen a módon definiált környezeti változók listáját.

apache_response_headers

(PHP 4 >= 4.3.0)

apache_response_headers -- visszadja az összes HTTP válasz fejlécet

Leírás

array apache_response_headers ( void )

apache_response_headers() visszaadja az összes HTTP válasz-fejlécet. Ez a függvény csak a PHP 4.3.0 és magasabb verzióiban használható.

Lásd még getallheaders() és headers_sent()!

Megjegyzés: A PHP 4.3.3-as változatától fölfele ugyanez a függvény az NSAPI szervermodullal is használható lesz, a Netscape/iPlanet/SunONE webszervereken is.

apache_setenv

(PHP 4 >= 4.2.0)

apache_setenv -- Apache subprocess_env változóit állítja be

Leírás

int apache_setenv ( string variable, string value [, bool walk_to_top])

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ascii2ebcdic

(PHP 3>= 3.0.17)

ascii2ebcdic -- Átalakít egy stringet ASCII-ből EBCDIC-be

Leírás

int ascii2ebcdic ( string ascii_str)

Az ascii2ebcdic() egy Apache-specifikus függvény, és csak EBCDIC alapú operációs rendszereken érhető el (OS/390, BS2000). Egy ASCII kódolt ascii_str szöveget alakít át az annak megfelelő EBCDIC reprezentációvá (binary safe módon). Visszatérési értéke az eredmény.

Lásd még az ellentétes funkciót betöltő ebcdic2ascii() függvényt.

ebcdic2ascii

(PHP 3>= 3.0.17)

ebcdic2ascii -- Átalakít egy stringet EBCDIC-ből ASCII-be

Description

int ebcdic2ascii ( string ebcdic_str)

Az ebcdic2ascii() egy Apache-specifikus függvény, és csak EBCDIC alapú operációs rendszereken érhető el (OS/390, BS2000). Egy EBCDIC kódolt ebcdic_str szöveget alakít át az annak megfelelő ASCII reprezentációvá (binary safe módon). Visszatérési értéke az eredmény.

Lásd még az ellentétes funkciót betöltő ascii2ebcdic() függvényt.

getallheaders

(PHP 3, PHP 4 )

getallheaders -- visszaadja az összes HTTP-kérés fejlécet

Leírás

array getallheaders ( void )

getallheaders() a apache_request_headers() függvény álneve. Ez a függvény az aktuális HTTP kérés összes fejlécét visszadja egy asszociatív tömbben. Bővebb információért olvasd el a apache_request_headers() dokumentációját!

Megjegyzés: PHP 4.3.0-ban a getallheaders() csak a apache_request_headers() álneveként funkcionál tovább. Valójában a függvény nevét megváltoztatták, mivel csak akkor működik, ha a PHP Apache modulként fut.

Lásd még apache_request_headers()!

virtual

(PHP 3, PHP 4 )

virtual -- Végrehajt egy Apache allekérést

Leírás

int virtual ( string filename)

A virtual() egy Apache-specifikus függvény, amely megegyezik a mod_include <!--#include virtual...--> megoldásával. Végrehajt egy Apache alkérést. Ez hasznos CGI szkriptek vagy .shtml fájlok beillesztésénél, vagy bármi másnál, amit egyébként az Apache dolgozott volna fel. Fontos a CGI szkripteknél, hogy a szkript érvényes CGI fejléceket generáljon. Ezt azt jelenti, hogy minimálisan egy Content-type fejlécet kell ki kell adnia. A PHP fájlokhoz az include() vagy require() függvényeket kell használni. A virtual() nem használható olyan dokumentum beillesztéséhez, amely maga is PHP fájl.

Az alkérés futtatásához minden puffert le kell zárni és kiűríteni a tartalmát a kliens böngésző felé, és ezzel együtt minden függőben lévő fejléc is kiküldésre kerül.

II. Tömbkezelő függvények

Bevezetés

Ezekkel a függvényekkel különféle módon változtathatók, módosíthatók a tömbök. A tömbök elengedhetetlenek változók sorozatának tárolásához, rendezéséhez, igazgatásához és azok változtatásához.

A PHP az egy- és többdimenziós tömböket is támogatja, amelyeket akár "manuálisan" vagy valamilyen függvénnyel is létre lehet hozni. Vannak bizonyos adatbázis-kezelő függvények, amelyek adatbázis-lekérdezések alapján töltenek fel tömböket, és vannak, amelyek tömböket adnak vissza.

Nézd át a Tömbök fejezetet, ahol részletes leírást található a PHP-s tömbök megvalósításáról és működéséről.


Követelmények

Az itt leírt függvények használatához semmilyen külső függvénykönyvtár megléte nem szükségeltetik.


Telepítés

Semmilyen telepítés nem szükséges ezen függvények használatához, a PHP alapelemei.


Futásidejű beállítások

Ez a kiterjesztés semmilyen konfigurációs beállításokat nem definiál a php.ini állományban.


Erőforrás típusok

Ez a kiterjesztés semmilyen erőforrás típust nem definiál.


Előre definiált állandók

Az itt felsorolt konstansok mindig elérthetőek, mivel részei a PHP alaptelepítésének.

CASE_LOWER (integer)

CASE_LOWER az array_change_key_case() függvény paramétereként használható, és arra utasítja a függvényt, hogy a tömb kulcsait cserélje kisbetűs megfelelőikre. Ez az array_change_key_case() alapértelmezésbeli viselkedése is.

CASE_UPPER (integer)

CASE_LOWER az array_change_key_case() függvény paramétereként használható, és arra utasítja a függvényt, hogy a tömb kulcsait cserélje nagybetűs megfelelőikre.

Tartalom
array_change_key_case -- visszaad egy kis vagy nagybetűsre cserélt string indexű tömböt
array_chunk -- feldarabolja a tömböt
array_combine --  Creates an array by using one array for keys and another for its values
array_count_values -- összeszámolja minden érték előfordulását a tömbben
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_diff -- tömbök közti különbséget számolja ki
array_fill -- feltölt egy tömböt egy megadott értékkel
array_filter --  megsszűri a tömb elemeit egy függvény visszahívásával
array_flip -- felcseréli a tömb elemeit és kulcsait
array_intersect_assoc -- Computes the intersection of arrays with additional index check
array_intersect -- kiszámítja a tömbök metszetét
array_key_exists -- ellenőrzi a keresett index/kulcs létezését a tömbben
array_keys -- visszaadja egy tömb összes indexét
array_map --  egy függvényt alkalmaz minden megadott tömb elemére
array_merge_recursive -- rekurzívan egyesít két vagy több tömböt
array_merge --  egyesít két vagy több tömböt
array_multisort --  egyszerre több tömböt vagy egy többdimenziós tömböt rendez
array_pad --  adott méretűre bővít és tölt fel egy tömböt
array_pop -- kivesz egy elemet a tömb végéről
array_push --  egy vagy több elemet illeszt a tömb végére
array_rand --  véletlenszerűen egy vagy több elemet hoz elő a tömbből
array_reduce --  elemi értékre csökkenti a tömböt tetszőleges függvény meghívásával
array_reverse --  tömb fordított sorrendű elemeivel tér vissza
array_search --  adott elemet keres a tömbben és az indexével tér vissza
array_shift --  kivesz egy elemet a tömb elejéről
array_slice -- a tömb egy részével tér vissza
array_splice --  lecseréli a tömb egy részét
array_sum --  tömbbeli elemek összegét számolja ki
array_udiff_assoc -- Computes the difference of arrays with additional index check. The data is compared by using a callback function.
array_udiff_uassoc -- Computes the difference of arrays with additional index check. The data is compared by using a callback function. The index check is done by a callback function also
array_udiff -- Computes the difference of arrays by using a callback function for data comparison.
array_unique -- törli az ismétlődő elemeket
array_unshift --  beszúr a tömb elejére egy vagy több elemet
array_values -- visszadja az összes tömbben előforduló értéket
array_walk --  felhasználói függvényt futtat a tömb minden elemén
array --  létrehoz egy tömböt
arsort --  fordított sorrendben rendez egy tömböt megtartva az indextársítást
asort -- tömb elemeit rendezi megtartva az indextársítást
compact --  tömbbe tömöríti a változókat és értékeiket
count -- megszámolja az elemeket egy változóban
current -- visszaadja egy tömb aktuális elemét
each --  visszaadja a tömb pillanatnyilag kijelölt elemét és lépteti a belső mutatót
end --  az utolsó elemre állítja a tömb belső mutatóját
extract --  tömbből változókat helyez el az aktuális szimbólumtáblába
in_array -- TRUE-val tér vissza, ha létezik az érték a tömbben
key --  asszociatív tömb pillanatnyilag kiválasztott kulcsát adja vissza
krsort -- kulcsok alapján fordított sorrendbe rendez egy tömböt
ksort -- kulcsok alapján rendezi a tömböt
list --  értéket rendel a felsorolt változókhoz
natcasesort --  tömböt rendez a "natural order" (természetes sorrend) algoritmus alapján kis-nagybetűk figyelembevétele nélkül
natsort --  tömböt rendez a "natural order" (természetes sorrend) algoritmus alapján
next --  előre mozgatja a tömb belső mutatóját
pos -- visszaadja a tömb aktuális elemét
prev -- visszlépteti a tömb belső mutatóját
range --  egy tartományt lefedő tömböt készít
reset --  a tömb belső mutatóját az első elemére állítja
rsort -- fordított sorrendben rendez egy tömböt
shuffle -- összekeveri a tömb elemeit
sizeof -- visszadja a változó elemszámát
sort -- tömböt rendez
uasort --  tömböt rendez egy felhasználó összehasonlító függvénnyel megtartva az indextársítást
uksort --  tömböt rendez kulcsai alapján egy felhasználó összehasonlító függvénnyel
usort --  tömböt rendez elemértékei alapján egy felhasználó összehasonlító függvénnyel

array_change_key_case

(PHP 4 >= 4.2.0)

array_change_key_case -- visszaad egy kis vagy nagybetűsre cserélt string indexű tömböt

Leírás

array array_change_key_case ( array input [, int case])

A array_change_key_case() kis vagy nagybetűsre cseréli az input tömb string típusú indexeit A változtatást az elhagyható case paraméter szabályozza, amelynek két állandót lehet átadni: CASE_UPPER és CASE_LOWER, az alapértelmezés a CASE_LOWER. A numerikus indexet változatlanul hagyja a függvény.

Példa 1. array_change_key_case() példa

$bemenet = array("ElSo" => 1, "MasODIk" => 4);
print_r(array_change_key_case($bemenet, CASE_UPPER));

A fenti programrészlet a következőt írja ki:
Array
(
    [ELSO] => 1
    [MASODIK] => 2
)

array_chunk

(PHP 4 >= 4.2.0)

array_chunk -- feldarabolja a tömböt

Leírás

array array_chunk ( array input, int size [, bool preserve_keys])

A array_chunk() feloszt egy tömböt több tömbre a size értéke alapján. A legutolsó tömbben elképzelhető, hogy ennél kevesebb elem szerepel. A tömböket egy többdimenziós tömb elemeiként adja vissza, amely 0-tól kezdve numerkius indexelt.

A lehetséges preserve_keys paraméter TRUE-ra állításával, kikényszeríthető, hogy az eredeti tömb indexelését megtartsák a visszaadott tömbdarabok. Ha e paraméter értéke FALSE, akkor minden tömbdarabban az elemek sorszámozása 0-tól újra kezdődik. Az alapértelmezés az utóbbi: FALSE.

Példa 1. array_chunk() példa

$input_array = array('a', 'b', 'c', 'd', 'e');
print_r(array_chunk($input_array, 2));
print_r(array_chunk($input_array, 2, TRUE));

A fenti program kimenete:
Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [0] => c
            [1] => d
        )

    [2] => Array
        (
            [0] => e
        )

)
Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [2] => c
            [3] => d
        )

    [2] => Array
        (
            [4] => e
        )

)

array_combine

(PHP 5 CVS only)

array_combine --  Creates an array by using one array for keys and another for its values

Description

array array_combine ( array keys, array values)

Returns an array by using the values from the keys array as keys and the values from the values array as the corresponding values.

Returns FALSE if the number of elements for each array isn't equal or if the arrays are empty.

Példa 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);
?>

Outputs:

Array
(
    [green]  => avocado
    [red]    => apple
    [yellow] => banana
)

See also array_merge(), array_walk(), and array_values().

array_count_values

(PHP 4 )

array_count_values -- összeszámolja minden érték előfordulását a tömbben

Leírás

array array_count_values ( array input)

Az array_count_values() olyan tömböt ad vissza, amelynek a kulcsai az input tömb értékei és az input tömbbeli előfordulási gyakoriságuk a hozzájuk tartozó értékek.

Példa 1. array_count_values() példa

$tomb = array (1, "hello", 1, "világ", "hello");
print_r(array_count_values ($tomb));

A fenti példa kiírja:

Array
(
   [1] => 2
   [hello] => 2
   [világ] => 1
)

array_diff_assoc

(PHP 4 >= 4.3.0)

array_diff_assoc -- Computes the difference of arrays with additional index check

Description

array array_diff_assoc ( array array1, array array2 [, array ...])

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

Példa 1. array_diff_assoc() example

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

The result is:

Array
(
    [b] => brown
    [c] => blue
    [0] => red
)

In our example above you see the "a" => "green" pair is present in both arrays and thus it is not in the ouput from the function. Unlike this, the pair 0 => "red" is in the ouput because in the second argument "red" has key which is 1.

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.

Megjegyzés: 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_diff_assoc($array1[0], $array2[0]);.

See also array_diff(), array_intersect(), and array_intersect_assoc().

array_diff_uassoc

(no version information, might be only in CVS)

array_diff_uassoc -- Computes the difference of arrays with additional index check which is performed by a user supplied callback function.

Description

array array_diff_assoc ( array array1, array array2 [, array ..., callback key_compare_func])

array_diff_uassoc() 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(). This comparison is done by a user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. This is unlike array_diff_assoc() where an internal function for comparing the indices is used.

Példa 1. array_diff_uassoc() example

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

The result is:

Array
(
    [b] => brown
    [c] => blue
    [0] => red
)

In our example above you see the "a" => "green" pair is present in both arrays and thus it is not in the ouput from the function. Unlike this, the pair 0 => "red" is in the ouput because in the second argument "red" has key which is 1.

The equality of 2 indices is checked by the user supplied callback function.

Megjegyzés: 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_diff_uassoc($array1[0], $array2[0], "key_compare_func");.

See also array_diff(), array_diff_assoc(), array_udiff(), array_udiff_assoc(), array_udiff_uassoc(), array_intersect(), array_intersect_assoc(), array_uintersect(), array_uintersect_assoc() and array_uintersect_uassoc().

array_diff

(PHP 4 >= 4.0.1)

array_diff -- tömbök közti különbséget számolja ki

Leírás

array array_diff ( array array1, array array2 [, array ...])

Az array_diff() olyan tömböt ad vissza, amely azokat az elemeket tartalmazza, amelyek csak array1-ben szerepelnek és semelyik másik paraméterként átadott tömbben nem. Az indexelést megőrzi.

Példa 1. array_diff() példa

$tomb1 = array ("a" => "zöld", "vörös", "kék", "vörös");
$tomb2 = array ("b" => "zöld", "sárga", "piros");
$eredmeny = array_diff ($tomb1, $tomb2);

Ez azt eredményezi, hogy a $eredmeny értéke:

Array
(
    [2] => kék
)

Az $tomb1-ben előforduló többszörös értékeket ugyanúgy kezeli a függvény.

Megjegyzés: Két elem akkor és csakis akkor tekinthető egyenlőnek, ha (string) $elem1 === (string) $elem2, azaz ha sztring ábrázolásuk megegyezik.

Megjegyzés: Ez a függvény csak egydimenziós tömbökön működik, illetve többdimenzós tömbök első dimenziójában. Ha további dimenziókon kell használni, akkor a array_diff($tomb1[0], $tomb2[0]); formában kell meghívni.

Figyelem

PHP 4.0.4-ben hibásan működött!

Lásd még: array_intersect()!

array_fill

(PHP 4 >= 4.2.0)

array_fill -- feltölt egy tömböt egy megadott értékkel

Leírás

array array_fill ( int start_index, int num, mixed value)

Az array_fill() a num paraméterben megadott számú elemmel egy tömböt hoz létre, amelyben minden elem value értékű és az indexelésük start_index-től kezdődik.

Példa 1. array_fill() példa

$a = array_fill(5, 6, 'banán');

most $a-ban a következő elemek vannak (print_r()):
Array  
(  
    [5]  => banán  
    [6]  => banán  
    [7]  => banán  
    [8]  => banán  
    [9]  => banán  
    [10] => banán  
)

array_filter

(PHP 4 >= 4.0.6)

array_filter --  megsszűri a tömb elemeit egy függvény visszahívásával

Leírás

array array_filter ( array input [, mixed callback])

Az array_filter() olyan tömbbel tér vissza, amely az input tömb összes ún. 'callback' függvény által megszűrt elemét tartalmazza. Ez azt jelenti, hogy a array_filter() az input minden elemére meghívja ezt a függvényt, amely visszatérési értékeként megadja, hogy az elem átment a szűrőn vagy sem. Ha az input tömb asszociatív, akkor a kulcsok megőrzésre kerülnek.

Példa 1. array_filter() példa

function paratlan($var) {
    return ($var % 2 == 1);
}

function paros($var) {
    return ($var % 2 == 0);
}

$tomb1 = array ("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);
$tomb2 = array (6, 7, 8, 9, 10, 11, 12);

echo "Páratlan számok:\n";
print_r(array_filter($tomb1, "paratlan"));
echo "Páros számok:\n";
print_r(array_filter($tomb2, "paros"));

A fenti program kimenete:
Páratlan számok: 
Array 
( 
    [a] => 1 
    [c] => 3 
    [e] => 5 
) 
Páros számok:
Array 
( 
    [0] => 6 
    [2] => 8 
    [4] => 10 
    [6] => 12 
)

Megjegyzés: A függvény neve helyett egy tömböt is átadhatsz, ami egy objektum referenciát és egy metódus nevet kell tartalmazzon.

A feldolgozandó tömböt a visszahívott függvényen belül nem lehet megváltoztatni, tehát nem lehet egyik vagy másik elemét, esetleg az egész tömböt törölni. Ha ez mégis megtörténik, akkor ennek a függvénynek a viselkedését nem lehet megjósolni.

Lásd még: array_map() és array_reduce()!

array_flip

(PHP 4 )

array_flip -- felcseréli a tömb elemeit és kulcsait

Leírás

array array_flip ( array trans)

Az array_flip() felcseréli a tömb elemeit és kulcsait egymással, úgyhogy a trans tömb értékei lesznek az új kulcsok és a kulcsai pedig a hozzátartozó értékek. Látható, hogy array-t ad vissza.

Figyelj arra, hogy a trans elemértékeinek érvényes kulcsoknak kell lenniük, azaz vagy integer vagy string típusúaknak. Egy figyelmeztető "nem fatális" hibaüzenetet (warning) küld, ha az elemérték típusa nem megfelelő, és a kérdéses kulcs - érték pár nem lesz felcserélve.

Ha egy érték többször szerepel, akkor a legutolsó kulcsot fogja használni ahhoz az értékhez, és a többit figyelmen kívül hagyja.

Az array_flip() FALSE-tal tér vissza sikertelenség esetén.

Példa 1. array_flip() példa

$atalakitva = array_flip ($atalakitva);
$eredeti    = strtr ($str, $atalakitva);

Példa 2. array_flip() példa az (érték)ütközésre

$atalakitva = array ("a" => 1, "b" => 1, "c" => 2);
$atalakitva = array_flip ($atalakitva);
print_r($atalakitva);

most $atalakitva értéke:
Array 
( 
    [1] => b 
    [2] => c 
)

array_intersect_assoc

(PHP 4 >= 4.3.0)

array_intersect_assoc -- Computes the intersection of arrays with additional index check

Description

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 used in the comparison unlike in array_intersect().

Példa 1. array_intersect_assoc() example

<?php
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "green", "yellow", "red");
$result_array = array_intersect_assoc($array1, $array2);
?>

$result_array will look like:

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 it's key is 0 while the key of "red" in $array2 is 1.

The two values from the key => value pairs are considered equal only if (string) $elem1 === (string) $elem2 . In otherwords a strict type check is executed so the string representation must be the same.

See also array_intersect(), array_diff() and array_diff_assoc().

array_intersect

(PHP 4 >= 4.0.1)

array_intersect -- kiszámítja a tömbök metszetét

Leírás

array array_intersect ( array array1, array array2 [, array ...])

Az array_intersect() olyan tömböt ad vissza, amely az array1 azon elemeit tartalmazza, amelyek minden paraméterként átadott tömbben megtalálhatók. Az indexelést megőrzi.

Példa 1. array_intersect() példa

$tomb1 = array ("a" => "zöld", "vörös", "kék", "vörös");
$tomb2 = array ("b" => "zöld", "sárga", "piros");
$eredmeny = array_intersect ($tomb1, $tomb2);

Ez a $eredmeny tömbben a következő értékeket képezi:
Array 
( 
    [a] => zöld 
    [0] => piros 
)

Megjegyzés: Két elem akkor és csakis akkor tekinthető egyenlőnek, ha (string) $elem1 === (string) $elem2, azaz ha sztring ábrázolásuk megegyezik.

Figyelem

PHP 4.0.4-ben hibásan működött!

Lásd még: array_diff()!

array_key_exists

(PHP 4 >= 4.1.0)

array_key_exists -- ellenőrzi a keresett index/kulcs létezését a tömbben

Leírás

bool array_key_exists ( mixed key, array search)

Az array_key_exists() TRUE-val tér vissza, ha az adott key be van állítva a search tömbben. A key bármilyen lehetséges tömbindex érték lehet.

Példa 1. array_key_exists() példa

$keress = array("első" => 1, "második" => 4);
if ( array_key_exists("első", $keress) ) {
    echo "Az 'első' indexű elem a tömbben van.";
}

Megjegyzés: A PHP 4.0.6-ban a függvény neve key_exists() volt.

Lásd még: isset()!

array_keys

(PHP 4 )

array_keys -- visszaadja egy tömb összes indexét

Leírás

array array_keys ( array input [, mixed search_value])

Az array_keys() az input tömb összes - numerikus és sztring - típusú indexét (kulcsát) adja vissza.

Ha az elhagyható search_value is meg an adva, akkor csak azokkal a kulcsokkal tér vissza, amelyek a megadott értékhez tartoznak. Egyébként az input összes kulcsa átadásra kerül.

Példa 1. array_keys() példa

$tomb = array (0 => 100, "szin" => "piros");
print_r(array_keys ($tomb));

$tomb = array ("kék", "piros", "zöld", "kék", "kék");
print_r(array_keys ($tomb, "kék"));

$tomb = array ("szín" => array("kék", "piros", "zöld"), "méret" => array("kicsi", "közepes", "nagy"));
print_r(array_keys ($tomb));

A fenti program kimenete:
Array 
( 
  [0] => 0 
  [1] => szín 
) 
Array 
( 
  [0] => 0 
  [1] => 3 
  [2] => 4 
) 
Array 
( 
  [0] => szín 
  [1] => méret 
)

Megjegyzés: Ez a függvény PHP 4-től használható, alább látható egy megvalósítása azok számára, akik még mindig PHP 3-t használnak.

Példa 2. array_keys() megvalósítása PHP 3-ban

function array_keys ($arr, $term="") {
    $t = array();
    while ( list($k,$v) = each($arr) ) {
        if ( $term && $v != $term ) {
            continue;
        }
        $t[] = $k;
    }
    return $t;
}

Lásd még: array_values()!

array_map

(PHP 4 >= 4.0.6)

array_map --  egy függvényt alkalmaz minden megadott tömb elemére

Leírás

array array_map ( mixed callback, array array1 [, array array2...])

Az array_map() olyan tömböt ad vissza, amelyben az array1 tömb callback nevű függvény által kiszámolt értékei vannak. A callback függvény által fogadható paraméterek száma meg kell egyezzen az array_map()-nak átadott tömbök számával.

Példa 1. array_map() példa

function kob($n) {
    return $n*$n*$n;
}

$a = array(1, 2, 3, 4, 5);
$b = array_map("kob", $a);

Így a $b tömb értéke:
Array 
( 
  [0] => 1 
  [1] => 8 
  [2] => 27 
  [3] => 64 
  [4] => 125 
)

Példa 2. array_map() - több tömb használata

function ird_spanyolul($n, $m) {
    return "A(z) $n spanyolul: $m ";
}

function osszerendel_spanyolul($n, $m) {
    return array ($n => $m);
}

$a = array(1, 2, 3, 4, 5);
$b = array("uno", "dos", "tres", "cuatro", "cinco");

$c = array_map("ird_spanyolul", $a, $b);
print_r($c);

$d = array_map("osszerendel_spanyolul", $a , $b);
print_r($d);

This results:
// $c szerkezete
Array 
( 
  [0] => A(z) 1 spanyolul: uno  
  [1] => A(z) 2 spanyolul: dos  
  [2] => A(z) 3 spanyolul: tres  
  [3] => A(z) 4 spanyolul: cuatro  
  [4] => A(z) 5 spanyolul: cinco  
) 

// $d szerkezete
Array 
( 
  [0] => Array 
      ( 
          [1] => uno 
      ) 

  [1] => Array 
      ( 
          [2] => dos 
      ) 

  [2] => Array 
      ( 
          [3] => tres 
      ) 

  [3] => Array 
      ( 
          [4] => cuatro 
      ) 

  [4] => Array 
      ( 
          [5] => cinco 
      ) 

)

Több tömb használata esetén a tömbök hosszának meg kell egyeznie, mert a meghívott callback függvény párhuzomsan halad végig rajtuk mindig a megfelelő elemeket használva fel. Ha a tömbök nem megegyező méretűek, akkor a legrövidebbek üres elemekkel lesznek feltöltve.

Ennek a függvénynek érdekes felhasználási módja, hogy tömböket tartalmazó tömböt lehet vele létrehozni, ha a callback függvényként a NULL értéket adjuk át.

Példa 3. tömböket tartalmazó tömb létrehozása

$a = array(1, 2, 3, 4, 5);
$b = array("egy", "kettő", "három", "négy", "öt");
$c = array("uno", "dos", "tres", "cuatro", "cinco");

$d = array_map(null, $a, $b, $c);
print_r($d);

A fenti program kimenete, a $d tömb szerkezete:
Array
(
    [0] => Array
        (
            [0] => 1
            [1] => egy
            [2] => uno
        )

    [1] => Array
        (
            [0] => 2
            [1] => kettő
            [2] => dos
        )

    [2] => Array
        (
            [0] => 3
            [1] => három
            [2] => tres
        )

    [3] => Array
        (
            [0] => 4
            [1] => négy
            [2] => cuatro
        )

    [4] => Array
        (
            [0] => 5
            [1] => öt
            [2] => cinco
        )

)

Lásd még: array_filter() és array_reduce()!

array_merge_recursive

(PHP 4 >= 4.0.1)

array_merge_recursive -- rekurzívan egyesít két vagy több tömböt

Leírás

array array_merge_recursive ( array array1, array array2 [, array ...])

Az array_merge_recursive() egyesíti két vagy több tömb elemeit úgy, hogy az egyik elemeit a másik után fűzi, és visszadja az eredményül kapott tömböt.

Ha a megadott tömbökben ugyanolyan string kulcsok vannak, akkor az ezekhez tartozó elemértékeket egy tömbbe gyűjti össze. Ezt rekurzívan teszi a függvény, tehát ha az elemek egyike ugyancsak tömb, akkor ennek a tömbnek az elemeire is hasonlóképp lefut az egyesítő algoritmus. Ha viszont a numerikus indexek egyeznek meg, akkor a későbbi nem felülírja a korábbi értéket, hanem azok után fűzi.

Példa 1. array_merge_recursive() példa

$tomb1 = array ("szín" => array ("kedvenc" => "piros"), 5);
$tomb2 = array (10, "szín" => array ("kedvenc" => "zöld", "kék"));
$eredmeny = array_merge_recursive ($tomb1, $tomb2);

Az $eredmeny tömb értéke:
Array 
( 
  [szín] => Array 
      ( 
          [kedvenc] => Array 
              ( 
                  [0] => piros 
                  [1] => zöld 
              ) 

          [0] => kék 
      ) 

  [0] => 5 
  [1] => 10 
)

Lásd még: array_merge()!

array_merge

(PHP 4 )

array_merge --  egyesít két vagy több tömböt

Leírás

array array_merge ( array array1, array array2 [, array ...])

Az array_merge() egyesíti két vagy több tömb elemeit úgy, hogy a második tömb elemeit hozzáfűzi az elsőéhez, és visszadja az eredményül kapott tömböt.

Ha a megadott tömbökben ugyanolyan string kulcsok vannak, akkor a későbbi felülírja az előzőt. Ha a tömböknek ugyanolyan numerikus indexei vannak, akkor nem ez történik, hanem mindegyiket új értékként a tömbbe illeszti.

Példa 1. array_merge() példa

$tomb1 = array ("szín" => "piros", 2, 4);
$tomb2 = array ("a", "b", "szín" => "zöld", "alak" => "trapéz", 4);
$eredmeny = array_merge ($tomb1, $tomb2);

Az $eredmeny tömb értéke:
Array
(
    [szín] => zöld
    [0] => 2
    [1] => 4
    [2] => a
    [3] => b
    [alak] => trapéz
    [4] => 4
)

Példa 2. Egyszerű array_merge() példa

$tomb1    = array();
$tomb2    = array(1 => "adat");
$eredmeny = array_merge($tomb1, $tomb2);

Nem szabad elfelejteni, hogy a numerikus indexeket újraszámozza a függvény!
Array
(
    [0] => adat
)

Ha teljesen meg kell őrizni a tömb indexeit, akkor a + operátorral kell egymáshoz fűzni azokat:
$tomb1    = array();
$tomb2    = array(1 => "adat");
$eredmeny = $tomb1 + $tomb2;
The numeric key will be preserved and thus the association remains.
Array
(
    [1] => adat
)

Megjegyzés: A közös indexek "elnyomják" egymást, ami azt jelenti, hogy az első index előforduláshoz tartozó értéket fogja az eredmény tartalmazni.

Lásd még: array_merge_recursive()!

array_multisort

(PHP 4 )

array_multisort --  egyszerre több tömböt vagy egy többdimenziós tömböt rendez

Leírás

bool array_multisort ( array ar1 [, mixed arg [, mixed ... [, array ...]]])

Az array_multisort() arra használható, hogy egyszerre több tömböt vagy egy többdimenzós tömböt rendezzen sorba valamelyik dimenziója szerint. A kulcsokat megőrzi a rendezés során.

A megadott tömböket egy képzeletbeli, sorok alapján rendezendő táblázat oszlopainak tekinthetők. Ez hasonlít az SQL ORDER BY cikkelyének feladatára. Ez első tömb, ami alapján először rendez. Az ebben a tömbben levő ugyanolyan sorok (elemek) a soron következő tömb szerint lesznek tovább rendezve, és így tovább végig a tömbökön.

Ennek a függvénynek a argumentumlistája kicsit szokatlan, de nagyon rugalmas. A legelső paraméternek mindig tömbnek kell lennie, ezután minden paraméter lehet egy tömb vagy egy a következő rendezést szabályzó jelzőértékek közül.

Sorrendi jelzők:

  • SORT_ASC - növekvő sorrendbe rendez

  • SORT_DESC - csökkenő sorrendbe rendez

Rendezési jelzők:

  • SORT_REGULAR - megszokott módon hasonlítja össze az elemeket

  • SORT_NUMERIC - számként hasonlítja össze az elemeket

  • SORT_STRING - szövegként hasonlítja össze az elemeket

Nem lehet két ugyanolyan típusú jelzőt egymás után megadni. Ezek a jelzők csak a közvetlenül előttük álló tömb szerinti rendezést befolyásolják, minden tömb paraméternél az alapértelmezés lép életbe: SORT_ASC és SORT_REGULAR.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Példa 1. Több tömb alapján történő rendezés

$ar1 = array ("10", 100, 100, "a");
$ar2 = array (1, 3, "2", 1);
array_multisort ($ar1, $ar2);

A rendezés után a $ar1 és a $ar2: (A második tömb elemei az első tömb megegyező elemeinek megfelelően (100, 100) szintén rendezettek.)

Array // $ar1
(
    [0] => 10
    [1] => a
    [2] => 100
    [3] => 100
)
Array // $ar2
(
    [0] => 1
    [1] => 1
    [2] => 2
    [3] => 3
)

Példa 2. Többdimenziós tömbök rendezése

$ar = array (array ("10", 100, 100, "a"), array (1, 3, "2", 1));
array_multisort ($ar[0], SORT_ASC, SORT_STRING,
                 $ar[1], SORT_NUMERIC, SORT_DESC);

A rendezés után a $ar tömb: (Az első szövegként növekvő sorrendbe rendezve, a másodikban számként csökkenő sorrendbe rendezve.)

Array
(
    [0] => Array
        (
            [0] => 10
            [1] => 100
            [2] => 100
            [3] => a
        )

    [1] => Array
        (
            [0] => 1
            [1] => 3
            [2] => 2
            [3] => 1
        )

)

array_pad

(PHP 4 )

array_pad --  adott méretűre bővít és tölt fel egy tömböt

Leírás

array array_pad ( array input, int pad_size, mixed pad_value)

Az array_pad() az input tömb pad_size paraméterben megadott méretre bővített másolatát adja vissza, amelyben az új elemeket a pad_value értékkel töltötte fel. Ha a pad_size pozitív szám, akkor a tömb végére kerülnek az új elemek, ha negatív, akkor az elejére. Ha a pad_size abszolút értéke kisebb vagy egyenlő a tömb méretével, akkor az input tömbön nem történik változtatás.

Példa 1. array_pad() példa

$bemenet  = array (12, 10, 9);

$eredmeny = array_pad ($bemenet, 5, 0);
// array (12, 10, 9, 0, 0)

$eredmeny = array_pad ($bemenet, -7, -1);
// array (-1, -1, -1, -1, 12, 10, 9)

$eredmeny = array_pad ($bemenet, 2, "noop");
// nincs kitöltés

array_pop

(PHP 4 )

array_pop -- kivesz egy elemet a tömb végéről

Leírás

mixed array_pop ( array array)

Az array_pop() kiveszi az array tömbből annak utolsó elemét, és ezt adja vissza. Ha az array tömb üres vagy nem tömb, akkor NULL-lal tér vissza.

Példa 1. array_pop() példa

$verem = array ("narancs", "banán", "alma", "málna");
$gyumolcs = array_pop ($verem);

Ezután a $verem csak 3 eleme lesz:
Array 
  ( 
      [0] => narancs 
      [1] => banán 
      [2] => alma 
  )
és a $gyumolcs értéke málna lesz.

Figyelem

Ez a függvény a logikai típusú FALSE értékkel is visszatérhet, olyan nem logikai típusú értékek mellett, amik szintén FALSE értékként jelenhetnek meg (mint pl. 0 vagy ""). Olvasd el a Logikai típusról szóló részt további információkért. Használd a === operátort a visszatérési érték ellenőrzésére.

Lásd még: array_push(), array_shift() és array_unshift()!

array_push

(PHP 4 )

array_push --  egy vagy több elemet illeszt a tömb végére

Leírás

int array_push ( array array, mixed var [, mixed ...])

Az array_push() az array tömböt veremként kezeli, és annak a tetejére - a tömb végére - teszi a paraméterként megadott értékeket. Az array tömb mérete a hozzáfűzött elemek számával fog nőni. Ennek ugyanaz a hatása, mintha a :
$tomb[] = $var;
kódot ismételnéd meg mindenegyes var paraméterre.

A tömbbeli elemek új számával tér vissza.

Példa 1. array_push() példa

$verem = array ("narancs", "banán");
array_push ($verem, "alma", "málna");

E példában a $verem tömbnek 4 eleme lesz:
Array 
( 
    [0] => narancs
    [1] => banán
    [2] => alma 
    [3] => málna
)

Lásd még: array_pop(), array_shift() és array_unshift()!

array_rand

(PHP 4 )

array_rand --  véletlenszerűen egy vagy több elemet hoz elő a tömbből

Leírás

mixed array_rand ( array input [, int num_req])

Az array_rand() különösen akkor hasznos, ha egy vagy több tömbbeli elemet kell véletlenszerűen kiválasztani. A függvény az input tömbből az elhagyható num_req paraméterben megadott számú elemet választja ki és adja vissza. A kívánt elemek száma alapértelmezás szerint 1.

Ha csak egy elemet választ ki, akkor az array_rand() ennek az elemnek az indexével tér vissza. Több elem esetén ezeknek az indexeiből alkotott tömbbel. Ezzel a megoldással kulcsokat és elemértékeket is véletlenszerűen ki lehet választani egy tömbből.

Az srand() függvényt meg kell hívni, hogy inicializálja a véletlenszám-generátort.

Példa 1. array_rand() példa

srand ((float) microtime() * 10000000);
$input = array ("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
$rand_keys = array_rand ($input, 2);
print $input[$rand_keys[0]]."\n";
print $input[$rand_keys[1]]."\n";

array_reduce

(PHP 4 >= 4.0.5)

array_reduce --  elemi értékre csökkenti a tömböt tetszőleges függvény meghívásával

Leírás

mixed array_reduce ( array input, mixed callback [, int initial])

Az array_reduce() ismétlődve meghívja a callback függvényt paraméterként az input tömb elemeivel, hogy végül egy elemi értékké alakítsa át a tömböt. Az elhagyható intial megadásával beállítható egy tetszőleges kezdő érték a folyamat legelején. Ha üres a tömb, akkor ez lesz a visszadott érték is.

Példa 1. array_reduce() példa

function rsum($v, $w) {
    $v += $w;
    return $v;
}

function rmul($v, $w) {
    $v *= $w;
    return $v;
}

$a = array(1, 2, 3, 4, 5);
$x = array();
$b = array_reduce($a, "rsum");
$c = array_reduce($a, "rmul", 10);
$d = array_reduce($x, "rsum", 1);

Ennek eredménye: $b = 15, $c = 1200 (= 1*2*3*4*5*10) és $d = 1.

Lásd még: array_filter() és array_map()!

array_reverse

(PHP 4 )

array_reverse --  tömb fordított sorrendű elemeivel tér vissza

Leírás

array array_reverse ( array array [, bool preserve_keys])

Az array_reverse() veszi az array tömböt, és visszaad egy olyan tömböt, amelyben elemek fordított sorrendben szerepelnek. Ha preserve_keys értéke TRUE, akkor megőrzi az elemek indexelését a visszaadandó tömbben.

Példa 1. array_reverse() példa

$bemenet  = array ("php", 4.0, array ("zöld", "piros"));
$eredmeny = array_reverse ($bemenet);
$indexelt_eredmeny = array_reverse ($bemenet, TRUE);

Ezután az $eredmeny és a $indexelt_eredmeny tömbnek ugyanazok az elemei lesznek, de az indexelésük eltérő. A $eredmeny és a $indexelt_bemenet így néz ki:
Array 
( 
  [0] => Array 
      ( 
          [0] => zöld 
          [1] => kék 
      ) 

  [1] => 4 
  [2] => php 
) 
Array 
( 
  [2] => Array 
      ( 
          [0] => zöld 
          [1] => kék 
      ) 

  [1] => 4 
  [0] => php 
)

Megjegyzés: A második paraméter PHP 4.0.3-től használható.

array_search

(PHP 4 >= 4.0.5)

array_search --  adott elemet keres a tömbben és az indexével tér vissza

Leírás

mixed array_search ( mixed needle, array haystack [, bool strict])

Átnézi a haystack tömböt a needle elemet keresve, ha megtalálta, akkor visszaadja az indexét/kulcsát, egyébként FALSE-ot.

Ha a harmadik, strict paraméter értéke TRUE, akkor az array_search() a needle típusát is összeveti a haystack tömb elemeiével.

Megjegyzés: PHP 4.2.0 előtti verziókban hiba esetén az array_search() NULL adott vissza FALSE helyett.

Figyelem

Ez a függvény a logikai típusú FALSE értékkel is visszatérhet, olyan nem logikai típusú értékek mellett, amik szintén FALSE értékként jelenhetnek meg (mint pl. 0 vagy ""). Olvasd el a Logikai típusról szóló részt további információkért. Használd a === operátort a visszatérési érték ellenőrzésére.

Lásd még: array_keys() és in_array()!

array_shift

(PHP 4 )

array_shift --  kivesz egy elemet a tömb elejéről

Leírás

mixed array_shift ( array array)

Az array_shift() kilépteti az array tömb első elemét, és ezt adja vissza. Az array tömb eggyel kevesebb elemet fog tartalmazni, és minden eleme eggyel előrébb (első index felé) tolódik, és minden numerikus index módosul, hogy az indexelés 0-tól kezdődjön. A nem numerikus (asszociatív) indexelés nem változik. Ha a tömb üres volt, akkor NULL-lal tér vissza.

Példa 1. array_shift() példa

$sor      = array ("narancs", "banán", "alma", "málna");
$gyumolcs = array_shift ($sor);

Ez azt eredményezi, hogy $sor tömbnek 3 eleme marad:
Array 
( 
    [0] => banán 
    [1] => alma 
    [2] => málna
)
és a $gyumolcs értéke "narancs" lesz.

Lásd még: array_unshift(), array_push() és array_pop()!

array_slice

(PHP 4 )

array_slice -- a tömb egy részével tér vissza

Leírás

array array_slice ( array array, int offset [, int length])

Az array_slice() függvény az array tömb offset és length paraméterek által meghatározott elemsorozatával tér vissza.

Pozitív offset esetén, az elemsorozat ennyiedik sorszámú elemtől kezdődik, negatív offset esetén az array tömb végétől visszafelé számolva ennyiedik elemtől kezdődik.

Ha a length meg van adva és pozitív, akkor az elemsorozatba ennyi darab elem kerül bele. Negatív length esetén az elemsorozat az array tömb vége előtt ennyi darab elemmel "áll meg", amely azt jelenti, hogy az ezután következő elemek nem kerülnek bele a sorozatba. Ha nincs megadva a length, akkor az offset által meghatározott ponttól kezdve a tömb végéig minden elem belekerül a sorozatba.

Megjegyzés: Az array_slice() figyelmen kívül hagyja a tömb aktuális indexelését, és az offset-et és a length-et az elemek pillanatnyi elhelyezkedése alapján számolja.

Példa 1. array_slice() példák

$input = array ("a", "b", "c", "d", "e");
                                        // visszatérési értékek
$output = array_slice ($input, 2);      // "c", "d", "e"
$output = array_slice ($input, 2, -1);  // "c", "d"
$output = array_slice ($input, -2, 1);  // "d"
$output = array_slice ($input, 0, 3);   // "a", "b", "c"

Lásd még: array_splice()!

array_splice

(PHP 4 )

array_splice --  lecseréli a tömb egy részét

Leírás

array array_splice ( array input, int offset [, int length [, array replacement]])

Az array_splice() eltávolítja az input tömb offset és length paraméterek által meghatározott sorozatát, és helyébe - ha meg van adva - a replacement tömböt illeszti. Az eltávolított elemek tömbjével tér vissza.

Pozitív offset esetén, a törlendő elemsorozat ennyiedik sorszámú elemtől kezdődik, negatív offset esetén az array tömb végétől visszafelé számolva ennyiedik elemtől kezdődik.

Ha nincs megadva a length, akkor az offset által meghatározott ponttól kezdve a tömb végéig minden elemet eltávolít. Ha a length meg van adva és pozitív, akkor ennyi darab elem kerül törlésre. Negatív length esetén az array tömb végétől visszafelé ennyiedik elemig törlődik minden. Jótanácsként: ha a tömb végéig kell mindent lecserélni a replacement-re, akkor a count($input)-ot kell a length paraméterben megadni.

Ha a replacement tömb is meg van adva, akkor a törölt elemek helyére ennek a tömbnek az elemei kerülnek. Ha offset és length alapján nem történt törlés, akkor a replacement elemei az offset által mutatott helyre kerülnek beillesztésre. Jótanácsként: ha a replacement egyelemű, akkor nem szükséges array()-t használni, kivéve ha ez az egy elem maga is tömb kell legyen.

A következők egyenértékűek:
array_push ($bemenet, $x, $y)     array_splice ($bemenet, count ($bemenet), 0, array ($x, $y))
array_pop ($bemenet)              array_splice ($bemenet, -1)
array_shift ($bemenet)            array_splice ($bemenet, 0, 1)
array_unshift ($bemenet, $x, $y)  array_splice ($bemenet, 0, 0, array ($x, $y))
$bemenet[$x] = $y                 array_splice ($bemenet, $x, 1, $y)

A törölt elemek tömbjével tér vissza a függvény.

Példa 1. array_splice() példák

$bemenet = array ("piros", "zöld", "kék", "sárga");
array_splice ($bemenet, 2);
// $bemenet most: array ("piros", "zöld")

$bemenet = array ("piros", "zöld", "kék", "sárga");
array_splice ($bemenet, 1, -1);
// $bemenet most: array ("piros", "sárga")

$bemenet = array ("piros", "zöld", "kék", "sárga");
array_splice ($bemenet, 1, count($bemenet), "narancs");
// $bemenet most:  array ("piros", "narancs")

$bemenet = array ("piros", "zöld", "kék", "sárga");
array_splice ($bemenet, -1, 1, array("fekete", "gesztenye"));
// $bemenet most:  array ("piros", "zöld", "kék", "fekete", "gesztenye")

Lásd még: array_slice()!

array_sum

(PHP 4 >= 4.0.4)

array_sum --  tömbbeli elemek összegét számolja ki

Leírás

mixed array_sum ( array array)

Az array_sum() az array tömb elemeinek integer vagy float típusú értékével tér vissza.

Példa 1. array_sum() példák

$a = array(2, 4, 6, 8);
echo "összeg(a) = ".array_sum($a);  // kiírja: összeg(a) = 20

$b = array("a"=>1.2,"b"=>2.3,"c"=>3.4);
echo "összeg(b) = ".array_sum($b);  // kiírja: összeg(b) = 6.9

Megjegyzés: A 4.0.6 verziót megelőzően a PHP módosította a paraméterként átadott tömböt, a sztringeket számmá konvertálta, ami majdnem mindig 0-val volt egyenlő.

array_udiff_assoc

(no version information, might be only in CVS)

array_udiff_assoc -- Computes the difference of arrays with additional index check. The data is compared by using a callback function.

Description

array array_udiff_assoc ( array array1, array array2 [, array ..., callback data_compare_func])

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.

Példa 1. array_udiff_assoc() example

<?php
class cr {
    private $priv_member;
    function cr($val) 
    {
        $this->priv_member = $val;
    }
    
    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);
?>

The result is:

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 ouput from the function.

For comparison is used the user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

Megjegyzés: 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");.

See also array_diff(), array_diff_assoc(), array_diff_uassoc(), array_udiff(), array_udiff_uassoc(), array_intersect(), array_intersect_assoc(), array_uintersect(), array_uintersect_assoc() and array_uintersect_uassoc().

array_udiff_uassoc

(no version information, might be only in CVS)

array_udiff_uassoc -- Computes the difference of arrays with additional index check. The data is compared by using a callback function. The index check is done by a callback function also

Description

array array_udiff_uassoc ( array array1, array array2 [, array ..., callback data_compare_func, callback key_compare_func])

array_udiff_uassoc() 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 : data_compare_func. In this aspect the behaviour is opposite to the behaviour of array_diff_assoc() which uses internal function for comparison. 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.

Példa 1. array_udiff_uassoc() example

<?php
class cr {
    private $priv_member;
    function cr($val) 
    {
        $this->priv_member = $val;
    }

    function comp_func_cr($a, $b) 
    {
        if ($a->priv_member === $b->priv_member) return 0;
        return ($a->priv_member > $b->priv_member)? 1:-1;
    }
    
    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);
?>

The result is:

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 ouput from the function. Keep in mind that you have to supply 2 callback functions.

For comparison is used the user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

Megjegyzés: 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");.

See also array_diff(), array_diff_assoc(), array_diff_uassoc(), array_udiff(), array_udiff_assoc(), array_intersect(), array_intersect_assoc(), array_uintersect(), array_uintersect_assoc() and array_uintersect_uassoc().

array_udiff

(no version information, might be only in CVS)

array_udiff -- Computes the difference of arrays by using a callback function for data comparison.

Description

array array_udiff ( array array1, array array2 [, array ..., callback data_compare_func])

array_udiff() returns an array containing all the values of array1 that are not present in any of the other arguments. Note that keys are preserved. For the comparison of the data data_compare_func is used. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. This is unlike array_diff() which uses an internal function for comparing the data.

Példa 1. array_udiff() example

<?php
class cr {
    private $priv_member;
    function cr($val) 
    {
        $this->priv_member = $val;
    }
    
    function comp_func_cr($a, $b) 
    {
        if ($a->priv_member === $b->priv_member) return 0;
        return ($a->priv_member > $b->priv_member)? 1:-1;
    }
}
$a = array("0.1" => new cr(9), "0.5" => new cr(12), 0 => new cr(23), 1=> new cr(4), 2 => new cr(-15),);
$b = array("0.2" => new cr(9), "0.5" => new cr(22), 0 => new cr(3), 1=> new cr(4), 2 => new cr(-15),);

$result = array_udiff($a, $b, array("cr", "comp_func_cr"));
print_r($result);
?>

The result is:

Array
(
    [0.5] => cr Object
        (
            [priv_member:private] => 12
        )

    [0] => cr Object
        (
            [priv_member:private] => 23
        )

)

Megjegyzés: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same.

Megjegyzés: 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");.

See also array_diff(), array_diff_assoc(), array_diff_uassoc(), array_udiff_assoc(), array_udiff_uassoc(), array_intersect(), array_intersect_assoc(), array_uintersect(), array_uintersect_assoc() and array_uintersect_uassoc().

array_unique

(PHP 4 >= 4.0.1)

array_unique -- törli az ismétlődő elemeket

Leírás

array array_unique ( array array)

Az array_unique() a bemenetként kapott array tömbből minden értéket egyszer vesz, és az így keletkezett tömbbel tér vissza.

Az indexelést megtartja. Az array_unique() először sorba rendezi a tömbértékeket, majd az összetartozó értékek közül az elsőként megtalált elem indexét tartja meg, a többi ezután következőt eldobja. Ez nem azt jelenti, hogy az eredeti tömbbeli legelső elem indexét tartja meg.

Megjegyzés: Két elem akkor és csakis akkor tekinthető egyenlőnek, ha (string) $elem1 === (string) $elem2, azaz ha sztring ábrázolásuk megegyezik.

Figyelem

PHP 4.0.4-ben hibásan működött.

Példa 1. array_unique() példa

$bemenet  = array ("a" => "zöld", "piros", "b" => "zöld", "kék", "piros");
$eredmeny = array_unique ($bemenet);
print_r($eredmeny);

A következőt írja ki: (PHP 4.0.6)
Array
(
    [b] => zöld
    [1] => kék
    [2] => piros
)

Példa 2. array_unique() és a típusok kapcsolata

$bemenet  = array (4,"4","3",4,3,"3");
$eredmeny = array_unique ($bemenet);
var_dump($eredmeny);

A következőt írja ki: (PHP 4.0.6)
array(2) {
  [3]=>
  int(4)
  [4]=>
  int(3)
}

array_unshift

(PHP 4 )

array_unshift --  beszúr a tömb elejére egy vagy több elemet

Leírás

int array_unshift ( array array, mixed var [, mixed ...])

Az array_unshift() az array tömb után megadott elemeket a tömb elejébe beszúrja. A beszúrandó elemeket listaként kezeli a függvény, így egymáshoz képesti sorrendjük nem változik meg. A numerikus indexek megváltoznak, 0-tól kezdve újraindexeli az elemeket, a szövegindexek nem változnak.

Az array elemeinek új számával tér vissza.

Példa 1. array_unshift() példa

$sor      = array('narancs', 'banán');
$gyumolcs = array_unshift($sor, 'alma', 'málna');

Ez azt eredményezi, hogy a $sor tömbnek 4 eleme lesz:
Array 
( 
    [0] => alma 
    [1] => málna
    [2] => narancs
    [3] => banán 
)

Lásd még: array_shift(), array_push() és array_pop()!

array_values

(PHP 4 )

array_values -- visszadja az összes tömbben előforduló értéket

Leírás

array array_values ( array input)

Az array_values() visszadja az összes input tömbben előforduló értéket.

Példa 1. array_values() példa

$tomb = array ("méret" => "XL", "szín" => "arany");
array_values ($tomb);

A fenti program kimenete:
Array
(
    [0] => XL
    [1] => arany
)

Megjegyzés: Ez a függvény PHP 4-től hozzáférhető, a PHP 3-at használók számára itt van egy lehetséges megvalósítás:

Példa 2. array_values() megvalósítása PHP 3-ban

function array_values ($arr) {
    $t = array();
    while (list($k, $v) = each ($arr)) {
        $t[] = $v;
    }
    return $t;
}

Lásd még: array_keys()!

array_walk

(PHP 3>= 3.0.3, PHP 4 )

array_walk --  felhasználói függvényt futtat a tömb minden elemén

Leírás

int array_walk ( array array, string func [, mixed userdata])

A func paraméterben megadott nevű felhasználói függvényt alkalmazza az array tömb minden elemére. A func függvény hívásakor első paraméterként a tömbérték, másodikként az indexe kerül átadásra. Ha a userdata is szerepel, akkor ez lesz a harmadik paraméter. A func nevű függvénynek a felhasználó által definiáltnak kell lennie, és nem lehet natív PHP függvény. Emiatt nem lehet az array_walk()-nak például közvetlenül a str2lower()-t meghívni, hanem először létre kell hozni egy saját függvényt, majd ennek átadni a paramétereket.

Megjegyzés: A függvény neve helyett egy tömböt is átadhatsz, ami egy objektum referenciát és egy metódus nevet kell tartalmazzon.

Ha func két vagy három argumentumnál többet igényel a userdata-tól függően, akkor figyelmeztető hibaüzenet (warning) keletkezik minden alkalommal, amikor az array_walk() meghívja a func függvényt. Ezeket a figyelmeztetések elnyomhatók a '@' karaktert az array_walk() elé írva vagy az error_reporting() használatával.

Megjegyzés: Ha a func függvénynek a tényleges tömbértékekkel kell dolgoznia, akkor a func függvény első paraméterét referenciaként kell átadni. Ezután az ezen a változón végzett változtatás az eredeti tömbben is változást idéz elő.

Az array tömb func függvényen belüli módosítása megjósolhatatlan viselkedést eredményezhet.

Megjegyzés: Az index és a userdata értékek átadása a func függvénynek a 4.0 verziótól elérhető.

PHP 4-ben reset() függvényt szükség szerint meg kell hívni, mivel az array_walk() nem inicializálja a tömböt alapértelmezés szerint.

A feldolgozandó tömböt a visszahívott függvényen belül nem lehet megváltoztatni, tehát nem lehet egyik vagy másik elemét, esetleg az egész tömböt törölni. Ha ez mégis megtörténik, akkor ennek a függvénynek a viselkedését nem lehet megjósolni.

Példa 1. array_walk() példa

$gyumolcsok = array ("d"=>"citrom", "a"=>"narancs", "b"=>"banán", "c"=>"alma");

function teszt_atir (&$elem1, $index, $prefix) {
    $elem1 = "$prefix: $elem1";
}

function teszt_kiir ($elem2, $index) {
    echo "$index. $elem2<br>\n";
}
echo "Előtte ...:\n";
array_walk ($gyumolcsok, 'test_kiir');
reset ($gyumolcsok);
array_walk ($gyumolcsok, 'test_atir', 'gyumolcs');
echo "... és utána:\n";
reset ($gyumolcsok);
array_walk ($gyumolcsok, 'test_kiir');

A fenti program kimenete:
Előtte ...:
d. citrom
a. narancs
b. banán
c. alma
... és utána:
d. gyumolcs: citrom
a. gyumolcs: narancs
b. gyumolcs: banán
c. gyumolcs: alma

Lásd még: each() és list()!

array

(PHP 3, PHP 4 )

array --  létrehoz egy tömböt

Leírás

array array ( [mixed ...])

A paramétereként átadott értékekből képzett tömböt ad vissza, az elemekhez az indexük is hozzárendelhető a => operátorral.

Megjegyzés: Az array() nyelvi építőelem tömbök létrehozására, és nem szokványos függvény.

Az "index => érték" szintaxis - egymástól vesszővel elválasztva - meghatároz egy indexet a hozzátartozó értékkel. Az index lehet sztring vagy egész szám is. Ha nincs index megadva, akkor egy automatikusan generált egész szám lesz az elem indexe. (Az automatikus indexelés 0-tól kezdődik.) Ha az index egy egész szám, akkor a következőként generált index az eddigi legnagyobb egész számú indextől eggyel nagyobb szám lesz. Figyelj arra, hogy ha két azonos indexű elemet definiálsz, akkor az utolsó felülírja az elsőt.

A következő példák segítenek megérteni, hogyan lehet kétdimenziós tömböket létrehozni, asszociatív tömbök kulcsait megadni, illetve hogyan lehet helyeket kihagyni és folytatni numerikus indexelést.

Példa 1. array() példa

$gyumolcsok = array (
    "gyümölcsök"  => array ("a"=>"narancs", "b"=>"banán", "c"=>"alma"),
    "számok"      => array (1, 2, 3, 4, 5, 6),
    "lyukak"      => array ("első", 5 => "második", "harmadik")
);

Példa 2. Automatikus indexelés az array() "függvénnyel"

$tomb = array( 1, 1, 1, 1,  1, 8=>1,  4=>1, 19, 3=>13);
print_r($tomb);

ezt fogja kiírni:
Array
(
    [0] => 1
    [1] => 1
    [2] => 1
    [3] => 13
    [4] => 1
    [8] => 1
    [9] => 19
)
Figyeld meg, hogy a 3. indexű elemet kétszer definiáltuk, és a végső értéke a 13. A 4. elemet a 8. után hoztuk létre, és a következő elemnek (19-nek) generált index értéke 9, mivel a legnagyobb létező index a tömbben a 8 volt.

Ez a példa egy olyan tömböt hoz létre, amelynek az indexelése 1-től kezdődik.

Példa 3. 1-től indexelt tömb létrehozása array() "függvénnyel"

$elsonegyedev  = array(1 => 'Január', 'Február', 'Március');
print_r($elsonegyedev);
ezt írja ki:
Array
(
    [1] => 'Január'
    [2] => 'Február'
    [3] => 'Március'
)

Lásd még: array_pad(), list() és range()!

arsort

(PHP 3, PHP 4 )

arsort --  fordított sorrendben rendez egy tömböt megtartva az indextársítást

Leírás

void arsort ( array array [, int sort_flags])

Ez a függvény úgy rendezi az array tömböt, hogy az indexek megtartják kapcsolatukat a hozzájuk rendelt tömb elemeivel. Főként akkor használják, ha az asszociatív tömbök rendezésénél az aktuális elemsorrend is fontos.

Példa 1. arsort() példa

$gyumolcsok = array ("d"=>"citrom", "a"=>"narancs", "b"=>"banán", "c"=>"alma");
arsort ($gyumolcsok);
 reset ($gyumolcsok);
while (list ($key, $val) = each ($gyumolcsok)) {
    echo "$key = $val\n";
}

Ez a példa a következőt írja ki:
a = narancs
d = citrom
b = banán
c = alma

A gyümölcsök az abc szerint fordított sorrendben vannak rendezve, és az indexek az eredeti elemekre mutatnak.

A rendezést befolyásolja a sort_flags paraméter, részletesebben lásd a sort() függvénynél!

Lásd még: asort(), rsort(), ksort() és sort()!

asort

(PHP 3, PHP 4 )

asort -- tömb elemeit rendezi megtartva az indextársítást

Leírás

void asort ( array array [, int sort_flags])

Ez a függvény úgy rendezi az array tömböt, hogy az indexek megtartják kapcsolatukat a hozzájuk rendelt tömbelemekkel. Főként akkor használják, ha az asszociatív tömbök rendezésénél az aktuális elemsorrend is fontos.

Példa 1. asort() példa

$gyumolcsok = array ("d"=>"citrom", "a"=>"narancs", "b"=>"banán", "c"=>"alma");
asort ($gyumolcsok);
reset ($gyumolcsok);
while (list ($key, $val) = each ($gyumolcsok)) {
    echo "$key = $val\n";
}

Ez a példa a következőt írja ki:
c = alma
b = banán
d = citrom
a = narancs

A gyümölcsök az abc-nek megfelelően növekvő sorrendben vannak rendezve, és az indexek az eredeti elemekre mutatnak.

A rendezést befolyásolja a sort_flags paraméter, részletesebben lásd a sort() függvénynél!

Lásd még: arsort(), rsort(), ksort() és sort()!

compact

(PHP 4 )

compact --  tömbbe tömöríti a változókat és értékeiket

Leírás

array compact ( mixed varname [, mixed ...])

A compact() változó számú paramétert fogad el. Minden paraméter lehet egy változónevet tartalmazó sztring vagy akár tömb is. A tömbben lehetnek újabb tömbök is, amelyek a változók neveit tárolják, a compact() rekurzívan kezeli ezt.

A compact() a neve alapján megkeresi a változót az aktuális szimbólumtáblában, és hozzáadja a kimeneti tömbhöz. A változó neve lesz a kulcs és a kulcshoz tartozó tömbérték pedig a változó értéke. Röviden, az extract()-tal ellentétesen működik. Az összes hozzáadott változót tároló kimeneti tömbbel tér vissza.

Az a sztring, amelynek megfelelő változó definiálatlan, ki lesz hagyva.

Példa 1. compact() példa

$varos    = "Miskolc";
$megye    = "BAZ";
$esemeny  = "P.A. elhagyja a varost";

$helyrajz = array ("varos", "megye");

$eredmeny = compact ("esemeny", "semmi_ilyen_valtozo_nincs", $helyrajz);

A $eredmeny értéke:
Array
(
    [esemeny] => P.A. elhagyja a varost
    [varos] => Miskolc
    [megye] => BAZ
)

Lásd még: extract()!

count

(PHP 3, PHP 4 )

count -- megszámolja az elemeket egy változóban

Leírás

int count ( mixed var)

Visszaadja a var változó elemeinek számát, amely általában array(tömb) típusú (mivel bármi másnak csak egy eleme lehet).

Ha a var változó nem tömb, akkor 1-et ad vissza, kivétel a count(NULL) ami egyenlő 0-val.

Figyelem

A count() 0-val térhet vissza definiálatlan változók esetén és üres tömbök esetén is. Az isset() segítségével lehet megvizsgálni, hogy a változó be van-e állítva.

Olvasd át a kézikönyv Tömbök c. fejezetét a PHP-ban megvalósított tömbök részletes magyarazátáért.

Példa 1. count() példa

$a[0] = 1;
$a[1] = 3;
$a[2] = 5;
$eredmeny = count ($a);
// $eredmeny == 3

$b[0] = 7;
$b[5] = 9;
$b[10] = 11;
$eredmeny = count ($b);
// $eredmeny == 3;

Megjegyzés: A sizeof() függvény a count() függvény álneve.

Lásd még: is_array(), isset() és strlen()!

current

(PHP 3, PHP 4 )

current -- visszaadja egy tömb aktuális elemét

Leírás

mixed current ( array array)

Minden tömbnek van egy ún. belső mutatója, amely a jelenlegi elemre mutat. A tömbbe beszúrt első elemre van inicializálva.

A current() függvény egyszerűen visszaadja a belső mutató által megjelölt tömbelemet. A mutató soha nem mozdul el erről az elemről. Ha a belső mutató az elemlista vége mögé mutat, akkor current() függvény FALSE-ot ad vissza.

Figyelem

Ha a tömb üres elemeket tartalmaz (0 vagy "" - üres string), akkor ez a függvény az ilyen elemeknél FALSE-ot ad vissza. Ez lehetetlenné teszi annak megállapítását a current() függvénnyel, hogy valóban a lista végére került-e a mutató. Az each() függvénnyel helyesen végig lehet lépkedni egy üres elemeket tartalmazó tömbön.

Lásd még: end(), next(), prev() és reset()!

each

(PHP 3, PHP 4 )

each --  visszaadja a tömb pillanatnyilag kijelölt elemét és lépteti a belső mutatót

Leírás

array each ( array array)

Az each() visszaadja az array tömb jelenlegi index-érték párját, és előre mozgatja a tömb belső mutatóját. Ez a index-érték pár egy négyelemű tömbben kerül visszaadásra az alábbi kulcsokkal: 0, 1, key, and value, valamint az alábbi elemekkel. 0, 1,key és value. A 0 és a key tartalmazza a tömbelem kulcsát, 1 és value pedig az adatokat.

Ha a belső mutató az elemlista vége mögé mutat, akkor each() függvény FALSE-ot ad vissza.

Példa 1. each() példák

$ize = array ("bob", "fred", "jussi", "jouni", "egon", "marliese");
$bigyo = each ($ize);

$bigyo tartalma most:
Array (
    0 => 0
    1 => 'bob'
    key => 0
    value => 'bob'
)

$ize = array ("Robert" => "Bob", "Seppo" => "Sepi");
$bigyo = each ($ize);

$bigyo tartalma most:
Array (
    0 => Robert
    1 => 'Bob'
    key => Robert
    value => 'Bob'
)

Az each()-et a list()-tel együtt szokás használni tömbök bejárására, mint például a $_POST:

Példa 2. $_POST bejárása each() függvénnyel

echo "POST metódussal elküldött változók:<br>";
reset ($_POST);
while (list ($key, $val) = each ($_POST)) {
    echo "$key => $val<br>";
}

Az each()() függvény lefutása után a belső tömbmutató a tömb következő elemére ugrik, vagy az utolsó elemre, ha a tömb végén áll a mutató. Használd a reset()-et, ha újból végig kell lépkedni a tömbön.

Lásd még: key(), list(), current(), reset(), next(), prev() és foreach()!

end

(PHP 3, PHP 4 )

end --  az utolsó elemre állítja a tömb belső mutatóját

Leírás

mixed end ( array array)

Az end() az array tömb belső mutatóját annak utolsó elemére állítja, és azt adja vissza.

Példa 1. Egyszerű példa az end() használatára

<?php
  $gyumolcsok = array('alma','banán','áfonya');
  print end($gyumolcsok); // áfonya
?>

Lásd még: current(), each(), next() és reset()!

extract

(PHP 3>= 3.0.7, PHP 4 )

extract --  tömbből változókat helyez el az aktuális szimbólumtáblába

Leírás

int extract ( array var_array [, int extract_type [, string prefix]])

Ez a függvény arra szolgál, hogy egy tömb tartalma alapján változókat helyezzen el az aktuális szimbólumtáblában. A paraméterként kapott var_array tömb kulcsait tekinti a változók neveinek és a tömbelemek értékeit a változók tartalmának. Minden kulcs-érték párból készül egy változó a szimbólumtáblában, az extract_type és prefix paraméterektől függően.

Megjegyzés: PHP 4.0.5-től kezdve a beillesztett változók számával tér vissza a függvény.

Megjegyzés: EXTR_IF_EXISTS és EXTR_PREFIX_IF_EXISTS 4.2.0 verzótól használhatók.

Megjegyzés: EXTR_REFS 4.3.0-tól használható.

Az extract() megvizsgál minden kulcsot (indexet), hogy az lehet-e egy érvényes változónév vagy sem, és hogy ilyen nevű változó létezik-e már a szimbólumtáblában (ütközés). Az érvénytelen változónevek és ütközések az extract_type paraméterben megadottak szerint lesz kezelve. Lehetséges értékei:

EXTR_OVERWRITE

Ütközéskor felülírja a már létező változót.

EXTR_SKIP

Ütközéskor nem írja felül a létező változót.

EXTR_PREFIX_SAME

Ütközéskor a létrehozandó változó neve elé prefix kerül.

EXTR_PREFIX_ALL

Minden létrehozandó változó neve elé prefix kerül. PHP 4.0.5-től kezdve ez érvényes a numerikus indexű elemekre is.

EXTR_PREFIX_INVALID

Minden érvénytelen nevű változónév elé a prefix kerül. PHP 4.0.5-től kezdve használható ez beállítás.

EXTR_IF_EXISTS

Csak akkor írja felül az adott nevű változót, ha az már létezik az aktuális szimbólimtáblában, egyébként nem csinál semmit. Ez hasznos lehet, ha : érvényes változókat előre definiálni, majd létrehozni a $_REQUEST tömbön kívül definiált változókat. PHP 4.2.0-től használható.

EXTR_PREFIX_IF_EXISTS

Csak akkor hozza létre a toldalékolt nevű változót, ha annak a toldalék nélküli megfelelője már létezik már létezik az aktuális szimbólimtáblában. PHP 4.2.0-től használható.

EXTR_REFS

A változókat referenciaként bontja ki, ami valójában azt jelenti, hogy a létrehozott változók referenciaként hivatkoznak az eredeti, var_array paraméterben átadott tömb elemeinek értékeire. Ez a módosító tetszés szerint önállóan vagy más módosítókkal logikai VAGY kapcsolattal együtt használható a extract_type paraméter értékeként. Ez a kapcsoló PHP 4.3.0. verziójától használható.

Ha nincs megadva az extract_type, akkor EXTR_OVERWRITE az alapértelmezés.

A prefix csak akkor szükséges, ha az extract_type EXTR_PREFIX_SAME, EXTR_PREFIX_ALL, EXTR_PREFIX_INVALID vagy EXTR_PREFIX_IF_EXISTS értékű. Ha prefixszel ellátott változónév sem érvényes, akkor az nem kerül bele a szimbólumtáblába.

Az extract() a sikeresen beillesztett változók számával tér vissza.

Az extract függvény egy lehetséges használata azoknak a változóknak a szimbólumtáblába importálása, amelyeket a wddx_deserialize() adott vissza egy asszociatív tömbben.

Példa 1. extract() példa

<?php

/* Feltételezi, hogy a $var_array egy a
   wddx_deserialize által visszaadott tömb*/

$méret    = "nagy";
$var_tomb = array ("szín"  => "kék",
                    "méret" => "közepes",
                    "alak"  => "gömb");
extract ($var_tomb, EXTR_PREFIX_SAME, "wddx");

print "$szín, $méret, $alak, $wddx_méret\n";
?>

A fenti példa ezt eredményezi:
kék, nagy, gömb, közepes

A $méret változó nem lett felülírva az EXTR_PREFIX_SAME megadása miatt, amely azt eredményezte, hogy ehelyett a $wddx_méret változóba került az új érték. Ha EXTR_SKIP-et használtunk volna, akkor a $wddx_méret sem került volna létrehozásra. Az EXTR_OVERWRITE pedig azt okozta volna, hogy a $méret értéke "közepes"-re változott volna. Az EXTR_PREFIX_ALL-lal pedig minden változó neve wddx előtaggal kezdődne: $wddx_szín, $wddx_méret és $wddx_alak.

Asszociatív tömböket kell használni, mert a numerikusan indexeltek nem adnak eredményt, kivéve EXTR_PREFIX_ALL vagy EXTR_PREFIX_INVALID jelzők használatakor.

Lásd még: compact()!

in_array

(PHP 4 )

in_array -- TRUE-val tér vissza, ha létezik az érték a tömbben

Leírás

bool in_array ( mixed needle, array haystack [, bool strict])

Átnézi a haystack tömböt a needle elemet keresve, ha megtalálta, akkor TRUE-t ad vissza, egyébként FALSE-ot.

Ha a strict harmadik paraméter értéke TRUE, akkor az in_array() a needle típusát is összeveti a haystack tömb elemeiével.

Megjegyzés: Ha a needle paraméter sztring, akkor az összehasonlítás kis- és nagybetűk különbözőségére érzékeny.

Megjegyzés: A PHP 4.2.0 verziója előtt a needle paraméter nem lehetett tömb.

Példa 1. in_array() példa

$os = array ("Mac", "NT", "Irix", "Linux");
if (in_array ("Irix", $os)) {
    print "Got Irix";
}
if (in_array ("mac", $os)) { 
                             
    print "Got mac";
}

A második feltétel nem teljesül, mert az in_array() érzékeny a kis- és nagybetűk különbségére, ezért a program kimenete :
Got Irix

Példa 2. in_array() strict paraméterrel

<?php
$a = array('1.10', 12.4, 1.13);

if (in_array('12.4', $a, TRUE))
    echo "szigorúan '12.4'-ot találtam meg.\n";
if (in_array(1.13, $a, TRUE))
    echo "szigorúan 1.13-ot találtam meg. \n";
?>

Ez a következőt írja ki:
szigorúan 1.13-ot találtam meg.

Példa 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'-t megtaláltam.\n";
}
if ( in_array(array ('f', 'i'), $a) ){
  echo "'fi'-t megtaláltam.\n";
}
if ( in_array('o', $a) ){
  echo "'o'-t megtaláltam.\n";
}
?>
Ez a következőt írja ki:
'ph'-t megtaláltam.
'o'-t megtaláltam.

Lásd még: array_search()!

key

(PHP 3, PHP 4 )

key --  asszociatív tömb pillanatnyilag kiválasztott kulcsát adja vissza

Leírás

mixed key ( array array)

A key() a belső tömbmutató által pillanatnyilag kijelölt elem kulcsával tér vissza.

Lásd még: current() és next()!

krsort

(PHP 3>= 3.0.13, PHP 4 )

krsort -- kulcsok alapján fordított sorrendbe rendez egy tömböt

Leírás

int krsort ( array array [, int sort_flags])

Ez a függvény úgy rendezi az array tömböt a kulcsai alapján, hogy az indexek megtartják kapcsolatukat a hozzájuk rendelt tömb elemeivel. Főként asszociatív tömbök rendezéséhez használatos.

Példa 1. krsort() példa

$gyumolcsok = array ("d"=>"citrom", "a"=>"narancs", "b"=>"banán", "c"=>"alma");
krsort ($gyumolcsok);
 reset ($gyumolcsok);
while (list ($key, $val) = each ($gyumolcsok)) {
    echo "$key = $val\n";
}

Ez a példa a következőt írja ki:

d = citrom
c = alma
b = banán
a = narancs

A rendezést befolyásolja a sort_flags paraméter, részletesebben lásd a sort() függvénynél!

Lásd még: asort(), arsort(), ksort() sort(), natsort() és rsort()!

ksort

(PHP 3, PHP 4 )

ksort -- kulcsok alapján rendezi a tömböt

Leírás

int ksort ( array array [, int sort_flags])

Ez a függvény úgy rendezi az array tömböt a kulcsai alapján, hogy az indexek megtartják kapcsolatukat a hozzájuk rendelt tömb elemeivel. Főként asszociatív tömbök rendezéséhez használatos.

Példa 1. ksort() példa

$gyumolcsok = array ("d"=>"citrom", "a"=>"narancs", "b"=>"banán", "c"=>"alma");
ksort ($gyumolcsok);
reset ($gyumolcsok);
while (list ($key, $val) = each ($gyumolcsok)) {
    echo "$key = $val\n";
}

Ez a példa a következőt írja ki:

a = narancs
b = banán
c = alma
d = citrom

A rendezést befolyásolja a sort_flags paraméter, részletesebben lásd a sort() függvénynél!

Lásd még: asort(), arsort(), krsort(), uksort(), sort(), natsort() és rsort()!

Megjegyzés: A második paraméter PHP 4-ben használható.

list

(PHP 3, PHP 4 )

list --  értéket rendel a felsorolt változókhoz

Leírás

void list ( mixed ...)

Az array()-hoz hasonlóan a list() sem valódi függvény, hanem nyelvi építőelem. A list() a több változó érték-hozzárendelésére szolgál egy műveleten belül.

Megjegyzés: A list() csak numerikus indexelésű tömbökön működik helyesen, és akkor is csak, ha az indexelés 0-tól kezdődik.

Példa 1. list() példák

<?php

$info = array('kávé', 'barna', 'koffein');

// az összes változó kiírása
list($ital, $szin, $ero) = $info;
print "A $ital $szin és a $ero teszi különlegessé.\n";

// csak néhány változó kiírása
list($ital, , $ero) = $info;
print "A {$ital}ban van $ero.\n";

// vagy a harmadik, legutols= kirása
list( , , $ero) = $info;
print "Kérek {$power}t!\n";

?>

Példa 2. Példa a list() használatára

<table>
 <tr>
  <th>Alkalmazott neve</th>
  <th>fizetése</th>
 </tr>

<?php

$result = mysql_query ("SELECT id, nev, fizetes FROM alkalmazottak",$conn);
while (list ($id, $nev, $fizetes) = mysql_fetch_row ($result)) {
    print (" <tr>\n".
           "  <td><a href=\"info.php?id=$id\">$nev</a></td>\n".
           "  <td>$fizetes</td>\n".
           " </tr>\n");
}

?>

</table>

Figyelem

A list() az értékek hozzárendelését jobbról kezdi el. Sima változók esetében ez nem okoz különösebb fejtörést, de tömbelemek esetén általában az az elvárt viselkedés, hogy az elemek felsorolásuk sorrendjében kerülnek a tömbbe, azaz a list() paraméterlistájában elfoglalt helyüknek megfelelően balról - jobbra haladva. Ez azonban nem így van, a hozzárendelés jobbról balra halad:

Példa 3. A list() használata indexelt tömbelemekkel

<?php
$info = array('kávé', 'fekete', 'koffein');
list($a[0], $a[1], $a[2]) = $info;

var_dump($a);
A következő kimenetet adja. Vesd össze az elemek tömbbeli sorrendjét a a list() paraméterlistájában elfoglalt helyükkel:
array(3) {
  [2]=>
  string(8) "koffein"
  [1]=>
  string(5) "fekete"
  [0]=>
  string(6) "kávé"
}

Lásd még: each(), extract() és array()!

natcasesort

(PHP 4 )

natcasesort --  tömböt rendez a "natural order" (természetes sorrend) algoritmus alapján kis-nagybetűk figyelembevétele nélkül

Leírás

void natcasesort ( array array)

Ez a függvény olyan rendező algoritmust valósít meg, amely az alfanumerikus sztringeket úgy rendezi, ahogy azt egy ember tenné. Ezt az eljárást nevezik "natural ordering"-nek - természetes rendezésnek.

A natcasesort() függvény a natsort() olyan változata, amely érzéketlen a kis- és nagybetűk különbségére. Lásd a natsort() függvényt a reguláris és a természetes rendezési algortimusok közötti különbségért!

Részletesebb leírásért lásd: Martin Pool Natural Order String Comparison c. oldalát!

Lásd még: sort(), natsort(), strnatcmp() és strnatcasecmp()!

natsort

(PHP 4 )

natsort --  tömböt rendez a "natural order" (természetes sorrend) algoritmus alapján

Leírás

void natsort ( array array)

Ez a függvény olyan rendező algoritmust valósít meg, amely az alfanumerikus sztringeket úgy rendezi, ahogy azt egy ember tenné. Ezt az eljárást nevezik "natural ordering"-nek - természetes rendezésnek. A sort() függvény reguláris rendezési algortimusa és eközötti különbséget szemlélteti a következő példa:

Példa 1. natsort() példa

<?php
$tomb1 = $tomb2 = array ("img12.png", "img10.png", "img2.png", "img1.png");

sort($tomb1);
echo "Hagyományos rendezés\n";
print_r($tomb1);

natsort($tomb2);
echo "\nTermészetes rendezés\n";
print_r($tomb2);
?>

Ez a példa a következőt írja ki:

Hagyományos rendezés
Array
(
    [0] => img1.png
    [1] => img10.png
    [2] => img12.png
    [3] => img2.png
)

Természetes rendezés
Array
(
    [3] => img1.png
    [2] => img2.png
    [1] => img10.png
    [0] => img12.png
)
Részletesebb leírásért lásd: Martin Pool Natural Order String Comparison c. oldalát!

Megjegyzés: Az index - érték párosítások megőrzésére az usort($tomb, 'strnatcmp') forma alkalmazása javasolt.

Lásd még: natcasesort(), strnatcmp() és strnatcasecmp()!

next

(PHP 3, PHP 4 )

next --  előre mozgatja a tömb belső mutatóját

Leírás

mixed next ( array array)

Visszaadja belső tömbmutató poziciója utáni elemet, vagy FALSE-ot, ha nincs következő elem.

A next() a current()-hoz hasonlóan viselkedik egy különbséggel. A belső tömbmutatót egy hellyel előbbre állítja, mielött visszadná az elemet. Ez azt jelenti, hogy a mostani pozició után következő elemmel tér vissza, és a belső tömbmutatót is eggyel előre lépteti. Ha a belső tömbmutató az elemlista végére ér, akkor a next() FALSE-ot ad vissza.

Figyelem

Ha a tömb üres elemeket is tartalmaz, akkor ezeknél az elemeknél a függvény ugyanúgy FALSE-szal tér vissza. Üres elemeket tartalmazó tömb bejárásához nézd meg az each() függvényt!

Lásd még: current(), end(), prev() és reset()!

pos

(PHP 3, PHP 4 )

pos -- visszaadja a tömb aktuális elemét

Leírás

mixed pos ( array array)

Ez a current() függvény álneve.

Lásd még: end(), next(), prev() és reset()!

prev

(PHP 3, PHP 4 )

prev -- visszlépteti a tömb belső mutatóját

Leírás

mixed prev ( array array)

Visszaadja belső tömbmutató pozíciója előtti tömbelemet, vagy FALSE-ot ha nincs következő elem.

Figyelem

Ha a tömb üres elemeket is tartalmaz, akkor ezeknél az elemeknél a függvény ugyanúgy FALSE-szal tér vissza. Üres elemeket tartalmazó tömb bejárásához nézd meg az each() függvényt!

A prev() a next()-hez hasonlóan működik, kivéve hogy a tömbmutatót visszafelé lépteti nem pedig előre.

Lásd még: current(), end(), next() és reset()!

range

(PHP 3>= 3.0.8, PHP 4 )

range --  egy tartományt lefedő tömböt készít

Leírás

array range ( mixed low, mixed high)

A range() a low és high közé eső elemekből alkotott tömbbel tér vissza. Ha low nagyobb, mint high, akkor a sorozat high-tól indul low felé.

Példa 1. range() példák

foreach(range(0, 9) as $szam) {
    echo $szam;
}
foreach(range('a', 'z') as $betu) {
    echo $betu;
}
foreach(range('z', 'a') as $betu) {
    echo $betu;
}

Megjegyzés: A 4.1.0 verziót megelőzően a range() függvény csak a növekvő egészszámokból álló tömböt tudott generálni. A karakteres tartomány és a csökkenő sorrendű elemek támogatása a 4.1.0 verziótól létezik.

Példa 2. csökkenő és a karakteres tartományok szimulációja

// array_reverse használható arra, hogy megfordítsa a tömböt
foreach(array_reverse(range(0,9)) as $szam) {
  echo $szam;
}

# array_map() és chr() használható arra, hogy számokból karaktereket alkosson
foreach(array_map('chr', range(ord('a'),ord('z'))) as $karakter) {
  echo $karakter;
}

Lásd még a shuffle() függvényt további példákért!

reset

(PHP 3, PHP 4 )

reset --  a tömb belső mutatóját az első elemére állítja

Leírás

mixed reset ( array array)

A reset() visszaállítja az array tömb belső tömbmutatóját az első elemre.

reset() a tömb első elemével tér vissza.

Lásd még: current(), each(), next() és prev()!

rsort

(PHP 3, PHP 4 )

rsort -- fordított sorrendben rendez egy tömböt

Leírás

void rsort ( array array [, int sort_flags])

Ez a függvény fordított sorrendben rendezi át a tömböt: a legnagyobbtól a legkisebb felé.

Példa 1. rsort() példa

$gyumolcsok = array ("citrom", "narancs", "banán", "alma");
rsort ($gyumolcsok);
reset ($gyumolcsok);
while (list ($key, $val) = each ($gyumolcsok)) {
    echo "$key = $val\n";
}

Ez a példa a következőt írja ki:

0 = narancs
1 = citrom
2 = banán
3 = alma

A gyümölcsök az abc szerint fordított sorrendben vannak rendezve.

A rendezést befolyásolja a sort_flags paraméter, részletesebben lásd a sort() függvénynél!

Lásd még: arsort(), asort(), ksort(), sort() és usort()!

shuffle

(PHP 3>= 3.0.8, PHP 4 )

shuffle -- összekeveri a tömb elemeit

Leírás

void shuffle ( array array)

Ez a függvény véletlenszerűen összekeveri a tömb elemeit. Az srand() függvényt meg kell hívni, hogy inicializálja a véletlenszám-generátort!

Példa 1. shuffle() példa

$numbers = range (1,20);
srand ((float)microtime()*1000000);
shuffle ($numbers);
while (list (, $number) = each ($numbers)) {
    echo "$number ";
}

Lásd még: arsort(), asort(), ksort(), rsort(), sort() és usort()!

sizeof

(PHP 3, PHP 4 )

sizeof -- visszadja a változó elemszámát

Leírás

int sizeof ( mixed var)

A sizeof() függvény a count() álneve.

Lásd még: count()!

sort

(PHP 3, PHP 4 )

sort -- tömböt rendez

Leírás

void sort ( array array [, int sort_flags])

Ez a függvény egy tömb elemeit rendezi sorba a legkisebbtől haladva a legnagyobb felé - azaz növekvő sorrendben.

Példa 1. sort() példa

<?php

$gyumolcsok = array ("citrom", "narancs", "banán", "alma");
sort ($gyumolcsok);
reset ($gyumolcsok);
while (list ($key, $val) = each ($gyumolcsok)) {
    echo "gyumolcsok[".$key."] = ".$val."\n";
}

?>

Ez a példa a következőt írja ki:

gyumolcsok[0] = alma
gyumolcsok[1] = banán
gyumolcsok[2] = citrom
gyumolcsok[3] = narancs

A gyümölcsök az abc sorrendben vannak rendezve.

A rendezést befolyásolja a sort_flags paraméter, amelynek a következő értékei lehetnek:

(a rendezést befolyásoló jelzők)

  • SORT_REGULAR - az elemeket hagyományosan hasonlítja össze

  • SORT_NUMERIC - az elemeket számokként hasonlítja össze

  • SORT_STRING - az elemeket szövegként hasonlítja össze

Lásd még: arsort(), asort(), ksort(), natsort(), natcasesort(), rsort(), usort(), array_multisort() és uksort()!

Megjegyzés: A második paraméter PHP 4-től használható.

uasort

(PHP 3>= 3.0.4, PHP 4 )

uasort --  tömböt rendez egy felhasználó összehasonlító függvénnyel megtartva az indextársítást

Leírás

void uasort ( array array, function cmp_function)

Ez a függvény úgy rendez egy tömböt, hogy megtartja az indexek és az értékek közti relációt. Főleg akkor használatos, amikor az asszociatív tömböket rendezzünk, ahol az elemek sorrendje fontos. Az összehasonlítást végző függvényt a felhasználó határozza meg.

Megjegyzés: További példákért lásd a usort() és uksort() példáit, hogyan kell felhasználói függvényeket használni!

Megjegyzés: A függvény neve helyett egy tömböt is átadhatsz, ami egy objektum referenciát és egy metódus nevet kell tartalmazzon.

Lásd még: usort(), uksort(), sort(), asort(), arsort(), ksort() és rsort()!

uksort

(PHP 3>= 3.0.4, PHP 4 )

uksort --  tömböt rendez kulcsai alapján egy felhasználó összehasonlító függvénnyel

Leírás

void uksort ( array array, function cmp_function)

Ez a függvény egy felhasználói függvénnyel átrendezi a tömböt a kulcsok szerint. Akkor használjuk ezt a függvényt, ha a rendezendő tömböt nem szokványos feltétel alapján akarjuk rendezni,

Példa 1. uksort() példa

function cmp ($a, $b) {
    if ($a == $b) return 0;
    return ($a > $b) ? -1 : 1;
}

$a = array (4 => "négy", 3 => "három", 20 => "húsz", 10 => "tíz");

uksort ($a, "cmp");

while (list ($key, $val) = each ($a)) {
    echo "$key: $val\n";
}

Ez a példa a következőt írja ki:

20: húsz
10: tíz
4: négy
3: három

Megjegyzés: A függvény neve helyett egy tömböt is átadhatsz, ami egy objektum referenciát és egy metódus nevet kell tartalmazzon.

Lásd még: usort(), uasort(), sort(), asort(), arsort(), ksort(), natsort() és rsort()!

usort

(PHP 3>= 3.0.3, PHP 4 )

usort --  tömböt rendez elemértékei alapján egy felhasználó összehasonlító függvénnyel

Leírás

void usort ( array array, string cmp_function)

Ez a függvény a cmp_function paraméterben megadott nevű felhasználói függvénnyel rendezi az array tömb elemeit. Ha a rendezendő tömböt nem szokványos feltétel alapján akarjuk rendezni, akkor használjuk ezt a függvényt.

Az összehasonlító függvénynek 0-nál kisebb vagy nagyobb ill. 0 értéket kell visszaadnia, ha az első elem kisebb vagy nagyobb a másodiknál, ill. ha egyenlők.

Megjegyzés: Ha két elem egyenlő, sorrendjük a rendezett tömbben nem definiált. A 4.0.6-os verzióig a felhasználói függvény ezen elemek eredeti sorrendjét meg tudta őrizni. A PHP 4.1.0-ban bevezetett új rendezőalgoritmus erre már nem nyújt lehetőséget, mivel nincs rá hatékony módszer.

Példa 1. usort() példa

function cmp ($a, $b) {
    if ($a == $b) return 0;
    return ($a > $b) ? -1 : 1;
}

$a = array (3, 2, 5, 6, 1);

usort ($a, "cmp");

while (list ($key, $val) = each ($a)) {
    echo "$key: $value\n";
}

Ez a példa a következőt írja ki:

0: 6
1: 5
2: 3
3: 2
4: 1

Megjegyzés: Ebben az egyszerű esetben nyilvánvalóan jobb választás az rsort() függvény használata.

Példa 2. Az usort() használata több dimenziós tömbökön

function cmp ($a, $b) {
    return strcmp($a["gyumolcs"], $b["gyumolcs"]);
}

$gyumolcsok[0]["gyumolcs"] = "citrom";
$gyumolcsok[1]["gyumolcs"] = "alma";
$gyumolcsok[2]["gyumolcs"] = "szőlő";

usort($gyumolcsok, "cmp");

while (list ($key, $val) = each ($gyumolcsok)) {
    echo "\$gyumolcsok[$key]: " . $value["gyumolcs"] . "\n";
}

Több dimenziós tömbökre alkalmazva $a és $b az első indexre mutató referenciákat fog tartalmazni.

Ez a példa a következőt írja ki:

$gyumolcsok[0]: alma
$gyumolcsok[1]: citrom
$gyumolcsok[2]: szőlő

Megjegyzés: A függvény neve helyett egy tömböt is átadhatsz, ami egy objektum referenciát és egy metódus nevet kell tartalmazzon.

Példa 3. Objektum tagfüggvényének (metódus) használata az usort()-tal

class TestObj {
    var $nev;

    function TestObj($nev)
    {
        $this->nev = $nev;
    }

    /* ez statikus összehasonlító függvény: */
    function cmp_obj($a, $b)
    {
        $al = strtolower($a->nev);
        $bl = strtolower($b->nev);
        if ($al == $bl) return 0;
        return ($al > $bl) ? +1 : -1;
    }
}

$a[] = new TestObj("c");
$a[] = new TestObj("b");
$a[] = new TestObj("d");

uasort($a, array ("TestObj", "cmp_obj"));

foreach ($a as $elem) {
    print $elem->nev."\n";
}

Ez a példa a következőt írja ki:

b
c
d

Figyelem

Néhány C könyvtárban (mint például a Solaris rendszerekben) a gyorsrendezés alapjául szolgáló függvény a PHP összeomlását okozhatja, ha az összehasonlító függvény nem következetes értéket ad vissza.

Lásd még: uasort(), uksort(), sort(), asort(), arsort(),ksort(), natsort() és rsort()!

III. Aspell függvények [ellenjavallt]

Az aspell() függvények ellenőrzik egy szó helyesírását és javaslatokat kínálnak fel.

Megjegyzés: Az aspell csak a nagyon régi (a .27.* verzióig) aspell könyvtárakkal működik együtt. Ez a modul sem és az aspell könyvtár azon verziói sem támogatottak a továbbiakban. Ha helyesírásellenőrzési funkciókat szeretnél használni a PHP-ban, használd a pspell könyvtárat. Az a pspell könyvtárat használja, és képes az újabb aspell verzókkal együttműködni.

A függvényekhez aspell könyvár szükséges, amely beszerezhető a http://aspell.sourceforge.net/ címen.

Tartalom
aspell_check_raw --  Ellenőriz egy szót kis- és nagybetűk cseréje illetve a szöveg trimmelése nélkül [ellenjavallt]
aspell_check -- Ellenőriz egy szót [ellenjavallt]
aspell_new -- Betölt egy új szótárt [ellenjavallt]
aspell_suggest -- Egy szó helyesírására tesz javaslatot [ellenjavallt]

aspell_check_raw

(PHP 3>= 3.0.7, PHP 4 <= 4.2.3)

aspell_check_raw --  Ellenőriz egy szót kis- és nagybetűk cseréje illetve a szöveg trimmelése nélkül [ellenjavallt]

Leírás

bool aspell_check_raw ( int dictionary_link, string word)

Az aspell_check_raw() ellenőrzi egy szó helyesírását anélkül, hogy manipulálná (megváltoztatná a kis- és nagybetűket vagy levágná a stringet), és TRUE-t ad vissza, ha a helyesírás jó, egyébként FALSE-ot.

Példa 1. aspell_check_raw() példa

$aspell_link=aspell_new ("english");
if (aspell_check_raw ($aspell_link, "test")) {
    echo "A helyesírás jó";
} else {
    echo "Bocs, de a helyesírás rossz";
}

aspell_check

(PHP 3>= 3.0.7, PHP 4 <= 4.2.3)

aspell_check -- Ellenőriz egy szót [ellenjavallt]

Leírás

bool aspell_check ( int dictionary_link, string word)

Az aspell_check() ellenőrzi egy szó helyesírását és TRUE-t ad vissza, ha a helyesírás jó, egyébként FALSE-ot.

Példa 1. aspell_check() példa

$aspell_link=aspell_new ("english");
if (aspell_check ($aspell_link, "testt")) {
    echo "A helyesírás jó";
} else {
    echo "Bocs, de a helyesírás rossz";
}

aspell_new

(PHP 3>= 3.0.7, PHP 4 <= 4.2.3)

aspell_new -- Betölt egy új szótárt [ellenjavallt]

Leírás

int aspell_new ( string master [, string personal])

Az aspell_new() megnyit egy új szótárt, és visszaadja a szótárkapcsolat azonosítóját, amely a többi aspell függvényben használható. Hiba esetén FALSE-szal tér vissza.

Példa 1. aspell_new() példa

$aspell_link=aspell_new ("english");

aspell_suggest

(PHP 3>= 3.0.7, PHP 4 <= 4.2.3)

aspell_suggest -- Egy szó helyesírására tesz javaslatot [ellenjavallt]

Leírás

array aspell_suggest ( int dictionary_link, string word)

Az aspell_suggest() visszaadja az adott szó helyesírási javaslatait egy tömbben.

Példa 1. aspell_suggest() példa

$aspell_link = aspell_new("english");

if (!aspell_check ($aspell_link, "test")) {
    $javaslatok = aspell_suggest($aspell_link, "test");

    foreach ( $javaslatok as $javaslat ) {
        echo "Lehetséges helyesírási változatok:: " . $javaslat . "&lt;br>"; 
    }
}

IV. BCMath tetszőleges pontosságú matematikai függvények

Ha tetszőleges pontosságú matematikai műveleteket szeretnél végezni, a PHP a Binary Calculator Mathematics (BCMath) függvényeket kínálja erre a célra. Ezek a függvények tetszőleges méretben és pontossággal tudnak számokat ábrázolni karaktersorozatok felhasználásával.


Előfeltételek

Licensz kérdések miatt a BCMATH könyvtár a standard PHP csomagtól különálló elemként tölthető le. Egy tar-gzippelt verzió beszerezhető a http://www.php.net/extra/number4.tar.gz címen. Olvasd el a README.BCMATH fájlt a PHP csomagodban további információkért.


Telepítés

PHP 4-ben ezek a függvények csak akkor érhetőek el, ha a PHP-t a --enable-bcmath beállítással fordítottad. PHP 3-ban ezek a függvények csak akkor érhetőek el, ha a PHP-t NEM a --disable-bcmath beállítással fordítottad.


Futásidejű beállítások

Ez a kiterjesztés semmilyen konfigurációs beállításokat nem definiál a php.ini állományban.


Erőforrás típusok

Ez a kiterjesztés semmilyen erőforrás típust nem definiál.


Előredefiniált állandók

Ez a kiterjesztés semmilyen konstans értéket nem definiál.

Tartalom
bcadd -- Összead két tetszőleges pontosságú számot
bccomp -- Összehasonlít két tetszőleges pontosságú számot
bcdiv -- Eloszt két tetszőleges pontosságú számot
bcmod --  Kiszámítja két tetszőleges pontosságú szám modulusát
bcmul -- Összeszoroz két tetszőleges pontosságú számot
bcpow --  Egy tetszőleges pontosságú számot egy másik hatványára emel
bcpowmod --  Raise an arbitrary precision number to another, reduced by a specified modulus.
bcscale --  Beállítja az alapértelmezett skálázási értéket az összes BCMath matematikai függvény részére
bcsqrt --  Kiszámítja egy tetszőleges pontosságú szám négyzetgyökét
bcsub --  Kivon egy tetszőleges pontosságú számot egy másikból

bcadd

(PHP 3, PHP 4 )

bcadd -- Összead két tetszőleges pontosságú számot

Leírás

string bcadd ( string left_operand, string right_operand [, int scale])

Hozzáadja a left_operand-ot a right_operand-hoz, és visszatér az összeget tartalmazó stringgel. Az elhagyható scale paraméter határozza meg az eredményben a tizedes pont utáni számjegyek számát.

Lásd még: bcsub()!

bccomp

(PHP 3, PHP 4 )

bccomp -- Összehasonlít két tetszőleges pontosságú számot

Leírás

int bccomp ( string left_operand, string right_operand [, int scale])

Összehasonlítja a left_operand-ot a right_operand-al, és az eredményt egészként visszaadja. Az elhagyható scale paraméter beállítja a tizedes pont utáni számjegyek számát, amely felhasználásra kerül az összehasonlításban. A visszatérési érték 0, ha a két operandus egyenlő. Ha a left_operand nagyobb a right_operand-nál, az eredmény +1, de ha a left_operand kisebb nála, az eredmény -1.

bcdiv

(PHP 3, PHP 4 )

bcdiv -- Eloszt két tetszőleges pontosságú számot

Leírás

string bcdiv ( string left_operand, string right_operand [, int scale])

Elosztja a left_operand-ot a right_operand-al, és visszaadja az eredményt. Az elhagyható scale paraméter beállítja az eredményben a tizedespont utáni számjegyek számát.

Lásd még: bcmul()!

bcmod

(PHP 3, PHP 4 )

bcmod --  Kiszámítja két tetszőleges pontosságú szám modulusát

Leírás

string bcmod ( string left_operand, string modulus)

Kiszámítja a left_operand-nak a modulus-sal történő osztás utáni maradékát.

Lásd még: bcdiv()!

bcmul

(PHP 3, PHP 4 )

bcmul -- Összeszoroz két tetszőleges pontosságú számot

Leírás

string bcmul ( string left_operand, string right_operand [, int scale])

Összeszorozza a left_operand-ot a right_operand-dal, és visszaadja az eredményt. Az elhagyható scale paraméter határozza meg az eredményben a tizedespont utáni számjegyek számát.

Lásd még: bcdiv()!

bcpow

(PHP 3, PHP 4 )

bcpow --  Egy tetszőleges pontosságú számot egy másik hatványára emel

Leírás

string bcpow ( string x, string y [, int scale])

Kiszámítja x szám y. hatványát. Az elhagyható scale paraméter beállítja az eredményben a tizedes pont utáni számjegyek számát.

Lásd még: bcsqrt()!

bcpowmod

(PHP 5 CVS only)

bcpowmod --  Raise an arbitrary precision number to another, reduced by a specified modulus.

Description

string bcpowmod ( string x, string y, string modulus [, int scale])

Use the fast-exponentiation method to raise x to the power y with respect to the modulus modulus. The optional scale can be used to set the number of digits after the decimal place in the result.

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. 

?>

Megjegyzés: Because this method uses the modulus operation, non-natural numbers may give unexpected results. A natural number is any positive non-zero integer.

See also bcpow(), and bcmod().

bcscale

(PHP 3, PHP 4 )

bcscale --  Beállítja az alapértelmezett skálázási értéket az összes BCMath matematikai függvény részére

Leírás

string bcscale ( int scale)

Ez a függvény beállítja a skálázási értékét minden bc matematikai függvény részére, így nem kell mindig explicit módon megadni a scale paramétert, csak ha szükséges.

bcsqrt

(PHP 3, PHP 4 )

bcsqrt --  Kiszámítja egy tetszőleges pontosságú szám négyzetgyökét

Leírás

string bcsqrt ( string operand [, int scale])

Visszaadja az operand négyzetgyökét. Az elhagyható scale paraméter beállítja az eredményben a tizedes pont utáni számjegyek számát.

Lásd még: bcpow()!

bcsub

(PHP 3, PHP 4 )

bcsub --  Kivon egy tetszőleges pontosságú számot egy másikból

Leírás

string bcsub ( string left_operand, string right_operand [, int scale])

Kivonja a right_operand-ot a left_operand-ból, és visszaadja az eredményt tartalmazó string-et. Az elhagyható scale paraméter beállítja az eredményben a tizedes pont utáni számjegyek számát.

Lásd még: bcadd()!

V. Bzip2 tömörítési függvények

Bevezetés

A bzip2 (.bz2) tömörítési eljárással tömörített állományokat és a bennük levő fájlokat írja-olvassa.


Követelmények

Ez a modul Julian Seward bzip2 függvénykönyvtárát használja.


Telepítés

Bzip2 support in PHP is not enabled by default. You will need to use the --with-bz2[=DIR] configuration option when compiling PHP to enable bzip2 support.


Futásidejű beállítások

Ez a kiterjesztés semmilyen konfigurációs beállításokat nem definiál a php.ini állományban.


Erőforrás típusok

Ez a kiterjesztés egyetlen erőforrástípust definiál: egy fájlmutatót a feldolgozás alatt álló bz2 fájlokra.


Előre definiált állandók

Ez a kiterjesztés semmilyen konstans értéket nem definiál.


Rövid példa

A következő példaprogram megnyit egy próbafájlt, beleír egy rövid szöveget, majd kiírja a fájl tartalmát.

Példa 1. Rövid bzip2 példa

<?php

$filename = "/tmp/testfile.bz2";
$str = "Ez egy próbaszövegecske.\n";

// megnyitás írásra - "w" kapcsoló használatával
$bz = bzopen($filename, "w");

// beleírja a próbaszöveget a fájlba
bzwrite($bz, $str);

// bezárja a fájlot
bzclose($bz);

// újra megnyitja, de most olvasásra - "r" kapcsolót használ
$bz = bzopen($filename, "r");

// beolvas 10 karaktert a fájlból
print bzread($bz, 10);

// A fájl végéig (vagy a következő 1024 karakterig) kiírja a tartalmát, majd bezárja a fájlt
print bzread($bz);

bzclose($bz);

?>
Tartalom
bzclose -- Bezár egy bzip2 fájl mutatót
bzcompress -- bzip2 algoritmus szerint tömörít egy jelsorozatot
bzdecompress -- Kitcsomagol bzip2 tömörített adatokat
bzerrno -- A bzip2 hiba számával tér vissza
bzerror -- A bzip2 hiba számát és a hibás sztringet egy tömbbe pakolva tér vissza.
bzerrstr -- A bzip2 hibasztringgel tér vissza
bzflush -- Kikényszeríti az összes pufferelt adat írását
bzopen -- Megnyit egy bzip2 tömörített fájlt
bzread -- Bináris bzip2 fájlokat olvas
bzwrite -- Bináris bzip2 fájlba ír

bzclose

(4.0.4 - 4.3.2 only)

bzclose -- Bezár egy bzip2 fájl mutatót

Leírás

int bzclose ( int bz)

Bezár egy bzip2 fájlot, amire a bz fájl mutatóval (file pointer) utaltunk. (A fájl mutató megértését megkönnyítheti az első, "rövid bzip2 példa" hetedik sora.)

TRUE értékkel tér vissza ha sikerül, egyébként FALSE-szal.

A fájl mutatónak egy létező és bzopen() függvénnyel sikeresen megnyitott fájlra kell mutatnia.

Lásd még: bzopen()!

bzcompress

(4.0.4 - 4.3.2 only)

bzcompress -- bzip2 algoritmus szerint tömörít egy jelsorozatot

Leírás

string bzcompress ( string source [, int blocksize [, int workfactor]])

A bzcompress() függvény tömöríti a source paraméterben megadott forrásfájlt és visszatér ennek bzip2-ben tömörített változatával.

Az elhagyható blocksize paraméterrel meghatározhatjuk a tömörítéshez használt blokkméretet, 1 és 9 között. A 9 adja a legjobb tömörítést, de ez a leginkább erőforrás-igényesebb is. A blocksize paraméter alpértelmezett értéke: 4.

A szintén elhagyható workfactor paraméter a tömörítési fázisok viselkedését befolyásolja, hogyan viselkedjenek a legrosszabb esetben, vagyis amikor temérdek ismétlődő adat követi egymást. Az értéke 0 és 250 között lehet, a 250 és a 0 különleges esetekben használatos, míg a 30 az alapértelmezett érték. A workfactor paramétertől függetlneül, a generált kimenet ugyanaz lesz.

Példa 1. bzcompress() Példa

<?php
$str = "minta adat";
$bzstr = bzcompress($str, 9);
print( $bzstr );
?>

Lásd még: bzdecompress()!

bzdecompress

(4.0.4 - 4.3.2 only)

bzdecompress -- Kitcsomagol bzip2 tömörített adatokat

Leírás

string bzdecompress ( string source [, int small])

A bzdecompress() kitömöríti sourceparaméterben megadott, bzip2 tömörített adatot. Ha a small elhagyható paraméter TRUE (logikai IGAZ), akkor egy alternatív kicsomagoló algoritmust fog használni, ami ugyan kevesebb memóriát fogyaszt - a maximális memóriaszükséglet kb. 2300K-ra csökken -, de durván feleakkora sebességgel fut. Nézd meg a bzip2 dokumentációt a részletesebb információkért e témában.

Példa 1. bzdecompress()

<?php
$start_str = "Hát nem édes pofa?";
$bzstr = bzcompress($start_str);

print( "A tömörített szting: " );
print( $bzstr );
print( "\n<br>\n" );

$str = bzdecompress($bzstr);
print( "A kicsomagolt sztring: " );
print( $str );
print( "\n<br>\n" );
?>

Lásd még: bzcompress()!

bzerrno

(4.0.4 - 4.3.2 only)

bzerrno -- A bzip2 hiba számával tér vissza

Leírás

int bzerrno ( int bz)

Bármilyen bzip2 művelet során fellépő hiba számával tér vissza, amit a bz fájl mutató (file pointer) szolgáltat.

Lásd még: bzerror() ésbzerrstr().

bzerror

(4.0.4 - 4.3.2 only)

bzerror -- A bzip2 hiba számát és a hibás sztringet egy tömbbe pakolva tér vissza.

Leírás

array bzerror ( int bz)

Egy asszociatív tömbbe teszi a bzip2 művelet során fellépett hibákat és a hozzájuk tartozó hibás sztringeket, amiket a bz fájl mutatótól (file pointer) vesz át .

Példa 1. bzerror() Példa

<?php
$hiba = bzerror($bz);

echo $hiba["errno"];
echo $hiba["errstr"];
?>

Lásd még bzerrno() és bzerrstr().

bzerrstr

(4.0.4 - 4.3.2 only)

bzerrstr -- A bzip2 hibasztringgel tér vissza

Leírás

string bzerrstr ( int bz)

Egy bzip2 művelet alatt fellépő hiba hibáüzenetével tér vissza, amit a bz fájl mutató (file pointer) ad át a függvénynek.

Lásd még: bzerrno() és bzerror().

bzflush

(4.0.4 - 4.3.2 only)

bzflush -- Kikényszeríti az összes pufferelt adat írását

Leírás

int bzflush ( int bz)

Az összes pufferelt bzip2 adat írását kikényszeríti a bz fájl mutató (file pointer) számára.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Lásd még: bzread() és bzwrite()!

bzopen

(4.0.4 - 4.3.2 only)

bzopen -- Megnyit egy bzip2 tömörített fájlt

Leírás

int bzopen ( string filename, string mode)

Megnyit egy bzip2 (.bz2 kiterjesztésű) fájlt olvasásra vagy írásra. filename paraméter a fájl neve, amit ki szeretnénk nyitni. A mode paraméter hasonlóan működik, mint a fopen() függvénynél (`r' - olvasás, `w' - írás, stb.).

Ha a művelet sikertelen, akkor FALSE-szal (logikai HAMIS), egyébként az újonnan megnyitott fájlra mutatóval (file pointer) tér vissza.

Példa 1. bzopen() Példa

<?php
$bz = bzopen("/tmp/foo.bz2", "r");
$tömörített_fájl = bzread($bz, filesize("/tmp/foo.bz2"));
bzclose($bz);

print( "Íme a /tmp/foo.bz2 tartalma: " );
print( "\n<br>\n" );
print( $tömörített_fájl );
?>

Lásd még: bzclose()!

bzread

(4.0.4 - 4.3.2 only)

bzread -- Bináris bzip2 fájlokat olvas

Leírás

string bzread ( int bz [, int length])

A bzread() függvény beolvas length hosszúságú bájtot a bz paraméterben megadott bzip2 fájl mutatóból (file pointer). Addig olvas, amíg a length paraméternek megfelelő (tömörítetlen!) mennyiségű bájtot beolvassa vagy a fájlvég-jelet (EOF) eléri; már amelyik előbb bekövetkezik. Ha az elhagyható length paramétert nem állítottuk be, akkor a bzread() függvény 1024 (tömörítetlen) bájtot olvas egyszerre.

Példa 1. bzread() Példa

<?php
$bz = bzopen("/tmp/foo.bz2", "r");
$str = bzread($bz, 2048);
print( $str );
?>

Lásd még: bzwrite() és bzopen()!

bzwrite

(4.0.4 - 4.3.2 only)

bzwrite -- Bináris bzip2 fájlba ír

Leírás

int bzwrite ( int bz, string data [, int length])

A bzwrite() függvény a data paraméterben megadott sztringet abba a bzip2 fájlba írja, amelyre a bz mutat. Ha az elhagyható length paramétert megadtuk, akkor az írás befejeződik, miután elérte a megadott (tömörítetlen) bájt hosszt ill. elérte a fájlvég-jelet (EOF), ha az hamarább bekövetkezik.

Példa 1. bzwrite() Példa

<?php
$str = "tömörítetlen adat";
$bz = bzopen("/tmp/foo.bz2", "w");
bzwrite($bz, $str, strlen($str));
bzclose($bz);
?>

Lásd még: bzread() és bzopen()!

VI. Naptár függvények

Bevezetés

A naptár kiterjesztés egy sereg függvényt bocsát rendelkezésre két naptárformátum egyszerű konvertálásához. A közvetítő vagy standard a Julián dátumon alapul. A Julián dátum egy elég korai dátumtól kezdődik, ezért nem akadhat vele probléma (kb i.e. 4000). A naptárrendszerek közti átszámoláshoz először Julián dátumra kell átszámítani a dátumot, majd a válaszott rendszerre. A Julián dátum nagyon különbözik a Julián-féle naptártól! (Erről további információkért látogass el a http://www.hermetic.ch/cal_stud/jdn.htm címre!) A naptárrendszerek információjához látogass el a http://www.boogle.com/info/cal-overview.html címre. Erről az oldalról néhány idézett kivonat megtalálható ebben az instrukcióban.


Telepítés

Ahhoz, hogy ezek a függvények működjenek az --enable-calendar kapcsolóval kell fordítani a PHP-t.


Futásidejű beállítások

Ez a kiterjesztés semmilyen konfigurációs beállításokat nem definiál a php.ini állományban.


Erőforrás típusok

Ez a kiterjesztés semmilyen erőforrás típust nem definiál.


Előre definiált állandók

Az itt listázott állandókat ez a kiterjesztés definiálja, és csak akkor elérhetőek, ha az adott kiterjesztés be van fordítva a PHP-be, vagy dinamikusan betöltött.

CAL_GREGORIAN (integer)

CAL_JULIAN (integer)

CAL_JEWISH (integer)

CAL_FRENCH (integer)

CAL_NUM_CALS (integer)

CAL_DOW_DAYNO (integer)

CAL_DOW_SHORT (integer)

CAL_DOW_LONG (integer)

CAL_MONTH_GREGORIAN_SHORT (integer)

CAL_MONTH_GREGORIAN_LONG (integer)

CAL_MONTH_JULIAN_SHORT (integer)

CAL_MONTH_JULIAN_LONG (integer)

CAL_MONTH_JEWISH (integer)

CAL_MONTH_FRENCH (integer)

The following constants are available since PHP 4.3.0 :

CAL_EASTER_DEFAULT (integer)

CAL_EASTER_ROMAN (integer)

CAL_EASTER_ALWAYS_GREGORIAN (integer)

CAL_EASTER_ALWAYS_JULIAN (integer)

The following constants are available since PHP 5.0.0 :

CAL_JEWISH_ADD_ALAFIM_GERESH (integer)

CAL_JEWISH_ADD_ALAFIM (integer)

CAL_JEWISH_ADD_GERESHAYIM (integer)

Tartalom
cal_days_in_month -- A megadott hónap napjainak számával tér vissza az adott naptár adott évében
cal_from_jd -- Julián naptárból egy támogatott naptártípusba konvertál és további információkat szolgáltat
cal_info -- Különleges naptártípusokról ad információt
cal_to_jd -- Egy támogatott naptártípusból Julián naptárba konvertál
easter_date --  Kiszámolja egy adott év húsvétjának UNIX időbélyeggel megadott éjféli időpontját
easter_days --  Kiszámolja adott évben a március 21-től húsvétig terjedő napok számát
FrenchToJD --  Francia Köztársasági naptárt konvertál Julián dátumba
GregorianToJD --  Gergely dátumot konvertál Julián dátumba
JDDayOfWeek -- Visszaadja a hét egy napjának nevét
JDMonthName -- Visszaadja egy hónap nevét
JDToFrench --  Julián dátumot konvertál Francia Köztársasági naptárba
JDToGregorian -- Julián dátumot konvertál Gergely dátumba
JDToJewish --  Julián dátumot konvertál Zsidó naptárba
JDToJulian --  Julián dátumot konvertál Julian-féle naptári dátumba
jdtounix -- Julián dátumot konvertál UNIX időpontba
JewishToJD --  Zsidó naptárt konvertál Julián dátumba
JulianToJD --  Julián-féle naptári dátumot konvertál Julián dátumba
unixtojd -- UNIX időbélyeget konvertál Julián dátumba

cal_days_in_month

(PHP 4 >= 4.1.0)

cal_days_in_month -- A megadott hónap napjainak számával tér vissza az adott naptár adott évében

Leírás

int cal_days_in_month ( int calendar, int month, int year)

Ez a függvény a napok számával tér vissza, month hónapban, year évben, és a calendar naptár paraméterekben megadott értékek szerint.

Lásd még: jdtounix()!

Megjegyzés: Ez a függvény csak a PHP 4RC1 verzió óta használható.

cal_from_jd

(PHP 4 >= 4.1.0)

cal_from_jd -- Julián naptárból egy támogatott naptártípusba konvertál és további információkat szolgáltat

Leírás

array cal_from_jd ( int jd, int calendar)

cal_info

(PHP 4 >= 4.1.0)

cal_info -- Különleges naptártípusokról ad információt

Leírás

array cal_info ( int calendar)

cal_to_jd

(PHP 4 >= 4.1.0)

cal_to_jd -- Egy támogatott naptártípusból Julián naptárba konvertál

Leírás

int cal_to_jd ( int calendar, int month, int day, int year)

easter_date

(PHP 3>= 3.0.9, PHP 4 )

easter_date --  Kiszámolja egy adott év húsvétjának UNIX időbélyeggel megadott éjféli időpontját

Leírás

int easter_date ( [int évszám])

Visszaadja az adott év húsvét éjfélt meghatározó UNIX időbélyeget (timestamp).

A PHP 4.3.0 változatától kezdődően az évszám paraméter megadása nem kötelező, elhagyása esetén az alapértelmezett évként a rendszeridő szerinti évszám lesz feldolgozva.

Figyelem: A függvény figyelmeztetést generál, ha az év kivül esik az UNIX dátum értelmezési tartományán (1970 előtti vagy 2037 utáni év).

Példa 1. easter_date() példa

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

Húsvét napját a Niceai Zsinat i.sz. 325-ben a tavaszi napéjegyenlőség napjára eső vagy az azutáni első telehold utáni vasárnapban határozta meg. A tavaszi napéjegyenlőséget mindig március 21-re fetételezték, hogy a számítást csökkentsék a telehold és az azt követő vasárnap meghatározására. Az algoritmust kb. 532-ben vezette be Dionyius Exiguus. A Julián naptár szerint (1753 előtti évekre vonatkoztatva) egy egyszerű 19 éves ciklust használtak a hold fázisainak nyomonkövetésére. A Clavius és Lillius által kigondolt, XIII. Gergely pápa által bevezetett és Nagy-Britanniában és gyarmatain 1752 szeptember 22.-én életbe lépett Gergely naptár szerint (1753 utáni évekre vonatkoztatva) két korrekciós tényezőt is belevettek a ciklus még pontosabbá tételéhez.

(A kód Simon Kershaw C programján alapul, <webmaster@ely.anglican.org>)

Lásd az easter_days() függvényt a húsvét kiszámításához 1970 elött és 2037 után.

easter_days

(PHP 3>= 3.0.9, PHP 4 )

easter_days --  Kiszámolja adott évben a március 21-től húsvétig terjedő napok számát

Leírás

int easter_days ( [int évszám [, int számítási_módszer]])

Kiszámolja adott évben a március 21-től húsvétig terjedő napok számát. Ha nem adod meg a year paramétert, az aktuális évet veszi alapul.

A PHP 4.3.0 változatától kezdődően az évszám paraméter megadása nem kötelező, elhagyása esetén az alapértelmezett évként a rendszeridő szerinti évszám lesz feldolgozva.

A számítási_módszer paraméter szintén a PHP 4.3.0 változatával került bevezetésre, és ezáltal lehetőség nyílik arra, hogy az 1582 - 1752 évekre vonatkozó, a Gregorián naptár szerinti számításokat elvégezhessük. Ehhez ebben a második paraméterben kell megadnunk a következő állandó értéket: CAL_EASTER_ROMAN. A további, itt megadható számítási módozatok állandóinak teljes listáját lásd itt : naptárkezeléssel kapcsolatos állandók.

Ez a függvény használható az easter_date() helyett, hogy kiszámolja a UNIX értelmezési tartományon kívülre eső évekre (i.sz. 1970 előtt vagy 2037 után) húsvét napját.

Példa 1. easter_days() példa

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

Húsvét napját a Niceai Zsinat i.sz. 325-ben a tavaszi napéjegyenlőség napjára eső vagy az azutáni első telehold utáni vasárnapban határozta meg. A tavaszi napéjegyenlőséget mindig március 21-re fetételezték, hogy a számítást csökkentsék a telehold és az azt követő vasárnap meghatározására. Az algoritmust kb. 532-ben vezette be Dionyius Exiguus. A Julián naptár szerint (1753 előtti évekre vonatkoztatva) egy egyszerű 19 éves ciklust használtak a hold fázisainak nyomonkövetésére. A Clavius és Lillius által kigondolt, XIII. Gergely pápa által bevezetett és Nagy-Britanniában és gyarmatain 1752 szeptember 22.-én életbe lépett Gergely naptár szerint (1753 utáni évekre vonatkoztatva) két korrekciós tényezőt is belevettek a ciklus még pontosabbá tételéhez.

(A kód Simon Kershaw C programján alapul, <webmaster@ely.anglican.org>)

Lásd még: easter_date()!

FrenchToJD

(PHP 3, PHP 4 )

FrenchToJD --  Francia Köztársasági naptárt konvertál Julián dátumba

Leírás

int frenchtojd ( int month, int day, int year)

Francia köztársasági dátumból konvertál egy dátumot Julián dátumba.

Ezek a műveletek csak az 1-14 év közötti dátumokat számítják át. (Gergely naptár szerint 1792 szeptember 22. - 1806 szeptember 22.). Ez hosszabb intervallum, mint ameddig a naptárt használták.

GregorianToJD

(PHP 3, PHP 4 )

GregorianToJD --  Gergely dátumot konvertál Julián dátumba

Leírás

int gregoriantojd ( int month, int day, int year)

A Gergely dátum értelmezési tartománya i.e. 4714 és i.sz. 9999 között van

Noha ez a szoftver a dátumokat i.e. 4714-ig képes kezelni, ilyen használata nem biztos, hogy értelmes adatot szolgáltat. A Gergely naptár 1582 október 15-től érvényes (vagy a Julián naptár szerint 1582 október 5-től). Néhány ország csak sokkal később fogadta el. Például Nagy-Britannia 1752-ben, a Szovjetúnió 1918-ban, Görögország 1923-ban ban tért át. A legtöbb európai ország a Julián naptárt használta a Gergely naptár előtt.

Példa 1. Naptár függvények

<?php
$jd = GregorianToJD (10,11,1970);
echo "$jd\n";
$gregorian = JDToGregorian ($jd);
echo "$gregorian\n";
?>

JDDayOfWeek

(PHP 3, PHP 4 )

JDDayOfWeek -- Visszaadja a hét egy napjának nevét

Leírás

mixed jddayofweek ( int julianday, int mode)

Visszaadja a hét egy napjának nevét. Sztringet vagy egészt adhat vissza a mode paramétertól függően.

Táblázat 1. Naptár hét módok

modejelentés
0 Visszaad egy egész típusú napsorszámot (0=vasárnap, 1=hétfő. stb.)
1 Visszaadja a napnevet egy sztringben (angol - Gergely naptári)
2 Visszaadja a rövidített napnevet egy sztringben (angol - Gergely naptári)

JDMonthName

(PHP 3, PHP 4 )

JDMonthName -- Visszaadja egy hónap nevét

Leírás

string jdmonthname ( int julianday, int mode)

Visszaadja a hónap nevét tartalmazó sztringet. A mode megadja a függvénynek, hogy milyen dátumtípusba konvertálja a Julián dátumot és milyen típusú hónapneveket adjon vissza.

Táblázat 1. Naptár módok

modejelentésértékek
0Gergely naptár - rövidítettJan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
1Gergely naptárJanuary, February, March, April, May, June, July, August, September, October, November, December
2Julián naptár - rövidítettJan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
3Julián naptárJanuary, February, March, April, May, June, July, August, September, October, November, December
4Zsidó naptárTishri, Heshvan, Kislev, Tevet, Shevat, AdarI, AdarII, Nisan, Iyyar, Sivan, Tammuz, Av, Elul
5Francia KöztársaságiVendemiaire, Brumaire, Frimaire, Nivose, Pluviose, Ventose, Germinal, Floreal, Prairial, Messidor, Thermidor, Fructidor, Extra

JDToFrench

(PHP 3, PHP 4 )

JDToFrench --  Julián dátumot konvertál Francia Köztársasági naptárba

Leírás

string jdtofrench ( int juliandaycount)

Julián dátumot konvertál Francia Köztársasági naptárba.

JDToGregorian

(PHP 3, PHP 4 )

JDToGregorian -- Julián dátumot konvertál Gergely dátumba

Leírás

string jdtogregorian ( int julianday)

Julián dátumot konvertál Gergely dátumot leíró formába ("hónap/nap/év").

JDToJewish

(PHP 3, PHP 4 )

JDToJewish --  Julián dátumot konvertál Zsidó naptárba

Leírás

string jdtojewish ( int julianday)

Julián dátumot konvertál Zsidó naptárba.

JDToJulian

(PHP 3, PHP 4 )

JDToJulian --  Julián dátumot konvertál Julian-féle naptári dátumba

Leírás

string jdtojulian ( int julianday)

Julián dátumot konvertál Julián-féle naptári dátum formátumú sztringbe ("hónap/nap/év").

jdtounix

(PHP 4 )

jdtounix -- Julián dátumot konvertál UNIX időpontba

Leírás

int jdtounix ( int jday)

Ez a függvény egy UNIX időbélyeget ad vissza a megadott jday Julián naphoz, vagy false-al tér vissza, ha a jday nincs a UNIX értelmezési tartományán belül (Gergely naptár szerint 1970 és 2037 között, azaz 2440588 <= jday <= 2465342). Az időbélyeget helyi idő, és nem GMT szerint adja vissza.

Lásd még:unixtojd()!

JewishToJD

(PHP 3, PHP 4 )

JewishToJD --  Zsidó naptárt konvertál Julián dátumba

Leírás

int jewishtojd ( int month, int day, int year)

Éretelmezési tartomány: Noha ez a szoftver a dátumokat i.e. 3761-ig képes kezelni (ez az első év), ilyen használata nem biztos, hogy értelmes adatot szolgáltat.

A zsidó naptárat évezredek óta használják, de korábban nem volt módszer egy hónap kezdetének meghatározására. Az új hónap mindig újholdkor kezdődött.

JulianToJD

(PHP 3, PHP 4 )

JulianToJD --  Julián-féle naptári dátumot konvertál Julián dátumba

Leírás

int juliantojd ( int month, int day, int year)

A Julián dátum értelmezési tartománya i.e. 4713 és i.sz. 9999 között van

Noha ez a szoftver a dátumokat i.e. 4713-ig képes kezelni, ilyen használata nem biztos, hogy értelmes adatot szolgáltat. A Julián naptárt i.e. 46-ban alkották, de teljes egészében csak i.sz. 8-ban vagy csak a IV. században lett bevezetve. Hasonlóan az év kezdete kultúráról kultúrára változott nem mindenhol fogadták el a januárt az első hónapnak.

unixtojd

(PHP 4 )

unixtojd -- UNIX időbélyeget konvertál Julián dátumba

Leírás

int unixtojd ( [int timestamp])

Visszaadja a Unix timestamp-hez (1970 január 1. óta eltelt másodpercek), vagy a mai naphoz tartozó Julián dátumot, ha nincs megadott timestamp paraméter.

Lásd még: jdtounix()!

Megjegyzés: Ez a függvény csak a PHP 4RC1 verzió óta használható.

VII. CCVS függvények

Ezek a függvények a CCVS API használatát teszik lehetővé, amik a CCVS közvetlen használatát biztosítják a PHP szriptek számára. A CCVS a RedHat megoldása a köztes pontra ("middle-man") a bankkártyák feldolgozásában. Ez lehetőséget ad a bankkártyák kiegyenlítési eljárásainak kezelésére egy *nix rendszer és egy modem segítségével. E modul segítéségével közvetlenül kezelheted a bankkártyákat a CCVS rendszer segítségével. Az alább olvasható referencia megmutatja, hogyan.

Ahhoz, hogy bekapcsold a PHP CCVS támogatását, először ellenőrizd a CCVS telepítési könyvtáradat. Utána a PHP fordításakor add meg a configure-nak a --with-ccvs paramétert. Ha a CCVS telepítési könyvtár megadása nélkül használod ezt a paramétert, a PHP az alapbeállítású CCVS elérési utat veszi alapul (/usr/local/ccvs). Ha a CCVS nem a hagyományos könyvtárban található, a --with-ccvs=$ccvs_eleresi_ut megoldást használd, ahol a $ccvs_eleresi_ut a CCVS telepítési könyvtára. Fontos megjegyezni, hogy a CCVS támogatáshoz elengedhetetlen, hogy a $ccvs_eleresi_ut/lib és a $ccvs_eleresi_ut/include létezik, és a cv_api.h magtalálható az include könyvtárban, a libccvs.a pedig a lib könyvtárban.

Ráadásul egy ccvsd a PHP-vel megegyező beállításokkal kell, hogy fusson. Úgyszintén meg kell győződnöd arról is, hogy a PHP processek ugyanazzal a userid-vel futnak, amivel a CCVS-t telepítetted. Ha például a CCVS-t a 'ccvs' user-rel telepítetted, a PHP processek a 'ccvs' felhasználói név alatt kell, hogy fussanak.

A CCVS-ről további információ található a ??? címen.

Ez a dokumentáció még fejlesztések előtt áll. Addig is a Radhat által fenntartott, kicsit aktualitását vesztett, de hasznos dokumentációját tudjuk ajánlani a http://redhat.com/docs/manuals/ccvs/ címen.

A CCVS fejlesztését a Red Hat már nem végzi, és nincsenek tervek a további folytatásra. Azoknak, akik helyettesítő terméket keresnek, a Main Street Softworks MCVE termékét ajánljuk, mint lehetséges helyettesítőt. Hasonló a felépítése, és dokumentált PHP támogatással rendelkezik.

Tartalom
ccvs_add -- Adat hozzáadása tranzakcióhoz
ccvs_auth --  Tranzakció kredit azonosítás ellenőrzése
ccvs_command --  Egy konkrét protokollal végrehajtható parancs futtatása, amit az általános CCVS API nem tud lekezelni
ccvs_count --  Tranzakció típusok szerinti összegzés a tranzakciók számáról
ccvs_delete -- Tranzakció törlése
ccvs_done -- A CCVS motor megállítása, és felaszabadítás
ccvs_init -- CCVS beállítása használatra
ccvs_lookup --  Egy megadott típusú elem megkeresése a megadott számú adatbázisban
ccvs_new -- Új, üres trantakció létrehozása
ccvs_report -- Egy háttérben futó kommunikációs folyamat állapotát adja vissza
ccvs_return --  Átutalás a kereskedőtől a kártyatulajdonos számára
ccvs_reverse --  Kezelt tranzakció teljes visszavonása
ccvs_sale --  Átutalás a kártyatulajdonostól a kereskedőnek
ccvs_status -- Számla állapot ellenőrzése
ccvs_textvalue -- A legutóbbi függvényhívás szöveges visszetérési értéke
ccvs_void --  Befejezett tranzakció teljes visszavonása

ccvs_add

(4.0.2 - 4.2.3 only)

ccvs_add -- Adat hozzáadása tranzakcióhoz

Leírás

string ccvs_add ( string session, string invoice, string argtype, string argval)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ccvs_auth

(4.0.2 - 4.2.3 only)

ccvs_auth --  Tranzakció kredit azonosítás ellenőrzése

Leírás

string ccvs_auth ( string session, string invoice)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ccvs_command

(4.0.2 - 4.2.3 only)

ccvs_command --  Egy konkrét protokollal végrehajtható parancs futtatása, amit az általános CCVS API nem tud lekezelni

Leírás

string ccvs_command ( string session, string type, string argval)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ccvs_count

(4.0.2 - 4.2.3 only)

ccvs_count --  Tranzakció típusok szerinti összegzés a tranzakciók számáról

Leírás

int ccvs_count ( string session, string type)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ccvs_delete

(4.0.2 - 4.2.3 only)

ccvs_delete -- Tranzakció törlése

Leírás

string ccvs_delete ( string session, string invoice)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ccvs_done

(4.0.2 - 4.2.3 only)

ccvs_done -- A CCVS motor megállítása, és felaszabadítás

Leírás

string ccvs_done ( string sess)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ccvs_init

(4.0.2 - 4.2.3 only)

ccvs_init -- CCVS beállítása használatra

Leírás

string ccvs_init ( string name)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ccvs_lookup

(4.0.2 - 4.2.3 only)

ccvs_lookup --  Egy megadott típusú elem megkeresése a megadott számú adatbázisban

Leírás

string ccvs_lookup ( string session, string invoice, int inum)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ccvs_new

(4.0.2 - 4.2.3 only)

ccvs_new -- Új, üres trantakció létrehozása

Leírás

string ccvs_new ( string session, string invoice)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ccvs_report

(4.0.2 - 4.2.3 only)

ccvs_report -- Egy háttérben futó kommunikációs folyamat állapotát adja vissza

Leírás

string ccvs_report ( string session, string type)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ccvs_return

(4.0.2 - 4.2.3 only)

ccvs_return --  Átutalás a kereskedőtől a kártyatulajdonos számára

Leírás

string ccvs_return ( string session, string invoice)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ccvs_reverse

(4.0.2 - 4.2.3 only)

ccvs_reverse --  Kezelt tranzakció teljes visszavonása

Leírás

string ccvs_reverse ( string session, string invoice)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ccvs_sale

(4.0.2 - 4.2.3 only)

ccvs_sale --  Átutalás a kártyatulajdonostól a kereskedőnek

Leírás

string ccvs_sale ( string session, string invoice)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ccvs_status

(4.0.2 - 4.2.3 only)

ccvs_status -- Számla állapot ellenőrzése

Leírás

string ccvs_status ( string session, string invoice)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ccvs_textvalue

(4.0.2 - 4.2.3 only)

ccvs_textvalue -- A legutóbbi függvényhívás szöveges visszetérési értéke

Leírás

string ccvs_textvalue ( string session)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ccvs_void

(4.0.2 - 4.2.3 only)

ccvs_void --  Befejezett tranzakció teljes visszavonása

Leírás

string ccvs_void ( string session, string invoice)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

VIII. COM támogató függvények Windowshoz

Ezek a függvények csak Windows alatt érhetőek el, a PHP 4-es verziójában kerültek bevezetésre.

Tartalom
COM -- COM class
VARIANT -- VARIANT class
com_addref --  Increases the components reference counter.
com_get -- COM komponenes egy tulajdonságának értékét adja vissza
com_invoke -- Egy COM komponens egy metódusát hívja
com_isenum -- Grabs an IEnumVariant
com_load_typelib -- Loads a Typelib
com_load -- Létrehoz egy új referenciát egy COM komponensre
com_propget -- COM komponenes egy tulajdonságának értékét adja vissza
com_propput -- Értéket ad COM komponenes egy tulajdonságának
com_propset -- Értéket ad COM komponenes egy tulajdonságának
com_release --  Decreases the components reference counter.
com_set -- Értéket ad COM komponenes egy tulajdonságának

COM

(no version information, might be only in CVS)

COM -- COM class

Áttekintés

$obj = new COM("server.object")

Description

The COM class provides a framework to integrate (D)COM components into your PHP scripts.

Methods

string COM::COM ( string module_name [, string server_name [, int codepage]])

COM class constructor. Parameters:

module_name

name or class-id of the requested component.

server_name

name of the DCOM server from which the component should be fetched. If NULL, localhost is assumed. To allow DCOM com.allow_dcom has to be set to TRUE in php.ini.

codepage

specifies the codepage that is used to convert php-strings to unicode-strings and vice versa. Possible values are CP_ACP, CP_MACCP, CP_OEMCP, CP_SYMBOL, CP_THREAD_ACP, CP_UTF7 and CP_UTF8.

Példa 1. COM example (1)

<?php
// starting word
$word = new COM("word.application") or die("Unable to instanciate 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->Release();
$word = null;
?>

Példa 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->Release();
$conn->Release();

$rs = null;
$conn = null;

?>

VARIANT

(no version information, might be only in CVS)

VARIANT -- VARIANT class

Áttekintés

$vVar = new VARIANT($var)

Description

A simple container to wrap variables into VARIANT structures.

Methods

string VARIANT::VARIANT ( [mixed value [, int type [, int codepage]]])

VARIANT class constructor. Parameters:

value

initial value. if omitted an VT_EMPTY object is created.

type

specifies the content type of the VARIANT object. Possible values are VT_UI1, VT_UI2, VT_UI4, VT_I1, VT_I2, VT_I4, VT_R4, VT_R8, VT_INT, VT_UINT, VT_BOOL, VT_ERROR, VT_CY, VT_DATE, VT_BSTR, VT_DECIMAL, VT_UNKNOWN, VT_DISPATCH and VT_VARIANT. These values are mutual exclusive, but they can be combined with VT_BYREF to specify being a value. If omitted, the type of value is used. Consult the MSDN library for additional information.

codepage

specifies the codepage that is used to convert php-strings to unicode-strings and vice versa. Possible values are CP_ACP, CP_MACCP, CP_OEMCP, CP_SYMBOL, CP_THREAD_ACP, CP_UTF7 and CP_UTF8.

com_addref

(4.1.0 - 4.3.2 only)

com_addref --  Increases the components reference counter.

Description

void com_addref ( void )

Increases the components reference counter.

com_get

(PHP 3>= 3.0.3, 4.0.5 - 4.3.2 only)

com_get -- COM komponenes egy tulajdonságának értékét adja vissza

Leírás

mixed com_get ( resource com_object, string property)

Visszaadja a property értékét a com_object-el megadott COM komponensből. FALSE értékkel tér vissza hiba esetén.

com_invoke

(PHP 3>= 3.0.3)

com_invoke -- Egy COM komponens egy metódusát hívja

Leírás

mixed com_invoke ( resource com_object, string function_name [, mixed function parameters, ...])

A com_invoke() a com_object által mutatott COM komponens megadott metódusát hívja meg. A function_name függvény visszatérési értékét adja sikeres futásnál, FALSE értékkel tér vissza hiba esetén.

com_isenum

(4.1.0 - 4.3.2 only)

com_isenum -- Grabs an IEnumVariant

Description

void com_isenum ( object com_module)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

com_load_typelib

(4.1.0 - 4.3.2 only)

com_load_typelib -- Loads a Typelib

Description

void com_load_typelib ( string typelib_name [, int case_insensitive])

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

com_load

(PHP 3>= 3.0.3)

com_load -- Létrehoz egy új referenciát egy COM komponensre

Leírás

string com_load ( string module name [, string server name])

A com_load() egy új COM komponenst hoz létre, egy erre hivatkozó referenciát ad vissza. FALSE értékkel tér vissza hiba esetén.

com_propget

(PHP 3>= 3.0.3, 4.0.5 - 4.3.2 only)

com_propget -- COM komponenes egy tulajdonságának értékét adja vissza

Leírás

mixed com_propget ( resource com_object, string property)

Ez egy alternatív név (alias) a com_get() függvényre.

com_propput

(PHP 3>= 3.0.3, 4.0.5 - 4.3.2 only)

com_propput -- Értéket ad COM komponenes egy tulajdonságának

Leírás

void com_propput ( resource object, string property, mixed value)

Ez egy alternatív név (alias) a com_set() függvényre.

com_propset

(PHP 3>= 3.0.3, 4.0.5 - 4.3.2 only)

com_propset -- Értéket ad COM komponenes egy tulajdonságának

Leírás

void com_propset ( resource object, string property, mixed value)

Ez egy alternatív név (alias) a com_set() függvényre.

com_release

(4.1.0 - 4.3.2 only)

com_release --  Decreases the components reference counter.

Description

void com_release ( void )

Decreases the components reference counter.

com_set

(PHP 3>= 3.0.3, 4.0.5 - 4.3.2 only)

com_set -- Értéket ad COM komponenes egy tulajdonságának

Leírás

void com_set ( resource com_object, string property, mixed value)

Beállítja a com_object COM komponenes property tulajdonságának értékét. TRUE értékkel tér vissza siker esetén, FLASE értékkel, ha hiba történt.

IX. Osztály/Objektum függvények

Bevezetés

A függvényekről

Ezek a függvények PHP osztályokról és objektumpéldányokról adnak információkat, mint például: az objektum osztályának nevét (típusát), a tagváltozóit másnéven tulajdonságait, és metódusait is. Ezekkel a függvényekkel egy objektumnak nem csak az osztály-tagságát lehet megállapítani, hanem a származását is, azaz, melyik osztályt kiterjesztése az adott objektum osztály.


Egy használati példa

Ebben a példában definiálunk egy alap osztályt, és ennek egy kiterjesztését. Az alap osztály leír egy zöldséget (Zoldseg), meghatározva, hogy ehető-e vagy sem (eheto), és hogy milyen színű. Az alosztály a paraj (Paraj) hozzáad egy új metódust, hogy megfőzhesd, és egy másikat, hogy megállapítsd, hogy főtt-e.

Példa 1. classes.inc

<?php
// alap osztály tulajdonságokkal és metódusokkal
class Zoldseg {

  var $eheto;
  var $szin;

  function Zoldseg ( $eheto, $szin="zöld" ) {
    $this->eheto = $eheto;
    $this->szin = $szin;
  }

  function eheto_e() {
    return $this->eheto;
  }

  function milyen_szinu() {
    return $this->szin;
  }
  
} // vége a Zoldseg osztálynak

// kiterjesztjük az alap osztályt
class Paraj extends Zoldseg {

  var $megfozve = false;

  function Paraj() {
    $this->Zoldseg ( true, "zöld" );
  }

  function fozes() {
    $this->megfozve = true;
  }

  function fott_e() {
    return $this->megfozve;
  }
  
} // vége a Paraj osztéynak

?>

Most két példányt létrehozunk a fenti osztályokból, és információkat írunk ki rólunk, beleértve az származásukat is. Definiálunk néhány hasznos függvényt, főleg azért, hogy ezeket az információkat szépen írjuk ki.

Példa 2. test_script.php

<pre>
<?php

include "classes.inc";

// hasznos függvények

function valtozok_kiirasa($obj) {
  $tomb = get_object_vars($obj);
  while (list($tul, $ertek) = each($tomb))
    echo "\t$tul = $ertek\n";
}

function metodusok_kiirasa($obj) {
  $tomb = get_class_methods(get_class($obj));
  foreach ($tomb as $metodus)
    echo "\tfunction $metodus()\n";
}

function os_osztaly($obj, $osztaly) {
  global $$obj;
  if (is_subclass_of($$obj, $osztaly)) {
    echo "A $obj a " . get_class($$obj) . " osztályhoz tartozik, ";
    echo "ami a $class egy alosztálya.\n";
  } else {
    echo "A $obj nem tartozik $class egy alosztályához.\n";
  }
}

// két objektumpéldány létrehozása

$karalabe  = new Zoldseg(true,"kék");
$soklevelu = new Paraj();

// objektuminformációk kiírása
echo "karalabe: CLASS " . get_class($karalabe) . "\n";
echo "soklevelu: CLASS " . get_class($soklevelu);
echo " PARENT " . get_parent_class($soklevelu) . "\n";

// a karalábé tulajdonságai
echo "\nkaralabe: Tulajdonságok\n";
valtozok_kiirasa($karalabe);

// a soklevelű paraj metódusai
echo "\nsoklevelu: Metódusok\n";
metodusok_kiirasa($soklevelu);

echo "\nSzülők:\n";
os_osztaly("soklevelu", "Paraj");
os_osztaly("soklevelu", "Zoldseg");
?>
</pre>

Fontos észrevenni, hogy a fenti példában a $soklevelu a Paraj objektum egy példánya, amely a Zoldseg egy alosztálya objektumnak, ezért a programunk utolsó része a következőt írja ki (szerencsére nincs probléma a névelőkkel :)

[...]
Szülők:
A soklevelu nem tartozik Paraj egy alosztályához.
A soklevelu a paraj osztályhoz tartozik, ami a Zoldseg egy alosztálya.

Tartalom
call_user_method_array --  meghívja az adott objektum egy metódusát paramétertömbbel [ellenjavallt]
call_user_method --  Egy megadott objektumon belül meghív egy függvényt [ellenjavallt]
class_exists -- megvizsgálja, hogy definiált-e az osztály
get_class_methods -- Osztálymetódusnevek tömbjével tér vissza.
get_class_vars --  visszaadja az osztály alaptulajdonságait egy tömbben
get_class -- visszaadja egy objektum osztályának a nevét
get_declared_classes -- visszaadja a jelenlegi szkriptben definiált osztályok neveit
get_object_vars -- Objektumtulajdonságok asszociatív tömbjével tér vissza
get_parent_class -- visszaadja egy objektum vagy osztály szülő osztályát
is_a --  megvizsgálja, hogy az objektum leszármazottja vagy tagja-e egy osztálynak
is_subclass_of --  megviszgálja, hogy egy objektum egy megadott osztálynak egy alosztályához tartozik-e
method_exists -- ellenőrzi az osztálymetódus létezését

call_user_method_array

(PHP 4 >= 4.0.5)

call_user_method_array --  meghívja az adott objektum egy metódusát paramétertömbbel [ellenjavallt]

Leírás

mixed call_user_method_array ( string method_name, object obj [, array paramarr])

Figyelem

A call_user_method_array() függvény PHP 4.1.0-től kezdve ellenjavallt. Helyette a call_user_func_array() függvényt kell használni a függvénynév paraméterében az array(&$obj, "method_name") szintaxissal.

Meghívja a felhasználó által definiált obj objektum method_name paraméterben megnevezett metódusát. A metóusnak átadandó paramétereket a paramarr tömbből tölti fel sorjában.

Lásd még: call_user_func_array(), call_user_func() és call_user_method()!

Megjegyzés: Ez a függvény a PHP 4.0.4pl1 kiadása után került a CVS-be.

call_user_method

(PHP 3>= 3.0.3, PHP 4 )

call_user_method --  Egy megadott objektumon belül meghív egy függvényt [ellenjavallt]

Leírás

mixed call_user_method ( string method_name, object obj [, mixed parameter [, mixed ...]])

Figyelem

A call_user_method() függvény PHP 4.1.0-től kezdve ellenjavallt. Helyette a call_user_func() függvényt kell használni a függvénynév paraméterében az array(&$obj, "method_name") szintaxissal.

Meghívja a felhasználó által definiált obj objektum method_name paraméterben megnevezett metódusát. Az alábbi felhasználási példában definiálunk egy osztályt, létrehozunk egy objektumpéldányt, és a call_user_method() függvényt használjuk arra, hogy indirekten meghívjuk az objektum print_info metódusát.

<?php
class Orszag {
  var $NEV;
  var $TLD;
  
  function Orszag($nev, $tld) {
    $this->NEV = $nev;
    $this->TLD = $tld;
  }

  function print_info($prestr="") {
    echo $prestr."Ország: ".$this->NEV."\n";
    echo $prestr."Top Level Domain: ".$this->TLD."\n";
  }
}

$orsz = new Orszag("Peru","pe");

echo "* Az objektum metódusának közvetlen hívása\n";
$orsz->print_info();

echo "\n* Ugyanannak a közvetett meghívása\n";
call_user_method ("print_info", $orsz, "\t");
?>

Lásd még: call_user_func()!

class_exists

(PHP 4 )

class_exists -- megvizsgálja, hogy definiált-e az osztály

Leírás

bool class_exists ( string class_name)

Ez a függvény TRUE-val tér vissza, ha a class_name osztály definiálva van, máskülönben FALSE-szal.

get_class_methods

(PHP 4 )

get_class_methods -- Osztálymetódusnevek tömbjével tér vissza.

Leírás

array get_class_methods ( mixed class_name)

Ez a függvény a class_name által megadott osztály metódusainak nevei adja vissza egy tömbben.

Megjegyzés: PHP 4.0.6-tól kezdve, class_name osztálynév helyett közvetlenül az objektumot is át lehet adni paraméterként, például:

$metodusok = get_class_methods($en_objektumom); // lásd lent a teljes példát!

Példa 1. get_class_methods() példa

<?php

class en_osztalyom {
    // konstruktor
    function en_osztalyom() {
        return(TRUE);
    }

    // 1. metódus
    function en_methodusom1() {
        return(TRUE);
    }

    // 2. metódus
    function en_methodusom2() {
        return(TRUE);
    }
}

$en_objektumom  = new en_osztalyom();

$methodus_nevek = get_class_methods(get_class($en_objektumom));

foreach ($metodus_nevek as $metodus_nev) {
    echo "$metodus_nev\n";
}

?>

A fenti példa a következőt írja ki:

en_osztalyom
en_methodusom1
en_methodusom2

Lásd még: get_class_vars() és get_object_vars()!

get_class_vars

(PHP 4 )

get_class_vars --  visszaadja az osztály alaptulajdonságait egy tömbben

Leírás

array get_class_vars ( string class_name)

Ez a függvény az osztály alaptulajdonságainak tömbjével tér vissza.

Megjegyzés: Inicializálatlan - kezdő érték nélküli - alaptulajdonságokat (tagváltozókat) nem ad vissza a get_class_vars().

Példa 1. get_class_vars() példa

<?php

class en_osztalyom {

    var $var1; // ennek nincs kezdő értéke...
    var $var2 = "xyz";
    var $var3 = 100;
    
    // konstruktor
    function en_osztalyom() {
        return(TRUE);
    }

}

$en_objektumom      = new en_osztalyom();

$alap_tulajdonsagok = get_class_vars(get_class($en_objektumom));

foreach ( $alap_tulajdonsagok as $nev => $ertek ) {
    echo "$nev : $ertek\n";
}

?>

A fenti példa a következőt írja ki:

var2 : xyz
var3 : 100

Lásd még: get_class_methods() és get_object_vars()!

get_class

(PHP 4 )

get_class -- visszaadja egy objektum osztályának a nevét

Leírás

string get_class ( object obj)

Ez a függvény visszaadja annak az osztálynak a nevét, amelynek az obj objektum egy példánya.

Megjegyzés: get_class() a felhasználó által definiált osztályok neveit mindig csupa kisbetűsként adja vissza, míg a kiterjesztésekben definiáltakat az eredeti elnevezésők szerint.

Lásd még: get_parent_class(), gettype() és is_subclass_of()!

get_declared_classes

(PHP 4 )

get_declared_classes -- visszaadja a jelenlegi szkriptben definiált osztályok neveit

Leírás

array get_declared_classes ( void )

Ez a függvény az aktuális szkriptben definiált osztályok neveit adja vissza egy tömbben.

Megjegyzés: A PHP 4.0.1pl2-ben, három extra osztályt ad vissza a függvény a tömb elején stdClass (ami a Zend/zend.c-ben definiált), OverloadedTestClass (ami az ext/standard/basic_functions.c-ben definiált) és Directory (ami az ext/standard/dir.c-ben definiált).

Attól függően, hogy milyen kiterjesztések vannak betöltve, egyéb osztályok is megjelenhetnek a listában. Ez azt jelenti, hogy saját osztályokat ilyen nevekkel már nem lehet definiálni. A függelékben vannak felsorolva az előre definiált osztályok hasonló című fejezetben.

get_object_vars

(PHP 4 )

get_object_vars -- Objektumtulajdonságok asszociatív tömbjével tér vissza

Leírás

array get_object_vars ( object obj)

Ez a függvény az obj paraméterben átadott objektumban definiált tulajdonságokat (tagváltozókat) és értékeiket adja vissza egy asszociatív tömbben. Az obj típusát jelentő osztályban deklarált, de kezdőérték nélküli tagváltozókat nem adja vissza a függvény.

Példa 1. get_object_vars() használata

<?php
class Pont2D {
    var $x, $y;
    var $cimke;

    function Pont2D($x, $y) {
        $this->x = $x;
        $this->y = $y;
    }

    function Cimkez($cimke) {
        $this->cimke = $cimke;
    }

    function holaPont() {
        return array("x" => $this->x,
                     "y" => $this->y,
                     "cimke" => $this->cimke);
    }
}

// $cimke deklarálva van, de nincs érték hozzárendelve
$p1 = new Pont2D(1.233, 3.445);
print_r(get_object_vars($p1));

$p1->Cimkez("pont #1");
print_r(get_object_vars($p1));

?>
A fenti program a következőt írja ki:
Array
 (
     [x] => 1.233
     [y] => 3.445
 )

 Array
 (
     [x] => 1.233
     [y] => 3.445
     [cimke] => pont #1
 )

Lásd még: get_class_methods() és get_class_vars()!

get_parent_class

(PHP 4 )

get_parent_class -- visszaadja egy objektum vagy osztály szülő osztályát

Leírás

string get_parent_class ( mixed obj)

Ha obj objektum típusú, akkor visszaadja az obj példány "típusát" jelentő osztály szülőosztályának nevét.

Ha obj sztring típusú, akkor visszaadja az ilyen nevű osztály szülőosztályának nevét. Ez PHP 4.0.5-től kezdve használható.

Lásd még: get_class() és is_subclass_of()!

is_a

(PHP 4 >= 4.2.0)

is_a --  megvizsgálja, hogy az objektum leszármazottja vagy tagja-e egy osztálynak

Leírás

bool is_a ( object object, string class_name)

Ez a függvény TRUE-t ad vissza, ha az object a class_name osztály vagy annak egy leszármazott osztályának példánya, egyébként FALSE-t ad vissza.

Lásd még: get_class(), get_parent_class() és is_subclass_of()!

is_subclass_of

(PHP 4 )

is_subclass_of --  megviszgálja, hogy egy objektum egy megadott osztálynak egy alosztályához tartozik-e

Leírás

bool is_subclass_of ( object obj, string class_name)

Ez a függvény TRUE-val tér vissza, ha az obj objektum olyan osztálynak egy példánya, amely alosztálya/leszármazottja a class_name nevű osztálynak. Másik esetben FALSE-t ad vissza.

Lásd még: get_class() és get_parent_class()!

method_exists

(PHP 4 )

method_exists -- ellenőrzi az osztálymetódus létezését

Leírás

bool method_exists ( object object, string method_name)

Ez a függvény TRUE-val tér vissza, ha a method_name nevű metódus definiálva van az adott object objektumhoz, különben FALSE-szal.

X. ClibPDF függvények

A ClibPDF segítségével PDF dokumentumokat lehet létrehozni PHP-vel. Ez elérhető a FastIO-nál, de nem szabad használatú (free) szoftver. Mielőtt dolgozni kezdesz a ClibPDF-fel tanácsos elolvasnod a licence-t. Ha nem fogadod el, használhatod Thomas Merz pdflib-jét, amelyik szintén kiválóan alkalmazható. A ClibPDF és az API hasonló Thomas Merz pdflib-jéhez de a FastIO-nak köszönhetően a ClibPDF gyorsabb, és ráadásul kisebb dokumentumokat állít elő. Ez valószinűleg változni fog a pdflib 2.0 verziójában. Egy egyszerű benchmark (a pdflib 2.0-ből php-ba fordított a pdfclock.c példa) nem mutat különbséget a sebességben. A fájlméret is hasonló, ha kikapcsoljuk a tömörítést. Tehát próbáld ki mindkettőt és nézd meg melyik jobb neked.

Ezt a dokumentációt ajánlatos a ClibPDF kézikönyvvel együtt olvasni mivel az a függvényeket nagyobb részletességgel magyarázza.

Sok függvény az alap ClibPDF-ben, a PHP modulban, valamint a pdflib-ben a ugyanazzal a névvel rendelkezik. Az összes függvény, kivéve a cpdf_open() első paramétereként a dokumentum kezelőjét (handler) kéri. Jelenleg ez a kezelőt a PHP belsőleg nem használja, mivel a ClibPDF nem támogatja több PDF dokumentum egyidejű létrehjozását. Ezt most ne is próbáld ki, mert az eredményt nem lehet előre megjósolni. Nem tudhatom, hogy a többszálas környezetben ez milyen következnényekkel járna. A ClibPDF szerzője szerint ez változni fog a következő változatnál (az írás idején a jelenlegi verzió az 1.10). Ha mégis szükséged van erre a lehetőségre, használd a pdflib modult.

Megjegyzés: A cpdf_set_font() függvény megváltozott a PHP 3 óta, hogy támogassa az ázsiai betűkészleteket. Az encoding paraméter már nem egy integer, hanem egy string!

A pdflib-el szemben van egy nagy előnye a ClibPDF-nek. PDF doumentumokat tud létrehozni a memóriában ideiglenes fájlok használata nélkül. Lehetőséget ad továbbá arra, hogy koordinátákat adj át egy előre definiált mértékegységben. Ez egy nagyon jó lehetőség de szimulálható a pdf_translate()-el.

A legtöbb függvény egyszerűen használható. A legnehezebb rész valószínűleg egy nagyon egyszerű PDF létrehozása. A következő példa segíthet az elindulásban. Ez egy egy oldalas dokumentumot készít. Az oldal tartalmazza a "Times-Roman" szöveget egy 30 pont méretű körvonalas betűtípusssal. A szöveg aláhúzott.

Példa 1. Egyszerű ClibPDF példa

<?php
$cpdf = cpdf_open(0);
cpdf_page_init($cpdf, 1, 0, 595, 842);
cpdf_add_outline($cpdf, 0, 0, 0, 1, "Page 1");
cpdf_set_font($cpdf, "Times-Roman", 30, "WinAnsiEncoding");
cpdf_set_text_rendering($cpdf, 1);
cpdf_text($cpdf, "Times Roman outlined", 50, 750);
cpdf_moveto($cpdf, 50, 740);
cpdf_lineto($cpdf, 330, 740);
cpdf_stroke($cpdf);
cpdf_finalize($cpdf);
Header("Content-type: application/pdf");
cpdf_output_buffer($cpdf);
cpdf_close($cpdf);
?>

A pdflib csomag egy összetettebb példát tartalmaz, amely egy oldalsorozatot állít elő egy analóg órával. Ez itt a ClibPDF kiterjesztést használó PHP-be konvertált változat:

Példa 2. pdfclock példa a pdflib 2.0 csomagból

<?php
$radius = 200;
$margin = 20;
$pagecount = 40;

$pdf = cpdf_open(0);
cpdf_set_creator($pdf, "pdf_clock.php3");
cpdf_set_title($pdf, "Analog Clock");
  
while($pagecount-- > 0) {
  cpdf_page_init($pdf, $pagecount+1, 0, 2 * ($radius + $margin), 2 * ($radius + $margin), 1.0);
  
  cpdf_set_page_animation($pdf, 4, 0.5, 0, 0, 0);  /* wipe */
  
  cpdf_translate($pdf, $radius + $margin, $radius + $margin);
  cpdf_save($pdf);
  cpdf_setrgbcolor($pdf, 0.0, 0.0, 1.0);
  
  /* minute strokes */
  cpdf_setlinewidth($pdf, 2.0);
  for ($alpha = 0; $alpha < 360; $alpha += 6)
    {
    cpdf_rotate($pdf, 6.0);
    cpdf_moveto($pdf, $radius, 0.0);
    cpdf_lineto($pdf, $radius-$margin/3, 0.0);
    cpdf_stroke($pdf);
    }
  
  cpdf_restore($pdf);
  cpdf_save($pdf);
 
  /* 5 minute strokes */
  cpdf_setlinewidth($pdf, 3.0);
  for ($alpha = 0; $alpha < 360; $alpha += 30)
  {
    cpdf_rotate($pdf, 30.0);
    cpdf_moveto($pdf, $radius, 0.0);
    cpdf_lineto($pdf, $radius-$margin, 0.0);
    cpdf_stroke($pdf);
  }

  $ltime = getdate();

  /* draw hour hand */
  cpdf_save($pdf);
  cpdf_rotate($pdf, -(($ltime['minutes']/60.0) + $ltime['hours'] - 3.0) * 30.0);
  cpdf_moveto($pdf, -$radius/10, -$radius/20);
  cpdf_lineto($pdf, $radius/2, 0.0);
  cpdf_lineto($pdf, -$radius/10, $radius/20);
  cpdf_closepath($pdf);
  cpdf_fill($pdf);
  cpdf_restore($pdf);

  /* draw minute hand */
  cpdf_save($pdf);
  cpdf_rotate($pdf, -(($ltime['seconds']/60.0) + $ltime['minutes'] - 15.0) * 6.0);
  cpdf_moveto($pdf, -$radius/10, -$radius/20);
  cpdf_lineto($pdf, $radius * 0.8, 0.0);
  cpdf_lineto($pdf, -$radius/10, $radius/20);
  cpdf_closepath($pdf);
  cpdf_fill($pdf);
  cpdf_restore($pdf);

  /* draw second hand */
  cpdf_setrgbcolor($pdf, 1.0, 0.0, 0.0);
  cpdf_setlinewidth($pdf, 2);
  cpdf_save($pdf);
  cpdf_rotate($pdf, -(($ltime['seconds'] - 15.0) * 6.0));
  cpdf_moveto($pdf, -$radius/5, 0.0);
  cpdf_lineto($pdf, $radius, 0.0);
  cpdf_stroke($pdf);
  cpdf_restore($pdf);

  /* draw little circle at center */
  cpdf_circle($pdf, 0, 0, $radius/30);
  cpdf_fill($pdf);

  cpdf_restore($pdf);

  cpdf_finalize_page($pdf, $pagecount+1);
}

cpdf_finalize($pdf);
Header("Content-type: application/pdf");
cpdf_output_buffer($pdf);
cpdf_close($pdf);
?>
Tartalom
cpdf_add_annotation -- Megjegyzés hozzáfűzése
cpdf_add_outline -- Könyvjelzőt helyez el az aktuális oldalon
cpdf_arc -- Ívet rajzol
cpdf_begin_text -- Szöveg szekciót kezd el
cpdf_circle -- Kört rajzol
cpdf_clip -- Kivágja az aktuális alakzatot
cpdf_close -- Bezárja a pdf dokumentumot
cpdf_closepath_fill_stroke -- Bezárja, kitölti és körvonalazza az aktuális alakzatot
cpdf_closepath_stroke -- Bezárja az alakzatot és körvonalat rajzol az alakzat mentén
cpdf_closepath -- Befejez egy alakzatot
cpdf_continue_text -- Szöveget helyez a következő sorba
cpdf_curveto -- Görbét rajzol
cpdf_end_text -- Befejezi a szöveg szekciót
cpdf_fill_stroke -- Kitölti és körvonalazza az aktuális alakzatot
cpdf_fill -- Kitölti az aktuális alakzatot
cpdf_finalize_page -- Befejezi az oldalt
cpdf_finalize -- Befejezi a dokumentumot
cpdf_global_set_document_limits -- A pdf dokumentumra vonatkozó korlátozások beállítására szolgál
cpdf_import_jpeg -- Megnyit egy JPEG képet
cpdf_lineto -- Egyenest rajzol
cpdf_moveto -- Beállítja az aktuális pontot
cpdf_newpath --  Új alakzatot kezd
cpdf_open -- Megnyit egy új pdf dokumentumot
cpdf_output_buffer -- A memóriapufferből kiiratja a pdf dokumentumot
cpdf_page_init -- Új oldalt kezd
cpdf_place_inline_image -- Képet helyez el az oldalon
cpdf_rect -- Téglalapot rajzol
cpdf_restore -- Visszaállítja a korábban elmentett környezetet
cpdf_rlineto -- Egyenest rajzol
cpdf_rmoveto -- Beállítja az aktuális pontot
cpdf_rotate_text --  Sets text rotation angle
cpdf_rotate -- Beállítja a forgatást
cpdf_save_to_file -- A pdf dokumentumot fájlba írja
cpdf_save -- Elmenti az aktuális környezetet
cpdf_scale -- Beállítja a méretezést
cpdf_set_action_url --  Sets hyperlink
cpdf_set_char_spacing -- Beállítja a betűtávolságot
cpdf_set_creator -- A pdf dokumentumban a létrehozó(creator) mezőt állítja
cpdf_set_current_page -- Beállítja az aktuális oldalt
cpdf_set_font_directories --  Sets directories to search when using external fonts
cpdf_set_font_map_file --  Sets fontname to filename translation map when using external fonts
cpdf_set_font -- Kiválaszja az aktuális betűtípust és méretet
cpdf_set_horiz_scaling -- Beállítja a szöveg vízszintes méretezését
cpdf_set_keywords -- Beállítja a pdf dokumentum kulcsszavak mezőjét
cpdf_set_leading -- Beállítja a szöveg sortávolságát
cpdf_set_page_animation -- Beállítja az oldalak közti átmeneti időtartamot
cpdf_set_subject -- Beállítja a pdf dokumentum tárgy mezőjét
cpdf_set_text_matrix -- Beállítja a szövegmátrixot
cpdf_set_text_pos -- Beállítja a szövegpozíciót
cpdf_set_text_rendering -- Meghatározza hogyan legyen a szöveg kirajzolva
cpdf_set_text_rise -- Beállítja a szöveg emelkedését
cpdf_set_title -- A pdf dokumentumban a cím(title) mezőt állítja
cpdf_set_viewer_preferences --  How to show the document in the viewer
cpdf_set_word_spacing -- Beállítja a szótávolságot
cpdf_setdash -- Beállítja a szaggatott vonalmintát
cpdf_setflat -- Beállítja a simaságot
cpdf_setgray_fill -- Szürke értékre állítja a kitöltő színt
cpdf_setgray_stroke -- Szürke értékre állítja a körvonalrajzoló színt
cpdf_setgray -- Szürke értékre állítja a rajzoló és kitöltő színt
cpdf_setlinecap -- Beállítja a vonalcsúcs paramétert
cpdf_setlinejoin -- Beállítja a vonalak kapcsolódási módját
cpdf_setlinewidth -- Beállítja a vonalvastagságot
cpdf_setmiterlimit -- Beállítja a hegyesszög határát
cpdf_setrgbcolor_fill -- Rgb színértékre állítja be a kitöltő színt
cpdf_setrgbcolor_stroke -- Rgb színértékre állítja be a körvonalrajzoló színt
cpdf_setrgbcolor -- Rgb színértékre állítja be a körvonalrajzoló és kitöltő színt
cpdf_show_xy -- Szöveget helyez adott pozícióba
cpdf_show -- Szöveget helyez az aktuális pozícióba
cpdf_stringwidth -- Visszaadja a szöveg szélességét az aktuális font alapján
cpdf_stroke -- Körvonalat rajzol egy alakzat mentén
cpdf_text -- Szöveget helyez el paraméterekkel
cpdf_translate -- Beállítja a koordinátarendszer kezdőpontját

cpdf_add_annotation

(PHP 3>= 3.0.12, PHP 4 )

cpdf_add_annotation -- Megjegyzés hozzáfűzése

Leírás

void cpdf_add_annotation ( int pdf document, double llx, double lly, double urx, double ury, string title, string content, int mode)

A cpdf_add_annotation() függvény egy megjegyzést helyez el a bal alsó sarkával az (llx, lly) koordinátájú pontban és jobb felső sarkával az (urx, ury) pontban.

Az utolsó elhagyható paraméter megadja a hosszúsági egységet. Ha ez 0 vagy el van hagyva, az alapértelmezett érték az oldal számára meghatározott érték. Egyébként a koordinátákat postcript pontok szerint veszi figyelembe.

cpdf_add_outline

(PHP 3>= 3.0.9, PHP 4 )

cpdf_add_outline -- Könyvjelzőt helyez el az aktuális oldalon

Leírás

void cpdf_add_outline ( int pdf document, string text)

A cpdf_add_outline() függvény a text szöveggel egy könyvjelzőt helyez el, amely az aktuális oldalra mutat.

Példa 1. Oldalvázlat hozzáadása

<?php
$cpdf = cpdf_open(0);
cpdf_page_init($cpdf, 1, 0, 595, 842);
cpdf_add_outline($cpdf, 0, 0, 0, 1, "1. oldal");
// ...
// némi rajzolás
// ...
cpdf_finalize($cpdf);
Header("Content-type: application/pdf");
cpdf_output_buffer($cpdf);
cpdf_close($cpdf);
?>

cpdf_arc

(PHP 3>= 3.0.8, PHP 4 )

cpdf_arc -- Ívet rajzol

Leírás

void cpdf_arc ( int pdf document, double x-koor, double y-koor, double radius, double start, double end, int mode)

A cpdf_arc() függvény ívet rajzol az (x-koor, y-koor) középpont köré radius sugárral, start kezdőszögtől end végszögig.

Az utolsó elhagyható paraméter megadja a hosszúsági egységet. Ha ez 0 vagy el van hagyva, az alapértelmezett érték az oldal számára meghatározott érték. Egyébként a koordinátákat postcript pontok szerint veszi figyelembe.

Lásd még: cpdf_circle().

cpdf_begin_text

(PHP 3>= 3.0.8, PHP 4 )

cpdf_begin_text -- Szöveg szekciót kezd el

Leírás

void cpdf_begin_text ( int pdf document)

A cpdf_begin_text() függvény egy szöveg szekciót kezd el. Ennek a cpdf_end_text() függvény meghívásával kell végződnie.

Példa 1. Szöveg kimenet

<?php 
cpdf_begin_text($pdf);
cpdf_set_font($pdf, 16, "Helvetica", "WinAnsiEncoding");
cpdf_text($pdf, 100, 100, "Some text");
cpdf_end_text($pdf) 
?>

Lásd még: cpdf_end_text().

cpdf_circle

(PHP 3>= 3.0.8, PHP 4 )

cpdf_circle -- Kört rajzol

Leírás

void cpdf_circle ( int pdf document, double x-koor, double y-koor, double radius, int mode)

A cpdf_circle() függvény egy kört rajzol az (x-koor, y-koor) középpont köré radius sugárral.

Az utolsó elhagyható paraméter megadja a hosszúsági egységet. Ha ez 0 vagy el van hagyva, az alapértelmezett érték az oldal számára meghatározott érték. Egyébként a koordinátákat postcript pontok szerint veszi figyelembe.

Lásd még: cpdf_arc().

cpdf_clip

(PHP 3>= 3.0.8, PHP 4 )

cpdf_clip -- Kivágja az aktuális alakzatot

Leírás

void cpdf_clip ( int pdf document)

A cpdf_clip() függvény vágja az összes rajzot az aktuális alakzathoz.

cpdf_close

(PHP 3>= 3.0.8, PHP 4 )

cpdf_close -- Bezárja a pdf dokumentumot

Leírás

void cpdf_close ( int pdf document)

A cpdf_close() függvény bezárja a pdf dokumentumot. Ajánlatos, hogy ez legyen az utolsó tevékenység a cpdf_finalize(), cpdf_output_buffer() és cpdf_save_to_file() függvények után.

Lásd még: cpdf_open().

cpdf_closepath_fill_stroke

(PHP 3>= 3.0.8, PHP 4 )

cpdf_closepath_fill_stroke -- Bezárja, kitölti és körvonalazza az aktuális alakzatot

Leírás

void cpdf_closepath_fill_stroke ( int pdf document)

A cpdf_closepath_fill_stroke() függvény bezárja, kitölti az aktuális alakzatot az aktuális színező színnel és kirajzolja azt.

Lásd még: cpdf_closepath(), cpdf_stroke(), cpdf_fill(), cpdf_setgray_fill(), cpdf_setgray(), cpdf_setrgbcolor_fill(), cpdf_setrgbcolor().

cpdf_closepath_stroke

(PHP 3>= 3.0.8, PHP 4 )

cpdf_closepath_stroke -- Bezárja az alakzatot és körvonalat rajzol az alakzat mentén

Leírás

void cpdf_closepath_stroke ( int pdf document)

A cpdf_closepath_stroke() függvény a cpdf_closepath() és a cpdf_stroke() függvények kombinációja. Törli az alakzatot.

Lásd még: cpdf_closepath(), cpdf_stroke().

cpdf_closepath

(PHP 3>= 3.0.8, PHP 4 )

cpdf_closepath -- Befejez egy alakzatot

Leírás

void cpdf_closepath ( int pdf document)

A cpdf_closepath() lezárja az aktuális alakzatot.

cpdf_continue_text

(PHP 3>= 3.0.8, PHP 4 )

cpdf_continue_text -- Szöveget helyez a következő sorba

Leírás

void cpdf_continue_text ( int pdf document, string text)

A cpdf_continue_text() függvény a text stringben megadott szöveget a következő sorba helyezi.

Lásd még: cpdf_show_xy(), cpdf_text(), cpdf_set_leading(), cpdf_set_text_pos().

cpdf_curveto

(PHP 3>= 3.0.8, PHP 4 )

cpdf_curveto -- Görbét rajzol

Leírás

void cpdf_curveto ( int pdf document, double x1, double y1, double x2, double y2, double x3, double y3, int mode)

A cpdf_curveto() függvény Bezier-görbét rajzol az aktuális pozícióból a (x3, y3) pontba, felhasználva az (x1, y1) és (x2, y2) pontokat, mint kontrollpontokat.

Az utolsó elhagyható paraméter megadja a hosszúsági egységet. Ha ez 0 vagy el van hagyva, az alapértelmezett érték az oldal számára meghatározott érték. Egyébként a koordinátákat postcript pontok szerint veszi figyelembe.

Lásd még: cpdf_moveto(), cpdf_rmoveto(), cpdf_rlineto(), cpdf_lineto().

cpdf_end_text

(PHP 3>= 3.0.8, PHP 4 )

cpdf_end_text -- Befejezi a szöveg szekciót

Leírás

void cpdf_end_text ( int pdf document)

A cpdf_end_text() függvény befejezi a szöveg szekciót amely a cpdf_begin_text() függvényel lett megkezdve.

Példa 1. Szöveg kimenet

<?php
cpdf_begin_text($pdf);
cpdf_set_font($pdf, 16, "Helvetica", "WinAnsiEncoding");
cpdf_text($pdf, 100, 100, "Some text");
cpdf_end_text($pdf)
?>

Lásd még: cpdf_begin_text().

cpdf_fill_stroke

(PHP 3>= 3.0.8, PHP 4 )

cpdf_fill_stroke -- Kitölti és körvonalazza az aktuális alakzatot

Leírás

void cpdf_fill_stroke ( int pdf document)

A cpdf_fill_stroke() függvény kitölti az aktuális alakzat belsejét az aktuális színező színnel és kirajzolja azt.

Lásd még: cpdf_closepath(), cpdf_stroke(), cpdf_fill(), cpdf_setgray_fill(), cpdf_setgray(), cpdf_setrgbcolor_fill(), cpdf_setrgbcolor().

cpdf_fill

(PHP 3>= 3.0.8, PHP 4 )

cpdf_fill -- Kitölti az aktuális alakzatot

Leírás

void cpdf_fill ( int pdf document)

A cpdf_fill() függvény kitölti az aktuális alakzat belsejét az aktuális színező szinnel.

Lásd még: cpdf_closepath(), cpdf_stroke(), cpdf_setgray_fill(), cpdf_setgray(), cpdf_setrgbcolor_fill(), cpdf_setrgbcolor().

cpdf_finalize_page

(PHP 3>= 3.0.10, PHP 4 )

cpdf_finalize_page -- Befejezi az oldalt

Leírás

void cpdf_finalize_page ( int pdf_document, int page_number)

A cpdf_finalize_page() függvény befejzi a page_number számú oldalt. Ez a függvény csak memóriafelszabadításra szolgál. A befejezett oldal kevesebb memóriát foglal el de tovább már nem módosítható.

Lásd még: cpdf_page_init().

cpdf_finalize

(PHP 3>= 3.0.8, PHP 4 )

cpdf_finalize -- Befejezi a dokumentumot

Leírás

void cpdf_finalize ( int pdf_document)

A cpdf_finalize() függvény befejezi a dokumentumot. Ezután a cpdf_close()-t még mindenképpen meg kell hívni.

Lásd még: cpdf_close().

cpdf_global_set_document_limits

(PHP 4 )

cpdf_global_set_document_limits -- A pdf dokumentumra vonatkozó korlátozások beállítására szolgál

Leírás

void cpdf_global_set_document_limits ( int maxpages, int maxfonts, int maximages, int maxannotations, int maxobjects)

A cpdf_global_set_document_limits() függvény számos dokumentummal kapcsolatos korlátozást állít. A függvényt a cpdf_open() függvény meghívása előtt kell meghívni, mert csak a függvényhívás után megnyitott dokumentumok korlátait állítja.

Lásd még a cpdf_open() függvényt!

cpdf_import_jpeg

(PHP 3>= 3.0.9, PHP 4 )

cpdf_import_jpeg -- Megnyit egy JPEG képet

Leírás

int cpdf_open_jpeg ( int pdf_document, string file_name, double x-koor, double y-koor, double angle, double width, double height, double x-scale, double y-scale, int mode)

A cpdf_import_jpeg() függvény megnyit egy, a file_name nevű fájlban tárolt képet. A képformátum kötelezően jpeg. A képet az aktuális oldal (x-koor, y-koor) koordinátájú pontjában helyezi el. A kép elforgatható angle fokkal.

Az utolsó elhagyható paraméter megadja a hosszúsági egységet. Ha ez 0 vagy el van hagyva, az alapértelmezett érték az oldal számára meghatározott érték. Egyébként a koordinátákat postcript pontok szerint veszi figyelembe.

Lásd még: cpdf_place_inline_image(),

cpdf_lineto

(PHP 3>= 3.0.8, PHP 4 )

cpdf_lineto -- Egyenest rajzol

Leírás

void cpdf_lineto ( int pdf_document, double x-koor, double y-koor, int mode)

A cpdf_lineto() függvény vonalat rajzol az aktuális pozícióból az (x-koor, y-koor) koordinátájú pontba.

Az utolsó elhagyható paraméter megadja a hosszúsági egységet. Ha ez 0 vagy el van hagyva, az alapértelmezett érték az oldal számára meghatározott érték. Egyébként a koordinátákat postcript pontok szerint veszi figyelembe.

Lásd még: cpdf_moveto(), cpdf_rmoveto(), cpdf_curveto().

cpdf_moveto

(PHP 3>= 3.0.8, PHP 4 )

cpdf_moveto -- Beállítja az aktuális pontot

Leírás

void cpdf_moveto ( int pdf_document, double x-koor, double y-koor, int mode)

A cpdf_moveto() függvény beállítja az aktuális pozíciót az x-koor és y-koor koordinátájú pontra.

Az utolsó elhagyható paraméter megadja a hosszúsági egységet. Ha ez 0 vagy el van hagyva, az alapértelmezett érték az oldal számára meghatározott érték. Egyébként a koordinátákat postcript pontok szerint veszi figyelembe.

cpdf_newpath

(PHP 3>= 3.0.9, PHP 4 )

cpdf_newpath --  Új alakzatot kezd

Leírás

void cpdf_newpath ( int pdf_document)

A cpdf_newpath() új alakzatot kezd a pdf_document által megadott dokumentumban.

cpdf_open

(PHP 3>= 3.0.8, PHP 4 )

cpdf_open -- Megnyit egy új pdf dokumentumot

Leírás

int cpdf_open ( int compression, string filename)

A cpdf_open() függvény megnyit egy új pdf dokumentumot. Az első paraméter bekapcsolja a a dokumentum tömörítést, ha nem egyenlő NULLával. A második elhagyható paraméter beállítja azt a fájlt, amelybe a dokumentum kerül. Ha elhagyjuk, akkor a memóriában készül el és a cpdf_save_to_file() függvénnyel fájlba írható vagy a standard kimenetre küldhető a cpdf_output_buffer()-el.

Megjegyzés: A visszaadott értékre a ClibPDF későbbi verzióinál mint első paraméterre szükség lesz minden más pdf dokumentumba író függvény esetében.

A ClibPDF könyvtár a "-" filenevet a standard kimenet szinonímájaként veszi. Ha a PHP egy apache modulként van installálva, ez nem működik, mivel a ClibPDF kiiratási módja a starndard kimenetre nem működik együtt az apache-al. Megoldhatod a problémát, ha kihagyod a filenevet és a cpdf_output_buffer() függvényt használod a pdf kiiratásához.

Lásd még: cpdf_close(), cpdf_output_buffer().

cpdf_output_buffer

(PHP 3>= 3.0.9, PHP 4 )

cpdf_output_buffer -- A memóriapufferből kiiratja a pdf dokumentumot

Leírás

void cpdf_output_buffer ( int pdf_document)

A cpdf_output_buffer() függvény a standard kimenetre küldi a pdf dokumentumot. Ehhez a dokumentumot a memóriában kell elkészíteni, azaz a cpdf_open() hívásnál nem kell filenév paramétert megadni.

Lásd még: cpdf_open().

cpdf_page_init

(PHP 3>= 3.0.8, PHP 4 )

cpdf_page_init -- Új oldalt kezd

Leírás

void cpdf_page_init ( int pdf_document, int page_number, int orientation, double height, double width, double unit)

A cpdf_page_init() függvény új oldalt kezd height magassággal és width szélességgel. Az oldal száma page_number és orientációja orientation. Az orientation paraméter 0 álló és 1 fekvő irányítottság esetén. Az utolsó elhagyható unit paraméter beállítja a koordinátarendszer egységét. Értéke a postcript pontok száma egységenként. Mivel egy hüvelyk (inch) 72 ponttal egyenlő, a 72 érték felel meg egy hüvelyknek. Az alapértelmezés szintén a 72.

Lásd még: cpdf_set_current_page().

cpdf_place_inline_image

(PHP 3>= 3.0.9, PHP 4 )

cpdf_place_inline_image -- Képet helyez el az oldalon

Leírás

void cpdf_place_inline_image ( int pdf_document, int image, double x-koor, double y-koor, double angle, double width, double height, int mode)

A cpdf_place_inline_image() függvény egy php képfüggvényekkel készített képet helyez el az oldalon az (x-koor, y-koor) pontban. A kép ezzel egyidőben méretezhető.

Az utolsó elhagyható paraméter megadja a hosszúsági egységet. Ha ez 0 vagy el van hagyva, az alapértelmezett érték az oldal számára meghatározott érték. Egyébként a koordinátákat postcript pontok szerint veszi figyelembe.

Lásd még: cpdf_import_jpeg(),

cpdf_rect

(PHP 3>= 3.0.8, PHP 4 )

cpdf_rect -- Téglalapot rajzol

Leírás

void cpdf_rect ( int pdf document, double x-koor, double y-koor, double width, double height, int mode)

A cpdf_rect() függvény egy téglalapot rajzol, amelynek jobb alsó sarkának koordinátája (x-koor, y-koor) pont. A téglalap szélessége widgth, magassága height.

Az utolsó elhagyható paraméter megadja a hosszúsági egységet. Ha ez 0 vagy el van hagyva, az alapértelmezett érték az oldal számára meghatározott érték. Egyébként a koordinátákat postcript pontok szerint veszi figyelembe.

cpdf_restore

(PHP 3>= 3.0.8, PHP 4 )

cpdf_restore -- Visszaállítja a korábban elmentett környezetet

Leírás

void cpdf_restore ( int pdf document)

A cpdf_restore() függvény visszaállítja a cpdf_save() függvénnyel elmentett környezetet. Ez úgy működik, mint a postscript grestore parancs. Nagyon hasznos, ha egy objektumot anélkül akarunk áthelyezni vagy elforgatni, hogy az más objektumokra is hatással legyen.

Példa 1. Save/Restore

<?php 
cpdf_save($pdf);
// forgatások, transzformációk ...
cpdf_restore($pdf) 
?>

Lásd még: cpdf_save().

cpdf_rlineto

(PHP 3>= 3.0.9, PHP 4 )

cpdf_rlineto -- Egyenest rajzol

Leírás

void cpdf_rlineto ( int pdf document, double x-koor, double y-koor, int mode)

A cpdf_rlineto() függvény vonalat rajzol az aktuális pozícióból az (x-koor, y-koor) relatív koordinátájú ponthoz.

Az utolsó elhagyható paraméter megadja a hosszúsági egységet. Ha ez 0 vagy el van hagyva, az alapértelmezett érték az oldal számára meghatározott érték. Egyébként a koordinátákat postcript pontok szerint veszi figyelembe.

Lásd még: cpdf_moveto(), cpdf_rmoveto(), cpdf_curveto().

cpdf_rmoveto

(PHP 3>= 3.0.9, PHP 4 )

cpdf_rmoveto -- Beállítja az aktuális pontot

Leírás

void cpdf_rmoveto ( int pdf document, double x-koor, double y-koor, int mode)

A cpdf_rmoveto() függvény beálítja az aktuális pontot az x-koor és y-koor relatív koordinátájú ponthoz.

Az utolsó elhagyható paraméter megadja a hosszúsági egységet. Ha ez 0 vagy el van hagyva, az alapértelmezett érték az oldal számára meghatározott érték. Egyébként a koordinátákat postcript pontok szerint veszi figyelembe.

Lásd még: cpdf_moveto().

cpdf_rotate_text

(PHP 3>= 3.0.9, PHP 4 )

cpdf_rotate_text --  Sets text rotation angle

Description

bool cpdf_rotate_text ( int pdfdoc, float angle)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

cpdf_rotate

(PHP 3>= 3.0.8, PHP 4 )

cpdf_rotate -- Beállítja a forgatást

Leírás

void cpdf_rotate ( int pdf document, double angle)

A cpdf_rotate() függvény beállítja az elforgatás szögét angle értékre.

cpdf_save_to_file

(PHP 3>= 3.0.8, PHP 4 )

cpdf_save_to_file -- A pdf dokumentumot fájlba írja

Leírás

void cpdf_save_to_file ( int pdf document, string filename)

A cpdf_save_to_file() függvény fájlba írja a pdf dokumentumot ha ez korábban a memóriában készült el. Nem szükséges, ha a pdf dokumentumot úgy nyitottad meg, hogy adtál filenév paramétert a cpdf_open()-nek.

Lásd még: cpdf_output_buffer(), cpdf_open().

cpdf_save

(PHP 3>= 3.0.8, PHP 4 )

cpdf_save -- Elmenti az aktuális környezetet

Leírás

void cpdf_save ( int pdf document)

A cpdf_save() függvény elmenti az aktuális környezetet. Ez úgy működik, mint a postscript gsave parancs. Nagyon hasznos, ha egy objektumot anélkül akarunk áthelyezni vagy elforgatni, hogy az más objektumokra is hatással legyen.

Lásd még: cpdf_restore().

cpdf_scale

(PHP 3>= 3.0.8, PHP 4 )

cpdf_scale -- Beállítja a méretezést

Leírás

void cpdf_scale ( int pdf document, double x-scale, double y-scale)

A cpdf_scale() függvény beállítja a méretezési faktort mindkét irányban.

cpdf_set_action_url

(PHP 3>= 3.0.9, PHP 4 )

cpdf_set_action_url --  Sets hyperlink

Description

bool cpdf_set_action_url ( int pdfdoc, float xll, float yll, float xur, float xur, string url [, int mode])

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

cpdf_set_char_spacing

(PHP 3>= 3.0.8, PHP 4 )

cpdf_set_char_spacing -- Beállítja a betűtávolságot

Leírás

void cpdf_set_char_spacing ( int pdf document, double space)

A cpdf_set_char_spacing() függvény beállítja a karakterek közötti távolságot.

Lásd még: cpdf_set_word_spacing(), cpdf_set_leading().

cpdf_set_creator

(PHP 3>= 3.0.8, PHP 4 )

cpdf_set_creator -- A pdf dokumentumban a létrehozó(creator) mezőt állítja

Leírás

void cpdf_set_creator ( string creator)

A cpdf_set_creator() függvény a pdf dokumentum szerző mezőjét állítja.

Lásd még a cpdf_set_subject(), cpdf_set_title() és a cpdf_set_keywords() függvényt!

cpdf_set_current_page

(PHP 3>= 3.0.9, PHP 4 )

cpdf_set_current_page -- Beállítja az aktuális oldalt

Leírás

void cpdf_set_current_page ( int pdf document, int page number)

A cpdf_set_current_page() függvény beállítja azt az oldalt, amelyre az összes továbii művelet vonatkozik. Egy oldal választható, ameddig nincs befejezve a cpdf_finalize_page()-al.

Lásd még: cpdf_finalize_page().

cpdf_set_font_directories

(PHP 4 >= 4.0.6)

cpdf_set_font_directories --  Sets directories to search when using external fonts

Description

bool cpdf_set_font_directories ( int pdfdoc, string pfmdir, string pfbdir)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

cpdf_set_font_map_file

(PHP 4 >= 4.0.6)

cpdf_set_font_map_file --  Sets fontname to filename translation map when using external fonts

Description

bool cpdf_set_font_map_file ( int pdfdoc, string filename)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

cpdf_set_font

(PHP 3>= 3.0.8, PHP 4 )

cpdf_set_font -- Kiválaszja az aktuális betűtípust és méretet

Leírás

void cpdf_set_font ( int pdf_document, string font_name, double size, string encoding)

A cpdf_set_font() függvény beállítja az aktuális betűtípust, betűméretet és kódolást. Jelenleg csak a standard postscript betűtípusok támogatottak. Az utolsó encoding paraméter a következő értékeket veheti fel: "MacRomanEncoding", "MacExpertEncoding", "WinAnsiEncoding", és "NULL". "NULL" jelenti a betűtípus beépített kódolását. Lásd a ClibPDF Kézikönyvet további információért főleg az ázsiai fontok támogatását illetően.

cpdf_set_horiz_scaling

(PHP 3>= 3.0.8, PHP 4 )

cpdf_set_horiz_scaling -- Beállítja a szöveg vízszintes méretezését

Leírás

void cpdf_set_horiz_scaling ( int pdf document, double scale)

A cpdf_set_horiz_scaling() függvény beállítja a vízszintes méretezést a scale százalékra.

cpdf_set_keywords

(PHP 3>= 3.0.8, PHP 4 )

cpdf_set_keywords -- Beállítja a pdf dokumentum kulcsszavak mezőjét

Leírás

void cpdf_set_keywords ( string keywords)

A cpdf_set_keywords() függvény beállítja a pdf dokumentum kulcsszavait.

Lásd még: cpdf_set_title(), cpdf_set_creator(), cpdf_set_subject().

cpdf_set_leading

(PHP 3>= 3.0.8, PHP 4 )

cpdf_set_leading -- Beállítja a szöveg sortávolságát

Leírás

void cpdf_set_leading ( int pdf document, double distance)

A cpdf_set_leading() függvény beállítja a szövegsorok közötti távolságot. Ez a cpdf_continue_text() függvénnyel elhelyezett szövegnél használatos.

Lásd még: cpdf_continue_text().

cpdf_set_page_animation

(PHP 3>= 3.0.9, PHP 4 )

cpdf_set_page_animation -- Beállítja az oldalak közti átmeneti időtartamot

Leírás

void cpdf_set_page_animation ( int pdf document, int transition, double duration)

A cpdf_set_page_animation() függvény beállítja az átmenetet két egymást követő oldal között.

A transition értéke lehet

0: nincs átmenet,
1: két, a képernyőn végigseprő vonal fedi fel az új oldalt,
2: több, a képernyőn végigseprő vonal fedi fel az új oldalt,
3: egy négyzet fedi fel az új oldalt,
4: egy, a képernyőn végigseprő vonal fedi fel az új oldalt,
5: a régi oldal szétoszolva fedi fel az új oldalt,
6: egy szétoszló effektus mozog az egyik képernyőszéltől a másikig,
7: a régi oldal egyszerűen helyettesítődik az új oldallal (alapértelmezés)

A duration értéke a képek közötti átmenet másodperceinek száma.

cpdf_set_subject

(PHP 3>= 3.0.8, PHP 4 )

cpdf_set_subject -- Beállítja a pdf dokumentum tárgy mezőjét

Leírás

void cpdf_set_subject ( string subject)

A cpdf_set_subject() függvény beállítja a pdf dokumentum tárgyát.

Lásd még: cpdf_set_title(), cpdf_set_creator(), cpdf_set_keywords().

cpdf_set_text_matrix

(PHP 3>= 3.0.8, PHP 4 )

cpdf_set_text_matrix -- Beállítja a szövegmátrixot

Leírás

void cpdf_set_text_matrix ( int pdf document, array matrix)

A cpdf_set_text_matrix() függvény beállít egy mátrixot, amely leír egy, az aktuális betűtípusra alkalmazott transzformációt.

cpdf_set_text_pos

(PHP 3>= 3.0.8, PHP 4 )

cpdf_set_text_pos -- Beállítja a szövegpozíciót

Leírás

void cpdf_set_text_pos ( int pdf document, double x-koor, double y-koor, int mode)

A cpdf_set_text_pos() függvény beállítja a szöveg pozícióját a következő cpdf_show() függvényhíváshoz.

Az utolsó elhagyható mode paraméter megadja a hosszúsági egységet. Ha ez 0 vagy el van hagyva, az alapértelmezett érték az oldal számára meghatározott érték. Egyébként a koordinátákat postcript pontok szerint veszi figyelembe.

Lásd még: cpdf_show(), cpdf_text().

cpdf_set_text_rendering

(PHP 3>= 3.0.8, PHP 4 )

cpdf_set_text_rendering -- Meghatározza hogyan legyen a szöveg kirajzolva

Leírás

void cpdf_set_text_rendering ( int pdf document, int mode)

A cpdf_set_text_rendering() függvény meghatározza, hogy hogyan legyen egy szöveg kirajzolva. A lehetséges értékek a mode paraméter részére: 0=szöveg kitöltés, 1=szöveg körvonala, 2=szöveg kitöltése és körvonala, 3=láthatatlan, 4=szövegkitöltés és kivágó alakzat készítése, 5=szöveg körvonala és kivágó alakzat készítése, 6=szöveg kitöltése, körvonala és kivágó alakzat készítése, 7=csak kivágó alakzat készítése.

cpdf_set_text_rise

(PHP 3>= 3.0.8, PHP 4 )

cpdf_set_text_rise -- Beállítja a szöveg emelkedését

Leírás

void cpdf_set_text_rise ( int pdf document, double value)

A cpdf_set_text_rise() függvény beállítja a szöveg emelkedését a value egységre.

cpdf_set_title

(PHP 3>= 3.0.8, PHP 4 )

cpdf_set_title -- A pdf dokumentumban a cím(title) mezőt állítja

Leírás

void cpdf_set_title ( string title)

A cpdf_set_title() függvény a pdf dokumentum cím mezőjét állítja.

Lásd még a cpdf_set_subject(), cpdf_set_creator(), cpdf_set_keywords() függvényeket!

cpdf_set_viewer_preferences

(PHP 3>= 3.0.9, PHP 4 )

cpdf_set_viewer_preferences --  How to show the document in the viewer

Description

bool cpdf_set_viewer_preferences ( int pdfdoc, array preferences)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

cpdf_set_word_spacing

(PHP 3>= 3.0.8, PHP 4 )

cpdf_set_word_spacing -- Beállítja a szótávolságot

Leírás

void cpdf_set_word_spacing ( int pdf document, double space)

A cpdf_set_word_spacing() függvény beállítja a szavak közötti távolságot.

Lásd még: cpdf_set_char_spacing(), cpdf_set_leading().

cpdf_setdash

(PHP 3>= 3.0.8, PHP 4 )

cpdf_setdash -- Beállítja a szaggatott vonalmintát

Leírás

void cpdf_setdash ( int pdf document, double white, double black)

A cpdf_setdash() függvény beállítja a szaggatott vonalminta white fehér és black fekete egységre. Ha mindkettő 0, akkor sima vonalat állít be.

cpdf_setflat

(PHP 3>= 3.0.8, PHP 4 )

cpdf_setflat -- Beállítja a simaságot

Leírás

void cpdf_setflat ( int pdf document, double value)

A cpdf_setflat() függvény beállítja a simaságot egy 0 - 100 közötti értékre.

cpdf_setgray_fill

(PHP 3>= 3.0.8, PHP 4 )

cpdf_setgray_fill -- Szürke értékre állítja a kitöltő színt

Leírás

void cpdf_setgray_fill ( int pdf document, double value)

A cpdf_setgray_fill() függvény beállítja az aktuális szürke értéket egy alakzat kitöltése céljából.

Lásd még: cpdf_setrgbcolor_fill().

cpdf_setgray_stroke

(PHP 3>= 3.0.8, PHP 4 )

cpdf_setgray_stroke -- Szürke értékre állítja a körvonalrajzoló színt

Leírás

void cpdf_setgray_stroke ( int pdf document, double gray value)

A cpdf_setgray_stroke() függvény az adott szürke értékre állítja az aktuális rajzoló színt.

Lásd még: cpdf_setrgbcolor_stroke().

cpdf_setgray

(PHP 3>= 3.0.8, PHP 4 )

cpdf_setgray -- Szürke értékre állítja a rajzoló és kitöltő színt

Leírás

void cpdf_setgray ( int pdf document, double gray value)

A cpdf_setgray_stroke() függvény az adott szürke színre állítja a rajzoló és kitöltő színt.

Lásd még: cpdf_setrgbcolor_stroke(), cpdf_setrgbcolor_fill().

cpdf_setlinecap

(PHP 3>= 3.0.8, PHP 4 )

cpdf_setlinecap -- Beállítja a vonalcsúcs paramétert

Leírás

void cpdf_setlinecap ( int pdf document, int value)

A cpdf_setlinecap() függvény beállítja a vonalcsúcs paramétert 0 - 2 közötti értékre. 0 = metszett, 1 = kerek, 2 = csapott négyszög.

cpdf_setlinejoin

(PHP 3>= 3.0.8, PHP 4 )

cpdf_setlinejoin -- Beállítja a vonalak kapcsolódási módját

Leírás

void cpdf_setlinejoin ( int pdf document, int value)

A cpdf_setlinejoin() függvény beállítja a vonalcsatlakozási paramétert 0 - 2 érték közé. 0 = hegyes, 1 = kerek, 2 = tompa.

cpdf_setlinewidth

(PHP 3>= 3.0.8, PHP 4 )

cpdf_setlinewidth -- Beállítja a vonalvastagságot

Leírás

void cpdf_setlinewidth ( int pdf document, double width)

A cpdf_setlinewidth() függvény beállítja a vonalvastagságot a width értékre.

cpdf_setmiterlimit

(PHP 3>= 3.0.8, PHP 4 )

cpdf_setmiterlimit -- Beállítja a hegyesszög határát

Leírás

void cpdf_setmiterlimit ( int pdf document, double value)

A cpdf_setmiterlimit() függvény beállítja a hegyesszög határának értékét 1-nél nagyobb vagy egyenlő értékre.

cpdf_setrgbcolor_fill

(PHP 3>= 3.0.8, PHP 4 )

cpdf_setrgbcolor_fill -- Rgb színértékre állítja be a kitöltő színt

Leírás

void cpdf_setrgbcolor_fill ( int pdf document, double red value, double green value, double blue value)

A cpdf_setrgbcolor_fill() függvény beállítja az aktuális rgb értéket egy alakzat kitöltése céljából.

Lásd még: cpdf_setrgbcolor_stroke(), cpdf_setrgbcolor().

cpdf_setrgbcolor_stroke

(PHP 3>= 3.0.8, PHP 4 )

cpdf_setrgbcolor_stroke -- Rgb színértékre állítja be a körvonalrajzoló színt

Leírás

void cpdf_setrgbcolor_stroke ( int pdf document, double red value, double green value, double blue value)

A cpdf_setrgbcolor_stroke() függvény beállítja az aktuális rajzolószínt az adott rgb szín értékre.

Lásd még: cpdf_setrgbcolor_fill(), cpdf_setrgbcolor().

cpdf_setrgbcolor

(PHP 3>= 3.0.8, PHP 4 )

cpdf_setrgbcolor -- Rgb színértékre állítja be a körvonalrajzoló és kitöltő színt

Leírás

void cpdf_setrgbcolor ( int pdf document, double red value, double green value, double blue value)

A cpdf_setrgbcolor_stroke() függvény beállítja az aktuális rajzoló és kitöltő színt a megadott rgb szín értékre.

Lásd még: cpdf_setrgbcolor_stroke(), cpdf_setrgbcolor_fill().

cpdf_show_xy

(PHP 3>= 3.0.8, PHP 4 )

cpdf_show_xy -- Szöveget helyez adott pozícióba

Leírás

void cpdf_show_xy ( int pdf document, string text, double x-koor, double y-koor, int mode)

A cpdf_show_xy() függvény a text stringben megadott szöveget az (x-koor, y-koor). kordinátájú pontba helyezi. Az utolsó elhagyható paraméter meghatározza az egységet. Ha ez 0 vagy nem szerepel, az alapértelmezett érték az oldal számára meghatározott. A koordinátákat postcript pontok szerint veszi figyelembe, az aktuális unit beállítástól függetlenül.

Megjegyzés: A cpdf_show_xy() függvény megegyezik a cpdf_text() függvénnyel az elhagyható paraméterektől eltekintve.

Lásd még: cpdf_text().

cpdf_show

(PHP 3>= 3.0.8, PHP 4 )

cpdf_show -- Szöveget helyez az aktuális pozícióba

Leírás

void cpdf_show ( int pdf document, string text)

A cpdf_show() függvény a text stringben levő szöveget az aktuális pozícióba helyezi.

Lásd még: cpdf_text(), cpdf_begin_text(), cpdf_end_text().

cpdf_stringwidth

(PHP 3>= 3.0.8, PHP 4 )

cpdf_stringwidth -- Visszaadja a szöveg szélességét az aktuális font alapján

Leírás

double cpdf_stringwidth ( int pdf document, string text)

A cpdf_stringwidth() függvény visszaadja a text szöveg szélességét. Előtte a betűtípust mindenképpen be kell állítani.

Lásd még: cpdf_set_font().

cpdf_stroke

(PHP 3>= 3.0.8, PHP 4 )

cpdf_stroke -- Körvonalat rajzol egy alakzat mentén

Leírás

void cpdf_stroke ( int pdf document)

A cpdf_stroke() függvény egy vonalat húz az aktuális alakzat mentén.

Lásd még: cpdf_closepath(), cpdf_closepath_stroke().

cpdf_text

(PHP 3>= 3.0.8, PHP 4 )

cpdf_text -- Szöveget helyez el paraméterekkel

Leírás

void cpdf_text ( int pdf document, string text, double x-koor, double y-koor, int mode, double orientation, int alignmode)

A cpdf_text() függvény a text stringben megadott szöveget a (x-koor, y-koor). által meghatározott pontba helyezi. Az elhagyható paraméter meghatározza az egységet. Ha ez 0 vagy nem szerepel, az alapértelmezett érték az oldal számára meghatározott. A koordinátákat postcript pontok szerint veszi figyelembe, az aktuális unit beállítástól függetlenül. Az elhagyható orientation paraméter a szöveg elforgatása fokban. Az alignmode elhagyható paraméter meghatározza a szöveg igazítását. Lásd a ClibPDF dokumentációt a lehetséges értékekre vonatkozólag.

Lásd még: cpdf_show_xy().

cpdf_translate

(PHP 3>= 3.0.8, PHP 4 )

cpdf_translate -- Beállítja a koordinátarendszer kezdőpontját

Leírás

void cpdf_translate ( int pdf document, double x-koor, double y-koor, int mode)

A cpdf_translate() függvény az kordinátarendszer kezdőpontját a (x-koor, y-koor) pontba helyezi.

Az utolsó elhagyható paraméter megadja a hosszúsági egységet. Ha ez 0 vagy el van hagyva, az alapértelmezett érték az oldal számára meghatározott érték. Egyébként a koordinátákat postscript pontok szerint veszi figyelembe.

XI. Crack functions

Bevezetés

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.


Követelmények

More information regarding CrackLib along with the library can be found at http://www.crypticide.org/users/alecm/.


Telepítés

In order to use these functions, you must compile PHP with Crack support by using the --with-crack[=DIR] option.


Futásidejű beállítások

Az alábbi függvények viselkedése befolyásolható a php.ini segítségével.

Táblázat 1. Crack configuration options

NameDefaultChangeable
crack.default_dictionaryNULLPHP_INI_SYSTEM
For further details and definition of the PHP_INI_* constants see ini_set().


Erőforrás típusok

Ez a kiterjesztés semmilyen erőforrás típust nem definiál.


Előre definiált állandók

Ez a kiterjesztés semmilyen konstans értéket nem definiál.


Példák

This example shows how to open a CrackLib dictionary, test a given password, retrieve any diagnostic messages, and close the dictionary.

Példa 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);
?>

Megjegyzés: If crack_check() returns TRUE, crack_getlastmessage() will return 'strong password'.

Tartalom
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

crack_check

(PHP 4 >= 4.0.5)

crack_check -- Performs an obscure check with the given password

Description

bool crack_check ( [resource dictionary, string password])

Returns TRUE if password is strong, or FALSE otherwise.

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

crack_check() performs an obscure check with the given password on the specified dictionary . If dictionary is not specified, the last opened dictionary is used.

crack_closedict

(PHP 4 >= 4.0.5)

crack_closedict -- Closes an open CrackLib dictionary

Description

bool crack_closedict ( [resource dictionary])

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

crack_closedict() closes the specified dictionary identifier. If dictionary is not specified, the current dictionary is closed.

crack_getlastmessage

(PHP 4 >= 4.0.5)

crack_getlastmessage -- Returns the message from the last obscure check

Description

string crack_getlastmessage ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

crack_getlastmessage() returns the message from the last obscure check.

crack_opendict

(PHP 4 >= 4.0.5)

crack_opendict -- Opens a new CrackLib dictionary

Description

resource crack_opendict ( string dictionary)

Returns a dictionary resource identifier on success, or FALSE on failure.

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

crack_opendict() opens the specified CrackLib dictionary for use with crack_check().

Megjegyzés: Only one dictionary may be open at a time.

See also: crack_check(), and crack_closedict().

XII. CURL, Client URL Library Functions

Bevezetés

PHP supports libcurl, a library created by Daniel Stenberg, that allows you to connect and communicate to many different types of servers with many different types of protocols. libcurl currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols. libcurl also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading (this can also be done with PHP's ftp extension), HTTP form based upload, proxies, cookies, and user+password authentication.

These functions have been added in PHP 4.0.2.


Követelmények

In order to use the CURL functions you need to install the CURL package. PHP requires that you use CURL 7.0.2-beta or higher. PHP will not work with any version of CURL below version 7.0.2-beta. In PHP version 4.2.3, you will need CURL version 7.9.0 or higher. From PHP 4.3.0, you will need a CURL version that's 7.9.8 or higher. PHP 5.0.0 will most likely require a CURL version greater than 7.10.5


Telepítés

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.

Note to Win32 Users: In order to enable this module on a Windows environment, you must copy libeay32.dll and ssleay32.dll from the DLL folder of the PHP/Win32 binary package to the SYSTEM folder of your Windows machine. (Ex: C:\WINNT\SYSTEM32 or C:\WINDOWS\SYSTEM)


Előre definiált állandók

Az itt listázott állandókat ez a kiterjesztés definiálja, és csak akkor elérhetőek, ha az adott kiterjesztés be van fordítva a PHP-be, vagy dinamikusan betöltött.

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

CURLOPT_FOLLOWLOCATION (integer)

CURLOPT_FTPASCII (integer)

CURLOPT_PUT (integer)

CURLOPT_MUTE (integer)

CURLOPT_USERPWD (integer)

CURLOPT_PROXYUSERPWD (integer)

CURLOPT_RANGE (integer)

CURLOPT_TIMEOUT (integer)

CURLOPT_POSTFIELDS (integer)

CURLOPT_REFERER (integer)

CURLOPT_USERAGENT (integer)

CURLOPT_FTPPORT (integer)

CURLOPT_LOW_SPEED_LIMIT (integer)

CURLOPT_LOW_SPEED_TIME (integer)

CURLOPT_RESUME_FROM (integer)

CURLOPT_COOKIE (integer)

CURLOPT_SSLCERT (integer)

CURLOPT_SSLCERTPASSWD (integer)

CURLOPT_WRITEHEADER (integer)

CURLOPT_SSL_VERIFYHOST (integer)

CURLOPT_COOKIEFILE (integer)

CURLOPT_SSLVERSION (integer)

CURLOPT_TIMECONDITION (integer)

CURLOPT_TIMEVALUE (integer)

CURLOPT_CUSTOMREQUEST (integer)

CURLOPT_STDERR (integer)

CURLOPT_TRANSFERTEXT (integer)

CURLOPT_RETURNTRANSFER (integer)

CURLOPT_QUOTE (integer)

CURLOPT_POSTQUOTE (integer)

CURLOPT_INTERFACE (integer)

CURLOPT_KRB4LEVEL (integer)

CURLOPT_HTTPPROXYTUNNEL (integer)

CURLOPT_FILETIME (integer)

CURLOPT_WRITEFUNCTION (integer)

CURLOPT_READFUNCTION (integer)

CURLOPT_PASSWDFUNCTION (integer)

CURLOPT_HEADERFUNCTION (integer)

CURLOPT_MAXREDIRS (integer)

CURLOPT_MAXCONNECTS (integer)

CURLOPT_CLOSEPOLICY (integer)

CURLOPT_FRESH_CONNECT (integer)

CURLOPT_FORBID_REUSE (integer)

CURLOPT_RANDOM_FILE (integer)

CURLOPT_EGDSOCKET (integer)

CURLOPT_CONNECTTIMEOUT (integer)

CURLOPT_SSL_VERIFYPEER (integer)

CURLOPT_CAINFO (integer)

CURLOPT_COOKIEJAR (integer)

CURLOPT_SSL_CIPHER_LIST (integer)

CURLOPT_BINARYTRANSFER (integer)

CURLCLOSEPOLICY_LEAST_RECENTLY_USED (integer)

CURLCLOSEPOLICY_LEAST_TRAFFIC (integer)

CURLCLOSEPOLICY_SLOWEST (integer)

CURLCLOSEPOLICY_CALLBACK (integer)

CURLCLOSEPOLICY_OLDEST (integer)

CURLINFO_EFFECTIVE_URL (integer)

CURLINFO_HTTP_CODE (integer)

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)

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)


Példák

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:

Példa 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);
?>

Tartalom
curl_close -- Close a CURL session
curl_errno -- Return the last error number
curl_error --  Return a string containing the last error for the current session
curl_exec -- Perform a CURL session
curl_getinfo --  Get information regarding a specific transfer
curl_init -- Initialize a CURL session
curl_multi_add_handle --  Add a normal cURL handle to a cURL multi handle
curl_multi_close --  Close a set of cURL handles
curl_multi_exec --  Run the sub-connections of the current cURL handle
curl_multi_getcontent --  Return the content of a cURL handle if CURLOPT_RETURNTRANSFER is set
curl_multi_info_read --  Get information about the current transfers
curl_multi_init --  Returns a new cURL multi handle
curl_multi_remove_handle --  Remove a multi handle from a set of cURL handles
curl_multi_select --  Get all the sockets associated with the cURL extension, which can then be "selected"
curl_setopt -- Set an option for a CURL transfer
curl_version -- Return the current CURL version

curl_close

(PHP 4 >= 4.0.2)

curl_close -- Close a CURL session

Description

void curl_close ( resource ch)

This function closes a CURL session and frees all resources. The CURL handle, ch, is also deleted.

curl_errno

(PHP 4 >= 4.0.3)

curl_errno -- Return the last error number

Description

int curl_errno ( resource ch)

Returns the error number for the last cURL operation on the resource ch, or 0 (zero) if no error occurred.

See also curl_error().

curl_error

(PHP 4 >= 4.0.3)

curl_error --  Return a string containing the last error for the current session

Description

string curl_error ( resource ch)

Returns a clear text error message for the last cURL operation on the resource ch, or '' (the empty string) if no error occurred.

See also curl_errno().

curl_exec

(PHP 4 >= 4.0.2)

curl_exec -- Perform a CURL session

Description

mixed curl_exec ( resource ch)

This function should be called after you initialize a CURL session and all the options for the session are set. Its purpose is simply to execute the predefined CURL session (given by the ch).

Megjegyzés: If you want to have the result returned instead of it being printed to the browser directly, use the CURLOPT_RETURNTRANSFER option of curl_setopt().

curl_getinfo

(PHP 4 >= 4.0.4)

curl_getinfo --  Get information regarding a specific transfer

Description

string curl_getinfo ( resource ch [, int opt])

Returns information about the last transfer, opt may be one of the following:

  • "CURLINFO_EFFECTIVE_URL" - Last effective URL

  • "CURLINFO_HTTP_CODE" - Last received HTTP code

  • "CURLINFO_FILETIME" - Remote time of the retrieved document, if -1 is returned the time of the document is unknown

  • "CURLINFO_TOTAL_TIME" - Total transaction time in seconds for last transfer

  • "CURLINFO_NAMELOOKUP_TIME" - Time in seconds until name resolving was complete

  • "CURLINFO_CONNECT_TIME" - Time in seconds it took to establish the connection

  • "CURLINFO_PRETRANSFER_TIME" - Time in seconds from start until just before file transfer begins

  • "CURLINFO_STARTTRANSFER_TIME" - Time in seconds until the first byte is about to be transferred

  • "CURLINFO_REDIRECT_TIME" - Time in seconds of all redirection steps before final transaction was started

  • "CURLINFO_SIZE_UPLOAD" - Total number of bytes uploaded

  • "CURLINFO_SIZE_DOWNLOAD" - Total number of bytes downloaded

  • "CURLINFO_SPEED_DOWNLOAD" - Average download speed

  • "CURLINFO_SPEED_UPLOAD" - Average upload speed

  • "CURLINFO_HEADER_SIZE" - Total size of all headers received

  • "CURLINFO_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 downloaded object, NULL indicates server did not send valid Content-Type: header

If called without the optional parameter opt an associative array is returned with the following array elements which correspond to opt options:

  • "url"

  • "content_type"

  • "http_encode"

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

curl_init

(PHP 4 >= 4.0.2)

curl_init -- Initialize a CURL session

Description

resource curl_init ( [string url])

The curl_init() will initialize a new session and return a CURL handle for use with the curl_setopt(), curl_exec(), and curl_close() functions. If the optional url parameter is supplied then the CURLOPT_URL option will be set to the value of the parameter. You can manually set this using the curl_setopt() function.

Példa 1. Initializing a new CURL session and fetching a webpage

<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);

curl_exec($ch);

curl_close($ch);
?>

See also: curl_close(), curl_setopt()

curl_multi_add_handle

(PHP 5 CVS only)

curl_multi_add_handle --  Add a normal cURL handle to a cURL multi handle

Description

int curl_multi_add_handle ( resource mh, resource ch)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

See also curl_multi_init(), curl_init(), and curl_multi_remove_handle().

curl_multi_close

(PHP 5 CVS only)

curl_multi_close --  Close a set of cURL handles

Description

void curl_multi_close ( resource mh)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

See also curl_multi_init() and curl_close().

curl_multi_exec

(PHP 5 CVS only)

curl_multi_exec --  Run the sub-connections of the current cURL handle

Description

int curl_multi_exec ( resource mh)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

See also curl_multi_init() and curl_exec().

curl_multi_getcontent

(PHP 5 CVS only)

curl_multi_getcontent --  Return the content of a cURL handle if CURLOPT_RETURNTRANSFER is set

Description

string curl_multi_getcontent ( resource ch)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

See also curl_multi_init().

curl_multi_info_read

(PHP 5 CVS only)

curl_multi_info_read --  Get information about the current transfers

Description

array curl_multi_info_read ( resource mh)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

See also curl_multi_init().

curl_multi_init

(PHP 5 CVS only)

curl_multi_init --  Returns a new cURL multi handle

Description

resource curl_multi_init ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

See also curl_init() and curl_multi_close().

curl_multi_remove_handle

(PHP 5 CVS only)

curl_multi_remove_handle --  Remove a multi handle from a set of cURL handles

Description

int curl_multi_remove_handle ( resource mh, resource ch)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

See also curl_multi_init(), curl_init(), and curl_multi_add_handle().

curl_multi_select

(PHP 5 CVS only)

curl_multi_select --  Get all the sockets associated with the cURL extension, which can then be "selected"

Description

int curl_multi_select ( resource mh [, float timeout])

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

See also curl_multi_init().

curl_setopt

(PHP 4 >= 4.0.2)

curl_setopt -- Set an option for a CURL transfer

Description

bool curl_setopt ( resource ch, string option, mixed value)

The curl_setopt() function will set options for a CURL session identified by the ch parameter. The option parameter is the option you want to set, and the value is the value of the option given by the option.

The value should be a long for the following options (specified in the option parameter):

  • CURLOPT_INFILESIZE: When you are uploading a file to a remote site, this option should be used to tell PHP what the expected size of the infile will be.

  • CURLOPT_VERBOSE: Set this option to a non-zero value if you want CURL to report everything that is happening.

  • CURLOPT_HEADER: Set this option to a non-zero value if you want the header to be included in the output.

  • CURLOPT_NOPROGRESS: Set this option to a non-zero value if you don't want PHP to display a progress meter for CURL transfers.

    Megjegyzés: PHP automatically sets this option to a non-zero parameter, this should only be changed for debugging purposes.

  • CURLOPT_NOBODY: Set this option to a non-zero value if you don't want the body included with the output.

  • CURLOPT_FAILONERROR: Set this option to a non-zero value if you want PHP to fail silently if the HTTP code returned is greater than 300. The default behavior is to return the page normally, ignoring the code.

  • CURLOPT_UPLOAD: Set this option to a non-zero value if you want PHP to prepare for an upload.

  • CURLOPT_POST: Set this option to a non-zero value if you want PHP to do a regular HTTP POST. This POST is a normal application/x-www-form-urlencoded kind, most commonly used by HTML forms.

  • CURLOPT_FTPLISTONLY: Set this option to a non-zero value and PHP will just list the names of an FTP directory.

  • CURLOPT_FTPAPPEND: Set this option to a non-zero value and PHP will append to the remote file instead of overwriting it.

  • CURLOPT_NETRC: Set this option to a non-zero value and PHP will scan your ~./netrc file to find your username and password for the remote site that you're establishing a connection with.

  • CURLOPT_FOLLOWLOCATION: Set this option to a non-zero value to follow any "Location: " header that the server sends as a part of the HTTP header (note this is recursive, PHP will follow as many "Location: " headers that it is sent.)

  • CURLOPT_PUT: Set this option to a non-zero value to HTTP PUT a file. The file to PUT must be set with the CURLOPT_INFILE and CURLOPT_INFILESIZE.

  • CURLOPT_MUTE: Set this option to a non-zero value and PHP will be completely silent with regards to the CURL functions.

  • CURLOPT_TIMEOUT: Pass a long as a parameter that contains the maximum time, in seconds, that you'll allow the CURL functions to take.

  • CURLOPT_LOW_SPEED_LIMIT: Pass a long as a parameter that contains the transfer speed in bytes per second that the transfer should be below during CURLOPT_LOW_SPEED_TIME seconds for PHP to consider too slow and abort.

  • CURLOPT_LOW_SPEED_TIME: Pass a long as a parameter that contains the time in seconds that the transfer should be below the CURLOPT_LOW_SPEED_LIMIT for PHP to consider it too slow and abort.

  • CURLOPT_RESUME_FROM: Pass a long as a parameter that contains the offset, in bytes, that you want the transfer to start from.

  • CURLOPT_CAINFO: Pass a filename of a file holding one or more certificates to verify the peer with. This only makes sense when used in combination with the CURLOPT_SSL_VERIFYPEER option.

  • CURLOPT_SSL_VERIFYPEER: Pass a long that is set to a zero value to stop curl from verifying the peer's certificate (curl 7.10 starting setting this option to TRUE by default). Alternate certificates to verify against can be specified with the CURLOPT_CAINFO option (added in curl 7.9.8) or a certificate directory can be specified with the CURLOPT_CAPATH option. As of curl 7.10, curl installs a default bundle. CURLOPT_SSL_VERIFYHOST may also need to be set to 1 or 0 if CURLOPT_SSL_VERIFYPEER is disabled (it defaults to 2).

  • CURLOPT_SSLVERSION: Pass a long as a parameter that contains the SSL version (2 or 3) to use. By default PHP will try and determine this by itself, although, in some cases you must set this manually.

  • CURLOPT_SSL_VERIFYHOST: Pass a long if CURL should verify the Common name of the peer certificate in the SSL handshake. A value of 1 denotes that we should check for the existence of the common name, a value of 2 denotes that we should make sure it matches the provided hostname.

  • CURLOPT_TIMECONDITION: Pass a long as a parameter that defines how the CURLOPT_TIMEVALUE is treated. You can set this parameter to TIMECOND_IFMODSINCE or TIMECOND_ISUNMODSINCE. This is a HTTP-only feature.

  • CURLOPT_TIMEVALUE: Pass a long as a parameter that is the time in seconds since January 1st, 1970. The time will be used as specified by the CURLOPT_TIMECONDITION option, or by default the TIMECOND_IFMODSINCE will be used.

  • CURLOPT_RETURNTRANSFER: Pass a non-zero value if you want CURL to directly return the transfer instead of printing it out directly.

The value parameter should be a string for the following values of the option parameter:

  • CURLOPT_URL: This is the URL that you want PHP to fetch. You can also set this option when initializing a session with the curl_init() function.

  • CURLOPT_USERPWD: Pass a string formatted in the [username]:[password] manner, for PHP to use for the connection.

  • CURLOPT_PROXYUSERPWD: Pass a string formatted in the [username]:[password] format for connection to the HTTP proxy.

  • CURLOPT_RANGE: Pass the specified range you want. It should be in the "X-Y" format, where X or Y may be left out. The HTTP transfers also support several intervals, separated with commas as in X-Y,N-M.

  • CURLOPT_POSTFIELDS: Pass a string containing the full data to post in an HTTP "POST" operation.

  • CURLOPT_REFERER: Pass a string containing the "referer" header to be used in an HTTP request.

  • CURLOPT_USERAGENT: Pass a string containing the "user-agent" header to be used in an HTTP request.

  • CURLOPT_FTPPORT: Pass a string containing the value which will be used to get the IP address to use for the ftp "POST" instruction. The POST instruction tells the remote server to connect to our specified IP address. The string may be a plain IP address, a hostname, a network interface name (under Unix), or just a plain '-' to use the systems default IP address.

  • CURLOPT_COOKIE: Pass a string containing the content of the cookie to be set in the HTTP header.

  • CURLOPT_SSLCERT: Pass a string containing the filename of PEM formatted certificate.

  • CURLOPT_SSLCERTPASSWD: Pass a string containing the password required to use the CURLOPT_SSLCERT certificate.

  • CURLOPT_COOKIEFILE: Pass a string containing 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.

  • CURLOPT_CUSTOMREQUEST: Pass a string to be used instead of GET or HEAD when doing an HTTP request. This is useful for doing DELETE or other, more obscure, HTTP requests. Valid values are things like GET, POST, 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.

    Megjegyzés: Don't do this without making sure your server supports the command first.

  • CURLOPT_PROXY: Give the name of the HTTP proxy to tunnel requests through.

  • CURLOPT_INTERFACE: Pass the name of the outgoing network interface to use. This can be an interface name, an IP address or a host name.

  • CURLOPT_KRB4LEVEL: Pass 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, then 'private' is used. Setting this Option to NULL, will disable KRB4 security. Currently KRB4 security only works with FTP transactions.

  • CURLOPT_HTTPHEADER: Pass an array of HTTP header fields to set.

  • CURLOPT_QUOTE: Pass an array of FTP commands to perform on the server prior to the FTP request.

  • CURLOPT_POSTQUOTE: Pass an array of FTP commands to execute on the server, after the FTP request has been performed.

The following options expect a file descriptor that is obtained by using the fopen() function:

  • CURLOPT_FILE: The file where the output of your transfer should be placed, the default is STDOUT.

  • CURLOPT_INFILE: The file where the input of your transfer comes from.

  • CURLOPT_WRITEHEADER: The file to write the header part of the output into.

  • CURLOPT_STDERR: The file to write errors to instead of stderr.

curl_version

(PHP 4 >= 4.0.2)

curl_version -- Return the current CURL version

Description

string curl_version ( void )

The curl_version() function returns a string containing the current CURL version.

XIII. Cybercash payment függvények

Ezek a függvények csak akkor használhatóak, ha az értelmező a --with-cybercash=[DIR]-rel lett lefordítva. Ezek a függvények a PHP 4-ben használhatóak.

Tartalom
cybercash_base64_decode -- base64 kódolt adatot visszafejt Cybercash számára
cybercash_base64_encode -- base64 kódolja az adatot Cybercash számára
cybercash_decr -- cybercash visszafejtés
cybercash_encr -- cybercash titkosítás

cybercash_base64_decode

(PHP 4 <= 4.2.3)

cybercash_base64_decode -- base64 kódolt adatot visszafejt Cybercash számára

Leírás

string cybercash_base64_decode ( string inbuff)

cybercash_base64_encode

(PHP 4 <= 4.2.3)

cybercash_base64_encode -- base64 kódolja az adatot Cybercash számára

Leírás

string cybercash_base64_encode ( string inbuff)

cybercash_decr

(PHP 4 <= 4.2.3)

cybercash_decr -- cybercash visszafejtés

Leírás

array cybercash_decr ( string wmk, string sk, string inbuff)

A függvény egy asszociatív tömböt ad vissza az "errcode" elemmel, és ha az FALSE, akkor az "outbuff" (string), "outLth" (long) és "macbuff" (string) elemekkel.

cybercash_encr

(PHP 4 <= 4.2.3)

cybercash_encr -- cybercash titkosítás

Leírás

array cybercash_encr ( string wmk, string sk, string inbuff)

A függvény egy asszociatív tömböt ad vissza az "errcode" elemmel, és ha az FALSE, akkor az "outbuff" (string), "outLth" (long) és "macbuff" (string) elemekkel.

XIV. Cyrus IMAP administration functions

Bevezetés

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

Megjegyzés: Ez a kiterjesztés nem működik Windows operációs rendszereken!


Telepítés

To enable Cyrus IMAP support and to use these functions you have to compile PHP with the --with-cyrus option.


Előre definiált állandók

Az itt listázott állandókat ez a kiterjesztés definiálja, és csak akkor elérhetőek, ha az adott kiterjesztés be van fordítva a PHP-be, vagy dinamikusan betöltött.

CYRUS_CONN_NONSYNCLITERAL (integer)

CYRUS_CONN_INITIALRESPONSE (integer)

CYRUS_CALLBACK_NUMBERED (integer)

CYRUS_CALLBACK_NOLITERAL (integer)

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

cyrus_authenticate

(4.1.0 - 4.3.2 only)

cyrus_authenticate -- Authenticate against a Cyrus IMAP server

Description

bool cyrus_authenticate ( resource connection [, string mechlist [, string service [, string user [, int minssf [, int maxssf]]]]])

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

cyrus_bind

(4.1.0 - 4.3.2 only)

cyrus_bind -- Bind callbacks to a Cyrus IMAP connection

Description

bool cyrus_bind ( resource connection, array callbacks)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

cyrus_close

(4.1.0 - 4.3.2 only)

cyrus_close -- Close connection to a Cyrus IMAP server

Description

bool cyrus_close ( resource connection)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

cyrus_connect

(4.1.0 - 4.3.2 only)

cyrus_connect -- Connect to a Cyrus IMAP server

Description

resource cyrus_connect ( [string host [, string port [, int flags]]])

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

cyrus_query

(4.1.0 - 4.3.2 only)

cyrus_query -- Send a query to a Cyrus IMAP server

Description

bool cyrus_query ( resource connection, string query)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

cyrus_unbind

(4.1.0 - 4.3.2 only)

cyrus_unbind -- Unbind ...

Description

bool cyrus_unbind ( resource connection, string trigger_name)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

XV. Character type functions

Bevezetés

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.

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.

Passing anything else but a string or integer will return FALSE immediately.


Követelmények

None besides functions from the standard C library which are always available.


Telepítés

Beginning with PHP 4.2.0 these functions are enabled by default. For older versions you have to configure and compile PHP with --enable-ctype. You can disable ctype support with --disable-ctype.

A PHP Windowsos változata beépített támogatással rendelkezik eme kiterjesztéshez. nincs szükség semmilyen kiterjesztés betöltésére, hogy az itt felsorolt függvnyeket használhasd.

Megjegyzés: Builtin support for ctype is available with PHP 4.3.0.


Futásidejű beállítások

Ez a kiterjesztés semmilyen konfigurációs beállításokat nem definiál a php.ini állományban.


Erőforrás típusok

Ez a kiterjesztés semmilyen erőforrás típust nem definiál.


Előre definiált állandók

Ez a kiterjesztés semmilyen konstans értéket nem definiál.

Tartalom
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

ctype_alnum

(PHP 4 >= 4.0.4)

ctype_alnum -- Check for alphanumeric character(s)

Description

bool ctype_alnum ( string text)

Returns TRUE if every character in text is either a letter or a digit, FALSE otherwise. In the standard C locale letters are just [A-Za-z] and the function is equivalent to preg_match('/^[a-z0-9]*$/i', $text).

See also ctype_alpha(), ctype_digit(), and setlocale().

ctype_alpha

(PHP 4 >= 4.0.4)

ctype_alpha -- Check for alphabetic character(s)

Description

bool ctype_alpha ( string text)

Returns TRUE if every character in text is a letter from the current locale, FALSE otherwise. 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.

See also ctype_upper(), ctype_lower(), and setlocale().

ctype_cntrl

(PHP 4 >= 4.0.4)

ctype_cntrl -- Check for control character(s)

Description

bool ctype_cntrl ( string text)

Returns TRUE if every character in text has a special control function, FALSE otherwise. Control characters are e.g. line feed, tab, esc.

ctype_digit

(PHP 4 >= 4.0.4)

ctype_digit -- Check for numeric character(s)

Description

bool ctype_digit ( string text)

Returns TRUE if every character in text is a decimal digit, FALSE otherwise.

See also ctype_alnum() and ctype_xdigit().

ctype_graph

(PHP 4 >= 4.0.4)

ctype_graph -- Check for any printable character(s) except space

Description

bool ctype_graph ( string text)

Returns TRUE if every character in text is printable and actually creates visible output (no white space), FALSE otherwise.

See also ctype_alnum(), ctype_print(), and ctype_punct().

ctype_lower

(PHP 4 >= 4.0.4)

ctype_lower -- Check for lowercase character(s)

Description

bool ctype_lower ( string text)

Returns TRUE if every character in text is a lowercase letter in the current locale.

See also ctype_alpha() and ctype_upper().

ctype_print

(PHP 4 >= 4.0.4)

ctype_print -- Check for printable character(s)

Description

bool ctype_print ( string text)

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.

See also ctype_cntrl(), ctype_graph(), and ctype_punct().

ctype_punct

(PHP 4 >= 4.0.4)

ctype_punct --  Check for any printable character which is not whitespace or an alphanumeric character

Description

bool ctype_punct ( string text)

Returns TRUE if every character in text is printable, but neither letter, digit or blank, FALSE otherwise.

See also ctype_cntrl(), ctype_graph(), and ctype_punct().

ctype_space

(PHP 4 >= 4.0.4)

ctype_space -- Check for whitespace character(s)

Description

bool ctype_space ( string text)

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.

ctype_upper

(PHP 4 >= 4.0.4)

ctype_upper -- Check for uppercase character(s)

Description

bool ctype_upper ( string text)

Returns TRUE if every character in text is an uppercase letter in the current locale.

See also ctype_alpha() and ctype_lower().

ctype_xdigit

(PHP 4 >= 4.0.4)

ctype_xdigit --  Check for character(s) representing a hexadecimal digit

Description

bool ctype_xdigit ( string text)

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.

See also ctype_digit().

XVI. Database (dbm-style) abstraction layer functions

Bevezetés

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 Sleepycat Software's DB2. (This is not to be confused with IBM's DB2 software, which is supported through the ODBC functions.)


Követelmények

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.

Táblázat 1. List of DBA handlers

HandlerNotes
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 Sleepycat Software's DB2. 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 Sleepycat Software's DB3.
db4 DB4 is Sleepycat Software's DB4. This is available since PHP 4.3.2.
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://qdbm.sourceforge.net.

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


Telepítés

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.

Figyelem

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 malfaunctioning single handlers but not combinations.

Táblázat 2. Supported DBA handlers

HandlerConfigure Switch
dbm To enable support for dbm add --with-dbm[=DIR].

Megjegyzés: 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].

Megjegyzés: 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 db2 add --with-db2[=DIR].

Megjegyzés: db2 conflicts with db3 and db4.

db3 To enable support for db3 add --with-db3[=DIR].

Megjegyzés: db3 conflicts with db2 and db4.

db4 To enable support for db4 add --with-db4[=DIR].

Megjegyzés: db4 conflicts with db2 and db3.

Megjegyzés: This 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.

cdb To enable support for cdb add --with-cdb[=DIR].

Megjegyzés: 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.

Megjegyzés: 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.

Megjegyzés: 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].

Megjegyzés: qdbm conflicts with dbm and gdbm.

Megjegyzés: This was added in PHP 5.0.0. The qdbm library can be loaded from http://qdbm.sourceforge.net.

Megjegyzés: 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 missconfigurations.


Futásidejű beállítások

Ez a kiterjesztés semmilyen konfigurációs beállításokat nem definiál a php.ini állományban.


Erőforrás típusok

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.


Előre definiált állandók

Ez a kiterjesztés semmilyen konstans értéket nem definiál.


Példák

Példa 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.

Példa 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);
}

for ($i = 0; $i < count($handle_later); $i++) {
    dba_delete($handle_later[$i], $id);
}

?>

Tartalom
dba_close -- Close database
dba_delete -- Delete 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 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

dba_close

(PHP 3>= 3.0.8, PHP 4 )

dba_close -- Close database

Description

void dba_close ( resource handle)

dba_close() closes the established database and frees all resources specified by handle.

handle is a database handle returned by dba_open().

dba_close() does not return any value.

See also: dba_open() and dba_popen()

dba_delete

(PHP 3>= 3.0.8, PHP 4 )

dba_delete -- Delete entry specified by key

Description

bool dba_delete ( string key, resource handle)

dba_delete() deletes the entry specified by key from the database specified with handle.

key is the key of the entry which is deleted.

handle is a database handle returned by dba_open().

dba_delete() returns TRUE or FALSE, if the entry is deleted or not deleted, respectively.

See also: dba_exists(), dba_fetch(), dba_insert(), and dba_replace().

dba_exists

(PHP 3>= 3.0.8, PHP 4 )

dba_exists -- Check whether key exists

Description

bool dba_exists ( string key, resource handle)

dba_exists() checks whether the specified key exists in the database specified by handle.

Key is the key the check is performed for.

Handle is a database handle returned by dba_open().

dba_exists() returns TRUE or FALSE, if the key is found or not found, respectively.

See also: dba_fetch(), dba_delete(), dba_insert(), and dba_replace().

dba_fetch

(PHP 3>= 3.0.8, PHP 4 )

dba_fetch -- Fetch data specified by key

Description

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.

Key is the key the data is specified by.

Skip is 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 is a database handle returned by dba_open().

dba_fetch() returns the associated string or FALSE, if the key/data pair is found or not found, respectively.

See also: dba_exists(), dba_delete(), dba_insert(), dba_replace() and dba_key_split().

Megjegyzés: The skip parameter is available since PHP 4.3 to support cdb's capability of multiple keys having the same name.

Megjegyzés: 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().

dba_firstkey

(PHP 3>= 3.0.8, PHP 4 )

dba_firstkey -- Fetch first key

Description

string dba_firstkey ( resource handle)

dba_firstkey() returns the first key of the database specified by handle and resets the internal key pointer. This permits a linear search through the whole database.

Handle is a database handle returned by dba_open().

dba_firstkey() returns the key or FALSE depending on whether it succeeds or fails, respectively.

See also: dba_firstkey(), dba_key_split() and example 2 in the DBA examples

dba_handlers

(PHP 4 >= 4.3.0)

dba_handlers -- List handlers available

Description

array dba_handlers ( void )

dba_handlers() returns an array with all handlers supported by this extension.

When the internal cdb library is used you will see 'cdb' and 'cdb_make'.

dba_insert

(PHP 3>= 3.0.8, PHP 4 )

dba_insert -- Insert entry

Description

bool dba_insert ( string key, string value, resource handle)

dba_insert() inserts the entry described with key and value into the database specified by handle. It fails, if an entry with the same key already exists.

key is the key of the entry to be inserted.

value is the value to be inserted.

handle is a database handle returned by dba_open().

dba_insert() returns TRUE or FALSE, depending on whether it succeeds of fails, respectively.

See also: dba_exists() dba_delete() dba_fetch() dba_replace()

dba_key_split

(no version information, might be only in CVS)

dba_key_split -- Splits a key in string representation into array representation

Description

mixed dba_key_split ( mixed key)

dba_key_split() returns an array of the form array(0=>group,1=>value_name). This function will return FALSE if key is NULL or FALSE.

key is the key in string representation.

See also dba_firstkey(), dba_nextkey() and dba_fetch().

dba_list

(PHP 4 >= 4.3.0)

dba_list -- List all open database files

Description

array dba_list ( void )

dba_list() returns an associative array with all open database files. This array is in the form: resourceid=>filename.

dba_nextkey

(PHP 3>= 3.0.8, PHP 4 )

dba_nextkey -- Fetch next key

Description

string dba_nextkey ( resource handle)

dba_nextkey() returns the next key of the database specified by handle and advances the internal key pointer.

handle is a database handle returned by dba_open().

dba_nextkey() returns the key or FALSE depending on whether it succeeds or fails, respectively.

See also: dba_firstkey(), dba_key_split() and example 2 in the DBA examples

dba_open

(PHP 3>= 3.0.8, PHP 4 )

dba_open -- Open database

Description

resource dba_open ( string path, string mode, string handler [, ...])

dba_open() establishes a database instance for path with mode using handler.

path is commonly a regular path in your filesystem.

mode 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. Additional you can set the database lock method with the next char. Use "l" to lock the database with an .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".

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

dba_open() returns a positive handle or FALSE, in the case the database was opened successfull or fails, respectively.

Megjegyzés: There can only be one writer for one database file. When you use dba on a webserver 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:

Táblázat 1. DBA locking

already openmode = "rl"mode = "rlt"mode = "wl"mode = "wlt"mode = "rd"mode = "rdt"mode = "wd"mode = "wdt"
not openokokokokokokokok
mode = "rl"okokwaitfalseillegalillegalillegalillegal
mode = "wl"waitfalsewaitfalseillegalillegalillegalillegal
mode = "rd"illegalillegalillegalillegalokokwaitfalse
mode = "wd"illegalillegalillegalillegalwaitfalsewaitfalse

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.

Megjegyzés: Since PHP 4.3.0 it is 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.

Megjegyzés: Locking and the mode modifiers "l", "d", "-" and "t" were added in PHP 4.3.0. In PHP versions before PHP 4.3.0 you must use semaphores to guard against simultaneous database access for any database handler with the exception of GDBM. See System V semaphore support.

Megjegyzés: Up to PHP 4.3.5 open mode 'c' is broken for several internal handlers and truncates the database instead of appending data to an existant database. Also dbm and ndbm fail on mode 'c' in typical configurations (this cannot be fixed).

See also: dba_popen() dba_close()

dba_optimize

(PHP 3>= 3.0.8, PHP 4 )

dba_optimize -- Optimize database

Description

bool dba_optimize ( resource handle)

dba_optimize() optimizes the underlying database specified by handle.

handle is a database handle returned by dba_open().

dba_optimize() returns TRUE or FALSE, if the optimization succeeds or fails, respectively.

See also: dba_sync()

dba_popen

(PHP 3>= 3.0.8, PHP 4 )

dba_popen -- Open database persistently

Description

resource dba_popen ( string path, string mode, string handler [, ...])

dba_popen() establishes a persistent database instance for path with mode using handler.

path is commonly a regular path in your filesystem.

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

dba_popen() returns a positive handle or FALSE, in the case the open is successful or fails, respectively.

See also: dba_open() dba_close()

dba_replace

(PHP 3>= 3.0.8, PHP 4 )

dba_replace -- Replace or insert entry

Description

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.

key is the key of the entry to be inserted.

value is the value to be inserted.

handle is a database handle returned by dba_open().

dba_replace() returns TRUE or FALSE, depending on whether it succeeds of fails, respectively.

See also: dba_exists(), dba_delete(), dba_fetch(), and dba_insert().

dba_sync

(PHP 3>= 3.0.8, PHP 4 )

dba_sync -- Synchronize database

Description

bool dba_sync ( resource handle)

dba_sync() synchronizes the database specified by handle. This will probably trigger a physical write to disk, if supported.

handle is a database handle returned by dba_open().

dba_sync() returns TRUE or FALSE, if the synchronization succeeds or fails, respectively.

See also: dba_optimize()

XVII. Dátummal és időponttal kapcsolatos függvények

Tartalom
checkdate -- Ellenőriz egy időpontot
date -- Egy időpontstringgel tér vissza
getdate -- Dátum/idő információ
gettimeofday -- Aktuális idő lekérése[???]
gmdate -- Egy GMT/CUT időponttal tér vissza
gmmktime -- GMT formátumú UNIX időbélyeggel tér vissza
gmstrftime --  Az aktuális helyi időből számított GMT/CUT időpontot ad vissza.
localtime -- Helyi időpontot állít elő
microtime --  Az aktuális UNIX időbélyeget állítja elő mikroszekundumban
mktime -- Egy időpont UNIX időbélyegét állítja elő
strftime --  Helyi időstringet formáz a megadott formátum (és időpont) szerint
strtotime --  Mindenféle angol szöveges időpontot UNIX időbélyeggé alakít
time -- Az aktuális UNIX időbélyeget számolja ki

checkdate

(PHP 3, PHP 4 )

checkdate -- Ellenőriz egy időpontot

Leírás

bool checkdate ( int month, int day, int year)

Visszatérési értéke TRUE, ha az argumentumban megadott dátum érvényes, egyébként FALSE. Egy dátum érvénes, ha:

  • az év 1 és 32767 között van

  • a hónap 1 és 12 között van

  • A day paraméter a month és a year paramétereknek megfelelő értéket vesz fel. (Szökőéveket természetesen helyesen kezeli)

Lásd még a mktime() és a strtotime() függvényt!

date

(PHP 3, PHP 4 )

date -- Egy időpontstringgel tér vissza

Leírás

string date ( string format [, int timestamp])

Egy stringgel tér vissza, amely a formátumstring szerinti alakban tartalmazza a timestamp dátumot, ennek hiányában az aktuális helyi időt.

Megjegyzés: Az időpont érvényes időpontja tipikusan 1901 Dec. 13. 20:25:54 és 2038. Jan. 19. 03:14:07 közötti időpontot jelent (Greenwich-i időpont szerint) (Ezek a dátumok a legkisebb és a legnagyobb 32-bites egész szám által reprezentált dátumok)

Ha egy karakterlánc által leírt időpontból szeretnél időpontot gyártani, akkor használhatod a strtotime() függvényt. Ráadásul, néhány adatbázisnak van rá függvénye, hogy a belső időpont-ábrázolásukat "unix timestamp"-pé alakítják (a MySQL UNIX_TIMESTAMP függvénye ilyen).

A formátum stringben a következő karakterek lehetnek:

  • a - "am" vagy "pm" (délelőtt vagy délután)

  • A - "AM" vagy "PM" (ugyanez nagybetűvel)

  • B - Swatch Internet time

  • d - nap, 2 számjegyű (előtte 0, ha kell) pl.: "01" .. "31"

  • D - a hét napja, betűvel, 3 betűs (angol[?]); pl.: "Fri"

  • F - hónap, betűvel, hosszú (angol); pl.:"January"

  • g - óra, 12-órás formátumban, "felesleges" nullák nélkül; pl.: "1" .. "12"

  • G - óra, 24-órás formátumban, "felesleges" nullák nélkül; pl.: "0" .. "23"

  • h - óra, 12-órás formátumban (2 számjegy); pl.: "01" .. "12"

  • H - óra, 24-órás formátumban (2 számjegy); pl.: "00" .. "23"

  • i - perc (2 számjegy); pl.: "00" .. "59"

  • I (Nagy i) - "1" a nyári időszámítás alatt, "0" egyébként.

  • j - nap, számmal, "felesleges" nullák nélkül; pl.: "1" .. "31"

  • l (kis 'L') - hét napja, betűvel, hosszú; pl.: "Friday"

  • L - logikai változó, jelzi, hogy szökőév van-e vagy se; pl.: "0" vagy "1"

  • m - hónap, számmal (2 számjegy); pl.: "01" .. "12"

  • M - hónap, betűvel, 3 betűs; pl.: "Jan"

  • n - hónap, számmal, "felesleges" nullák nélkül; pl.: "1" .. "12"

  • O - Különbség a Greenwich-i időhöz képest; pl.: "+0200"

  • r - RFC 822 formátumú dátum; pl: "Thu, 21 Dec 2000 16:01:07 +0200" (PHP 4.0.4 óta)

  • s - másodperc; pl.: "00" .. "59"

  • S - angol "sorszámnév-string" a hónap napjának megfelelően, betűvel, két karakteren; például "th", "nd"

  • t - napok száma az adott hónapban; pl.: "28" .. "31"

  • T - A gép időzóna-beállítása; pl. "MDT"

  • U - eltelt másodpercek száma a UNIX Epoch óta (1970. 01. 01.)

  • w - hét napja, számmal, pl.: "0" (Vasárnap) .. "6" (Szombat)

  • W - ISO-8601 hét szám; a hetek hétfőn kezdődnek (PHP 4.1.0-tól) [mi szombat???]

  • Y - év, 4 számjegy; pl.: "1999"

  • y - év, 2 számjegy; pl.: "99"

  • z - január 1 óta eltelt napok száma; pl.: "0" .. "365"

  • Z - időzóna eltolódás másodpercben(pl.: "-43200" .. "43200"). Az időzónák az UTC-től nyugatra mindig negatívak, keletre mindig pozitívak.

A formátumstringben levő, egyéb karakterek egy az egyben megjelennek. A "Z" betű mindig "0"-val tér vissza, ha a gmdate()-et használjuk.

Példa 1. date() példa

echo (date ("l dS of F Y h:i:s A"));
echo "July 1, 2000 is on a " . date ("l", mktime(0,0,0,7,1,2000));

A felismert karaktereket a formátumstringben backslash-sel tudod megvédeni. Ha a karakter backslash karakter után is speciális jelentéssel bír, akkor a backslash-t is meg kell védeni a kiértékeléstől.

Példa 2. Karakterek megvédése a date() függvényben

echo date("l \\t\h\e jS"); // Valami olyasmit ír ki, hogy 'Saturday the 8th'

A date()-et és a mktime()-ot ügyesen együtt használva információt szerezhetsz múltbeli és jövőbeli időpontokról.

Példa 3. date() és mktime() példa

$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);
# ezek mind működnek hónap végén, ill. januárban is. Ha nem hiszed, próbáld ki!

Megjegyzés: Ez sokkal megbízhatóbb, mint az időbélyegekkel számolni (gondolj a téli-nyári időszámításkori átállásokra)

Néhány példa a date() függvény formázására. Figyeld meg, hogy az összes karaktert meg kell védened a kiértékeléstől, nem csupán azokat, amlyeknek már most speciális jelentésük van, ugyanis egy jövőbeli PHP változatban ezek is jelentést kaphatnak. Amikor egy karaktert megvédesz az értelmezéstől, használj aposztrófokat a karakterlánc megadására, hogy pl. a \n újsorokká történő átalakítását megakadályozd.

Példa 4. A date() függvyény formátumstringje

/* Tegyük fel, hogy most March 10th, 2001, 5:16:18 pm  van*/
$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 z ');  // 05-16-17, 10-03-01, 1631 1618 6 Fripm01
$today = date('\M\a \a \h\ó\n\a\p j. \n\a\p\j\a \v\a\n.');   // Ma a hónap 10. napja van
$today = date("D M j G:i:s T Y");               // Sat Mar 10 15:16:08 MST 2001
$today = date('H:m:s \m = \h\ó\n\a\p');         // 17:03:17 m = hónap
$today = date("H:i:s");                         // 17:16:17

Ha a dátumokat más nyelven szeretnéd megkapni, használd a setlocale() és a strftime() függvényeket.

Lásd még a getlastmod(), gmdate(), mktime(), strftime() és a time() függvényeket.

getdate

(PHP 3, PHP 4 )

getdate -- Dátum/idő információ

Leírás

array getdate ( [int timestamp])

A timestamp-ben megadott időpontról (vagy a jelen pillanatról, ha nincs időpont megadva) ad információt asszociatív tömb formájában. A következő elemeket tartalmazza:

  • "seconds" - másodperc

  • "minutes" - perc

  • "hours" - óra

  • "mday" - nap

  • "wday" - hét napja, számmal (Vasárnap a 0, szombat a 6)

  • "mon" - hónap, számmal

  • "year" - év, számmal [miért, mással is lehet?]

  • "yday" - január 1 óta eltelt napok száma, számmal [detto]; pl.: "299"

  • "weekday" - hét napja, számmal, full; pl.: "Friday"

  • "month" - hónap, betűvel, teljes; pl.: "January"

Példa 1. getdate() példa

$today = getdate();
$month = $today['month'];
$mday = $today['mday'];
$year = $today['year'];
echo "$month $mday, $year";

gettimeofday

(PHP 3>= 3.0.7, PHP 4 )

gettimeofday -- Aktuális idő lekérése[???]

Leírás

array gettimeofday ( void )

Ez egy felület a gettimeofday(2)-höz. Egy asszociatív tömbbel tér vissza, tartalmazza a rendszerhívásból származó adatokat [??]

  • "sec" - másodperc

  • "usec" - mikroszekundum ["mikromásodperc"]

  • "minuteswest" - hány percet kell hozzáadni a helyi időhöz, hogy a Greenwichit kapjuk

  • "dsttime" - nyári időszámítási korrekció típusa [???]

gmdate

(PHP 3, PHP 4 )

gmdate -- Egy GMT/CUT időponttal tér vissza

Leírás

string gmdate ( string format [, int timestamp])

Azonos a date() függvénnyel, kivéve, hogy az időpont Greenwichi idő szerint van(GMT). Például, ha Finnországban fut (GMT +0200), az első sor lent kiírja, hogy "Jan 01 1998 00:00:00", míg a második pedig azt, hogy "Dec 31 1997 22:00:00".

Példa 1. gmdate() példa

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

Lásd még a date(), mktime(), gmmktime() és a strftime() függvényeket.

gmmktime

(PHP 3, PHP 4 )

gmmktime -- GMT formátumú UNIX időbélyeggel tér vissza

Leírás

int gmmktime ( int hour, int minute, int second, int month, int day, int year [, int is_dst])

Azonos a mktime() függvénnyel, kivéve, hogy az átadott paraméterek GMT időpontként értelmezettek.

gmstrftime

(PHP 3>= 3.0.12, PHP 4 )

gmstrftime --  Az aktuális helyi időből számított GMT/CUT időpontot ad vissza.

Leírás

string gmstrftime ( string format [, int timestamp])

A strftime()-hoz hasonlóan viselkedik, kivéve, hogy a függvény által visszaadott időpont GMT formátumban van. Például, ha "Keleti Standard Idő"-ben(GMT -0500) vagyunk, a következő sor kiírja, hogy "Dec 31 1998 20:00:00", míg a második azt írja ki, hogy "Jan 01 1999 01:00:00".

Példa 1. gmstrftime() példa

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

Lásd még a strftime() függvényt.

localtime

(PHP 4 )

localtime -- Helyi időpontot állít elő

Leírás

array localtime ( [int timestamp [, bool is_associative]])

A localtime() függvény egy tömböt ad vissza, ugyanolyan szerkezetben, mint azt a C nyelvbeli függvényhívás teszi. A localtime() függvény első argumentuma az időbélyeg; ha nincs megadva, az aktuális időt használja. A második argumentum az is_associative, ha 0, vagy nincs megadva, hagyományos tömböt (numerikusan indexelve) kapunk vissza. Ha az argumentum 1, akkor a localtime() függvény asszociatív tömböt ad vissza, tartalmazva az összes elemet olyan struktúrában, amint azt a C függvénye is teszi a localtime függvényben. Az asszociatív tömb kulcsainak nevei a következők:

  • "tm_sec" - másodperc

  • "tm_min" - perc

  • "tm_hour" - óra

  • "tm_mday" - nap

  • "tm_mon" - hónap (!!! A Január 0 !!!)

  • "tm_year" - év, az 1900 óta eltelt évek száma

  • "tm_wday" - hét napja

  • "tm_yday" - év napja - 1

  • "tm_isdst" - nyári időszámítás aktív-e

microtime

(PHP 3, PHP 4 )

microtime --  Az aktuális UNIX időbélyeget állítja elő mikroszekundumban

Leírás

string microtime ( void )

Visszatér egy stringgel, melynek formája "msec sec", ahol sec az Unix Epoch (0:00:00 January 1, 1970 GMT) óta eltelt másodpercek száma, és msec a mikroszekundumok száma. Ez a függvény csak olyan operációs rendszereken elérhető, amely támogatja a gettimeofday() rendszerhívást.

Mindkét részt másodpercben kapod meg.

Példa 1. microtime() example

function getmicrotime(){
    list($usec, $sec) = explode(" ",microtime());
    return ((float)$usec + (float)$sec);
    }

$time_start = getmicrotime();

for ($i=0; $i < 1000; $i++){
  // helyben járunk 1000-szer
}

$time_end = getmicrotime();
$time = $time_end - $time_start;

echo "Helyben jártunk $time másodpercig";

Lásd még time() függvényt.

mktime

(PHP 3, PHP 4 )

mktime -- Egy időpont UNIX időbélyegét állítja elő

Leírás

int mktime ( int hour, int minute, int second, int month, int day, int year [, int is_dst])

Figyeljé!!! Nézd meg, hogy az argumentumok sorrendje nem éppen szokásos, mert különbözik a hagyományos UNIX-os mktime()-étól, ezért nem igazán alkalmas arra, hogy lehagyd az utolsó néhány paramétert. Gyakori hiba scriptekben az argumentumok felcserélése.

Az argumentumok által megadott időpont UNIX időbélyegét adja. Ez tulajdonképpen egy nagy egész szám, a Unix Epoch (1970 Január 1.) és az adott idő közt eltelt másodpercek száma.

Jobbról elhagyhatsz argumentumokat; ezeket a php az aktuális helyi dátum és idő alapján pótolja.

Az Is_dst paramétert állíthatod 1-re, jelezve, hogy a nyári időszámításban vagy, 0-ra, hogy nem, vagy -1-re (ez az alapértelmezett), ha nem tudod.

Megjegyzés: Az Is_dst paraméter a 3.0.10.-es verzióban került a nyelvbe.

A mktime() függvény hasznos a dátumokkal való manipulálás, illetve dátumellenőrzés során, mivel automatikusan "korrekt" dátummá konvertálja a helytelenül megadott bemenetet.Példaul, az alábbi sorok mindegyike azt írja ki, hogy "Jan-01-1998".

Példa 1. mktime() példa

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));
A year 2 vagy 4 jegyű szám is lehet, ha értéke 0-69 között van, akkor a gép 2000-2069 közé teszi, ha 70-99 között van, 1970-1999-be rakja. (Azon rendszereken, ahol a time_t 32 bites egész, ami manapság a legelterjedtebb, a year paraméter helyes értéke kb. 1902 és 2037 között van).

Adott hónap utolsó napját a következő hónap "0." napjával fejezhetjük ki (NEM a -1.-kel!!!). Az alábbi két példa mind azt írja ki, hogy "2000 februárjának utolsó napja: 29".

Példa 2. Last day of next month

$lastday = mktime (0,0,0,3,0,2000);
echo strftime ("2000 februárjának utolsó napja: %d", $lastday);

$lastday = mktime (0,0,0,4,-31,2000);
echo strftime ("2000 februárjának utolsó napja: %d", $lastday);

Az olyan dátum, amelyben az év, hónap, és a nap is nulla, nem legális (máskülönben 1999. 11. 30.-ának kellene tekinteni, ami furcsa viselkedés lenne)

Lásd még a date() és a time() függvényeket.

strftime

(PHP 3, PHP 4 )

strftime --  Helyi időstringet formáz a megadott formátum (és időpont) szerint

Leírás

string strftime ( string format [, int timestamp])

A megadott formátumstringnek megfelelően formázott dátum-stringgel tér vissza, felhasználva a megadott timestamp paramétert, vagy ennek hiányában a helyi időt. Hónap, és napnevek, továbbá más nyelvfüggő stringek az setlocale() függvénnyel beállított értékeknek felelnek meg.

Az alábbi formátumstringeket ismeri fel a függvény:

  • %a - hét napja, rövidítve

  • %A - hét napja, teljes

  • %b - hónap neve, rövidítve

  • %B - hónap neve, teljes

  • %c - dátum és idő alapértelmezett formátumban

  • %C - évszám 2 utolsó jegy nélkül (trunc(év/100), értéke 00 és 99 között)

  • %d - nap, 2 számjegy ("01" .. "31")

  • %D - azonos %m/%d/%y-val

  • %e - nap, 2 karakter, extra szóközzel az egyjegyű számok előtt (" 1" .. "31")

  • %g - mint a %G, csak évszázad nélkül

  • %G - A 4-jegyű évszám, ami az ISO hétszámhoz tartozik (lásd a %V opciót). Ez azonos formátumú és értékű, mint a %Y, kivéve, hogy ha az ISO hétszám az előző, vagy a következő évhez tartozik, akkor azzal az évet adja.

  • %h - ugyanaz, mint a %b

  • %H - óra, 24-órás formátumban, 2 számjeggyel ("00" .. "23")

  • %I - óra, 12-órás formátumban, 2 számjeggyel ("01" .. "12")

  • %j - év napja, 3 számjegy ("001" .. "366" !!!)

  • %m - hónap, számmal ("01" .. "12") [van kitöltő szóköz]

  • %M - perc, [2 számjegy]

  • %n - újsor karakter

  • %p - `am' vagy `pm', annak megfelelően, hogy az adott időpont délelőtt, vagy délután van-e

  • %r - időpont 12 órás formátumban [pl.: 12:00:00 AM]

  • %R - időpont 24 órás formátumban [pl.: 00:00][Itt nincs másodperc!!!]

  • %S - másodperc [2 számjegy]

  • %t - tabulátor

  • %T - idő, azonos a %H:%M:%S-val

  • %u - hét napja, számmal [1,7], az 1 a hétfőt jelenti

    Figyelem

    Úgy tűnik, hogy Sun Solarison a vasárnap az 1-es, holott az ISO 9889:1999 (az aktuális C standard) világosan megmondja, hogy hétfőnek kell lennie.

  • %U - az aktuális év hányadik hetében járunk, a hét vasárnappal kezdődik, vagyis az "01" hét január első vasárnapján kezdődik. [Az első hét előtti napokat "00" hétnek jelzi!!!]

  • %V - Az ISO 8601:1988 hétszám ("01" .. 53), ahol az az első hét, amelynek legalább 4 napja van az újévben. A hét első napja hétfő. Használd a %G-t vagy a %g-t, ha egy év kell, ami egy időbélyeg hétszámához tartozik. [???] [Helyesen kezeli az előző évből átnyúló heteket is]

  • %W - év hete, az év első hétfőjén kezdődik az "01" hét

  • %w - hét napja számmal, a vasárnap a 0

  • %x - alapértelmezett dátumformátum idő nélkül

  • %X - alapértelmezett időpontformátum dátum nélkül

  • %y - év 2 számjeggyel ("00" .. "99")

  • %Y - év, évszázaddal együtt

  • %Z - időzóna neve [3 betű]

  • %% - a `%' karakter

Megjegyzés: Nem minden formátumstring van meg az összes C könyvtárban, ami azt jelenti, hogy a PHP strftime() függvényében sem lesznek elérhetők.

Példa 1. strftime() példa

setlocale (LC_TIME, "C");
print (strftime ("A finnül "));
setlocale (LC_TIME", "fi_FI");
print (strftime ("%A, franciául "));
setlocale (LC_TIME, "fr_FR");
print (strftime ("%A és magyarul "));
setlocale (LC_TIME, "hu_HU");
print (strftime ("%A.\n"));
Ez a példa akkor működik jól, ha a megfelelő locales beállításokat installálod.

Lásd még setlocale() és mktime() és az Open Group specification of strftime()() függvényeket.

strtotime

(PHP 3>= 3.0.12, PHP 4 )

strtotime --  Mindenféle angol szöveges időpontot UNIX időbélyeggé alakít

Leírás

int strtotime ( string time [, int now])

A függvény egy stringet vár, amiben egy angolul írt dátum van, és megpróbálja UNIX időbélyeggé konvertálni, a now paramétert, vagy ha az nincs megadva, az aktuális időpontot figyelembe véve. Ha a függvény nem tudja értelmezni a karakterláncot, -1-gyel tér vissza.

Mivel a strtotime() függvény a GNU dátum szintaxisnak megfelelően viselkedik, nézd meg a Date Input Formats című oldalakat a unix kézikönyvben (man). Ott le van írva a time paraméter pontos szintaxisa.

Példa 1. strtotime() példa

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

Példa 2. Meghiúsulás-próba

$str = 'Nem jó';
if (($idobelyeg = strtotime($str)) === -1) {
    echo "A string ($str) fura, nem értem";
} else {
echo "$str == ". date('l dS of F Y h:i:s A',$idobelyeg);
}

Megjegyzés: Az időpont érvényes időpontja tipikusan 1901 Dec. 13. 20:25:54 és 2038. Jan. 19. 03:14:07 közötti időpontot jelent (Greenwich-i időpont szerint) (Ezek a dátumok a legkisebb és a legnagyobb 32-bites egész szám által reprezentált dátumok)

time

(PHP 3, PHP 4 )

time -- Az aktuális UNIX időbélyeget számolja ki

Leírás

int time ( void )

A Unix Epoch (January 1 1970 00:00:00 GMT) óta eltelt másodpercek számát adja vissza.

Lásd még a date() függvényt.

XVIII. dBase functions

Bevezetés

These functions allow you to access records stored in dBase-format (dbf) databases.

There is no support for indexes or memo fields. There is no support for locking, too. Two concurrent webserver processes modifying the same dBase file will very likely ruin your database.

dBase files are simple sequential files of fixed length records. Records are appended to the end of the file and delete records are kept until you call dbase_pack().

We recommend that you do not use dBase files as your production database. Choose any real SQL server instead; MySQL or Postgres are common choices with PHP. dBase support is here to allow you to import and export data to and from your web database, because the file format is commonly understood by Windows spreadsheets and organizers.


Telepítés

In order to enable the bundled dbase library and to use these functions, you must compile PHP with the --enable-dbase option.


Futásidejű beállítások

Ez a kiterjesztés semmilyen konfigurációs beállításokat nem definiál a php.ini állományban.


Erőforrás típusok

Ez a kiterjesztés semmilyen erőforrás típust nem definiál.


Előre definiált állandók

Ez a kiterjesztés semmilyen konstans értéket nem definiál.

Tartalom
dbase_add_record -- Add a record to a dBase database
dbase_close -- Close a dBase database
dbase_create -- Creates a dBase database
dbase_delete_record -- Deletes a record from a dBase database
dbase_get_header_info -- Get the header info of a dBase database
dbase_get_record_with_names --  Gets a record from a dBase database as an associative array
dbase_get_record -- Gets a record from a dBase database
dbase_numfields --  Find out how many fields are in a dBase database
dbase_numrecords --  Find out how many records are in a dBase database
dbase_open -- Opens a dBase database
dbase_pack -- Packs a dBase database
dbase_replace_record -- Replace a record in a dBase database

dbase_add_record

(PHP 3, PHP 4 )

dbase_add_record -- Add a record to a dBase database

Description

bool dbase_add_record ( int dbase_identifier, array record)

Adds the data in the record to the database. If the number of items in the supplied record isn't equal to the number of fields in the database, the operation will fail and FALSE will be returned.

dbase_close

(PHP 3, PHP 4 )

dbase_close -- Close a dBase database

Description

bool dbase_close ( int dbase_identifier)

Closes the database associated with dbase_identifier.

dbase_create

(PHP 3, PHP 4 )

dbase_create -- Creates a dBase database

Description

int dbase_create ( string filename, array fields)

dbase_create() creates a dBase database in the file filename, with the fields fields.

The fields parameter is an array of arrays, each array describing the format of one field in the database. Each field consists of a name, a character indicating the field type, a length, and a precision.

The types of fields available are:

L

Boolean. These do not have a length or precision.

M

Memo. (Note that these aren't supported by PHP.) These do not have a length or precision.

D

Date (stored as YYYYMMDD). These do not have a length or precision.

N

Number. These have both a length and a precision (the number of digits after the decimal point).

C

String.

If the database is successfully created, a dbase_identifier is returned, otherwise FALSE is returned.

Példa 1. Creating a dBase database file

<?php

// "database" name
$dbname = "/tmp/test.dbf";

// 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($dbname, $def))
    echo "<strong>Error!</strong>";

?>

dbase_delete_record

(PHP 3, PHP 4 )

dbase_delete_record -- Deletes a record from a dBase database

Description

bool dbase_delete_record ( int dbase_identifier, int record)

Marks record to be deleted from the database. To actually remove the record from the database, you must also call dbase_pack().

dbase_get_header_info

(no version information, might be only in CVS)

dbase_get_header_info -- Get the header info of a dBase database

Description

array dbase_get_header_info ( int dbase_identifier)

Returns information on the column structure of the database referenced by dbase_identifier. For each column in the database, there is an entry in a numerically-indexed array. The array index starts at 0. Each array element contains an associative array of column information. If the database header information cannot be read, FALSE is returned.

The array elements are:

name

The name of the column

type

The human-readable name for the dbase type of the column (i.e. date, boolean, etc)

length

The number of bytes this column can hold

precision

The number of digits of decimal precision for the column

format

A suggested printf() format specifier for the column

offset

The byte offset of the column from the start of the row

Példa 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)
    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_get_record_with_names

(PHP 3>= 3.0.4, PHP 4 )

dbase_get_record_with_names --  Gets a record from a dBase database as an associative array

Description

array dbase_get_record_with_names ( int dbase_identifier, int record)

Returns the data from record in an associative array. The array also includes an associative member named 'deleted' which is set to 1 if the record has been marked for deletion (see dbase_delete_record()).

Each field is converted to the appropriate PHP type, except:

  • Dates are left as strings

  • Integers that would have caused an overflow (> 32 bits) are returned as strings

dbase_get_record

(PHP 3, PHP 4 )

dbase_get_record -- Gets a record from a dBase database

Description

array dbase_get_record ( int dbase_identifier, int record)

Returns the data from record in an array. The array is indexed starting at 0, and includes an associative member named 'deleted' which is set to 1 if the record has been marked for deletion (see dbase_delete_record().

Each field is converted to the appropriate PHP type, except:

  • Dates are left as strings

  • Integers that would have caused an overflow (> 32 bits) are returned as strings

dbase_numfields

(PHP 3, PHP 4 )

dbase_numfields --  Find out how many fields are in a dBase database

Description

int dbase_numfields ( int dbase_identifier)

Returns the number of fields (columns) in the specified database. Field numbers are between 0 and dbase_numfields($db)-1, while record numbers are between 1 and dbase_numrecords($db).

Példa 1. Using dbase_numfields()

<?php

$rec = dbase_get_record($db, $recno);
$nf  = dbase_numfields($db);
for ($i=0; $i < $nf; $i++) {
    echo $rec[$i]."<br />\n";
}

?>

dbase_numrecords

(PHP 3, PHP 4 )

dbase_numrecords --  Find out how many records are in a dBase database

Description

int dbase_numrecords ( int dbase_identifier)

Returns the number of records (rows) in the specified database. Record numbers are between 1 and dbase_numrecords($db), while field numbers are between 0 and dbase_numfields($db)-1.

dbase_open

(PHP 3, PHP 4 )

dbase_open -- Opens a dBase database

Description

int dbase_open ( string filename, int flags)

Returns a dbase_identifier for the opened database, or FALSE if the database couldn't be opened.

Parameter flags correspond to those for the open() system call (Typically 0 means read-only, 1 means write-only, and 2 means read and write).

Megjegyzés: Ha a safe mode be van kapcsolva, a PHP ellenőrzi, hogy az állományok vagy könyvtárak, amelyekkel dolgozni szeretnél, ugyanazzal a felhasználói azonosítóval (UID) rendelkeznek-e, mint az éppen futó program.

dbase_pack

(PHP 3, PHP 4 )

dbase_pack -- Packs a dBase database

Description

bool dbase_pack ( int dbase_identifier)

Packs the specified database (permanently deleting all records marked for deletion using dbase_delete_record()).

dbase_replace_record

(PHP 3>= 3.0.11, PHP 4 )

dbase_replace_record -- Replace a record in a dBase database

Description

bool dbase_replace_record ( int dbase_identifier, array record, int dbase_record_number)

Replaces the data associated with the record record_number with the data in the record in the database. If the number of items in the supplied record is not equal to the number of fields in the database, the operation will fail and FALSE will be returned.

dbase_record_number is an integer which spans from 1 to the number of records in the database (as returned by dbase_numrecords()).

XIX. DBM Functions [deprecated]

Bevezetés

These functions allow you to store records stored in a dbm-style database. This type of database (supported by the Berkeley DB, GDBM, and some system libraries, as well as a built-in flatfile library) stores key/value pairs (as opposed to the full-blown records supported by relational databases).

Megjegyzés: However, dbm support is deprecated and you are encouraged to use the Database (dbm-style) abstraction layer functions instead.


Követelmények

To use this functions you have to compile PHP with support for an underlying database. See the list of supported Databases.


Telepítés

In order to use these functions, you must compile PHP with dbm support by using the --with-db option. In addition you must ensure support for an underlying database or you can use some system libraries.


Futásidejű beállítások

Ez a kiterjesztés semmilyen konfigurációs beállításokat nem definiál a php.ini állományban.


Erőforrás típusok

The function dbmopen() returns an database identifier which is used by the other dbm-functions.


Előre definiált állandók

Ez a kiterjesztés semmilyen konstans értéket nem definiál.


Példák

Példa 1. DBM example

<?php

$dbm = dbmopen("lastseen", "w");
if (dbmexists($dbm, $userid)) {
    $last_seen = dbmfetch($dbm, $userid);
} else {
    dbminsert($dbm, $userid, time());
}
do_stuff();
dbmreplace($dbm, $userid, time());
dbmclose($dbm);

?>

Tartalom
dblist --  Describes the DBM-compatible library being used
dbmclose -- Closes a dbm database
dbmdelete --  Deletes the value for a key from a DBM database
dbmexists --  Tells if a value exists for a key in a DBM database
dbmfetch --  Fetches a value for a key from a DBM database
dbmfirstkey --  Retrieves the first key from a DBM database
dbminsert --  Inserts a value for a key in a DBM database
dbmnextkey --  Retrieves the next key from a DBM database
dbmopen -- Opens a DBM database
dbmreplace --  Replaces the value for a key in a DBM database

dblist

(PHP 3, PHP 4 )

dblist --  Describes the DBM-compatible library being used

Description

string dblist ( void )

Példa 1. Getting the information on the command line

[marcus@zaphod marcus]$ php -r 'echo dblist();'
This is GDBM version 1.8.0, as of May 19, 1999.

dbmclose

(PHP 3, PHP 4 )

dbmclose -- Closes a dbm database

Description

bool dbmclose ( resource dbm_identifier)

Unlocks and closes the specified database.

dbmdelete

(PHP 3, PHP 4 )

dbmdelete --  Deletes the value for a key from a DBM database

Description

bool dbmdelete ( resource dbm_identifier, string key)

Deletes the value for key in the database.

Returns FALSE if the key didn't exist in the database.

dbmexists

(PHP 3, PHP 4 )

dbmexists --  Tells if a value exists for a key in a DBM database

Description

bool dbmexists ( resource dbm_identifier, string key)

Returns TRUE if there is a value associated with the key.

dbmfetch

(PHP 3, PHP 4 )

dbmfetch --  Fetches a value for a key from a DBM database

Description

string dbmfetch ( resource dbm_identifier, string key)

Returns the value associated with key.

dbmfirstkey

(PHP 3, PHP 4 )

dbmfirstkey --  Retrieves the first key from a DBM database

Description

string dbmfirstkey ( resource dbm_identifier)

Returns the first key in the database. Note that no particular order is guaranteed since the database may be built using a hash-table, which doesn't guarantee any ordering.

dbminsert

(PHP 3, PHP 4 )

dbminsert --  Inserts a value for a key in a DBM database

Description

int dbminsert ( resource dbm_identifier, string key, string value)

Adds the value to the database with the specified key.

Returns -1 if the database was opened read-only, 0 if the insert was successful, and 1 if the specified key already exists. (To replace the value, use dbmreplace().)

dbmnextkey

(PHP 3, PHP 4 )

dbmnextkey --  Retrieves the next key from a DBM database

Description

string dbmnextkey ( resource dbm_identifier, string key)

Returns the next key after key. By calling dbmfirstkey() followed by successive calls to dbmnextkey() it is possible to visit every key/value pair in the dbm database. For example:

Példa 1. Visiting every key/value pair in a DBM database

<?php

$key = dbmfirstkey($dbm_id);
while ($key) {
    echo "$key = " . dbmfetch($dbm_id, $key) . "\n";
    $key = dbmnextkey($dbm_id, $key);
}

?>

dbmopen

(PHP 3, PHP 4 )

dbmopen -- Opens a DBM database

Description

resource dbmopen ( string filename, string flags)

The first argument is the full-path filename of the DBM file to be opened and the second is the file open mode which is one of "r", "n", "c" or "w" for read-only, new (implies read-write, and most likely will truncate an already-existing database of the same name), create (implies read-write, and will not truncate an already-existing database of the same name) and read-write respectively.

Returns an identifier to be passed to the other DBM functions on success, or FALSE on failure.

If NDBM support is used, NDBM will actually create filename.dir and filename.pag files. GDBM only uses one file, as does the internal flat-file support, and Berkeley DB creates a filename.db file. Note that PHP does its own file locking in addition to any file locking that may be done by the DBM library itself. PHP does not delete the .lck files it creates. It uses these files simply as fixed inodes on which to do the file locking. For more information on DBM files, see your Unix man pages, or obtain GNU's GDBM.

Megjegyzés: Ha a safe mode be van kapcsolva, a PHP ellenőrzi, hogy az állományok vagy könyvtárak, amelyekkel dolgozni szeretnél, ugyanazzal a felhasználói azonosítóval (UID) rendelkeznek-e, mint az éppen futó program.

dbmreplace

(PHP 3, PHP 4 )

dbmreplace --  Replaces the value for a key in a DBM database

Description

int dbmreplace ( resource dbm_identifier, string key, string value)

Replaces the value for the specified key in the database.

This will also add the key to the database if it didn't already exist.

XX. dbx függvények

Bevezetés

A dbx modul adatbázis-kezelő absztrakciós réteg, ahol az X jelenti a támogatott adatbáziskezelőket. A dbx függvényekkel azonos hívási konvenciót használva lehet elérni a támogatott adatbázisok mindegyikét. A dbx függvények önmagukban nem kommunikálnak az adatbázis-kiszolgálókkal, csak az őket támogató modulokkal/kiterjesztésekkel.


Követelmények

Annak érdekében, hogy ezeket a függvényeket használni lehessen,a be kell tölteni a dbx támogatást vagy hozzá kell linkelni a PHP-t. Jelenleg az alábbi adatbáziskezelőket támogatja a dbx:

Arról, hogyan kell új adatbázis támogatást implementálni a dbx modulba http://www.guidance.nl/php/dbx/doc/ címen találsz leírást.


Telepítés

Annak érdekében, hogy ezeket a függvényeket használni lehessen,a PHP-t dbx támogatással - az --enable-dbx kapcsoló - és minden használni kívánt adatbázisnak megfelelő kiterjesztéssel kell fordítani, azaz MySQL esetén --with-mysql kapcsolót is meg kell adni.


Futásidejű beállítások

Ez a kiterjesztés semmilyen konfigurációs beállításokat nem definiál a php.ini állományban.


Erőforrás típusok

Két erőforrástípust használ a dbx kiterjesztés (egy - egy object típusút): az egyik az adatbázis-kapcsolat leíró, a másik az eredményhalmaz kezeléséhez szükséges .


Előre definiált állandók

Az itt listázott állandókat ez a kiterjesztés definiálja, és csak akkor elérhetőek, ha az adott kiterjesztés be van fordítva a PHP-be, vagy dinamikusan betöltött.

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

DBX_PERSISTENT (integer)

DBX_RESULT_INFO (integer)

DBX_RESULT_INDEX (integer)

DBX_RESULT_ASSOC (integer)

DBX_RESULT_UNBUFFERED (integer) (CVS only)

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)

Tartalom
dbx_close -- lezárja a nyitott adatbázis-kapcsolatot
dbx_compare -- összehasonlít két sort rendezés céljából
dbx_connect -- kapcsolódik egy adatbázishoz
dbx_error --  visszaadja a modulban történt legutolsó hibát (nem feltétlenül a kapcsolathoz kötödő hibát)
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 --  végrehajt egy lekérdezést és visszaadja a teljes végeredményt (ha van)
dbx_sort --  dbx_query által visszaadott eredményhalmazt rendezi tetszőleges függvény segítségével

dbx_close

(PHP 4 >= 4.0.6)

dbx_close -- lezárja a nyitott adatbázis-kapcsolatot

Leírás

bool dbx_close ( object link_identifier)

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Példa 1. dbx_close() példa

<?php
$link = dbx_connect (DBX_MYSQL, "localhost", "db", "username", "password")
    or die ("Nem sikerült kapcsolódni.");

print("Sikeresen kapcsolódtam.");
dbx_close($link);
?>

Megjegyzés: Használd mindig az adatbázis specifikus dokumentációt is!

Lásd még: dbx_connect()!

dbx_compare

(PHP 4 >= 4.1.0)

dbx_compare -- összehasonlít két sort rendezés céljából

Leírás

int dbx_compare ( array row_a, array row_b, string column_key [, int flags])

0-val tér vissza, ha a row_a[$column_key] egyenlő a row_b[$column_key] kifejezéssel, és 1-gyel, ha az első nagyobb, illetve -1-gyel, ha ez kisebb. Ha flags értéke DBX_CMP_DESC, akkor pont fordított értékek adódnak eltérő bemenetek esetén. dbx_compare() kisegítő függvény a dbx_sort() használatához, hogy könnyebben lehessen írni és használni saját definiálású összehasonlító függvényeket.

A flags használható arra, hogy beállítsuk az a rendezés irányát:

  • DBX_CMP_ASC - növekvő sorrendet ír elő

  • DBX_CMP_DESC - csökkenő sorrendet ír elő

és az összehasonlítás típusát (milyen típusra konvertálja az értékeket):

  • DBX_CMP_NATIVE - típuskonverzió nélkül hasonlítja össze az elemeket

  • DBX_CMP_NUMBER - számként hasonlítja össze az elemeket

  • DBX_CMP_TEXT - szövegként hasonlítja össze az elemeket

Egy - egy irányra és típusra vonatkozó állandót a logikai VAGY kapcsolattal lehet kombinálni (|). A flags paraméter alapértelmezése a DBX_CMP_ASC | DBX_CMP_NATIVE.

Példa 1. dbx_compare() példa

<?php
function user_re_order ($a, $b) {
    $rv = dbx_compare ($a, $b, 'pid', DBX_CMP_DESC);
    // ha 'pid' szerint nem rendezhetőek sorba, akkor 'id' szerint
    if (!$rv) { 
        $rv = dbx_compare ($a, $b, 'id', DBX_CMP_NUMBER);
    }
    return $rv;
}

$link   = dbx_connect(DBX_ODBC, "", "db", "username", "password")
    or die ("Nem sikerült csatlakozni.");

$result = dbx_query($link, "SELECT id, pid, leiras FROM tabla ORDER BY id");
    // az eredmény most 'id' szerint van rendezve

dbx_sort ($result, "user_re_order");
    // az eredmény most csökkenő 'pid' szerint és azon túl 'id' szerint van rendezve
dbx_close ($link);
?>

Lásd még dbx_sort()!

dbx_connect

(PHP 4 >= 4.0.6)

dbx_connect -- kapcsolódik egy adatbázishoz

Leírás

object dbx_connect ( mixed module, string host, string database, string username, string password [, int persistent])

Sikeres csatlakozáskor egy object-et ad vissza, hiba esetén pedig FALSE-t. Ha sikerült a kapcsolatot létesíteni, de a megadott adatbázis nem elérhető, akkor a kapcsolatot lezárja és FALSE-t ad vissza. A persistent paraméternek DBX_PERSISTENT értéket adva perzisztens adatbázis kapcsolatot nyit.

A module paraméter lehet sztring is, de inkább a felsorolt állandók valamelyike használandó. A lehetséges értékek alább láthatók, de figyelembe veendő, hogy csak akkor működnek, ha az adott modul be van töltve.

  • DBX_MYSQL vagy "mysql"

  • DBX_ODBC vagy "odbc"

  • DBX_PGSQL vagy "pgsql"

  • DBX_MSSQL vagy "mssql"

  • DBX_FBSQL vagy "fbsql" (PHP 4.1.1-től kezdve)

  • DBX_SYBASECT vagy "sybase_ct" (PHP 4.2.0-tól kezdve)

A visszaadott objektum három tagváltozóval rendelkezik:

database

Az aktuálisan kiválasztott adatbázis nevét tartalmazza.

handle

Ennek a kapcsolatazonosítónak a segítségével szükség esetén az adott modulra jellemző függvények valamelyike hívható meg.

<?php
$link = dbx_connect (DBX_MYSQL, "localhost", "db", "username", "password");
mysql_close ($link->handle); // dbx_close($link) használata itt sokkal jobb lenne...
?>

module

Ezt a dbx kiterjesztés tartja fenn belső használatra, az éppen használt modul számát tárolja.

A host, database, username és a password paraméterek kötelezőek, de nem mindig kerülnek felhasználásra a modul ténylegesen kapcsolatot létesítő függvényétől függően.

Példa 1. dbx_connect() példa

<?php
$link = dbx_connect (DBX_ODBC, "", "db", "username", "password", DBX_PERSISTENT)
    or die ("Nem sikerült kapcsolódni.");
print ("Sikeresen kapcsolódtam.");
dbx_close ($link);
?>

Megjegyzés: Használd mindig az adatbázis specifikus dokumentációt is!

Lásd még: dbx_close()!

dbx_error

(PHP 4 >= 4.0.6)

dbx_error --  visszaadja a modulban történt legutolsó hibát (nem feltétlenül a kapcsolathoz kötödő hibát)

Leírás

string dbx_error ( object link_identifier)

A hiba szövegét tartalmazó sztringgel tér vissza, amely a modulban legutolsó függvényhívás óta történt (pl. a mysql modulban). Ha az adott modulban több kapcsolat is nyitva van, akkor is csak a legutolsó hibaüzenet kerül visszadásra. Ha több modulhoz történt csatlakozás, akkor a link_identifier által meghatározott modul utolsó hibaüzenetét adja vissza.

Példa 1. dbx_error() példa

<?php
$link   = dbx_connect (DBX_MYSQL, "localhost", "db", "username", "password")
    or die ("Nem sikerült kapcsolódni.");

$result = dbx_query ($link, "select id from nem_letezo_tabla");

if ( $result == 0 ) {
    print dbx_error ($link);
}
dbx_close ($link);
?>

Megjegyzés: Használd mindig az adatbázis specifikus dokumentációt is!

Microsoft SQL Server hibaüzenetei valójában a mssql_get_last_message() függvény visszatérési értékei.

dbx_escape_string

(PHP 4 >= 4.3.0)

dbx_escape_string --  Escape a string so it can safely be used in an sql-statement.

Description

string dbx_escape_string ( object link_identifier, string text)

dbx_escape_string() returns the text, escaped where necessary (such as quotes, backslashes etc). It returns NULL on error.

Példa 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);
?>

See also dbx_query().

dbx_fetch_row

(no version information, might be only in CVS)

dbx_fetch_row -- Fetches rows from a query-result that had the DBX_RESULT_UNBUFFERED flag set

Description

object dbx_fetch_row ( object result_identifier)

dbx_fetch_row() returns a row on success, and 0 on failure (e.g. when no more rows are available). 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().

Példa 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";
?>

The result_identifier parameter is the result object returned by a call to dbx_query().

The returned array 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_guery were set that way.

See also dbx_query().

dbx_query

(PHP 4 >= 4.0.6)

dbx_query --  végrehajt egy lekérdezést és visszaadja a teljes végeredményt (ha van)

Leírás

object dbx_query ( object link_identifier, string sql_statement [, long flags])

Az sql_statement sikeres végrehajtásakor 1-gyel vagy egy objektummal tér vissza, ez utóbbival csak olyan esetben, ha SQL utasításnak van végeredménye. Hiba esetén 0-t ad vissza.

Példa 1. A visszatérési érték lekezelésére

<?php
$link   = dbx_connect(DBX_ODBC, "", "db", "username", "password")
    or die("Could not connect");

$result = dbx_query($link, 'SELECT id, szulo_id, leiras FROM tabla');

if ( is_object($result) ) {
    // ... néhány további művelet, lásd még a lenti példákat ...
    // először, a mezőnevek és típusaik kiírása
    // azután,  egy táblába kiírni a kapott végeredményt
}
else if ( $result == 1 ) {
    echo("A lekérdezést sikeresen végrehajtva, nincs visszaadott eredményhalmaz");
}
else {
    exit("Sikertelen lekérdezés");
}

dbx_close($link);
?>

A flags paraméteren keresztül szabályozható a visszaadandó információ mennyisége. Ez a következő állandók logikai vagy kapcsolata lehet:

DBX_RESULT_INDEX

Ez mindig felhasználásra kerül , és hatására a visszatérési érték része lesz egy két dimenziós tömb, amelynek az első indexe a sorindex, a második az oszlopindex, azaz például a data[2][3]-ban a 2 jelöli a sort, a 3 az oszlopot. Az indexelés 0-tól kezdődik.

Ha a DBX_RESULT_ASSOC is meg van adva, akkor a minden esetben a DBX_RESULT_INFO-nak megfelelő értékeket is szolgáltatja a függvény.

DBX_RESULT_INFO

Az oszlopokról ad információt: a mezők számáról, neveikről és típusaikról.

DBX_RESULT_ASSOC

Ennek hatására az oszlopértékeket az oszlopnevekkel is lehet indexelni, azaz a visszaadott eredményhalmaz asszociatív tömbként is használható.

Ezek az asszociatív indexek valójában referenciák a numerikus indexelésű értékekre, így a data[0][0]-t módosítva a data[0]['az_első_oszlop_mező_neve'] is megváltozik.

Megjegyzendő, hogy a DBX_RESULT_INDEX-et mindig használja a függvény, függetlenül a flags paraméter értékétől. Emiatt valójában csak az alábbi kombinációk értelmesek:

  • DBX_RESULT_INDEX

  • DBX_RESULT_INDEX | DBX_RESULT_INFO

  • DBX_RESULT_INDEX | DBX_RESULT_INFO | DBX_RESULT_ASSOC - alapértelmezés, ha nincs megadva a flags.

A visszaadott objektumnak négy vagy öt tagváltozója van a flags-től függően:

handle

Érvényes kapcsolatazonosító az adatbázishoz, és így szükség esetén az adott modulra jellemző függvények hívásához használható:

$result = dbx_query ($link, "SELECT id FROM tabla");
$length = mysql_field_len($result->handle, 0);

cols and rows

A cols és rows tagváltozók tárolják az eredményhalmaz méreteit: az oszlopok/mezők és a sorok/rekordok számát.

$result = dbx_query ($link, "SELECT id FROM tabla");
echo "Az eredmény mérete: " . $result->rows . " x " . $result->cols . "<br/>\n";

info (optional)

Az info tagváltozó csak akkor érhető el, ha a DBX_RESULT_INFO és/vagy DBX_RESULT_ASSOC szerepel a flags paraméterben. Ez olyan kétdimenzós tömb, amelynek két nevesített sora van (name és type) a mezőinformációk eléréséhez.

Példa 2. minden mező nevének és típusának kilistázása

$result = dbx_query ($link, 'SELECT id FROM tabla', 
        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

A data tagváltozó tartalmazza a tényleges végeredményt, az eredményhalmazt, ha van ilyen. Ha a DBX_RESULT_ASSOC is része a flags-nek, akkor az adatok $result->data[2]["mező_neve"] alakban is elérhetők lesznek, asszociatív tömbként kezelve a data-t.

Példa 3. a data tagváltozó kiíratása HTML táblaként

$result = dbx_query ($link, 'SELECT id, szulo_id, leiras FROM tabla');

echo "<table>\n";
foreach ( $result->data as $sor ) {
    echo "<tr>\n";
    foreach ( $sor as $oszlop ) {
        echo "<td>$oszlop</td>";
    }
    echo "</tr>\n";
}
echo "</table>\n";

Megjegyzés: Használd mindig az adatbázis specifikus dokumentációt is!

Lásd még: dbx_connect()!

dbx_sort

(PHP 4 >= 4.0.6)

dbx_sort --  dbx_query által visszaadott eredményhalmazt rendezi tetszőleges függvény segítségével

Leírás

bool dbx_sort ( object result, string user_compare_function)

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Megjegyzés: Az SQL lekérdezésen belül használt rendezés (ORDER BY) mindig jobb hatásfokú, mint a dbx_sort() Ha lehet, mindig az előbbit használd!

Példa 1. dbx_sort() példa

<?php
function user_order ($a, $b) {
    $rv = dbx_compare($a, $b, "pid", DBX_CMP_DESC);
    // ha 'pid' szerint nem rendezhetőek sorba, akkor 'id' szerint
    if ( !$rv ) {    
        $rv = dbx_compare($a, $b, "id", DBX_CMP_NUMBER);
    }
    return $rv;
}

$link   = dbx_connect(DBX_ODBC, "", "db", "username", "password")
    or die ("Nem sikerült csatlakozni.");

$result = dbx_query($link, "SELECT id, pid, leiras FROM tabla ORDER BY id");
    // az eredmény most 'id' szerint van rendezve

dbx_sort ($result, "user_re_order");
    // az eredmény most csökkenő 'pid' szerint és 'id' szerint van rendezve

dbx_close ($link);
?>

Lásd még dbx_compare()!

XXI. DB++ Functions

Figyelem

Ez a kiterjesztés KÍSÉRLETI JELLEGGEL MŰKÖDIK. Ez azt jelenti, hogy minden itt dokumentált működés, beleértve a függvények nevét, működését vagy bármi más, amit a kiterjesztés kapcsán leírtunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a kiterjesztést csak a saját felelősségedre használd!


Bevezetés

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 a SQL database in the first place but provides its own AQL query language which is much more influenced by the relational algebra then 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.


Követelmények

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


Telepítés

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.


Futásidejű beállítások

Ez a kiterjesztés semmilyen konfigurációs beállításokat nem definiál a php.ini állományban.


Erőforrás típusok

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.


Előre definiált állandók

Az itt listázott állandókat ez a kiterjesztés definiálja, és csak akkor elérhetőek, ha az adott kiterjesztés be van fordítva a PHP-be, vagy dinamikusan betöltött.


db++ error codes

Táblázat 1. DB++ Error Codes

PHP Constantdb++ constantmeaning
DBPLUS_ERR_NOERR (integer) ERR_NOERRNull error condition
DBPLUS_ERR_DUPLICATE (integer) ERR_DUPLICATETried to insert a duplicate tuple
DBPLUS_ERR_EOSCAN (integer) ERR_EOSCANEnd of scan from rget()
DBPLUS_ERR_EMPTY (integer) ERR_EMPTYRelation is empty (server)
DBPLUS_ERR_CLOSE (integer) ERR_CLOSEThe server can't close
DBPLUS_ERR_WLOCKED (integer) ERR_WLOCKEDThe record is write locked
DBPLUS_ERR_LOCKED (integer) ERR_LOCKEDRelation was already locked
DBPLUS_ERR_NOLOCK (integer) ERR_NOLOCKRelation cannot be locked
DBPLUS_ERR_READ (integer) ERR_READRead error on relation
DBPLUS_ERR_WRITE (integer) ERR_WRITEWrite error on relation
DBPLUS_ERR_CREATE (integer) ERR_CREATECreate() system call failed
DBPLUS_ERR_LSEEK (integer) ERR_LSEEKLseek() system call failed
DBPLUS_ERR_LENGTH (integer) ERR_LENGTHTuple exceeds maximum length
DBPLUS_ERR_OPEN (integer) ERR_OPENOpen() system call failed
DBPLUS_ERR_WOPEN (integer) ERR_WOPENRelation already opened for writing
DBPLUS_ERR_MAGIC (integer) ERR_MAGICFile is not a relation
DBPLUS_ERR_VERSION (integer) ERR_VERSIONFile is a very old relation
DBPLUS_ERR_PGSIZE (integer) ERR_PGSIZERelation uses a different page size
DBPLUS_ERR_CRC (integer) ERR_CRCInvalid crc in the superpage
DBPLUS_ERR_PIPE (integer) ERR_PIPEPiped relation requires lseek()
DBPLUS_ERR_NIDX (integer) ERR_NIDXToo many secondary indices
DBPLUS_ERR_MALLOC (integer) ERR_MALLOCMalloc() call failed
DBPLUS_ERR_NUSERS (integer) ERR_NUSERSError use of max users
DBPLUS_ERR_PREEXIT (integer) ERR_PREEXITCaused by invalid usage
DBPLUS_ERR_ONTRAP (integer) ERR_ONTRAPCaused by a signal
DBPLUS_ERR_PREPROC (integer) ERR_PREPROCError in the preprocessor
DBPLUS_ERR_DBPARSE (integer) ERR_DBPARSEError in the parser
DBPLUS_ERR_DBRUNERR (integer) ERR_DBRUNERRRun error in db
DBPLUS_ERR_DBPREEXIT (integer) ERR_DBPREEXITExit condition caused by prexit() * procedure
DBPLUS_ERR_WAIT (integer) ERR_WAITWait a little (Simple only)
DBPLUS_ERR_CORRUPT_TUPLE (integer) ERR_CORRUPT_TUPLEA 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_FIFOCan't create a fifo
DBPLUS_ERR_PERM (integer) ERR_PERMPermission denied
DBPLUS_ERR_TCL (integer) ERR_TCLTCL_error
DBPLUS_ERR_RESTRICTED (integer) ERR_RESTRICTEDOnly 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 

Tartalom
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 -- ???
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 -- ???
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 -- ???
dbplus_setindex -- ???
dbplus_setindexbynumber -- ???
dbplus_sql -- Perform SQL query
dbplus_tcl -- Execute TCL code on server side
dbplus_tremove -- Remove tuple and return new current tuple
dbplus_undo -- ???
dbplus_undoprepare -- ???
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

dbplus_add

(4.1.0 - 4.2.3 only)

dbplus_add -- Add a tuple to a relation

Description

int dbplus_add ( resource relation, array tuple)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

This function will add a tuple to a relation. The tuple data is an array of attribute/value pairs to be inserted into the given relation. After successful execution the tuple array will contain the complete data of the newly created tuple, including all implicitly set domain fields like sequences.

The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.

dbplus_aql

(4.1.0 - 4.2.3 only)

dbplus_aql -- Perform AQL query

Description

resource dbplus_aql ( string query [, string server [, string dbpath]])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

dbplus_aql() will execute an AQL query on the given server and dbpath.

On success it will return a relation handle. The result data may be fetched from this relation by calling dbplus_next() and dbplus_current(). Other relation access functions will not work on a result relation.

Further information on the AQL A... Query Language is provided in the original db++ manual.

dbplus_chdir

(4.1.0 - 4.2.3 only)

dbplus_chdir -- Get/Set database virtual current directory

Description

string dbplus_chdir ( [string newdir])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

dbplus_chdir() will change the virtual current directory where relation files will be looked for by dbplus_open(). dbplus_chdir() will return the absolute path of the current directory. Calling dbplus_chdir() without giving any newdir may be used to query the current working directory.

dbplus_close

(4.1.0 - 4.2.3 only)

dbplus_close -- Close a relation

Description

int dbplus_close ( resource relation)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Calling dbplus_close() will close a relation previously opened by dbplus_open().

dbplus_curr

(4.1.0 - 4.2.3 only)

dbplus_curr -- Get current tuple from relation

Description

int dbplus_curr ( resource relation, array tuple)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

dbplus_curr() will read the data for the current tuple for the given relation and will pass it back as an associative array in tuple.

The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.

See also dbplus_first(), dbplus_prev(), dbplus_next(), and dbplus_last().

dbplus_errcode

(4.1.0 - 4.2.3 only)

dbplus_errcode --  Get error string for given errorcode or last error

Description

string dbplus_errcode ( int errno)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

dbplus_errcode() returns a cleartext error string for the error code passed as errno of for the result code of the last db++ operation if no parameter is given.

dbplus_errno

(4.1.0 - 4.2.3 only)

dbplus_errno -- Get error code for last operation

Description

int dbplus_errno ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

dbplus_errno() will return the error code returned by the last db++ operation.

See also dbplus_errcode().

dbplus_find

(4.1.0 - 4.2.3 only)

dbplus_find -- Set a constraint on a relation

Description

int dbplus_find ( resource relation, array constraints, mixed tuple)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

dbplus_find() will place a constraint on the given relation. Further calls to functions like dbplus_curr() or dbplus_next() will only return tuples matching the given 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.

See also dbplus_unselect().

dbplus_first

(4.1.0 - 4.2.3 only)

dbplus_first -- Get first tuple from relation

Description

int dbplus_first ( resource relation, array tuple)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

dbplus_curr() will read the data for the first tuple for the given relation, make it the current tuple and pass it back as an associative array in tuple.

The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.

See also dbplus_curr(), dbplus_prev(), dbplus_next(), and dbplus_last().

dbplus_flush

(4.1.0 - 4.2.3 only)

dbplus_flush -- Flush all changes made on a relation

Description

int dbplus_flush ( resource relation)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

dbplus_flush() will write all changes applied to relation since the last flush to disk.

The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.

dbplus_freealllocks

(4.1.0 - 4.2.3 only)

dbplus_freealllocks -- Free all locks held by this client

Description

int dbplus_freealllocks ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

dbplus_freealllocks() will free all tuple locks held by this client.

See also dbplus_getlock(), dbplus_freelock(), and dbplus_freerlocks().

dbplus_freelock

(4.1.0 - 4.2.3 only)

dbplus_freelock -- Release write lock on tuple

Description

int dbplus_freelock ( resource relation, string tname)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

dbplus_freelock() will release a write lock on the given tuple previously obtained by dbplus_getlock().

See also dbplus_getlock(), dbplus_freerlocks(), and dbplus_freealllocks().

dbplus_freerlocks

(4.1.0 - 4.2.3 only)

dbplus_freerlocks -- Free all tuple locks on given relation

Description

int dbplus_freerlocks ( resource relation)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

dbplus_freerlocks() will free all tuple locks held on the given relation.

See also dbplus_getlock(), dbplus_freelock(), and dbplus_freealllocks().

dbplus_getlock

(4.1.0 - 4.2.3 only)

dbplus_getlock -- Get a write lock on a tuple

Description

int dbplus_getlock ( resource relation, string tname)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

dbplus_getlock() will request a write lock on the specified tuple. It will return zero on success or a non-zero error code, especially DBPLUS_ERR_WLOCKED, on failure.

See also dbplus_freelock(), dbplus_freerlocks(), and dbplus_freealllocks().

dbplus_getunique

(4.1.0 - 4.2.3 only)

dbplus_getunique -- Get an id number unique to a relation

Description

int dbplus_getunique ( resource relation, int uniqueid)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

dbplus_getunique() will obtain a number guaranteed to be unique for the given relation and will pass it back in the variable given as uniqueid.

The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.

dbplus_info

(4.1.0 - 4.2.3 only)

dbplus_info -- ???

Description

int dbplus_info ( resource relation, string key, array )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Not implemented yet.

dbplus_last

(4.1.0 - 4.2.3 only)

dbplus_last -- Get last tuple from relation

Description

int dbplus_last ( resource relation, array tuple)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

dbplus_curr() will read the data for the last tuple for the given relation, make it the current tuple and pass it back as an associative array in tuple.

The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.

See also dbplus_first(), dbplus_curr(), dbplus_prev(), and dbplus_next().

dbplus_lockrel

(no version information, might be only in CVS)

dbplus_lockrel -- Request write lock on relation

Description

int dbplus_lockrel ( resource relation)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

dbplus_lockrel() will request a write lock on the given relation. Other clients may still query the relation, but can't alter it while it is locked.

dbplus_next

(4.1.0 - 4.2.3 only)

dbplus_next -- Get next tuple from relation

Description

int dbplus_next ( resource relation, array )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

dbplus_curr() will read the data for the next tuple for the given relation, will make it the current tuple and will pass it back as an associative array in tuple.

The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.

See also dbplus_first(), dbplus_curr(), dbplus_prev(), and dbplus_last().

dbplus_open

(4.1.0 - 4.2.3 only)

dbplus_open -- Open relation file

Description

resource dbplus_open ( string name)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

The relation file name will be opened. 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.

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

dbplus_prev

(4.1.0 - 4.2.3 only)

dbplus_prev -- Get previous tuple from relation

Description

int dbplus_prev ( resource relation, array tuple)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

dbplus_curr() will read the data for the next tuple for the given relation, will make it the current tuple and will pass it back as an associative array in tuple.

The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.

See also dbplus_first(), dbplus_curr(), dbplus_next(), and dbplus_last().

dbplus_rchperm

(4.1.0 - 4.2.3 only)

dbplus_rchperm -- Change relation permissions

Description

int dbplus_rchperm ( resource relation, int mask, string user, string group)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

dbplus_rchperm() will change access permissions as specified by mask, user and group. The values for these are operating system specific.

dbplus_rcreate

(4.1.0 - 4.2.3 only)

dbplus_rcreate -- Creates a new DB++ relation

Description

resource dbplus_rcreate ( string name, mixed domlist [, bool overwrite])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

dbplus_rcreate() will create a new relation named name. An existing relation by the same name will only be overwritten if the relation is currently not in use and overwrite is set to TRUE.

domlist should contain the domain specification for the new relation within an array of domain description strings. ( dbplus_rcreate() will also accept a string with space delimited domain description strings, but it is recommended to use an array). 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.

dbplus_rcrtexact

(4.1.0 - 4.2.3 only)

dbplus_rcrtexact -- Creates an exact but empty copy of a relation including indices

Description

resource dbplus_rcrtexact ( string name, resource relation, bool overwrite)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

dbplus_rcrtexact() will create an exact but empty copy of the given relation under a new name. An existing relation by the same name will only be overwritten if overwrite is TRUE and no other process is currently using the relation.

dbplus_rcrtlike

(4.1.0 - 4.2.3 only)

dbplus_rcrtlike -- Creates an empty copy of a relation with default indices

Description

resource dbplus_rcrtlike ( string name, resource relation, int flag)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

dbplus_rcrtexact() will create an empty copy of the given relation under a new name, but with default indices. An existing relation by the same name will only be overwritten if overwrite is TRUE and no other process is currently using the relation.

dbplus_resolve

(4.1.0 - 4.2.3 only)

dbplus_resolve -- Resolve host information for relation

Description

int dbplus_resolve ( string relation_name)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

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. The function will return an array containing these values under the keys 'sid', 'host' and 'host_path' or FALSE on error.

See also dbplus_tcl().

dbplus_restorepos

(4.1.0 - 4.2.3 only)

dbplus_restorepos -- ???

Description

int dbplus_restorepos ( resource relation, array tuple)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Not implemented yet.

dbplus_rkeys

(4.1.0 - 4.2.3 only)

dbplus_rkeys -- Specify new primary key for a relation

Description

resource dbplus_rkeys ( resource relation, mixed domlist)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

dbplus_rkeys() will replace the current primary key for relation with the combination of domains specified by domlist.

domlist may be passed as a single domain name string or as an array of domain names.

dbplus_ropen

(4.1.0 - 4.2.3 only)

dbplus_ropen -- Open relation file local

Description

resource dbplus_ropen ( string name)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

dbplus_ropen() will open the relation file locally for quick access without any client/server overhead. Access is read only and only dbplus_current() and dbplus_next() may be applied to the returned relation.

dbplus_rquery

(4.1.0 - 4.2.3 only)

dbplus_rquery -- Perform local (raw) AQL query

Description

int dbplus_rquery ( string query, string dbpath)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

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.

dbplus_rrename

(4.1.0 - 4.2.3 only)

dbplus_rrename -- Rename a relation

Description

int dbplus_rrename ( resource relation, string name)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

dbplus_rrename() will change the name of relation to name.

dbplus_rsecindex

(4.1.0 - 4.2.3 only)

dbplus_rsecindex --  Create a new secondary index for a relation

Description

resource dbplus_rsecindex ( resource relation, mixed domlist, int type)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

dbplus_rsecindex() will create a new secondary index for relation with consists of the domains specified by domlist and is of type type

domlist may be passed as a single domain name string or as an array of domain names.

dbplus_runlink

(4.1.0 - 4.2.3 only)

dbplus_runlink -- Remove relation from filesystem

Description

int dbplus_runlink ( resource relation)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

dbplus_unlink() will close and remove the relation.

dbplus_rzap

(4.1.0 - 4.2.3 only)

dbplus_rzap -- Remove all tuples from relation

Description

int dbplus_rzap ( resource relation)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

dbplus_rzap() will remove all tuples from relation.

dbplus_savepos

(4.1.0 - 4.2.3 only)

dbplus_savepos -- ???

Description

int dbplus_savepos ( resource relation)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Not implemented yet.

dbplus_setindex

(4.1.0 - 4.2.3 only)

dbplus_setindex -- ???

Description

int dbplus_setindex ( resource relation, string idx_name)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Not implemented yet.

dbplus_setindexbynumber

(4.1.0 - 4.2.3 only)

dbplus_setindexbynumber -- ???

Description

int dbplus_setindexbynumber ( resource relation, int idx_number)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Not implemented yet.

dbplus_sql

(4.1.0 - 4.2.3 only)

dbplus_sql -- Perform SQL query

Description

resource dbplus_sql ( string query, string server, string dbpath)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Not implemented yet.

dbplus_tcl

(4.1.0 - 4.2.3 only)

dbplus_tcl -- Execute TCL code on server side

Description

int dbplus_tcl ( int sid, string script)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

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.

See also dbplus_resolve().

dbplus_tremove

(4.1.0 - 4.2.3 only)

dbplus_tremove -- Remove tuple and return new current tuple

Description

int dbplus_tremove ( resource relation, array tuple [, array current])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

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

dbplus_undo

(4.1.0 - 4.2.3 only)

dbplus_undo -- ???

Description

int dbplus_undo ( resource relation)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Not implemented yet.

dbplus_undoprepare

(4.1.0 - 4.2.3 only)

dbplus_undoprepare -- ???

Description

int dbplus_undoprepare ( resource relation)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Not implemented yet.

dbplus_unlockrel

(4.1.0 - 4.2.3 only)

dbplus_unlockrel -- Give up write lock on relation

Description

int dbplus_unlockrel ( resource relation)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

dbplus_unlockrel() will release a write lock previously obtained by dbplus_lockrel().

dbplus_unselect

(4.1.0 - 4.2.3 only)

dbplus_unselect -- Remove a constraint from relation

Description

int dbplus_unselect ( resource relation)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Calling dbplus_unselect() will remove a constraint previously set by dbplus_find() on relation.

dbplus_update

(4.1.0 - 4.2.3 only)

dbplus_update -- Update specified tuple in relation

Description

int dbplus_update ( resource relation, array old, array new)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

dbplus_update() replaces the tuple given by old with the data from new if and only if old completely matches a tuple within relation.

dbplus_xlockrel

(4.1.0 - 4.2.3 only)

dbplus_xlockrel -- Request exclusive lock on relation

Description

int dbplus_xlockrel ( resource relation)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

dbplus_xlockrel() will request an exclusive lock on relation preventing even read access from other clients.

See also dbplus_xunlockrel().

dbplus_xunlockrel

(4.1.0 - 4.2.3 only)

dbplus_xunlockrel -- Free exclusive lock on relation

Description

int dbplus_xunlockrel ( resource relation)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

dbplus_xunlockrel() will release an exclusive lock on relation previously obtained by dbplus_xlockrel().

XXII. Direct IO functions

Bevezetés

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.

Megjegyzés: Ez a kiterjesztés nem működik Windows operációs rendszereken!


Követelmények

Az itt leírt függvények használatához semmilyen külső függvénykönyvtár megléte nem szükségeltetik.


Telepítés

To get these functions to work, you have to configure PHP with --enable-dio.


Futásidejű beállítások

Ez a kiterjesztés semmilyen konfigurációs beállításokat nem definiál a php.ini állományban.


Erőforrás típusok

One resource type is defined by this extension: a file descriptor returned by dio_open().


Előre definiált állandók

Ez a kiterjesztés semmilyen konstans értéket nem definiál.

Tartalom
dio_close -- Closes the file descriptor given by fd
dio_fcntl -- Performs a c library fcntl on fd
dio_open --  Opens a new filename with specified permissions of flags and creation permissions of mode
dio_read --  Reads n bytes from fd and returns them, if n is not specified, reads 1k block
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

dio_close

(PHP 4 >= 4.2.0)

dio_close -- Closes the file descriptor given by fd

Description

void dio_close ( resource fd)

The function dio_close() closes the file descriptor fd.

dio_fcntl

(PHP 4 >= 4.2.0)

dio_fcntl -- Performs a c library fcntl on fd

Description

mixed dio_fcntl ( resource fd, int cmd [, mixed arg])

The dio_fcntl() function performs the operation specified by cmd on the file descriptor fd. Some commands require additional arguments args to be supplied.

arg is an associative array, when cmd is F_SETLK or F_SETLLW, with the following keys:

  • "start" - offset where lock begins

  • "length" - size of locked area. zero means to end of file

  • "wenth" - Where l_start is relative to: can be SEEK_SET, SEEK_END and SEEK_CUR

  • "type" - type of lock: can be F_RDLCK (read lock), F_WRLCK (write lock) or F_UNLCK (unlock)

cmd can be one of the following operations:

  • F_SETLK - Lock is set or cleared. If the lock is held by someone else dio_fcntl() returns -1.

  • F_SETLKW - like F_SETLK, but in case the lock is held by someone else, dio_fcntl() waits until the lock is released.

  • F_GETLK - dio_fcntl() returns an associative array (as described above) if someone else prevents lock. If there is no obstruction key "type" will set to F_UNLCK.

  • F_DUPFD - finds the lowest numbered available file descriptor greater or equal than arg and returns them.

  • F_SETFL - Sets the file descriptors flags to the value specified by arg, which can be O_APPEND,O_NONBLOCK or O_ASYNC. To use O_ASYNC you will need to use the PCNTL extension.

dio_open

(PHP 4 >= 4.2.0)

dio_open --  Opens a new filename with specified permissions of flags and creation permissions of mode

Description

resource dio_open ( string filename, int flags [, int mode])

dio_open() opens a file and returns a new file descriptor for it, or FALSE if any error occurred. If flags is O_CREAT, the optional third parameter mode will set the mode of the file (creation permissions). The flags parameter can be one of the following options:

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

The flags parameter can also include any combination of the following flags:

  • O_CREAT - creates the file, if it doesn't already exist.

  • O_EXCL - if both, O_CREAT and O_EXCL are set, dio_open() fails, if the file already exists.

  • O_TRUNC - if the file exists, and its 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.

dio_read

(PHP 4 >= 4.2.0)

dio_read --  Reads n bytes from fd and returns them, if n is not specified, reads 1k block

Description

string dio_read ( resource fd [, int n])

The function dio_read() reads and returns n bytes from file with descriptor fd. If n is not specified, dio_read() reads 1K sized block and returns them.

dio_seek

(PHP 4 >= 4.2.0)

dio_seek -- Seeks to pos on fd from whence

Description

int dio_seek ( resource fd, int pos, int whence)

The function dio_seek() is used to change the file position of the file with descriptor fd. The parameter whence specifies how the position pos should be interpreted:

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

dio_stat

(PHP 4 >= 4.2.0)

dio_stat --  Gets stat information about the file descriptor fd

Description

array dio_stat ( resource fd)

Function dio_stat() returns information about the file with file descriptor fd. dio_stat() 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_tcsetattr

(PHP 4 >= 4.3.0)

dio_tcsetattr --  Sets terminal attributes and baud rate for a serial port

Description

dio_tcsetattr ( resource fd, array options)

The function dio_tcsetattr() sets the terminal attributes and baud rate of the open resource. 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.

Példa 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;
  }
} 

?>

dio_truncate

(PHP 4 >= 4.2.0)

dio_truncate --  Truncates file descriptor fd to offset bytes

Description

bool dio_truncate ( resource fd, int offset)

Function dio_truncate() causes the file referenced by fd to be truncated 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. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad..

dio_write

(PHP 4 >= 4.2.0)

dio_write --  Writes data to fd with optional truncation at length

Description

int dio_write ( resource fd, string data [, int len])

The function dio_write() writes up to len bytes from data to file fd. If len is not specified, dio_write() writes all data to the specified file. dio_write() returns the number of bytes written to fd.

XXIII. Könyvtárkezelő függvények

Tartalom
chdir -- Könyvtárat vált
chroot -- Megváltoztatja a gyökérkönyvtárat
dir -- Könyvtár osztály
closedir -- Bezárja a könyvtárat
getcwd -- Az aktuális munkakönytárat adja meg
opendir -- Megnyit egy könyvtárat
readdir -- Adott könyvtárból beolvas egy bejegyzést
rewinddir -- Visszaállítja a könyvtárkezelőt
scandir --  List files and directories inside the specified path

chdir

(PHP 3, PHP 4 )

chdir -- Könyvtárat vált

Leírás

int chdir ( string directory)

Megváltoztatja a PHP aktuális könyvtárát a directory könyvtárra. FALSE értékkel tér vissza, ha nem lehet a könyvtárváltást teljesíteni, egyébként TRUE értéket ad.

chroot

(PHP 4 >= 4.0.5)

chroot -- Megváltoztatja a gyökérkönyvtárat

Leírás

bool chroot ( string directory)

Megváltoztatja az aktuális processz gyökérkönyvtárát a directory paraméterben megadott értékre. FALSE értékkel tér vissza, ha nem jár sikerrel, TRUE értéket ad egyébként.

Megjegyzés: Nem helyes ennek a függvénynek a használata webszerver környezetben, mivel nem lehetséges a gyökérkönyvtár visszaállítása a / könyvtárra a kérés végeztével. Ez a függvény csak CGI módban fog megfelelően funkcionálni.

dir

(PHP 3, PHP 4 )

dir -- Könyvtár osztály

Leírás

object dir ( string directory)

Ez egy majdnem-objektum-orientált eljárás könyvtár listázásra. A megadott directory paraméter által meghatározott könyvtárat megnyitja. Ha a könyvtár megnyílt, a visszaadott objektum két tulajdonsága érhető el. A handle tulajdonság más könyvtárkezelő függvényekkel (mint pl. a readdir(), rewinddir() vagy a closedir()) való használatra szolgál. A path tulajdonság tartalmazza a könyvtár elérési útját. Három metódust alkalmazhatunk: read, rewind és close.

Példa 1. dir() példa

$d = dir("/etc");
echo "Handle: ".$d->handle."<br>\n";
echo "Path: ".$d->path."<br>\n";
while ($entry = $d->read()) {
    echo $entry."<br>\n";
}
$d->close();

closedir

(PHP 3, PHP 4 )

closedir -- Bezárja a könyvtárat

Leírás

void closedir ( int dir_handle)

Bezárja a dir_handle paraméterrel azonosított könyvtárat. A könyvtárat előzőleg meg kell nyitni az opendir() függvénnyel.

getcwd

(PHP 4 )

getcwd -- Az aktuális munkakönytárat adja meg

Leírás

string getcwd ( void )

Visszaadja az aktuális munkakönyvtárat.

opendir

(PHP 3, PHP 4 )

opendir -- Megnyit egy könyvtárat

Leírás

int opendir ( string path)

Egy könyvtárazonosítóval tér vissza, amit későbbi closedir(), readdir(), és rewinddir() hívásokban használhatsz.

Ha a path nem egy érvényes könyvtárat ad meg, vagy a könyvtár nem megnyítható jogosultsági korlátozások, vagy filerendszer hibák miatt, az opendir() FALSE értéket ad vissza, és PHP hibát ad. Letithatod az opendir() során fellépő hiba kiírását, ha egy `@' jelet teszel a függvény neve elé.

Példa 1. opendir() példa

<?php

if ($dir = @opendir("/tmp")) {
  while ($file = readdir($dir)) {
    echo "$file\n";
  }  
  closedir($dir);
}

?>

readdir

(PHP 3, PHP 4 )

readdir -- Adott könyvtárból beolvas egy bejegyzést

Leírás

string readdir ( int dir_handle)

A könyvtárban levő következő file nevével tér vissza. A fileneveket nem rendezetten adja vissza.

Példa 1. Összes file kilistázása az aktuális könyvtárban

<?php
$handle = opendir('.');
echo "Könyvtár azonosító: $handle\n";
echo "Tartalma:\n";
while ($file = readdir($handle)) {
    echo "$file\n";
}
closedir($handle); 
?>

Figyelj rá, hogy a readdir() függvény a . és a .. bejegyzéseket is visszaadja. Ha ezt nem szeretnéd, akkor hagyd ki azokat így:

Példa 2. Összes file listázása az aktuális könyvtárban a . és a .. bejegyzések nélkül

<?php
$handle = opendir('.');
while (false !== ($file = readdir($handle))) { 
    if ($file != "." && $file != "..") {
        echo "$file\n";
    }
}
closedir($handle);
?>

rewinddir

(PHP 3, PHP 4 )

rewinddir -- Visszaállítja a könyvtárkezelőt

Leírás

void rewinddir ( int dir_handle)

Visszaállítja a dir_handle kezelővel megnyitott könyvtárat az alapállapotba, vagyis a könyvtár "elejére megy".

scandir

(PHP 5 CVS only)

scandir --  List files and directories inside the specified path

Description

array scandir ( string directory [, int sorting_order [, resource context]])

Returns an array of files and directories from the directory. If directory is not a directory, then boolean FALSE is returned, and an error of level E_WARNING is generated.

By default, the sorted order is alphabetical in ascending order. If the optional sorting_order is used (set to 1), then sort order is alphabetical in descending order.

Példa 1. A simple scandir() example

<?php
$dir    = '/tmp';
$files1 = scandir($dir);
$files2 = scandir($dir, 1);

print_r($files1);
print_r($files2);
?>

Outputs something like:

Array
(
    [0] => .
    [1] => ..
    [2] => bar.php
    [3] => foo.txt
    [4] => somedir
)
Array
(
    [0] => somedir
    [1] => foo.txt
    [2] => bar.php
    [3] => ..
    [4] => .
)

Példa 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);

?>

Outputs something like:

Array
(
    [0] => .
    [1] => ..
    [2] => bar.php
    [3] => foo.txt
    [4] => somedir
)
Array
(
    [0] => somedir
    [1] => foo.txt
    [2] => bar.php
    [3] => ..
    [4] => .
)

Tipp: URL-t is megadhatsz az állomány név paraméter helyén ha a fopen wrappers szolgáltatás be van kapcsolva. Bővebb információk az fopen() leírásánál olvashatóak arról, milyen módon adhatod meg a fájlneveket, valamint érdemes megtekinteni a J Függelék oldalt a támogatott URL típusok listájának megtekintése gyanánt.

See also opendir(), readdir(), glob(), is_dir(), and sort().

XXIV. DOM XML függvények

Figyelem

Ez a kiterjesztés KÍSÉRLETI JELLEGGEL MŰKÖDIK. Ez azt jelenti, hogy minden itt dokumentált működés, beleértve a függvények nevét, működését vagy bármi más, amit a kiterjesztés kapcsán leírtunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a kiterjesztést csak a saját felelősségedre használd!

Ezek a függvények csak akkor használhatóak, ha a PHP-t a --with-dom=[DIR] paraméterrel fordítottad, felhasználva a GNOME xml könyvtárat. Szükséged lesz minimum a libxml-2.0.0-ra (a béta verzióval nem fog működni!) Ezek a függvények a PHP 4-ben kerültek a nyelvbe.

Ez a modul az alábbi konstansokat definiálja:

Táblázat 1. XML konstansok

KonstansÉrtékLeírás
XML_ELEMENT_NODE1 
XML_ATTRIBUTE_NODE2 
XML_TEXT_NODE3 
XML_CDATA_SECTION_NODE4 
XML_ENTITY_REF_NODE5 
XML_ENTITY_NODE6 
XML_PI_NODE7 
XML_COMMENT_NODE8 
XML_DOCUMENT_NODE9 
XML_DOCUMENT_TYPE_NODE10 
XML_DOCUMENT_FRAG_NODE11 
XML_NOTATION_NODE12 
XML_GLOBAL_NAMESPACE1 
XML_LOCAL_NAMESPACE2 

Ez a modul számos osztályt definiál. A DOM XML függvények visszaadnak egy végigjárt XML dokumentum fát, amelynek minden egyes csomópontja ezen osztályok egyikéhez tartozik.

Tartalom
DomAttribute->name --  Returns name of attribute
DomAttribute->specified --  Checks if attribute is specified
DomAttribute->value --  Returns value of attribute
DomDocument->add_root [deprecated] --  Adds a root node
DomDocument->create_attribute -- Create new attribute
DomDocument->create_cdata_section -- Create new cdata node
DomDocument->create_comment -- Create new comment node
DomDocument->create_element_ns --  Create new element node with an associated namespace
DomDocument->create_element -- Create new element node
DomDocument->create_entity_reference -- 
DomDocument->create_processing_instruction -- Creates new PI node
DomDocument->create_text_node -- Create new text node
DomDocument->doctype --  Returns the document type
DomDocument->document_element --  Returns root element node
DomDocument->dump_file --  Dumps the internal XML tree back into a file
DomDocument->dump_mem --  Dumps the internal XML tree back into a string
DomDocument->get_element_by_id --  Searches for an element with a certain id
DomDocument->get_elements_by_tagname -- 
DomDocument->html_dump_mem --  Dumps the internal XML tree back into a string as HTML
DomDocument->xinclude --  Substitutes XIncludes in a DomDocument Object.
DomDocumentType->entities --  Returns list of entities
DomDocumentType->internal_subset --  Returns internal subset
DomDocumentType->name --  Returns name of document type
DomDocumentType->notations --  Returns list of notations
DomDocumentType->public_id --  Returns public id of document type
DomDocumentType->system_id --  Returns system id of document type
DomElement->get_attribute_node --  Returns value of attribute
DomElement->get_attribute --  Returns value of attribute
DomElement->get_elements_by_tagname --  Gets elements by tagname
DomElement->has_attribute --  Checks to see if attribute exists
DomElement->remove_attribute --  Removes attribute
DomElement->set_attribute --  Adds new attribute
DomElement->tagname --  Returns name of element
DomNode->add_namespace --  Adds a namespace declaration to a node.
DomNode->append_child --  Adds new child at the end of the children
DomNode->append_sibling --  Adds new sibling to a node
DomNode->attributes --  Returns list of attributes
DomNode->child_nodes --  Returns children of node
DomNode->clone_node --  Clones a node
DomNode->dump_node --  Dumps a single node
DomNode->first_child --  Returns first child of node
DomNode->get_content --  Gets content of node
DomNode->has_attributes --  Checks if node has attributes
DomNode->has_child_nodes --  Checks if node has children
DomNode->insert_before --  Inserts new node as child
DomNode->is_blank_node --  Checks if node is blank
DomNode->last_child --  Returns last child of node
DomNode->next_sibling --  Returns the next sibling of node
DomNode->node_name --  Returns name of node
DomNode->node_type --  Returns type of node
DomNode->node_value --  Returns value of a node
DomNode->owner_document --  Returns the document this node belongs to
DomNode->parent_node --  Returns the parent of the node
DomNode->prefix --  Returns name space prefix of node
DomNode->previous_sibling --  Returns the previous sibling of node
DomNode->remove_child --  Removes child from list of children
DomNode->replace_child --  Replaces a child
DomNode->replace_node --  Replaces node
DomNode->set_content --  Sets content of node
DomNode->set_name --  Sets name of node
DomNode->set_namespace --  Sets namespace of a node.
DomNode->unlink_node --  Deletes node
DomProcessingInstruction->data --  Returns data of pi node
DomProcessingInstruction->target --  Returns target of pi node
DomXsltStylesheet->process --  Applies the XSLT-Transformation on a DomDocument Object.
DomXsltStylesheet->result_dump_file --  Dumps the result from a XSLT-Transformation into a file
DomXsltStylesheet->result_dump_mem --  Dumps the result from a XSLT-Transformation back into a string
domxml_new_doc --  Creates new empty XML document
domxml_open_file -- Creates a DOM object from XML file
domxml_open_mem -- Creates a DOM object of an XML document
domxml_version --  Get XML library version
domxml_xmltree --  Creates a tree of PHP objects from an XML document
domxml_xslt_stylesheet_doc --  Creates a DomXsltStylesheet Object from a DomDocument Object.
domxml_xslt_stylesheet_file --  Creates a DomXsltStylesheet Object from an XSL document in a file.
domxml_xslt_stylesheet --  Creates a DomXsltStylesheet Object from an XML document in a string.
xpath_eval_expression --  Evaluates the XPath Location Path in the given string
xpath_eval --  Evaluates the XPath Location Path in the given string
xpath_new_context --  Creates new xpath context
xptr_eval --  Evaluate the XPtr Location Path in the given string
xptr_new_context --  Create new XPath Context

DomAttribute->name

(no version information, might be only in CVS)

DomAttribute->name --  Returns name of attribute

Description

bool DomAttribute->name ( void )

This function returns the name of the attribute.

See also domattribute_value().

DomAttribute->specified

(no version information, might be only in CVS)

DomAttribute->specified --  Checks if attribute is specified

Description

bool DomAttribute->specified ( void )

Check DOM standard for a detailed explanation.

DomAttribute->value

(no version information, might be only in CVS)

DomAttribute->value --  Returns value of attribute

Description

bool DomAttribute->value ( void )

This function returns the value of the attribute.

See also domattribute_name().

DomDocument->add_root [deprecated]

(no version information, might be only in CVS)

DomDocument->add_root [deprecated] --  Adds a root node

Description

resource DomDocument->add_root ( string name)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Adds a root element node to a dom document and returns the new node. The element name is given in the passed parameter.

Példa 1. Creating a simple HTML document header

<?php
$doc = domxml_new_doc("1.0");
$root = $doc->add_root("HTML");
$head = $root->new_child("HEAD", "");
$head->new_child("TITLE", "Hier der Titel");
echo htmlentities($doc->dump_mem());
?>

DomDocument->create_attribute

(no version information, might be only in CVS)

DomDocument->create_attribute -- Create new attribute

Description

object DomDocument->create_attribute ( string name, string value)

This function returns a new instance of class DomAttribute. The name of the attribute is the value of the first parameter. The value of the attribute is the value of the second parameter. This node will not show up in the document unless it is inserted with e.g. domnode_append_child().

The return value is FALSE if an error occurred.

See also domnode_append_child(), domdocument_create_element(), domdocument_create_text(), domdocument_create_cdata_section(), domdocument_create_processing_instruction(), domdocument_create_entity_reference(), and domnode_insert_before().

DomDocument->create_cdata_section

(no version information, might be only in CVS)

DomDocument->create_cdata_section -- Create new cdata node

Description

string DomDocument->create_cdata_section ( string content)

This function returns a new instance of class DomCData. The content of the cdata is the value of the passed parameter. This node will not show up in the document unless it is inserted with e.g. domnode_append_child().

The return value is FALSE if an error occurred.

See also domnode_append_child(), domdocument_create_element(), domdocument_create_text(), domdocument_create_attribute(), domdocument_create_processing_instruction(), domdocument_create_entity_reference(), and domnode_insert_before().

DomDocument->create_comment

(no version information, might be only in CVS)

DomDocument->create_comment -- Create new comment node

Description

object DomDocument->create_comment ( string content)

This function returns a new instance of class DomComment. The content of the comment is the value of the passed parameter. This node will not show up in the document unless it is inserted with e.g. domnode_append_child().

The return value is FALSE if an error occurred.

See also domnode_append_child(), domdocument_create_element(), domdocument_create_text(), domdocument_create_attribute(), domdocument_create_processing_instruction(), domdocument_create_entity_reference() and domnode_insert_before().

DomDocument->create_element_ns

(no version information, might be only in CVS)

DomDocument->create_element_ns --  Create new element node with an associated namespace

Description

object DomDocument->create_element_ns ( string uri, string name [, string prefix])

This function returns a new instance of class DomElement. The tag name of the element is the value of the passed parameter name. The URI of the namespace is the value of the passed parameter uri. If there is already a namespace declaration with the same uri in the root-node of the document, the prefix of this is taken, otherwise it will take the one provided in the optional parameter prefix or generate a random one. This node will not show up in the document unless it is inserted with e.g. domnode_append_child().

The return value is FALSE if an error occurred.

See also domdocument_create_element_ns(), domnode_add_namespace(), domnode_set_namespace(), domnode_append_child(), domdocument_create_text(), domdocument_create_comment(), domdocument_create_attribute(), domdocument_create_processing_instruction(), domdocument_create_entity_reference(), and domnode_insert_before().

DomDocument->create_element

(no version information, might be only in CVS)

DomDocument->create_element -- Create new element node

Description

object DomDocument->create_element ( string name)

This function returns a new instance of class DomElement. The tag name of the element is the value of the passed parameter. This node will not show up in the document unless it is inserted with e.g. domnode_append_child().

The return value is FALSE if an error occurred.

See also domdocument_create_element_ns(), domnode_append_child(), domdocument_create_text(), domdocument_create_comment(), domdocument_create_attribute(), domdocument_create_processing_instruction(), domdocument_create_entity_reference(), and domnode_insert_before().

DomDocument->create_entity_reference

(no version information, might be only in CVS)

DomDocument->create_entity_reference -- 

Description

object DomDocument->create_entity_reference ( string content)

This function returns a new instance of class DomEntityReference. The content of the entity reference is the value of the passed parameter. This node will not show up in the document unless it is inserted with e.g. domnode_append_child().

The return value is FALSE if an error occurred.

See also domnode_append_child(), domdocument_create_element(), domdocument_create_text(), domdocument_create_cdata_section(), domdocument_create_processing_instruction(), domdocument_create_attribute(), and domnode_insert_before().

DomDocument->create_processing_instruction

(no version information, might be only in CVS)

DomDocument->create_processing_instruction -- Creates new PI node

Description

string DomDocument->create_processing_instruction ( string content)

This function returns a new instance of class DomCData. The content of the pi is the value of the passed parameter. This node will not show up in the document unless it is inserted with e.g. domnode_append_child().

The return value is FALSE if an error occurred.

See also domnode_append_child(), domdocument_create_element(), domdocument_create_text(), domdocument_create_cdata_section(), domdocument_create_attribute(), domdocument_create_entity_reference(), and domnode_insert_before().

DomDocument->create_text_node

(no version information, might be only in CVS)

DomDocument->create_text_node -- Create new text node

Description

object DomDocument->create_text_node ( string content)

This function returns a new instance of class DomText. The content of the text is the value of the passed parameter. This node will not show up in the document unless it is inserted with e.g. domnode_append_child().

The return value is FALSE if an error occurred.

See also domnode_append_child(), domdocument_create_element(), domdocument_create_comment(), domdocument_create_text(), domdocument_create_attribute(), domdocument_create_processing_instruction(), domdocument_create_entity_reference(), and domnode_insert_before().

DomDocument->doctype

(no version information, might be only in CVS)

DomDocument->doctype --  Returns the document type

Description

object DomDocument->doctype ( void )

This function returns an object of class DomDocumentType. In versions of PHP before 4.3 this has been the class Dtd, but the DOM Standard does not know such a class.

See also the methods of class DomDocumentType.

DomDocument->document_element

(no version information, might be only in CVS)

DomDocument->document_element --  Returns root element node

Description

object DomDocument->document_element ( void )

This function returns the root element node of a document.

The following example returns just the element with name CHAPTER and prints it. The other node -- the comment -- is not returned.

Példa 1. Retrieving root element

<?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$root = $dom->document_element();
print_r($root);
?>

DomDocument->dump_file

(no version information, might be only in CVS)

DomDocument->dump_file --  Dumps the internal XML tree back into a file

Description

string DomDocument->dump_file ( string filename [, bool compressionmode [, bool format]])

Creates an XML document from the dom representation. This function usually is called after building a new dom document from scratch as in the example below. The format specifies whether the output should be neatly formatted, or not. The first parameter specifies the name of the filename and the second parameter, whether it should be compressed or not.

Példa 1. Creating a simple HTML document header

<?php
$doc = domxml_new_doc("1.0");
$root = $doc->create_element("HTML");
$root = $doc->append_child($root);
$head = $doc->create_element("HEAD");
$head = $root->append_child($head);
$title = $doc->create_element("TITLE");
$title = $head->append_child($title);
$text = $doc->create_text_node("This is the title");
$text = $title->append_child($text);
$doc->dump_file("/tmp/test.xml", false, true);
?>

See also domdocument_dump_mem() domdocument_html_dump_mem().

DomDocument->dump_mem

(no version information, might be only in CVS)

DomDocument->dump_mem --  Dumps the internal XML tree back into a string

Description

string DomDocument->dump_mem ( [bool format [, string encoding]])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Creates an XML document from the dom representation. This function usually is called after building a new dom document from scratch as in the example below. The format specifies whether the output should be neatly formatted, or not.

Példa 1. Creating a simple HTML document header

<?php
$doc = domxml_new_doc("1.0");
$root = $doc->create_element("HTML");
$root = $doc->append_child($root);
$head = $doc->create_element("HEAD");
$head = $root->append_child($head);
$title = $doc->create_element("TITLE");
$title = $head->append_child($title);
$text = $doc->create_text_node("This is the title");
$text = $title->append_child($text);
echo "<PRE>";
echo htmlentities($doc->dump_mem(true));
echo "</PRE>";
?>

Megjegyzés: The first parameter was added in PHP 4.3.0.

See also domdocument_dump_file(), domdocument_html_dump_mem().

DomDocument->get_element_by_id

(no version information, might be only in CVS)

DomDocument->get_element_by_id --  Searches for an element with a certain id

Description

object DomDocument->get_element_by_id ( string id)

This function is similar to domdocument_get_elements_by_tagname() but searches for an element with a given id. According to the DOM standard this requires a DTD which defines the attribute ID to be of type ID, though the current implementation simply does an xpath search for "//*[@ID = '%s']". This does not comply to the DOM standard which requires to return null if it is not known which attribute is of type id. This behaviour is likely to be fixed, so do not rely on the current behaviour.

See also domdocument_get_elements_by_tagname()

DomDocument->get_elements_by_tagname

(no version information, might be only in CVS)

DomDocument->get_elements_by_tagname -- 

Description

array DomDocument->get_elements_by_tagname ( string name)

See also domdocument_add_root()

DomDocument->html_dump_mem

(no version information, might be only in CVS)

DomDocument->html_dump_mem --  Dumps the internal XML tree back into a string as HTML

Description

string DomDocument->html_dump_mem ( void )

Creates an HTML document from the dom representation. This function usually is called after building a new dom document from scratch as in the example below.

Példa 1. Creating a simple HTML document header

<?php
$doc = domxml_new_doc("1.0");
$root = $doc->create_element("HTML");
$root = $doc->append_child($root);
$head = $doc->create_element("HEAD");
$head = $root->append_child($head);
$title = $doc->create_element("TITLE");
$title = $head->append_child($title);
$text = $doc->create_text_node("This is the title");
$text = $title->append_child($text);
echo "<PRE>";
echo htmlentities($doc->html_dump_mem());
echo "</PRE>";
?>

See also domdocument_dump_file(), domdocument_html_dump_mem().

DomDocument->xinclude

(no version information, might be only in CVS)

DomDocument->xinclude --  Substitutes XIncludes in a DomDocument Object.

Description

int DomDocument->xinclude ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

DomDocumentType->entities

(no version information, might be only in CVS)

DomDocumentType->entities --  Returns list of entities

Description

array DomDocumentType->entities ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

DomDocumentType->internal_subset

(no version information, might be only in CVS)

DomDocumentType->internal_subset --  Returns internal subset

Description

bool DomDocumentType->internal_subset ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

DomDocumentType->name

(no version information, might be only in CVS)

DomDocumentType->name --  Returns name of document type

Description

string DomDocumentType->name ( void )

This function returns the name of the document type.

DomDocumentType->notations

(no version information, might be only in CVS)

DomDocumentType->notations --  Returns list of notations

Description

array DomDocumentType->notations ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

DomDocumentType->public_id

(no version information, might be only in CVS)

DomDocumentType->public_id --  Returns public id of document type

Description

string DomDocumentType->public_id ( void )

This function returns the public id of the document type.

The following example echos nothing.

Példa 1. Retrieving the public id

<?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$doctype = $dom->doctype();
echo $doctype->public_id();
?>

DomDocumentType->system_id

(no version information, might be only in CVS)

DomDocumentType->system_id --  Returns system id of document type

Description

string DomDocumentType->system_id ( void )

Returns the system id of the document type.

The following example echos '/share/sgml/Norman_Walsh/db3xml10/db3xml10.dtd'.

Példa 1. Retrieving the system id

<?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$doctype = $dom->doctype();
echo $doctype->system_id();
?>

DomElement->get_attribute_node

(no version information, might be only in CVS)

DomElement->get_attribute_node --  Returns value of attribute

Description

object DomElement->get_attribute_node ( object attr)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

DomElement->get_attribute

(no version information, might be only in CVS)

DomElement->get_attribute --  Returns value of attribute

Description

object DomElement->get_attribute ( string name)

Returns the attribute with name name of the current node.

(PHP >= 4.3 only) If no attribute with given name is found, an empty string is returned.

See also domelement_set_attribute()

DomElement->get_elements_by_tagname

(no version information, might be only in CVS)

DomElement->get_elements_by_tagname --  Gets elements by tagname

Description

bool DomElement->get_elements_by_tagname ( string name)

This function returns an array with all the elements which has name as his tagname. Every element of the array is an DomElement.

Példa 1. Getting a content

<?php
if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$root = $dom->document_element();

$node_array = $root->get_elements_by_tagname("element");

for ($i = 0; $i<count($node_array); $i++) {
	$node = $node_array[$i];
	echo "The element[$i] is: " . $node->get_content();
}

?>

DomElement->has_attribute

(no version information, might be only in CVS)

DomElement->has_attribute --  Checks to see if attribute exists

Description

bool DomElement->has_attribute ( string name)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

DomElement->remove_attribute

(no version information, might be only in CVS)

DomElement->remove_attribute --  Removes attribute

Description

bool DomElement->remove_attribute ( string name)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

DomElement->set_attribute

(no version information, might be only in CVS)

DomElement->set_attribute --  Adds new attribute

Description

bool DomElement->set_attribute ( string name, string value)

Sets an attribute with name name to the given value. If the attribute does not exist, it will be created.

Példa 1. Setting an attribute

<?php
$doc = domxml_new_doc("1.0");
$node = $doc->create_element("para");
$newnode = $doc->append_child($node);
$newnode->set_attribute("align", "left");
?>

See also domelement_get_attribute()

DomElement->tagname

(no version information, might be only in CVS)

DomElement->tagname --  Returns name of element

Description

string DomElement->tagname ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

DomNode->add_namespace

(no version information, might be only in CVS)

DomNode->add_namespace --  Adds a namespace declaration to a node.

Description

bool DomNode->add_namespace ( string uri, string prefix)

See also domdocument_create_element_ns(), domnode_set_namespace()

DomNode->append_child

(no version information, might be only in CVS)

DomNode->append_child --  Adds new child at the end of the children

Description

object DomNode->append_child ( object newnode)

This functions 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_create_element(), domdocument_create_text() etc. or simply by using any other node.

(PHP < 4.3) Before a new child is appended it is first duplicated. Therefore the new child is a completely new copy which can be modified without changing the node which was passed to this function. If the node passed has children itself, they will be duplicated as well, which makes it quite easy to duplicate large parts of an XML document. The return value is the appended child. If you plan to do further modifications on the appended child you must use the returned node.

(PHP 4.3.0/4.3.1) The new child newnode is first unlinked from its existing context, if it's already a child of DomNode. Therefore the node is moved and not copies anymore.

(PHP >= 4.3.2) The new child newnode is first unlinked from its existing context, if it's already in the tree. Therefore the node is moved and not copied. This is the behaviour according to the W3C specifications. If you want to duplicate large parts of an XML document, use DomNode->clone_node() before appending.

The following example will add a new element node to a fresh document and sets the attribute "align" to "left".

Példa 1. Adding a child

<?php
$doc = domxml_new_doc("1.0");
$node = $doc->create_element("para");
$newnode = $doc->append_child($node);
$newnode->set_attribute("align", "left");
?>
The above example could also be written as the following:

Példa 2. Adding a child

<?php
$doc = domxml_new_doc("1.0");
$node = $doc->create_element("para");
$node->set_attribute("align", "left");
$newnode = $doc->append_child($node);
?>
A more complex example is the one below. It first searches for a certain element, duplicates it including its children and adds it as a sibling. Finally a new attribute is added to one of the children of the new sibling and the whole document is dumped.

Példa 3. Adding a child

<?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$elements = $dom->get_elements_by_tagname("informaltable");
print_r($elements);
$element = $elements[0];

$parent = $element->parent_node();
$newnode = $parent->append_child($element);
$children = $newnode->children();
$attr = $children[1]->set_attribute("align", "left");

echo "<pre>";
$xmlfile = $dom->dump_mem();
echo htmlentities($xmlfile);
echo "</pre>";
?>
The above example could also be done with domnode_insert_before() instead of domnode_append_child().

See also domnode_insert_before(), domnode_clone_node().

DomNode->append_sibling

(no version information, might be only in CVS)

DomNode->append_sibling --  Adds new sibling to a node

Description

object DomNode->append_sibling ( object newnode)

This functions appends a sibling to an existing node. The child can be created with e.g. domdocument_create_element(), domdocument_create_text() etc. or simply by using any other node.

Before a new sibling is added it is first duplicated. Therefore the new child is a completely new copy which can be modified without changing the node which was passed to this function. If the node passed has children itself, they will be duplicated as well, which makes it quite easy to duplicate large parts of an XML document. The return value is the added sibling. If you plan to do further modifications on the added sibling you must use the returned node.

This function has been added to provide the behaviour of domnode_append_child() as it works till PHP 4.2.

See also domnode_append_before().

DomNode->attributes

(no version information, might be only in CVS)

DomNode->attributes --  Returns list of attributes

Description

array DomNode->attributes ( void )

This function only returns an array of attributes if the node is of type XML_ELEMENT_NODE.

(PHP >= 4.3 only) If no attributes are found, NULL is returned.

DomNode->child_nodes

(no version information, might be only in CVS)

DomNode->child_nodes --  Returns children of node

Description

array DomNode->child_nodes ( void )

Returns all children of the node.

See also domnode_next_sibling(), domnode_previous_sibling().

DomNode->clone_node

(no version information, might be only in CVS)

DomNode->clone_node --  Clones a node

Description

object DomNode->clone_node ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

DomNode->dump_node

(no version information, might be only in CVS)

DomNode->dump_node --  Dumps a single node

Description

string DomNode->dump_node ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

See also domdocument_dump_mem().

DomNode->first_child

(no version information, might be only in CVS)

DomNode->first_child --  Returns first child of node

Description

object DomNode->first_child ( void )

Returns the first child of the node.

(PHP >= 4.3 only) If no first child is found, NULL is returned.

See also domnode_last_child(), domnode_next_sibling(), domnode_previous_sibling().

DomNode->get_content

(no version information, might be only in CVS)

DomNode->get_content --  Gets content of node

Description

string DomNode->get_content ( void )

This function returns the content of the actual node.

Példa 1. Getting a content

<?php
if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$root = $dom->document_element();

$node_array = $root->get_elements_by_tagname("element");

for ($i = 0; $i<count($node_array); $i++) {
 	$node = $node_array[$i];
 	echo "The element[$i] is: " . $node->get_content();
}

?>

DomNode->has_attributes

(no version information, might be only in CVS)

DomNode->has_attributes --  Checks if node has attributes

Description

bool DomNode->has_attributes ( void )

This function checks if the node has attributes.

See also domnode_has_child_nodes().

DomNode->has_child_nodes

(no version information, might be only in CVS)

DomNode->has_child_nodes --  Checks if node has children

Description

bool DomNode->has_child_nodes ( void )

This function checks if the node has children.

See also domnode_child_nodes().

DomNode->insert_before

(no version information, might be only in CVS)

DomNode->insert_before --  Inserts new node as child

Description

object DomNode->insert_before ( object newnode, object refnode)

This function inserts the new node newnode right before the node refnode. The return value is the inserted node. If you plan to do further modifications on the appended child you must use the returned node.

(PHP >= 4.3 only) If newnode already is part of a document, it will be first unlinked from its existing context. If refnode is NULL, then newnode will be inserted at the end of the list of children.

domnode_insert_before() is very similar to domnode_append_child() as the following example shows which does the same as the example at domnode_append_child().

Példa 1. Adding a child

<?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$elements = $dom->get_elements_by_tagname("informaltable");
print_r($elements);
$element = $elements[0];

$newnode = $element->insert_before($element, $element);
$children = $newnode->children();
$attr = $children[1]->set_attribute("align", "left");

echo "<PRE>";
$xmlfile = $dom->dump_mem();
echo htmlentities($xmlfile);
echo "</PRE>";
?>

See also domnode_append_child().

DomNode->is_blank_node

(no version information, might be only in CVS)

DomNode->is_blank_node --  Checks if node is blank

Description

bool DomNode->is_blank_node ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

DomNode->last_child

(no version information, might be only in CVS)

DomNode->last_child --  Returns last child of node

Description

object DomNode->last_child ( void )

Returns the last child of the node.

(PHP >= 4.3 only) If no last child is found, NULL is returned.

See also domnode_first_child(), domnode_next_sibling(), domnode_previous_sibling().

DomNode->next_sibling

(no version information, might be only in CVS)

DomNode->next_sibling --  Returns the next sibling of node

Description

object DomNode->next_sibling ( void )

This function returns the next sibling of the current node. If there is no next sibling it returns FALSE (< 4.3) or null (>= 4.3). You can use this function to iterate over all children of a node as shown in the example.

Példa 1. Iterate over children

<?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$elements = $dom->get_elements_by_tagname("tbody");
$element = $elements[0];
$child = $element->first_child();

while ($child) {
   print_r($child);
   $child = $child->next_sibling();
}
?>

See also domnode_previous_sibling().

DomNode->node_name

(no version information, might be only in CVS)

DomNode->node_name --  Returns name of node

Description

string DomNode->node_name ( void )

Returns name of the node. The name has different meanings for the different types of nodes as illustrated in the following table.

Táblázat 1. Meaning of value

TypeMeaning
DomAttributevalue of attribute
DomAttribute 
DomCDataSection#cdata-section
DomComment#comment
DomDocument#document
DomDocumentTypedocument type name
DomElementtag name
DomEntityname of entity
DomEntityReferencename of entity reference
DomNotationnotation name
DomProcessingInstructiontarget
DomText#text

DomNode->node_type

(no version information, might be only in CVS)

DomNode->node_type --  Returns type of node

Description

int DomNode->node_type ( void )

Returns the type of the node. All possible types are listed in the table in the introduction.

DomNode->node_value

(no version information, might be only in CVS)

DomNode->node_value --  Returns value of a node

Description

string DomNode->node_value ( void )

Returns value of the node. The value has different meanings for the different types of nodes as illustrated in the following table.

Táblázat 1. Meaning of value

TypeMeaning
DomAttributevalue of attribute
DomAttribute 
DomCDataSectioncontent
DomCommentcontent of comment
DomDocumentnull
DomDocumentTypenull
DomElementnull
DomEntitynull
DomEntityReferencenull
DomNotationnull
DomProcessingInstructionentire content without target
DomTextcontent of text

DomNode->owner_document

(no version information, might be only in CVS)

DomNode->owner_document --  Returns the document this node belongs to

Description

object DomNode->owner_document ( void )

This function returns the document the current node belongs to.

The following example will create two identical lists of children.

Példa 1. Finding the document of a node

<?php
$doc = domxml_new_doc("1.0");
$node = $doc->create_element("para");
$node = $doc->append_child($node);
$children = $doc->children();
print_r($children);

$doc2 = $node->owner_document();
$children = $doc2->children();
print_r($children);
?>

See also domnode_insert_before().

DomNode->parent_node

(no version information, might be only in CVS)

DomNode->parent_node --  Returns the parent of the node

Description

object DomNode->parent_node ( void )

This function returns the parent node.

(PHP >= 4.3 only) If no parent is found, NULL is returned.

The following example will show two identical lists of children.

Példa 1. Finding the document of a node

<?php
$doc = domxml_new_doc("1.0");
$node = $doc->create_element("para");
$node = $doc->append_child($node);
$children = $doc->children();
print_r($children);

$doc2 = $node->parent_node();
$children = $doc2->children();
print_r($children);
?>

DomNode->prefix

(no version information, might be only in CVS)

DomNode->prefix --  Returns name space prefix of node

Description

string DomNode->prefix ( void )

Returns the name space prefix of the node.

DomNode->previous_sibling

(no version information, might be only in CVS)

DomNode->previous_sibling --  Returns the previous sibling of node

Description

object DomNode->previous_sibling ( void )

This function returns the previous sibling of the current node. If there is no previous sibling it returns FALSE (< 4.3) or NULL (>= 4.3). You can use this function to iterate over all children of a node as shown in the example.

See also domnode_next_sibling().

DomNode->remove_child

(no version information, might be only in CVS)

DomNode->remove_child --  Removes child from list of children

Description

object DomNode->remove_child ( object oldchild)

This functions removes a child from a list of children. If child cannot be removed or is not a child the function will return FALSE. If the child could be removed the functions returns the old child.

Példa 1. Removing a child

<?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$elements = $dom->get_elements_by_tagname("tbody");
$element = $elements[0];
$children = $element->child_nodes();
$child = $element->remove_child($children[0]);

echo "<PRE>";
$xmlfile = $dom->dump_mem(true);
echo htmlentities($xmlfile);
echo "</PRE>";
?>

See also domnode_append_child().

DomNode->replace_child

(no version information, might be only in CVS)

DomNode->replace_child --  Replaces a child

Description

object DomNode->replace_child ( object oldnode, object newnode)

(PHP 4.2) This function replaces the child oldnode with the passed new node. If the new node is already a child it will not be added a second time. If the old node cannot be found the function returns FALSE. If the replacement succeeds the old node is returned.

(PHP 4.3) This function replaces the child oldnode with the passed newnode, even if the new node already is a child of the DomNode. If newnode was already inserted in the document it is first unlinked from its existing context. If the old node cannot be found the function returns FALSE. If the replacement succeeds the old node is returned. (This behaviour is according to the W3C specs).

See also domnode_append_child()

DomNode->replace_node

(no version information, might be only in CVS)

DomNode->replace_node --  Replaces node

Description

object DomNode->replace_node ( object newnode)

(PHP 4.2) This function replaces an existing node with the passed new node. Before the replacement newnode is copied if it has a parent to make sure a node which is already in the document will not be inserted a second time. This behaviour enforces doing all modifications on the node before the replacement or to refetch the inserted node afterwards with functions like domnode_first_child(), domnode_child_nodes() etc..

(PHP 4.3) This function replaces an existing node with the passed new node. It is not copied anymore. If newnode was already inserted in the document it is first unlinked from its existing context. If the replacement succeeds the old node is returned.

See also domnode_append_child()

DomNode->set_content

(no version information, might be only in CVS)

DomNode->set_content --  Sets content of node

Description

bool DomNode->set_content ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

DomNode->set_name

(no version information, might be only in CVS)

DomNode->set_name --  Sets name of node

Description

bool DomNode->set_name ( void )

Sets name of node.

See also domnode_node_name().

DomNode->set_namespace

(no version information, might be only in CVS)

DomNode->set_namespace --  Sets namespace of a node.

Description

void DomNode->set_namespace ( string uri [, string prefix])

Sets the namespace of a node to uri. If there is already a namespace declaration with the same uri in one of the parent nodes of the node, the prefix of this is taken, otherwise it will take the one provided in the optional parameter prefix or generate a random one.

See also domdocument_create_element_ns(), domnode_add_namespace()

DomNode->unlink_node

(no version information, might be only in CVS)

DomNode->unlink_node --  Deletes node

Description

object DomNode->unlink_node ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

DomProcessingInstruction->data

(no version information, might be only in CVS)

DomProcessingInstruction->data --  Returns data of pi node

Description

string DomProcessingInstruction->data ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

DomProcessingInstruction->target

(no version information, might be only in CVS)

DomProcessingInstruction->target --  Returns target of pi node

Description

string DomProcessingInstruction->target ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

DomXsltStylesheet->process

(no version information, might be only in CVS)

DomXsltStylesheet->process --  Applies the XSLT-Transformation on a DomDocument Object.

Description

object DomXsltStylesheet->process ( object DomDocument [, array xslt_parameters [, bool param_is_xpath]])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

See also domxml_xslt_stylesheet(), domxml_xslt_stylesheet_file(), domxml_xslt_stylesheet_doc()

DomXsltStylesheet->result_dump_file

(no version information, might be only in CVS)

DomXsltStylesheet->result_dump_file --  Dumps the result from a XSLT-Transformation into a file

Description

string DomXsltStylesheet->result_dump_file ( object DomDocument, string filename)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

This function is only available since PHP 4.3

Since DomXsltStylesheet->process() always returns a well-formed XML DomDocument, no matter what output method was declared in <xsl:output> and similar attributes/elements, it's of not much use, if you want to output HTML 4 or text data. This function on the contrary honors <xsl:output method="html|text"> and other output control directives. See the example for instruction of how to use it.

Példa 1. Saving the result of a XSLT transformation in a file

<?php
$filename = "stylesheet.xsl";
$xmldoc = domxml_open_file("data.xml");
$xsldoc = domxml_xslt_stylesheet_file($filename);
$result =  $xsldoc->process($xmldoc);
echo $xsldoc->result_dump_file($result, "filename");     
?>

See also domxml_xslt_result_dump_mem(), domxml_xslt_process()

DomXsltStylesheet->result_dump_mem

(no version information, might be only in CVS)

DomXsltStylesheet->result_dump_mem --  Dumps the result from a XSLT-Transformation back into a string

Description

string DomXsltStylesheet->result_dump_mem ( object DomDocument)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

This function is only available since PHP 4.3

Since DomXsltStylesheet->process() always returns a well-formed XML DomDocument, no matter what output method was declared in <xsl:output> and similar attributes/elements, it's of not much use, if you want to output HTML 4 or text data. This function on the contrary honors <xsl:output method="html|text"> and other output control directives. See the example for instruction of how to use it.

Példa 1. Outputting the result of a XSLT transformation

<?php
$filename = "stylesheet.xsl";
$xmldoc = domxml_open_file("data.xml");
$xsldoc = domxml_xslt_stylesheet_file($filename);
$result =  $xsldoc->process($xmldoc);
echo $xsldoc->result_dump_mem($result);     
?>

See also domxml_xslt_result_dump_file(), domxml_xslt_process()

domxml_new_doc

(PHP 4 >= 4.2.1)

domxml_new_doc --  Creates new empty XML document

Description

object domxml_new_doc ( string version)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Creates a new dom document from scratch and returns it.

See also domdocument_add_root()

domxml_open_file

(PHP 4 >= 4.2.1)

domxml_open_file -- Creates a DOM object from XML file

Description

object domxml_open_file ( string filename)

The function parses the XML document in the file named filename and returns an object of class "Dom document", having the properties as listed above. The file is accessed read-only.

Példa 1. Opening an XML document from a file

<?php

if (!$dom = domxml_open_file("example.xml")) {
  echo "Error while parsing the document\n";
  exit;
}

$root = $dom->document_element();
?>

See also domxml_open_mem(), domxml_new_doc().

domxml_open_mem

(PHP 4 >= 4.2.1)

domxml_open_mem -- Creates a DOM object of an XML document

Description

object domxml_open_mem ( string str)

The function parses the XML document in str and returns an object of class "Dom document", having the properties as listed above. This function, domxml_open_file() or domxml_new_doc() must be called before any other function calls.

Példa 1. Opening an XML document in a string

<?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$root = $dom->document_element();
?>

See also domxml_open_file(), domxml_new_doc().

domxml_version

(PHP 4 >= 4.1.0)

domxml_version --  Get XML library version

Description

string domxml_version ( void )

This function returns the version of the XML library version currently used.

domxml_xmltree

(PHP 4 >= 4.2.1)

domxml_xmltree --  Creates a tree of PHP objects from an XML document

Description

object domxml_xmltree ( string str)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

The function parses the XML document in str and returns a tree PHP objects as the parsed document. This function is isolated from the other functions, which means you cannot access the tree with any of the other functions. Modifying it, for example by adding nodes, makes no sense since there is currently no way to dump it as an XML file. However this function may be valuable if you want to read a file and investigate the content.

domxml_xslt_stylesheet_doc

(PHP 4 >= 4.2.0)

domxml_xslt_stylesheet_doc --  Creates a DomXsltStylesheet Object from a DomDocument Object.

Description

object domxml_xslt_stylesheet_doc ( object DocDocument Object)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

See also domxsltstylesheet->process(), domxml_xslt_stylesheet(), domxml_xslt_stylesheet_file()

domxml_xslt_stylesheet_file

(PHP 4 >= 4.2.0)

domxml_xslt_stylesheet_file --  Creates a DomXsltStylesheet Object from an XSL document in a file.

Description

object domxml_xslt_stylesheet_file ( string xsl file)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

See also domxsltstylesheet->process(), domxml_xslt_stylesheet(), domxml_xslt_stylesheet_doc()

domxml_xslt_stylesheet

(PHP 4 >= 4.2.0)

domxml_xslt_stylesheet --  Creates a DomXsltStylesheet Object from an XML document in a string.

Description

object domxml_xslt_stylesheet ( string xsl document)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

See also domxsltstylesheet->process(), domxml_xslt_stylesheet_file(), domxml_xslt_stylesheet_doc()

xpath_eval_expression

(PHP 4 >= 4.0.4)

xpath_eval_expression --  Evaluates the XPath Location Path in the given string

Description

array xpath_eval_expression ( object xpath_context)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

See also xpath_eval()

xpath_eval

(PHP 4 >= 4.0.4)

xpath_eval --  Evaluates the XPath Location Path in the given string

Description

array xpath_eval ( object xpath context, string xpath expression [, object contextnode])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

The optional contextnode can be specified for doing relative XPath queries.

See also xpath_new_context()

xpath_new_context

(PHP 4 >= 4.0.4)

xpath_new_context --  Creates new xpath context

Description

object xpath_new_context ( object dom document)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

See also xpath_eval()

xptr_eval

(PHP 4 >= 4.0.4)

xptr_eval --  Evaluate the XPtr Location Path in the given string

Description

int xptr_eval ( [object xpath_context, string eval_str])

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

xptr_new_context

(PHP 4 >= 4.0.4)

xptr_new_context --  Create new XPath Context

Description

string xptr_new_context ( [object doc_handle])

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

XXV. .NET functions

Bevezetés

Figyelem

Ez a kiterjesztés KÍSÉRLETI JELLEGGEL MŰKÖDIK. Ez azt jelenti, hogy minden itt dokumentált működés, beleértve a függvények nevét, működését vagy bármi más, amit a kiterjesztés kapcsán leírtunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a kiterjesztést csak a saját felelősségedre használd!

Tartalom
dotnet_load -- Loads a DOTNET module

dotnet_load

(no version information, might be only in CVS)

dotnet_load -- Loads a DOTNET module

Description

int dotnet_load ( string assembly_name [, string datatype_name [, int codepage]])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

XXVI. Error Handling and Logging Functions

Bevezetés

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.


Követelmények

Az itt leírt függvények használatához semmilyen külső függvénykönyvtár megléte nem szükségeltetik.


Telepítés

Semmilyen telepítés nem szükséges ezen függvények használatához, a PHP alapelemei.


Futásidejű beállítások

Az alábbi függvények viselkedése befolyásolható a php.ini segítségével.

Táblázat 1. Errors and Logging Configuration Options

NameDefaultChangeable
error_reportingE_ALL & ~E_NOTICEPHP_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
ignore_repeated_errors"0"PHP_INI_ALL
ignore_repeated_source"0"PHP_INI_ALL
report_memleaks"1"PHP_INI_SYSTEM
track_errors"0"PHP_INI_ALL
html_errors"1"PHP_INI_ALL
docref_root""PHP_INI_ALL
docref_ext""PHP_INI_ALL
error_prepend_stringNULLPHP_INI_ALL
error_append_stringNULLPHP_INI_ALL
error_logNULLPHP_INI_ALL
warn_plus_overloadingNULLPHP_INI??
For further details and definition of the PHP_INI_* constants see ini_set().

Here's a short explanation of the configuration directives.

error_reporting integer

Set the error reporting level. The parameter is either an integer representing a bit field, or named constants. The error_reporting levels and constants are described in Predefined Constants, and in php.ini. To set at runtime, use the error_reporting() function. See also the display_errors directive.

In PHP 4 and PHP 5 the default value is E_ALL & ~E_NOTICE. This setting does not show E_NOTICE level errors. You may want to show them during development.

Megjegyzés: 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.

Megjegyzés: In PHP 5 a new error level E_STRICT is available. As E_STRICT is not included within E_ALL you have to explicitly enable this kind of error level. Enabling E_STRICT during development has some benefits. STRICT messages will help you to use the latest and greatest suggested method of coding, for example warn you about using deprecated functions.

In PHP 3, the default setting is (E_ERROR | E_WARNING | E_PARSE), meaning the same thing. Note, however, that since constants are not supported in PHP 3's php3.ini, the error_reporting setting there must be numeric; hence, it is 7.

display_errors boolean

This determines whether errors should be printed to the screen as part of the output or if they should be hidden from the user.

Megjegyzés: This is a feature to support your development and should never be used on production systems (e.g. systems connected to the internet).

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.

Megjegyzés: 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.

ignore_repeated_errors boolean

Do not log repeated messages. Repeated errors must occur in the same file on the same line until ignore_repeated_source is set true.

ignore_repeated_source boolean

Ignore source of message when ignoring repeated messages. When this setting is On you will not log errors with repeated messages from different files or sourcelines.

report_memleaks boolean

If this parameter is set to Off, then memory leaks will not be shown (on stdout or in the log). This has only effect in a debug compile, and if error_reporting includes E_WARNING in the allowed list

track_errors boolean

If enabled, the last error message will always be present in the variable $php_errormsg.

html_errors boolean

Turn off HTML tags in error messages. The new format for HTML errors produces clickable messages that direct the user to a page describing the error or function in causing the error. These references are affected by docref_root and docref_ext.

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.

Megjegyzés: 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.

Megjegyzés: 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. 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().

warn_plus_overloading boolean

If enabled, this option makes PHP output a warning when the plus (+) operator is used on strings. This is to make it easier to find scripts that need to be rewritten to using the string concatenator instead (.).


Előre definiált állandók

Az itt felsorolt konstansok mindig elérthetőek, mivel részei a PHP alaptelepítésének.

Megjegyzés: 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.

Táblázat 2. Errors and Logging

ValueConstantDescriptionNote
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. PHP 4 only
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. PHP 4 only
64 E_COMPILE_ERROR (integer) Fatal compile-time errors. This is like an E_ERROR, except it is generated by the Zend Scripting Engine. PHP 4 only
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. PHP 4 only
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(). PHP 4 only
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(). PHP 4 only
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(). PHP 4 only
2047 E_ALL (integer) All errors and warnings, as supported, except of level E_STRICT.  
2048 E_STRICT (integer) Run-time notices. Enable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code. PHP 5 only

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, however, and that no bitwise operators will be understood within php3.ini.


Példák

Below we can see an example of using the error handling capabilities in PHP. We define an error handling function which logs the information into a file (using an XML format), and e-mails the developer in case a critical error in the logic happens.

Példa 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 2,8,256,512 and 1024
    $errortype = array (
                1    =>  "Error",
                2    =>  "Warning",
                4    =>  "Parsing Error",
                8    =>  "Notice",
                16   =>  "Core Error",
                32   =>  "Core Warning",
                64   =>  "Compile Error",
                128  =>  "Compile Warning",
                256  =>  "User Error",
                512  =>  "User Warning",
                1024 =>  "User Notice"
                );
    // 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";

?>


Lásd még

See also syslog().

Tartalom
debug_backtrace --  Generates a backtrace
debug_print_backtrace --  Prints a backtrace
error_log -- Hiabüzenet küldése
error_reporting -- Beállítja a hibajelentési szintet
restore_error_handler --  Visszaállítja a korábbi hibakezelő függvényt
set_error_handler --  felhasználói hibakezelő függvényt regisztrál
trigger_error --  Felhasználói szintű hibát/figyelmeztetést/megjegyzést jelez
user_error --  Felhasználói szintű hibát/figyelmeztetést/megjegyzést jelez

debug_backtrace

(PHP 4 >= 4.3.0)

debug_backtrace --  Generates a backtrace

Description

array debug_backtrace ( void )

debug_backtrace() generates a PHP backtrace and returns this information as an associative array. The possible returned elements are listed in the following table:

Táblázat 1. Possible returned elements from debug_backtrace()

NameTypeDescription
functionstring The current function name. See also __FUNCTION__.
lineinteger The current line number. See also __LINE__.
filestring The current file name. See also __FILE__.
classstring The current class name. See also __CLASS__
typestring The current call type. If a method call, "->" is returned. If a static method call, "::" is returned. If a function call, nothing is returned.
argsarray If inside a function, this lists the functions arguments. If inside an included file, this lists the included file name(s).

The following is a simple example.

Példa 1. debug_backtrace() example

// filename: a.php
<?php

function a_test($str) 
{

    echo "\nHi: $str";

    var_dump(debug_backtrace());
}

a_test('friend');
?>

// filename: b.php
<?php
include_once '/tmp/a.php';
?>

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

See also trigger_error() and debug_print_backtrace().

debug_print_backtrace

(PHP 5 CVS only)

debug_print_backtrace --  Prints a backtrace

Description

void debug_print_backtrace ( void )

debug_print_backtrace() prints a PHP backtrace.

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

See also debug_backtrace().

error_log

(PHP 3, PHP 4 )

error_log -- Hiabüzenet küldése

Leírás

int error_log ( string message [, int message_type [, string destination [, string extra_headers]]])

Ezzel a függvénnyel hibaüzenetet küldhetsz a kiszolgáló hiba naplójába, egy TCP portra, vagy egy állományba. Az első, message paraméterben a hibaüzenetet kell megadnod, a második, message_type paraméterben az üzenet célját:

Táblázat 1. error_log() napőló típusok

0 A message paraméterben megadott üzenet a PHP rendszer naplójába kerül, az operációs rendszer naplóját vagy egy állományt megcélozva, az error_log beállítás értékétől függően.
1 A message paraméterben megadott üzenetet elektronikus levélben a destination paraméterben megadott címre küldi. Ez az egyetlen típus, amelynél a negyedik extra_headers paraméter használható. Ez a típus a mail() által is használt belső függvényt használja.
2 A message paraméterben megadott üzenetet a PHP debug kapcsolatán keresztül küldi tovább. Ez a lehetőség csak akkor elérhető, ha a távoli debugger támogatás engedélyezett. Ebben az esetben a destination paraméter azt a hoszt nevet vagy IP címet - és opcionálisan port számot - adja meg, ami a debug információkat fogadni képes.
3 A message paraméterben megadott üzenetet a destination állomány végén hozzáfűzésre kerül.

Figyelem

A távoli debug funkviók TCP/IP kapcsolaton keresztül a PHP 3-as verziókban elérhetőek voltak. Ez a funkció nem használható a PHP 4-es verziókban.

Példa 1. error_log() példák

// Naplózzuk a rendszer naplóba a sikertelen adatbázis
// kapcsolódási kísérletet
if (!Ora_Logon ($usernev, $jelszo)) {
    error_log ("Az Oracle adatbázis nem elérhető!", 0);
}

// Figyelmeztetés az adminisztátornak, ha kifogyunk az izéből
if (!($ize = uj_ize_lefoglalasa()) {
    error_log ("Nagy gond van, végképp nincs több izé!", 1,
               "webmester@pelda.hu");
}

// Más naplózási típusok
error_log ("Általános gond van!", 2, "127.0.0.1:7000");
error_log ("Általános gond van!", 2, "loghost");
error_log ("Általános gond van!", 3, "/var/tmp/my-errors.log");

error_reporting

(PHP 3, PHP 4 )

error_reporting -- Beállítja a hibajelentési szintet

Leírás

int error_reporting ( [int level])

Az error_reporting() függvény futási időben állítja be az error_reporting direktíva értékét. A PHP-ban sok különböző hibaszint van, ezzel a függvénnyel ezt a szintet lehet megváltoztatni a szkript futása idejére.

error_reporting() függvény beállítja a PHP hibakezelési szintjét, és az előzőleg érvényes szint értékét adja vissza. A level paraméter vagy egy bitmaszk vagy egy hibajelentési állandó. Az állandók használata erősen javasolt, mivel a számok megváltozhatnak a későbbi verziókban, ahogy egyre több hibaszintet definiál a PHP.

Példa 1. Hibajelentési változások

<?php

// minden hibajelzés kikapcsolása
error_reporting(0);

// csak az egyszerű futási hibák kijelzése
error_reporting  (E_ERROR | E_WARNING | E_PARSE);

// E_NOTICE szintű hibák kijelzése ugyancsak hasznos
// (inicializálatlan változók kijelzésére,
// vagy változónevek elgépelésének kiszűrésére)
error_reporting (E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

// E_NOTICEn kívül minden hiba kijelzése
// Ez az alapbeállítás a php.ini-ben
error_reporting (E_ALL ^ E_NOTICE);

// Minden PHP hiba kijelzése (bitenkénti 63 használható PHP 3-ban)
error_reporting (E_ALL);

// ugyanaz, mint fent: error_reporting (E_ALL);
ini_set ('error_reporting', E_ALL);

?>

A létező hibaszinteket reprezentáló állandók listáj aalább olvasható. A hibaszintek pontos jelentése a Hibakezelés fejezet alatt olvasható.

Táblázat 1. error_reporting() hibaszint állandók és értékeik

értékkonstans
1 E_ERROR
2 E_WARNING
4 E_PARSE
8 E_NOTICE
16 E_CORE_ERROR
32 E_CORE_WARNING
64 E_COMPILE_ERROR
128 E_COMPILE_WARNING
256 E_USER_ERROR
512 E_USER_WARNING
1024 E_USER_NOTICE

Lásd még: display_errors direktíva és ini_set()!

restore_error_handler

(PHP 4 >= 4.0.1)

restore_error_handler --  Visszaállítja a korábbi hibakezelő függvényt

Leírás

void restore_error_handler ( void )

Ez a függvényt a set_error_handler()-el átállított hibakezelő függvény visszaállítására használható (ami lehet a beépített, vagy korábban beállított hibakezelő).

Lásd még error_reporting(), set_error_handler(), trigger_error() és user_error().

set_error_handler

(PHP 4 >= 4.0.1)

set_error_handler --  felhasználói hibakezelő függvényt regisztrál

Leírás

string set_error_handler ( string error_handler)

A error_handler paraméterben megadott felhasználó által létrehozott hibakezelő függvényt állítja be a szkriptben felbukkanó hibák kezelésére. Visszatérési értéke a korábbi hibakazelő (ha volt ilyen), vagy FALSE hiba esetén. Ez a függvény használható futásidőben saját hibakezelő függvény definiálására, ha például a saját ideiglenes adatállományaid hiba esetén törlésre szorulnak, vagy ha a trigger_error() függvényt testreszabott hibaüzenetek küldésére szeretnéd használni.

Megjegyzés: A függvény neve helyett egy tömböt is átadhatsz, ami egy objektum referenciát és egy metódus nevet kell tartalmazzon.

Megjegyzés: A következő hibafajták nem kezelhetők le saját, felhasználói hibakezelő-függvényekkel: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR és E_COMPILE_WARNING.

A függvényt, amit megadsz két paramétert kell, hogy fogadjon, a hibakódot és a hibaüzenet karaktersorozatát. A PHP 4.0.2 verzió óta újabb három elhagyható paraméter is rendelkezésre áll: az állomány neve, ahol a hiba felbukkant, a sorszám, ahol a hiba megjelent, és az aktuális környezet (egy, a hiba létrejöttekor aktív szimbólum táblára mutató tömb).

A következő példa bemutatja, hogy hoyagn kell kezelni a belső kivételeket a felhasználói hibák keltésével, és egy felhasználó által definiált függvénnyel:

Példa 1. Hibakezelés a set_error_handler() és trigger_error() függvényekkel

<?php

// Rövidebb nevek a felhasználói hibákhoz - csak PHP 4-ben
define ('FATAL', E_USER_ERROR);
define ('ERROR', E_USER_WARNING);
define ('WARNING', E_USER_NOTICE);

// A hibajelentési szint beállítása
error_reporting (FATAL | ERROR | WARNING);

// Hibakezelő függvény létrehozása
function hibaKezelo ($hszam, $hszoveg, $hfile, $hsor) {
  switch ($hszam) {
  case FATAL:
    echo "<b>FATÁLIS HIBA</b> [$errno] $errstr<br>\n";
    echo " Fatális hiba a ".$errline.". sorban a ".$errfile;
    echo " állományban, PHP ".PHP_VERSION." (".PHP_OS.")<br>\n";
    echo "Kilépés...<br>\n";
    exit(1);
    break;
  case ERROR:
    echo "<b>HIBA</b> [$errno] $errstr<br>\n";
    break;
  case WARNING:
    echo "<b>FIGYELMEZTETÉS</b> [$errno] $errstr<br>\n";
    break;
    default:
    echo "Ismeretlen hibatípus: [$errno] $errstr<br>\n";
    break;
  }
}

// Függvény, ami teszteli a hibakezelést
function log_szorzas ($vektor, $mertek) {
  if (!is_numeric($mertek) || $mertek <= 0)
    trigger_error("log(x) x <= 0 esetén nem definiált (a megadott $mertek érték hibás)",
      FATAL);
  if (!is_array($vektor)) {
    trigger_error("Hibás vektor, értékek tömbjét kell megadni", ERROR);
    return null;
  }
  for ($i=0; $i<count($vektor); $i++) {
    if (!is_numeric($vektor[$i]))
      trigger_error("A vektor $i. eleme nem szám, nullával számolok",
        WARNING);
    $ideiglenes[$i] = log($mertek) * $vektor[$i];
  }
  return $ideiglenes;
}

// A felhasználói hibakezelő beállítása
$regi_hiba_kezelo = set_error_handler("hibaKezelo");

// Tömb nem szám értékkel
echo "'a' vektor\n";
$a = array(2,3,"izé",5.5,43.3,21.11);
print_r($a);

// Figyelmeztetés generálása, új tömb létrehozása
echo "----\n'b' vektor - figyelmeztetés (b = log(PI) * a)\n";
$b = log_szorzas($a, M_PI);
print_r($b);

// Ebből gond lesz, karaktersorozatot adunk át tömb helyett
echo "----\n'c' vektor - hiba\n";
$c = log_szorzas("ez nem tömb", 2.3);
var_dump($c);

// Ez kritikus hiba lesz, negatív szám logaritmusa nem értelmezett
echo "----\n'd' vektor - fatális hiba\n";
$d = log_szorzas($a, -2.5);

?>
Amikor futtatod a fenti példát, a következő kimetetet kapod:

'a' vektor
Array
(
    [0] => 2
    [1] => 3
    [2] => izé
    [3] => 5.5
    [4] => 43.3
    [5] => 21.11
)
----
'b' vektor - figyelmeztetés (b = log(PI) * a)
<b>FIGYELMEZTETÉS</b> [1024] A vektor 2. eleme nem szám, nullával számolok<br>
Array
(
    [0] => 2.2894597716988
    [1] => 3.4341896575482
    [2] => 0
    [3] => 6.2960143721717
    [4] => 49.566804057279
    [5] => 24.165247890281
)
----
'c' vektor - hiba
<b>HIBA</b> [512] Hibás vektor, értékek tömbjét kell megadni<br>
NULL
----
'd' vektor - fatális hiba
<b>FATÁLIS HIBA</b> [256] log(x) x <= 0 esetén nem definiált (a megadott -2.5 érték hibás)<br>
  Fatális hiba a 36. sorban a trigger_error.php állományban, PHP 4.0.2 (Linux)<br>
Kilépés...<br>

Fontos megjegyezni, hogy a PHP belső hibakezelője teljesen figyelmen kívül marad. Az error_reporting() beállítások nem befolyásolják a felhasználói hibakezelő meghívását, minden hiba esetén lefut a hibakezelő az aktuális szinttől függetlenül. Ha ezt el szeretnéd kerülni, a hibakezelőben olvasd be az aktuális szintet (error_reporting), és írd meg úgy a függvényt, hogy annak megfelelően viselkedjen. Szintén fontos megjegyezni, hogy ez az érték 0 lesz, ha azt a parancsot, ami éppen meghívásra került a @ hibakezelő oprátorral adták meg.

Arról sem szabad elfeledkezni, hogy a programozó felelőssége a szkript futás megszakítása, ha ez szükséges (például a exit() meghívásával). Ha a hibakezelő függvény visszatér, a szkript futása is folytatódni fog a következő paranccsal.

Megjegyzés: Ha bármilyen hiba keletkezik, még mielőtt a szkript elindulna (e.g. fájl feltöltésekor) a felhasználói hibakezelő nem indul, hiszen abban a pillanatban még nincs is regisztrálva.

Lásd még: error_reporting(), restore_error_handler(), trigger_error() és user_error()!

trigger_error

(PHP 4 >= 4.0.1)

trigger_error --  Felhasználói szintű hibát/figyelmeztetést/megjegyzést jelez

Leírás

void trigger_error ( string error_msg [, int error_type])

Ez a függvény a belső vagy saját hibakezelő függvény számára küldött felhasználói szintű jelzés keltésére használható. A saját hibakezelő függvényt a set_error_handler() függvénnyel állíthatod be. A trigger_error() csak az E_USER hibacsaláddal használható, alapbeállításban E_USER_NOTICE hibát jelez.

Ez a függvény hasznos, ha futás közben egy kivételt kell kezelned. Például:

if (assert ($nevezo == 0))
   trigger_error ("Nullával nem lehet osztani", E_USER_ERROR);

Megjegyzés: Lásd a set_error_handler() leírást, ahol egy bővebb példa található.

Lásd még error_reporting(), set_error_handler(), restore_error_handler() és user_error().

user_error

(PHP 4 )

user_error --  Felhasználói szintű hibát/figyelmeztetést/megjegyzést jelez

Leírás

void user_error ( string error_msg [, int error_type])

Ez a függvény tulajdonképpen csak egy második név a trigger_error() függvény számára.

Lásd még error_reporting(), set_error_handler(), restore_error_handler() és trigger_error().

XXVII. File alteration monitor functions

Bevezetés

FAM monitors files and directories, notifying interested applications of changes.

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.

Megjegyzés: Ez a kiterjesztés nem működik Windows operációs rendszereken!


Követelmények

This extension requires ... version ... as available on ...


Telepítés


Futásidejű beállítások

Ez a kiterjesztés semmilyen konfigurációs beállításokat nem definiál a php.ini állományban.


Erőforrás típusok

FAM resource


Előre definiált állandók

Az itt listázott állandókat ez a kiterjesztés definiálja, és csak akkor elérhetőek, ha az adott kiterjesztés be van fordítva a PHP-be, vagy dinamikusan betöltött.

Táblázat 1. FAM constants

Constantmeaning
FAMChanged (integer) The status of
FAMDeleted (integer)  
FAMStartExecuting (integer)  
FAMStopExecuting (integer)  
FAMCreated (integer)  
FAMMoved (integer)  
FAMAcknowledge (integer)  
FAMExists (integer)  
FAMEndExist (integer)  

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

fam_cancel_monitor

(PHP 5 CVS only)

fam_cancel_monitor -- Terminate monitoring

Description

bool fam_cancel_monitor ( resource fam, resource fam_monitor)

fam_cancel_monitor() terminates monitoring on a resource previously requested using one of the fam_monitor_...().

See also fam_monitor_file(), fam_monitor_directory(), fam_monitor_collection(), and fam_suspend_monitor()

fam_close

(PHP 5 CVS only)

fam_close -- Close FAM connection

Description

void fam_close ( resource fam)

fam_close() closes a connection to the FAM service previously opened using fam_open().

fam_monitor_collection

(PHP 5 CVS only)

fam_monitor_collection -- Monitor a collection of files in a directory for changes

Description

resource fam_monitor_collection ( resource fam, string dirname, int depth, string mask)

fam_monitor_file() requests monitoring for a collection of files within a directory. The actual files to be monitored are specified by a directory path in dirname, the maximum search depth starting from this directory and a shell pattern restricting the file names to look for.

See also fam_monitor_file(), fam_monitor_directory(), fam_cancel_monitor(), fam_suspend_monitor(), and fam_resume_monitor().

fam_monitor_directory

(PHP 5 CVS only)

fam_monitor_directory -- Monitor a directory for changes

Description

resource fam_monitor_directory ( resource fam, string dirname)

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

See also fam_monitor_file(), fam_monitor_collection(), fam_cancel_monitor(), fam_suspend_monitor(), and fam_resume_monitor().

fam_monitor_file

(PHP 5 CVS only)

fam_monitor_file -- Monitor a regular file for changes

Description

resource fam_monitor_file ( resource fam, string filename)

fam_monitor_file() requests monitoring for a single file. A FAM event will be generated whenever the file status (i.e. the result of function stat() on that file) changes.

See also fam_monitor_directory(), fam_monitor_collection(), fam_cancel_monitor(), fam_suspend_monitor(), and fam_resume_monitor().

fam_next_event

(PHP 5 CVS only)

fam_next_event -- ...

Description

array fam_next_event ( resource fam)

fam_next_event() returns the next pending FAM event. The function will block until an event is available which can be checked for using fam_pending().

fam_ext_event() will return an array that contains a FAM event code in element 'code', the path of the file this event applies to in element 'filename' and optionally a hostname in element 'hostname'.

The possible event codes are described in detail in the introduction part of this section.

See also fam_pending().

fam_open

(PHP 5 CVS only)

fam_open -- Open connection to FAM daemon

Description

resource fam_open ( [string appname])

fam_open() opens a connection to the FAM service daemon. The optional parameter appname should be set to a string identifying the application for logging reasons.

See also fam_close().

fam_pending

(PHP 5 CVS only)

fam_pending -- Check for pending FAM events

Description

bool fam_pending ( resource fam)

fam_pending() returns TRUE if events are available to be fetched using fam_next_event().

See also fam_next_event().

fam_resume_monitor

(PHP 5 CVS only)

fam_resume_monitor -- Resume suspended monitoring

Description

bool fam_resume_monitor ( resource fam, resource fam_monitor)

fam_resume_monitor() resumes monitoring of a resource previously suspend using fam_suspend_monitor().

See also fam_suspend_monitor().

fam_suspend_monitor

(PHP 5 CVS only)

fam_suspend_monitor -- Temporarily suspend monitoring

Description

bool fam_suspend_monitor ( resource fam, resource fam_monitor)

fam_suspend_monitor() temporarily suspend monitoring of a resource previously requested using one of the fam_monitor_...() functions. Monitoring can later be continued using fam_resume_monitor() without the need of requesting a complete new monitor.

See also fam_resume_monitor(), and fam_cancel_monitor().

XXVIII. FrontBase Functions

Bevezetés

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/FrontBase.woa/wa/productsPage?currentPage=Documentation.

Frontbase support has been added to PHP 4.0.6.


Követelmények

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


Telepítés

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.


Futásidejű beállítások

Az alábbi függvények viselkedése befolyásolható a php.ini segítségével.

Táblázat 1. FrontBase configuration options

NameDefaultChangeable
fbsql.allow_persistent"1"PHP_INI_SYSTEM
fbsql.generate_warnings"0"PHP_INI_SYSTEM
fbsql.autocommit"1"PHP_INI_SYSTEM
fbsql.max_persistent"-1"PHP_INI_SYSTEM
fbsql.max_links"128"PHP_INI_SYSTEM
fbsql.max_connections"128"PHP_INI_SYSTEM
fbsql.max_results"128"PHP_INI_SYSTEM
fbsql.batchSize"1000"PHP_INI_SYSTEM
fbsql.default_hostNULLPHP_INI_SYSTEM
fbsql.default_user"_SYSTEM"PHP_INI_SYSTEM
fbsql.default_password""PHP_INI_SYSTEM
fbsql.default_database""PHP_INI_SYSTEM
fbsql.default_database_password""PHP_INI_SYSTEM
For further details and definition of the PHP_INI_* constants see ini_set().


Erőforrás típusok


Előre definiált állandók

Az itt listázott állandókat ez a kiterjesztés definiálja, és csak akkor elérhetőek, ha az adott kiterjesztés be van fordítva a PHP-be, vagy dinamikusan betöltött.

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)

Tartalom
fbsql_affected_rows --  Get number of affected rows in previous FrontBase operation
fbsql_autocommit -- Enable or disable autocommit
fbsql_change_user --  Change logged in user of the active connection
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 numerical value of the error message from previous FrontBase operation
fbsql_error --  Returns the text of the error message from previous FrontBase 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 -- No description given yet
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_select_db -- Select a FrontBase database
fbsql_set_lob_mode --  Set the LOB retrieve mode for a FrontBase result set
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 -- Get table name of field
fbsql_username -- Get or set the host user used with a connection
fbsql_warnings -- Enable or disable FrontBase warnings

fbsql_affected_rows

(PHP 4 >= 4.0.6)

fbsql_affected_rows --  Get number of affected rows in previous FrontBase operation

Description

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. If the link identifier isn't specified, the last link opened by fbsql_connect() is assumed.

Megjegyzés: 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.

Megjegyzés: 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.

If the last query failed, this function will return -1.

See also: fbsql_num_rows().

fbsql_autocommit

(PHP 4 >= 4.0.6)

fbsql_autocommit -- Enable or disable autocommit

Description

bool fbsql_autocommit ( resource link_identifier [, bool OnOff])

fbsql_autocommit() returns the current autocommit status. If the optional OnOff 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().

See also: fbsql_commit() and fbsql_rollback()

fbsql_change_user

(no version information, might be only in CVS)

fbsql_change_user --  Change logged in user of the active connection

Description

resource fbsql_change_user ( string user, string password [, string database [, resource link_identifier]])

fbsql_change_user() changes the logged in user of the current active connection, or the connection given by the optional parameter link_identifier. If a database is specified, this will default or current database after the user has been changed. If the new user and password authorization fails, the current connected user stays active.

fbsql_close

(PHP 4 >= 4.0.6)

fbsql_close -- Close FrontBase connection

Description

bool fbsql_close ( [resource link_identifier])

Returns: TRUE on success, FALSE on error.

fbsql_close() closes the connection to the FrontBase server that's associated with the specified link identifier. If link_identifier isn't specified, the last opened link is used.

Using fbsql_close() isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.

Példa 1. fbsql_close() example

<?php
    $link = fbsql_connect("localhost", "_SYSTEM", "secret")
        or die("Could not connect");
    echo "Connected successfully";
    fbsql_close($link);
?>

See also: fbsql_connect() and fbsql_pconnect().

fbsql_commit

(PHP 4 >= 4.0.6)

fbsql_commit -- Commits a transaction to the database

Description

bool fbsql_commit ( [resource link_identifier])

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

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

See also: fbsql_autocommit() and fbsql_rollback()

fbsql_connect

(PHP 4 >= 4.0.6)

fbsql_connect -- Open a connection to a FrontBase Server

Description

resource fbsql_connect ( [string hostname [, string username [, string password]]])

Returns a positive FrontBase link identifier on success, or an error message on failure.

fbsql_connect() establishes a connection to a FrontBase server. The following defaults are assumed for missing optional parameters: hostname = 'NULL', username = '_SYSTEM' and password = empty password.

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

Példa 1. fbsql_connect() example

<?php

    $link = fbsql_connect("localhost", "_SYSTEM", "secret")
        or die("Could not connect");
    echo "Connected successfully";
    fbsql_close($link);

?>

See also fbsql_pconnect() and fbsql_close().

fbsql_create_blob

(PHP 4 >= 4.2.0)

fbsql_create_blob -- Create a BLOB

Description

string fbsql_create_blob ( string blob_data [, resource link_identifier])

Returns: A resource handle to the newly created blob.

fbsql_create_blob() creates a blob from blob_data. The returned resource handle can be used with insert and update commands to store the blob in the database.

Példa 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);
?>

See also: fbsql_create_clob(), fbsql_read_blob(), fbsql_read_clob(), and fbsql_set_lob_mode().

fbsql_create_clob

(PHP 4 >= 4.2.0)

fbsql_create_clob -- Create a CLOB

Description

string fbsql_create_clob ( string clob_data [, resource link_identifier])

Returns: A resource handle to the newly created CLOB.

fbsql_create_clob() creates a clob from clob_data. The returned resource handle can be used with insert and update commands to store the clob in the database.

Példa 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);
?>

See also: fbsql_create_blob(), fbsql_read_blob(), fbsql_read_clob(), and fbsql_set_lob_mode().

fbsql_create_db

(PHP 4 >= 4.0.6)

fbsql_create_db -- Create a FrontBase database

Description

bool fbsql_create_db ( string database_name [, resource link_identifier])

fbsql_create_db() attempts to create a new database named database_name on the server associated with the specified connection link_identifier.

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

See also: fbsql_drop_db().

fbsql_data_seek

(PHP 4 >= 4.0.6)

fbsql_data_seek -- Move internal result pointer

Description

bool fbsql_data_seek ( resource result_identifier, int row_number)

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

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

Row_number starts at 0.

Példa 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_database_password

(PHP 4 >= 4.0.6)

fbsql_database_password --  Sets or retrieves the password for a FrontBase database

Description

string fbsql_database_password ( resource link_identifier [, string database_password])

Returns: The database password associated with the link identifier.

fbsql_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 the second optional parameter is given the function sets the database password for the specified 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 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.

Példa 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);
?>

See also: fbsql_connect(), fbsql_pconnect() and fbsql_select_db().

fbsql_database

(PHP 4 >= 4.0.6)

fbsql_database -- Get or set the database name used with a connection

Description

string fbsql_database ( resource link_identifier [, string database])

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

fbsql_db_query

(PHP 4 >= 4.0.6)

fbsql_db_query -- Send a FrontBase query

Description

resource fbsql_db_query ( string database, string query [, resource link_identifier])

Returns: A positive FrontBase result identifier to the query result, or FALSE on error.

fbsql_db_query() selects a database and executes a query on it. If the optional link identifier isn't specified, the function will try to find an open link to the FrontBase server and if no such link is found it'll try to create one as if fbsql_connect() was called with no arguments

See also fbsql_connect().

fbsql_db_status

(PHP 4 >= 4.1.0)

fbsql_db_status -- Get the status for a given database

Description

int fbsql_db_status ( string database_name [, resource link_identifier])

Returns: An integer value with the current status.

fbsql_db_status() requests the current status of the database specified by database_name. If the link_identifier is omitted the default link_identifier will be used.

The return value 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.

See also: fbsql_start_db() and fbsql_stop_db().

fbsql_drop_db

(PHP 4 >= 4.0.6)

fbsql_drop_db -- Drop (delete) a FrontBase database

Description

bool fbsql_drop_db ( string database_name [, resource link_identifier])

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

fbsql_drop_db() attempts to drop (remove) an entire database from the server associated with the specified link identifier.

fbsql_errno

(PHP 4 >= 4.0.6)

fbsql_errno --  Returns the numerical value of the error message from previous FrontBase operation

Description

int fbsql_errno ( [resource link_identifier])

Returns the error number from the last fbsql function, or 0 (zero) if no error occurred.

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.

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

See also: fbsql_error() and fbsql_warnings().

fbsql_error

(PHP 4 >= 4.0.6)

fbsql_error --  Returns the text of the error message from previous FrontBase operation

Description

string fbsql_error ( [resource link_identifier])

Returns the error text from the last fbsql function, or '' (the empty string) if no error occurred.

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

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

See also: fbsql_errno() and fbsql_warnings().

fbsql_fetch_array

(PHP 4 >= 4.0.6)

fbsql_fetch_array --  Fetch a result row as an associative array, a numeric array, or both

Description

array fbsql_fetch_array ( resource result [, int result_type])

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

fbsql_fetch_array() is an extended version of fbsql_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 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

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.

The optional second argument result_type in fbsql_fetch_array() is a constant and can take the following values: FBSQL_ASSOC, FBSQL_NUM, and FBSQL_BOTH.

For further details, see also fbsql_fetch_row() and fbsql_fetch_assoc().

Példa 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);
?>

fbsql_fetch_assoc

(PHP 4 >= 4.0.6)

fbsql_fetch_assoc --  Fetch a result row as an associative array

Description

array fbsql_fetch_assoc ( resource result)

Returns an associative array that corresponds to the fetched row, or FALSE if there are no more rows.

fbsql_fetch_assoc() is equivalent to calling fbsql_fetch_array() with FBSQL_ASSOC for the optional 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().

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.

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.

For further details, see also fbsql_fetch_row() and fbsql_fetch_array().

Példa 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);
?>

fbsql_fetch_field

(PHP 4 >= 4.0.6)

fbsql_fetch_field --  Get column information from a result and return as an object

Description

object fbsql_fetch_field ( resource result [, int field_offset])

Returns an object containing field information.

fbsql_fetch_field() can be used in order to obtain information about fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by fbsql_fetch_field() is retrieved.

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

Példa 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);
?>

See also fbsql_field_seek().

fbsql_fetch_lengths

(PHP 4 >= 4.0.6)

fbsql_fetch_lengths --  Get the length of each output in a result

Description

array fbsql_fetch_lengths ( [resource result])

Returns: An array that corresponds to the lengths of each field in the last row fetched by fbsql_fetch_row(), or FALSE on error.

fbsql_fetch_lengths() 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, starting at offset 0.

See also: fbsql_fetch_row().

fbsql_fetch_object

(PHP 4 >= 4.0.6)

fbsql_fetch_object -- Fetch a result row as an object

Description

object fbsql_fetch_object ( resource result [, int result_type])

Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows.

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

The optional argument result_type is a constant and can take the following values: FBSQL_ASSOC, FBSQL_NUM, and FBSQL_BOTH.

Speed-wise, the function is identical to fbsql_fetch_array(), and almost as quick as fbsql_fetch_row() (the difference is insignificant).

Példa 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);
?>

See also: fbsql_fetch_array() and fbsql_fetch_row().

fbsql_fetch_row

(PHP 4 >= 4.0.6)

fbsql_fetch_row -- Get a result row as an enumerated array

Description

array fbsql_fetch_row ( resource result)

Returns: An array that corresponds to the fetched row, or FALSE if there are no more rows.

fbsql_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 fbsql_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.

See also: fbsql_fetch_array(), fbsql_fetch_object(), fbsql_data_seek(), fbsql_fetch_lengths(), and fbsql_result().

fbsql_field_flags

(PHP 4 >= 4.0.6)

fbsql_field_flags --  Get the flags associated with the specified field in a result

Description

string fbsql_field_flags ( resource result, int field_offset)

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

fbsql_field_len

(PHP 4 >= 4.0.6)

fbsql_field_len --  Returns the length of the specified field

Description

int fbsql_field_len ( resource result, int field_offset)

fbsql_field_len() returns the length of the specified field.

fbsql_field_name

(PHP 4 >= 4.0.6)

fbsql_field_name --  Get the name of the specified field in a result

Description

string fbsql_field_name ( resource result, int field_index)

fbsql_field_name() returns the name of the specified field index. result must be a valid result identifier and field_index is the numerical offset of the field.

Megjegyzés: field_index starts at 0.

e.g. The index of the third field would actually be 2, the index of the fourth field would be 3 and so on.

Példa 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);
?>

The above example would produce the following output:

user_id
password

fbsql_field_seek

(PHP 4 >= 4.0.6)

fbsql_field_seek --  Set result pointer to a specified field offset

Description

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.

See also: fbsql_fetch_field().

fbsql_field_table

(PHP 4 >= 4.0.6)

fbsql_field_table --  Get name of the table the specified field is in

Description

string fbsql_field_table ( resource result, int field_offset)

Returns the name of the table that the specified field is in.

fbsql_field_type

(PHP 4 >= 4.0.6)

fbsql_field_type --  Get the type of the specified field in a result

Description

string fbsql_field_type ( resource result, int field_offset)

fbsql_field_type() is similar to the fbsql_field_name() function. The arguments are identical, but the field type is returned instead. The field type will be one of "int", "real", "string", "blob", and others as detailed in the FrontBase documentation.

Példa 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();

?>

fbsql_free_result

(PHP 4 >= 4.0.6)

fbsql_free_result -- Free result memory

Description

bool fbsql_free_result ( resource result)

fbsql_free_result() will free all memory associated with the result identifier result.

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.

fbsql_get_autostart_info

(PHP 4 >= 4.1.0)

fbsql_get_autostart_info -- No description given yet

Description

array fbsql_get_autostart_info ( [resource link_identifier])

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

fbsql_hostname

(PHP 4 >= 4.0.6)

fbsql_hostname -- Get or set the host name used with a connection

Description

string fbsql_hostname ( resource link_identifier [, string host_name])

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

fbsql_insert_id

(PHP 4 >= 4.0.6)

fbsql_insert_id --  Get the id generated from the previous INSERT operation

Description

int fbsql_insert_id ( [resource link_identifier])

fbsql_insert_id() returns the ID generated for an column defined as DEFAULT UNIQUE by the previous INSERT query using the given link_identifier. If link_identifier isn't specified, the last opened link is assumed.

fbsql_insert_id() returns 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 fbsql_insert_id() immediately after the query that generates the value.

Megjegyzés: 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.

fbsql_list_dbs

(PHP 4 >= 4.0.6)

fbsql_list_dbs --  List databases available on a FrontBase server

Description

resource fbsql_list_dbs ( [resource link_identifier])

fbsql_list_dbs() will return a result pointer containing the databases available from the current fbsql daemon. Use the fbsql_tablename() function to traverse this result pointer.

Példa 1. fbsql_list_dbs() example

$link = fbsql_connect('localhost', 'myname', 'secret');
$db_list = fbsql_list_dbs($link);

while ($row = fbsql_fetch_object($db_list)) {
    echo $row->Database . "\n";
}

The above example would produce the following output:

database1
database2
database3
...

Megjegyzés: The above code would just as easily work with fbsql_fetch_row() or other similar functions.

fbsql_list_fields

(PHP 4 >= 4.0.6)

fbsql_list_fields -- List FrontBase result fields

Description

resource fbsql_list_fields ( string database_name, string table_name [, resource link_identifier])

fbsql_list_fields() retrieves information about the given tablename. Arguments are the database name and the table name. A result pointer is returned which can be used with fbsql_field_flags(), fbsql_field_len(), fbsql_field_name(), and fbsql_field_type().

A result identifier is a positive integer. The function returns FALSE if an error occurs. 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.

Példa 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";;
}
?>

The above example would produce the following output:

field1
field2
field3
...

fbsql_list_tables

(PHP 4 >= 4.0.6)

fbsql_list_tables -- List tables in a FrontBase database

Description

resource fbsql_list_tables ( string database [, resource link_identifier])

fbsql_list_tables() takes a database name and returns a result pointer much like the fbsql_db_query() function. The fbsql_tablename() function should be used to extract the actual table names from the result pointer.

fbsql_next_result

(PHP 4 >= 4.0.6)

fbsql_next_result --  Move the internal result pointer to the next result

Description

bool fbsql_next_result ( resource result_id)

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. The function will return TRUE if an additional result set was available or FALSE otherwise.

Példa 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_num_fields

(PHP 4 >= 4.0.6)

fbsql_num_fields -- Get number of fields in result

Description

int fbsql_num_fields ( resource result)

fbsql_num_fields() returns the number of fields in a result set.

See also: fbsql_db_query(), fbsql_query(), fbsql_fetch_field(), and fbsql_num_rows().

fbsql_num_rows

(PHP 4 >= 4.0.6)

fbsql_num_rows -- Get number of rows in result

Description

int fbsql_num_rows ( resource result)

fbsql_num_rows() returns the number of rows in a result set. This command is only valid for SELECT statements. To retrieve the number of rows returned from a INSERT, UPDATE or DELETE query, use fbsql_affected_rows().

Példa 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";

?>

See also: fbsql_affected_rows(), fbsql_connect(), fbsql_select_db(), and fbsql_query().

fbsql_password

(PHP 4 >= 4.0.6)

fbsql_password -- Get or set the user password used with a connection

Description

string fbsql_password ( resource link_identifier [, string password])

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

fbsql_pconnect

(PHP 4 >= 4.0.6)

fbsql_pconnect --  Open a persistent connection to a FrontBase Server

Description

resource fbsql_pconnect ( [string hostname [, string username [, string password]]])

Returns: A positive FrontBase persistent link identifier on success, or FALSE on error.

fbsql_pconnect() establishes a connection to a FrontBase server. The following defaults are assumed for missing optional parameters: host = 'localhost', username = "_SYSTEM" and password = empty password.

To set Frontbase 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'.

fbsql_query

(PHP 4 >= 4.0.6)

fbsql_query -- Send a FrontBase query

Description

resource fbsql_query ( string query [, resource link_identifier])

fbsql_query() sends a query to the currently active database on the server that's associated with the specified link identifier. If 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 fbsql_connect() was called with no arguments, and use it.

Megjegyzés: The query string shall always end with a semicolon.

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.

The following query is syntactically invalid, so fbsql_query() fails and returns FALSE:

Példa 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:

Példa 2. fbsql_query() example

<?php
$result = fbsql_query ("SELECT my_col FROM my_tbl")
    or die ("Invalid query");
?>

fbsql_query() will also fail and return FALSE if you don't have permission to access the table(s) referenced by the query.

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

For SELECT statements, fbsql_query() returns a new result identifier that you can pass to fbsql_result(). When you are done with the result set, you can free the resources associated with it by calling fbsql_free_result(). Although, the memory will automatically be freed at the end of the script's execution.

See also: fbsql_affected_rows(), fbsql_db_query(), fbsql_free_result(), fbsql_result(), fbsql_select_db(), and fbsql_connect().

fbsql_read_blob

(PHP 4 >= 4.2.0)

fbsql_read_blob -- Read a BLOB from the database

Description

string fbsql_read_blob ( string blob_handle [, resource link_identifier])

Returns: A string containing the BLOB specified by blob_handle.

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

Példa 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);
    
?>

See also: fbsql_create_blob(), fbsql_read_blob(), fbsql_read_clob(), and fbsql_set_lob_mode().

fbsql_read_clob

(PHP 4 >= 4.2.0)

fbsql_read_clob -- Read a CLOB from the database

Description

string fbsql_read_clob ( string clob_handle [, resource link_identifier])

Returns: A string containing the CLOB specified by clob_handle.

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

Példa 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);
    
?>

See also: fbsql_create_blob(), fbsql_read_blob(), fbsql_read_clob(), and fbsql_set_lob_mode().

fbsql_result

(PHP 4 >= 4.0.6)

fbsql_result -- Get result data

Description

mixed fbsql_result ( resource result, int row [, mixed field])

fbsql_result() returns the contents of one cell from a FrontBase result set. The field argument can be the field's offset, or the field's name, or the field's table dot field's name (tabledname.fieldname). If the column name has been aliased ('select foo as bar from...'), use the alias instead of the column name.

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(). Also, note that specifying a numeric offset for the field argument is much quicker than specifying a fieldname or tablename.fieldname argument.

Calls to fbsql_result() should not be mixed with calls to other functions that deal with the result set.

Recommended high-performance alternatives: fbsql_fetch_row(), fbsql_fetch_array(), and fbsql_fetch_object().

fbsql_rollback

(PHP 4 >= 4.0.6)

fbsql_rollback -- Rollback a transaction to the database

Description

bool fbsql_rollback ( [resource link_identifier])

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

fbsql_rollback() ends the current transaction by rolling back all statements issued since last commit. This command is only needed if autocommit is set to false.

See also: fbsql_autocommit() and fbsql_commit()

fbsql_select_db

(PHP 4 >= 4.0.6)

fbsql_select_db -- Select a FrontBase database

Description

bool fbsql_select_db ( string database_name [, resource link_identifier])

fbsql_select_db() sets the current active database on the server that's associated with the specified 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 fbsql_connect() was called, and use it.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

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.

if the database is protected with a database password, the user must call fbsql_database_password() before selecting the database.

See also fbsql_connect(), fbsql_pconnect(), fbsql_database_password(), and fbsql_query().

fbsql_set_lob_mode

(PHP 4 >= 4.2.0)

fbsql_set_lob_mode --  Set the LOB retrieve mode for a FrontBase result set

Description

bool fbsql_set_lob_mode ( resource result, string database_name)

Returns: TRUE on success, FALSE on error.

fbsql_set_lob_mode() sets the mode for retrieving LOB data from the database. When BLOB and CLOB data is stored in FrontBase it can be stored direct or indirect. Direct stored 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 stored directly.

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

See also: fbsql_create_blob(), fbsql_create_clob(), fbsql_read_blob(), and fbsql_read_clob().

fbsql_set_transaction

(PHP 4 >= 4.2.0)

fbsql_set_transaction --  Set the transaction locking and isolation

Description

void fbsql_set_transaction ( resource link_identifier, int Locking, int Isolation)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

fbsql_start_db

(PHP 4 >= 4.0.6)

fbsql_start_db -- Start a database on local or remote server

Description

bool fbsql_start_db ( string database_name [, resource link_identifier])

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

fbsql_start_db()

See also: fbsql_db_status() and fbsql_stop_db().

fbsql_stop_db

(PHP 4 >= 4.0.6)

fbsql_stop_db -- Stop a database on local or remote server

Description

bool fbsql_stop_db ( string database_name [, resource link_identifier])

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

fbsql_stop_db()

See also: fbsql_db_status() and fbsql_start_db().

fbsql_tablename

(PHP 4 >= 4.2.0)

fbsql_tablename -- Get table name of field

Description

string fbsql_tablename ( resource result, int i)

fbsql_tablename() takes a result pointer returned by the fbsql_list_tables() function as well as an integer index and returns the name of a table. The fbsql_num_rows() function may be used to determine the number of tables in the result pointer.

Példa 1. fbsql_tablename() example

<?php 
fbsql_connect("localhost", "_SYSTEM", "");
$result = fbsql_list_tables("wisconsin");
$i = 0;
while ($i < fbsql_num_rows($result)) {
    $tb_names[$i] = fbsql_tablename($result, $i);
    echo $tb_names[$i] . "<br />";
    $i++;
}
?>

fbsql_username

(PHP 4 >= 4.0.6)

fbsql_username -- Get or set the host user used with a connection

Description

string fbsql_username ( resource link_identifier [, string username])

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

fbsql_warnings

(PHP 4 >= 4.0.6)

fbsql_warnings -- Enable or disable FrontBase warnings

Description

bool fbsql_warnings ( [bool OnOff])

Returns TRUE if warnings is turned on otherwise FALSE.

fbsql_warnings() enables or disables FrontBase warnings.

XXIX. filePro függvények

Ezek a függvények lehetőséget adnak a filePro adatbázisok olvasásására.

A filePro az fP Technologies, Inc. bejegyzett védjegye. További információk a filePro-ról a http://www.fptech.com/ címen találhatóak.

Tartalom
filepro_fieldcount -- Visszaadja a mezők számát
filepro_fieldname -- Visszaadja a mező nevét
filepro_fieldtype -- Visszaadja a mező típusát
filepro_fieldwidth -- Visszaadja a mező hosszát
filepro_retrieve -- Adatok lekérése a filePro adatbázisból
filepro_rowcount -- Visszaadja a sorok számát
filepro -- Beolvassa, és ellenőrzi a map fájlt

filepro_fieldcount

(PHP 3, PHP 4 )

filepro_fieldcount -- Visszaadja a mezők számát

Leírás

int filepro_fieldcount ( void )

A megnyitott filePro adatbázis mezőinek (oszlopainak) számával tér vissza.

Lásd még a filepro() függvényt.

filepro_fieldname

(PHP 3, PHP 4 )

filepro_fieldname -- Visszaadja a mező nevét

Leírás

string filepro_fieldname ( int field_number)

Visszaadja a field_number számú mező nevét.

filepro_fieldtype

(PHP 3, PHP 4 )

filepro_fieldtype -- Visszaadja a mező típusát

Leírás

string filepro_fieldtype ( int field_number)

Visszaadja a field_number számú mező típusát.

filepro_fieldwidth

(PHP 3, PHP 4 )

filepro_fieldwidth -- Visszaadja a mező hosszát

Leírás

int filepro_fieldwidth ( int field_number)

Visszaadja a field_number számú mező hosszát.

filepro_retrieve

(PHP 3, PHP 4 )

filepro_retrieve -- Adatok lekérése a filePro adatbázisból

Leírás

string filepro_retrieve ( int row_number, int field_number)

Visszaadja az adatbázis megadott elérésén található adatot.

filepro_rowcount

(PHP 3, PHP 4 )

filepro_rowcount -- Visszaadja a sorok számát

Leírás

int filepro_rowcount ( void )

Visszaadja a megnyitott filePro adatbázis sorainak számát.

Lásd még a filepro() függvényt.

filepro

(PHP 3, PHP 4 )

filepro -- Beolvassa, és ellenőrzi a map fájlt

Leírás

bool filepro ( string directory)

Beolvassa, és ellenőrzi a map fájlt, ami a mezőszámot és információkat tartalmazza.

Nem történik kizárólagos lefoglalás (locking), ezért nem szabad a PHP által megnyitott filePro adatbázisokat módosítani.

XXX. Filesystem functions

Bevezetés


Követelmények

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.


Telepítés

Semmilyen telepítés nem szükséges ezen függvények használatához, a PHP alapelemei.


Futásidejű beállítások

Az alábbi függvények viselkedése befolyásolható a php.ini segítségével.

Táblázat 1. Filesystem and Streams Configuration Options

NameDefaultChangeable
allow_url_fopen"1"PHP_INI_ALL
user_agentNULLPHP_INI_ALL
default_socket_timeout"60"PHP_INI_ALL
fromNULL??
auto_detect_line_endings"Off"PHP_INI_ALL

Here's a short explanation of the configuration directives.

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.

Megjegyzés: 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.

Figyelem

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 XLI, Képmanipuláló függvények Referencia extension.

user_agent string

Define the user agent for PHP to send.

default_socket_timeout integer

Default timeout (in seconds) for socket based streams.

Megjegyzés: This configuration option was introduced in PHP 4.3.0

from="joe@example.com" string

Define the anonymous ftp password (your email address).

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.

Megjegyzés: This configuration option was introduced in PHP 4.3.0


Erőforrás típusok


Előre definiált állandók

Az itt listázott állandókat ez a kiterjesztés definiálja, és csak akkor elérhetőek, ha az adott kiterjesztés be van fordítva a PHP-be, vagy dinamikusan betöltött.

GLOB_BRACE (integer)

GLOB_ONLYDIR (integer)

GLOB_MARK (integer)

GLOB_NOSORT (integer)

GLOB_NOCHECK (integer)

GLOB_NOESCAPE (integer)

PATHINFO_DIRNAME (integer)

PATHINFO_BASENAME (integer)

PATHINFO_EXTENSION (integer)

FILE_USE_INCLUDE_PATH (integer)

FILE_APPEND (integer)

FILE_IGNORE_NEW_LINES (integer)

FILE_SKIP_EMPTY_LINES (integer)


Lásd még

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 J Függelék.

Tartalom
basename -- Returns filename 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 directory name component of path
disk_free_space -- Returns available space in directory
disk_total_space -- Returns the total size of a directory
diskfreespace -- Alias of 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
fputs -- Alias of 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 -- Tells file pointer read/write position
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 the filename is readable
is_uploaded_file -- Tells whether the file was uploaded via HTTP POST
is_writable -- Tells whether the filename is writable
is_writeable -- Alias of is_writable()
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
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 -- Returns canonicalized absolute pathname
rename -- Renames a file
rewind -- Rewind the position of a file pointer
rmdir -- Removes directory
set_file_buffer -- Alias of 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

basename

(PHP 3, PHP 4 )

basename -- Returns filename component of path

Description

string basename ( string path [, string suffix])

Given a string containing a path to a file, this function will return the base name of the file. If the filename ends in suffix this will also be cut off.

On Windows, both slash (/) and backslash (\) are used as path separator character. In other environments, it is the forward slash (/).

Példa 1. basename() example

<?php
$path = "/home/httpd/html/index.php";
$file = basename($path);        // $file is set to "index.php"
$file = basename($path, ".php"); // $file is set to "index"
?>

Megjegyzés: The suffix parameter was added in PHP 4.1.0.

See also: dirname()

chgrp

(PHP 3, PHP 4 )

chgrp -- Changes file group

Description

bool chgrp ( string filename, mixed group)

Attempts to change the group of the file filename to group (specified by name or number). 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.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Megjegyzés: Ez a függvény nem fog távoli fájlokkal működni, az a szerver helyi fájlrendszerén lesz keresve.

Megjegyzés: Ha a safe mode be van kapcsolva, a PHP ellenőrzi, hogy az állományok vagy könyvtárak, amelyekkel dolgozni szeretnél, ugyanazzal a felhasználói azonosítóval (UID) rendelkeznek-e, mint az éppen futó program.

See also chown() and chmod().

chmod

(PHP 3, PHP 4 )

chmod -- Changes file mode

Description

bool chmod ( string filename, int mode)

Attempts to change the mode of the file specified by filename to that given in mode.

Note that mode is not automatically assumed to be an octal value, so strings (such as "g+w") will not work properly. To ensure the expected operation, you need to prefix mode with a zero (0):

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

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Megjegyzés: 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.

Megjegyzés: Ez a függvény nem fog távoli fájlokkal működni, az a szerver helyi fájlrendszerén lesz keresve.

Megjegyzés: When safe mode 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

See also chown() and chgrp().

chown

(PHP 3, PHP 4 )

chown -- Changes file owner

Description

bool chown ( string filename, mixed user)

Attempts to change the owner of the file filename to user user (specified by name or number). Only the superuser may change the owner of a file.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Megjegyzés: Ez a függvény nem fog távoli fájlokkal működni, az a szerver helyi fájlrendszerén lesz keresve.

Megjegyzés: Ha a safe mode be van kapcsolva, a PHP ellenőrzi, hogy az állományok vagy könyvtárak, amelyekkel dolgozni szeretnél, ugyanazzal a felhasználói azonosítóval (UID) rendelkeznek-e, mint az éppen futó program.

See also chmod().

clearstatcache

(PHP 3, PHP 4 )

clearstatcache -- Clears file status cache

Description

void clearstatcache ( void )

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.

Megjegyzés: 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().

copy

(PHP 3, PHP 4 )

copy -- Copies file

Description

bool copy ( string source, string dest)

Makes a copy of the file source to dest. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Példa 1. copy() example

<?php
if (!copy($file, $file.'.bak')) {
    echo "failed to copy $file...<br />\n";
}
?>

Megjegyzés: As of PHP 4.3.0, both source and dest may be URLs if the "fopen wrappers" have been enabled. See fopen() for more details. If dest is a URL, the copy operation may fail if the wrapper does not support overwriting of existing files.

Figyelem

If the destination file already exists, it will be overwritten.

See also move_uploaded_file(), rename(), and the section of the manual about handling file uploads.

delete

(no version information, might be only in CVS)

delete -- See unlink() or unset()

Description

void delete ( string file)

This is a dummy manual entry to satisfy those people who are looking for unlink() or unset() in the wrong place.

See also: unlink() to delete files, unset() to delete variables.

dirname

(PHP 3, PHP 4 )

dirname -- Returns directory name component of path

Description

string dirname ( string path)

Given a string containing a path to a file, this function will return the name of the directory.

On Windows, both slash (/) and backslash (\) are used as path separator character. In other environments, it is the forward slash (/).

Példa 1. dirname() example

<?php
$path = "/etc/passwd";
$file = dirname($path); // $file is set to "/etc"
?>

Megjegyzés: In PHP 4.0.3, dirname() was fixed to be POSIX-compliant. Essentially, this means that 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. Note that this means that you will often get a slash or a dot back from dirname() in situations where the older functionality would have given you the empty string.

See also basename(), pathinfo(), and realpath().

disk_free_space

(PHP 4 >= 4.1.0)

disk_free_space -- Returns available space in directory

Description

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.

Példa 1. disk_free_space() example

<?php
// $df contains the number of bytes available on "/"
$df = disk_free_space("/");

// On Windows:
disk_free_space("C:");
disk_free_space("D:");
?>

Megjegyzés: Ez a függvény nem fog távoli fájlokkal működni, az a szerver helyi fájlrendszerén lesz keresve.

See also disk_total_space()

disk_total_space

(PHP 4 >= 4.1.0)

disk_total_space -- Returns the total size of a directory

Description

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.

Példa 1. disk_total_space() example

<?php
// $df contains the total number of bytes available on "/"
$df = disk_total_space("/");

// On Windows:
disk_total_space("C:");
disk_total_space("D:");
?>

Megjegyzés: Ez a függvény nem fog távoli fájlokkal működni, az a szerver helyi fájlrendszerén lesz keresve.

See also disk_free_space()

diskfreespace

diskfreespace -- Alias of disk_free_space()

Description

This function is an alias of disk_free_space().

fclose

(PHP 3, PHP 4 )

fclose -- Closes an open file pointer

Description

bool fclose ( resource handle)

The file pointed to by handle is closed.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen().

Példa 1. A simple fclose() example

<?php

  $handle = fopen('somefile.txt', 'r');
  
  fclose($handle);
  
?>

feof

(PHP 3, PHP 4 )

feof -- Tests for end-of-file on a file pointer

Description

bool feof ( resource handle)

Returns TRUE if the file pointer is at EOF or an error occurs (including socket timeout); otherwise returns FALSE.

Figyelem

feof() will return TRUE only if the connection opened by fsockopen() is closed. This can cause a script to timeout. The workaround for this is to use stream_set_timeout(), so that feof() will return FALSE on timeout.

The file pointer must be valid, and must point to a file successfully opened by fopen(), popen(), or fsockopen().

fflush

(PHP 4 >= 4.0.1)

fflush -- Flushes the output to a file

Description

bool fflush ( resource handle)

This function forces a write of all buffered output to the resource pointed to by the file handle handle. Returns TRUE if successful, FALSE otherwise.

The file pointer must be valid, and must point to a file successfully opened by fopen(), popen(), or fsockopen().

fgetc

(PHP 3, PHP 4 )

fgetc -- Gets character from file pointer

Description

string fgetc ( resource handle)

Returns a string containing a single character read from the file pointed to by handle. Returns FALSE on EOF.

The file pointer must be valid, and must point to a file successfully opened by fopen(), popen(), or fsockopen().

Figyelem

Ez a függvény a logikai típusú FALSE értékkel is visszatérhet, olyan nem logikai típusú értékek mellett, amik szintén FALSE értékként jelenhetnek meg (mint pl. 0 vagy ""). Olvasd el a Logikai típusról szóló részt további információkért. Használd a === operátort a visszatérési érték ellenőrzésére.

Példa 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";
}
?>

Megjegyzés: Ez a függvény "binary-safe", azaz helyesen kezeli a 127-es ASCII kód feletti karaktereket is.

See also fread(), fopen(), popen(), fsockopen(), and fgets().

fgetcsv

(PHP 3>= 3.0.8, PHP 4 )

fgetcsv -- Gets line from file pointer and parse for CSV fields

Description

array fgetcsv ( resource handle, int length [, string delimiter [, string enclosure]])

Similar to fgets() except that fgetcsv() parses the line it reads for fields in CSV format and returns an array containing the fields read. The optional third delimiter parameter defaults as a comma, and the optional enclosure defaults as a double quotation mark. Both delimiter and enclosure are limited to one character. If either is more than one character, only the first character is used.

Megjegyzés: The enclosure parameter was added in PHP 4.3.0.

The handle parameter must be a valid file pointer to a file successfully opened by fopen(), popen(), or fsockopen().

The length parameter must be greater than the longest line to be found in the CSV file (allowing for trailing line-end characters).

fgetcsv() returns FALSE on error, including end of file.

Megjegyzés: 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.

Példa 1. Read and print the entire contents of a CSV file

<?php
$row = 1;
$handle = fopen("test.csv", "r");
while ($data = fgetcsv($handle, 1000, ",")) {
    $num = count($data);
    echo "<p> $num fields in line $row: <br />\n";
    $row++;
    for ($c=0; $c < $num; $c++) {
        echo $data[$c] . "<br />\n";
    }
}
fclose($handle);
?>

See also explode(), file(), and pack()

fgets

(PHP 3, PHP 4 )

fgets -- Gets line from file pointer

Description

string fgets ( resource handle [, int length])

Returns a string of up to length - 1 bytes read from the file pointed to by handle. Reading ends when length - 1 bytes have been read, on a newline (which is included in the return value), or on EOF (whichever comes first). If no length is specified, the length defaults to 1k, or 1024 bytes.

If an error occurs, returns FALSE.

Common Pitfalls:

People used to the 'C' semantics of fgets() should note the difference in how EOF is returned.

The file pointer must be valid, and must point to a file successfully opened by fopen(), popen(), or fsockopen().

A simple example follows:

Példa 1. Reading a file line by line

<?php
$handle = fopen("/tmp/inputfile.txt", "r");
while (!feof($handle)) {
    $buffer = fgets($handle, 4096);
    echo $buffer;
}
fclose($handle);
?>

Megjegyzés: The length parameter became optional in PHP 4.2.0, if omitted, it would assume 1024 as the line length. As of PHP 4.3, omitting length will keep reading from the stream until it reaches the end of the line. 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.

Megjegyzés: This function is binary safe as of PHP 4.3. Earlier versions were not binary safe.

Megjegyzés: Ha problémád akadna PHP-ben Machintosh gépen létrehozott szöveges fileokban a sorvégek olvasásával, valószínűleg be kell kapcsolnod az auto_detect_line_endings beállítást.

See also fread(), fgetc(), stream_get_line(), fopen(), popen(), fsockopen(), and stream_set_timeout().

fgetss

(PHP 3, PHP 4 )

fgetss -- Gets line from file pointer and strip HTML tags

Description

string fgetss ( resource handle, int length [, string allowable_tags])

Identical to fgets(), except that fgetss attempts to strip any HTML and PHP tags from the text it reads.

You can use the optional third parameter to specify tags which should not be stripped.

Megjegyzés: allowable_tags was added in PHP 3.0.13, PHP 4.0.0.

Megjegyzés: Ha problémád akadna PHP-ben Machintosh gépen létrehozott szöveges fileokban a sorvégek olvasásával, valószínűleg be kell kapcsolnod az auto_detect_line_endings beállítást.

See also fgets(), fopen(), fsockopen(), popen(), and strip_tags().

file_exists

(PHP 3, PHP 4 )

file_exists -- Checks whether a file or directory exists

Description

bool file_exists ( string filename)

Returns TRUE if the file or directory specified by filename exists; FALSE otherwise.

On windows, use //computername/share/filename or \\computername\share\filename to check files on network shares.

Példa 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";
}
?>

Megjegyzés: Eme függvény eredményei elsőként csupán a gyorstárba kerülnek, nem lesznek azonnali hatással a fájlrendszerre. További információk a clearstatcache() oldalon olvashatók.

Tipp: As of PHP 5.0.0 this function can also be used with some URL wrappers. Refer to J Függelék for a listing of which wrappers support stat() family of functionality.

See also is_readable(), is_writable(), is_file() and file().

file_get_contents

(PHP 4 >= 4.3.0)

file_get_contents -- Reads entire file into a string

Description

string file_get_contents ( string filename [, bool use_include_path [, resource context]])

Identical to file(), except that file_get_contents() returns the file in a string. 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.

Megjegyzés: Ez a függvény "binary-safe", azaz helyesen kezeli a 127-es ASCII kód feletti karaktereket is.

Tipp: URL-t is megadhatsz az állomány név paraméter helyén ha a fopen wrappers szolgáltatás be van kapcsolva. Bővebb információk az fopen() leírásánál olvashatóak arról, milyen módon adhatod meg a fájlneveket, valamint érdemes megtekinteni a J Függelék oldalt a támogatott URL típusok listájának megtekintése gyanánt.

Megjegyzés: Context support was added with PHP 5.0.0.

See also: fgets(), file(), fread(), include(), and readfile().

file_put_contents

(PHP 5 CVS only)

file_put_contents -- Write a string to a file

Description

int file_put_contents ( string filename, string data [, int flags [, resource context]])

Identical to calling fopen(), fwrite(), and fclose() successively. The function returns the amount of bytes that were written to the file.

flags can take FILE_USE_INCLUDE_PATH and/or FILE_APPEND, however the FILE_USE_INCLUDE_PATH option should be used with caution.

Megjegyzés: Ez a függvény "binary-safe", azaz helyesen kezeli a 127-es ASCII kód feletti karaktereket is.

Tipp: URL-t is megadhatsz az állomány név paraméter helyén ha a fopen wrappers szolgáltatás be van kapcsolva. Bővebb információk az fopen() leírásánál olvashatóak arról, milyen módon adhatod meg a fájlneveket, valamint érdemes megtekinteni a J Függelék oldalt a támogatott URL típusok listájának megtekintése gyanánt.

See also: fopen(), fwrite(), fclose(), and file_get_contents().

file

(PHP 3, PHP 4 )

file -- Reads entire file into an array

Description

array file ( string filename [, int use_include_path [, resource context]])

Identical to readfile(), except that file() 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.

You can use the optional use_include_path parameter and set it to "1", if you want to search for the file in the include_path, too.

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

Tipp: URL-t is megadhatsz az állomány név paraméter helyén ha a fopen wrappers szolgáltatás be van kapcsolva. Bővebb információk az fopen() leírásánál olvashatóak arról, milyen módon adhatod meg a fájlneveket, valamint érdemes megtekinteni a J Függelék oldalt a támogatott URL típusok listájának megtekintése gyanánt.

Megjegyzés: Each line in the resulting array will include the line ending, so you still need to use rtrim() if you do not want the line ending present.

Megjegyzés: Ha problémád akadna PHP-ben Machintosh gépen létrehozott szöveges fileokban a sorvégek olvasásával, valószínűleg be kell kapcsolnod az auto_detect_line_endings beállítást.

Megjegyzés: As of PHP 4.3.0 you can use file_get_contents() to return the contents of a file as a string.

In PHP 4.3.0 file() became binary safe.

Megjegyzés: Context support was added with PHP 5.0.0.

See also readfile(), fopen(), fsockopen(), popen(), file_get_contents(), and include().

fileatime

(PHP 3, PHP 4 )

fileatime -- Gets last access time of file

Description

int fileatime ( string filename)

Returns the time the file was last accessed, or FALSE in case of an error. The time is returned as a Unix timestamp.

Note: The atime of a file is supposed to change whenever the data blocks of a file are being read. This can be costly performancewise 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.

Megjegyzés: Eme függvény eredményei elsőként csupán a gyorstárba kerülnek, nem lesznek azonnali hatással a fájlrendszerre. További információk a clearstatcache() oldalon olvashatók.

Tipp: As of PHP 5.0.0 this function can also be used with some URL wrappers. Refer to J Függelék for a listing of which wrappers support stat() family of functionality.

Példa 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));
}

?>

See also filemtime(), fileinode(), and date().

filectime

(PHP 3, PHP 4 )

filectime -- Gets inode change time of file

Description

int filectime ( string filename)

Returns the time the file was last changed, or FALSE in case of an error. The time is returned as a Unix timestamp.

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

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.

Megjegyzés: Eme függvény eredményei elsőként csupán a gyorstárba kerülnek, nem lesznek azonnali hatással a fájlrendszerre. További információk a clearstatcache() oldalon olvashatók.

Tipp: As of PHP 5.0.0 this function can also be used with some URL wrappers. Refer to J Függelék for a listing of which wrappers support stat() family of functionality.

Példa 1. fileatime() 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));
}

?>

See also filemtime()

filegroup

(PHP 3, PHP 4 )

filegroup -- Gets file group

Description

int filegroup ( string filename)

Returns the group ID of the file, or FALSE in case of an error. The group ID is returned in numerical format, use posix_getgrgid() to resolve it to a group name. Upon failure, FALSE is returned along with an error of level E_WARNING.

Megjegyzés: Eme függvény eredményei elsőként csupán a gyorstárba kerülnek, nem lesznek azonnali hatással a fájlrendszerre. További információk a clearstatcache() oldalon olvashatók.

Tipp: As of PHP 5.0.0 this function can also be used with some URL wrappers. Refer to J Függelék for a listing of which wrappers support stat() family of functionality.

See also fileowner(), and safe_mode_gid.

fileinode

(PHP 3, PHP 4 )

fileinode -- Gets file inode

Description

int fileinode ( string filename)

Returns the inode number of the file, or FALSE in case of an error.

Megjegyzés: Eme függvény eredményei elsőként csupán a gyorstárba kerülnek, nem lesznek azonnali hatással a fájlrendszerre. További információk a clearstatcache() oldalon olvashatók.

Tipp: As of PHP 5.0.0 this function can also be used with some URL wrappers. Refer to J Függelék for a listing of which wrappers support stat() family of functionality.

See also stat()

filemtime

(PHP 3, PHP 4 )

filemtime -- Gets file modification time

Description

int filemtime ( string filename)

Returns the time the file was last modified, or FALSE in case of an error. The time is returned as a Unix timestamp, which is suitable for the date() function.

Megjegyzés: Eme függvény eredményei elsőként csupán a gyorstárba kerülnek, nem lesznek azonnali hatással a fájlrendszerre. További információk a clearstatcache() oldalon olvashatók.

Tipp: As of PHP 5.0.0 this function can also be used with some URL wrappers. Refer to J Függelék for a listing of which wrappers support stat() family of functionality.

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.

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

See also filectime(), stat(), touch(), and getlastmod().

fileowner

(PHP 3, PHP 4 )

fileowner -- Gets file owner

Description

int fileowner ( string filename)

Returns the user ID of the owner of the file, or FALSE in case of an error. The user ID is returned in numerical format, use posix_getpwuid() to resolve it to a username.

Megjegyzés: Eme függvény eredményei elsőként csupán a gyorstárba kerülnek, nem lesznek azonnali hatással a fájlrendszerre. További információk a clearstatcache() oldalon olvashatók.

Tipp: As of PHP 5.0.0 this function can also be used with some URL wrappers. Refer to J Függelék for a listing of which wrappers support stat() family of functionality.

See also stat()

fileperms

(PHP 3, PHP 4 )

fileperms -- Gets file permissions

Description

int fileperms ( string filename)

Returns the permissions on the file, or FALSE in case of an error.

Megjegyzés: Eme függvény eredményei elsőként csupán a gyorstárba kerülnek, nem lesznek azonnali hatással a fájlrendszerre. További információk a clearstatcache() oldalon olvashatók.

Tipp: As of PHP 5.0.0 this function can also be used with some URL wrappers. Refer to J Függelék for a listing of which wrappers support stat() family of functionality.

See also is_readable(), and stat()

filesize

(PHP 3, PHP 4 )

filesize -- Gets file size

Description

int filesize ( string filename)

Returns the size of the file in bytes, or FALSE in case of an error.

Megjegyzés: Because PHP's integer type is signed and many platforms use 32bit integers, filesize() may return unexpected results for files which are larger than 2GB. For files between 2GB and 4GB in size this can usually be overcome by using sprintf("%u", filesize($file)).

Megjegyzés: Eme függvény eredményei elsőként csupán a gyorstárba kerülnek, nem lesznek azonnali hatással a fájlrendszerre. További információk a clearstatcache() oldalon olvashatók.

Tipp: As of PHP 5.0.0 this function can also be used with some URL wrappers. Refer to J Függelék for a listing of which wrappers support stat() family of functionality.

Példa 1. filesize() example

<?php

// outputs e.g.  somefile.txt: 1024 bytes

$filename = 'somefile.txt';
echo $filename . ': ' . filesize($filename) . ' bytes';

?>

See also file_exists()

filetype

(PHP 3, PHP 4 )

filetype -- Gets file type

Description

string filetype ( string filename)

Returns the type of the file. Possible values are fifo, char, dir, block, link, file, 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.

Megjegyzés: Eme függvény eredményei elsőként csupán a gyorstárba kerülnek, nem lesznek azonnali hatással a fájlrendszerre. További információk a clearstatcache() oldalon olvashatók.

Tipp: As of PHP 5.0.0 this function can also be used with some URL wrappers. Refer to J Függelék for a listing of which wrappers support stat() family of functionality.

Példa 1. filetype() example

<?php

echo filetype('/etc/passwd');  // file
echo filetype('/etc/');        // dir

?>

See also is_dir(), is_file(), is_link(), file_exists(), stat(), and mime_content_type().

flock

(PHP 3>= 3.0.7, PHP 4 )

flock -- Portable advisory file locking

Description

bool flock ( resource handle, int operation [, int &wouldblock])

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

flock() operates on handle which must be an open file pointer. operation is one of the following values:

  • To acquire a shared lock (reader), set operation to LOCK_SH (set to 1 prior to PHP 4.0.1).

  • To acquire an exclusive lock (writer), set operation to LOCK_EX (set to 2 prior to PHP 4.0.1).

  • To release a lock (shared or exclusive), set operation to LOCK_UN (set to 3 prior to PHP 4.0.1).

  • If you don't want flock() to block while locking, add LOCK_NB (4 prior to PHP 4.0.1) to operation.

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). The optional third argument is set to TRUE if the lock would block (EWOULDBLOCK errno condition)

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Példa 1. flock() example

<?php

$fp = fopen("/tmp/lock.txt", "w+");

if (flock($fp, LOCK_EX)) { // do an exclusive lock
    fwrite($fp, "Write something here\n");
    flock($fp, LOCK_UN); // release the lock
} else {
    echo "Couldn't lock the file !";
}

fclose($fp);

?>

Megjegyzés: 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()).

Figyelem

flock() will not work on NFS and many other networked file systems. Check your operating system documentation for more details.

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

fnmatch

(PHP 4 >= 4.3.0)

fnmatch -- Match filename against a pattern

Description

array fnmatch ( string pattern, string string [, int flags])

fnmatch() checks if the passed string would match the given shell wildcard pattern.

This 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 ereg() or preg_match() for frontend search expression input may be way more convenient for non-programming users.

Példa 1. Checking a color name against a shell wildcard pattern.

<?php
if (fnmatch("*gr[ae]y", $color)) {
  echo "some form of gray ...";
}
?>

See also glob(), ereg(), preg_match() and the Unix manpage on fnmatch(3) for flag names (as long as they are not documented here ).

fopen

(PHP 3, PHP 4 )

fopen -- Opens file or URL

Description

resource fopen ( string filename, string mode [, int use_include_path [, resource zcontext]])

fopen() binds a named resource, specified by filename, to a stream. 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 safe mode, 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.

Megjegyzés: The list of supported protocols can be found in J Függelék. 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. ( i.e. php.ini value user_agent used by the http wrapper) For a description of contexts and the zcontext parameter , refer to CIII, Stream functions Referencia .

The mode parameter specifies the type of access you require to the stream. It may be any of the following:

Táblázat 1. A list of possible modes for fopen() using mode

modeDescription
'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.
'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.
'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. This option is supported in PHP 4.3.2 and later, and only works for local files.
'x+' Create and open for reading and writing; 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. This option is supported in PHP 4.3.2 and later, and only works for local files.

Megjegyzés: 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.

For portability, it is strongly recommended that you always use the 'b' flag when opening files with fopen().

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.

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

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.

If the open fails, the function returns FALSE and an error of level E_WARNING is generated. You may use @ to suppress this warning.

Példa 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");
?>

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.

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:\\data\\info.txt", "r");
?>

Megjegyzés: Ha a safe mode be van kapcsolva, a PHP ellenőrzi, hogy a könyvtár, amelyben dolgozni szeretnél, ugyanazzal a felhasználói azonosítóval (UID) rendelkezik-e, mint az éppen futó program.

See also J Függelék, fclose(), fgets(), fread(), fwrite(), fsockopen(), file(), file_exists(), is_readable(), stream_set_timeout(), and popen().

fpassthru

(PHP 3, PHP 4 )

fpassthru -- Output all remaining data on a file pointer

Description

int fpassthru ( resource handle)

Reads to EOF on the given file pointer from the current position and writes the results to the output buffer.

If an error occurs, fpassthru() returns FALSE. Otherwise, fpassthru() returns the number of characters read from handle and passed through to the output.

The file pointer must be valid, and must point to a file successfully opened by fopen(), popen(), or fsockopen(). 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. The file is closed when fpassthru() is done reading it (leaving handle useless).

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.

Megjegyzés: 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.

Példa 1. Using fpassthru() with binary files

<?php

// open the file in a binary mode
$name = ".\public\dev\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;

?>

See also readfile(), fopen(), popen(), and fsockopen()

fputs

fputs -- Alias of fwrite()

Description

This function is an alias of fwrite().

fread

(PHP 3, PHP 4 )

fread -- Binary-safe file read

Description

string fread ( resource handle, int length)

fread() reads up to length bytes from the file pointer referenced by handle. Reading stops when length bytes have been read, EOF (end of file) is reached, or (for network streams) when a packet becomes available, whichever comes first.

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

Figyelem

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

Figyelem

When reading from network streams or pipes, such as those returned when reading remote files or from popen() and proc_open(), reading will stop after a packet is available. This means that you should collect the data together in chunks as shown in the example below.

<?php
$handle = fopen("http://www.example.com/", "rb");
$contents = "";
do {
    $data = fread($handle, 8192);
    if (strlen($data) == 0) {
        break;
    }
    $contents .= $data;
} while (true);
fclose($handle);
?>

Megjegyzés: The example above has better performance than the traditional approach using while(!feof()), as we are saving the overhead of a function call per iteration.

Megjegyzés: 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.

See also fwrite(), fopen(), fsockopen(), popen(), fgets(), fgetss(), fscanf(), file(), and fpassthru().

fscanf

(PHP 4 >= 4.0.1)

fscanf -- Parses input from a file according to a format

Description

mixed fscanf ( resource handle, string format [, string var1])

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

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.

Példa 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);
?>

Példa 2. users.txt

javier  argonaut        pe
hiroshi sculptor        jp
robert  slacker us
luigi   florist it

Megjegyzés: Prior to PHP 4.3.0, the maximum number of characters read from the file was 512 (or up to the first \n, whichever came first). As of PHP 4.3.0 arbitrarily long lines will be read and scanned.

See also fread(), fgets(), fgetss(), sscanf(), printf(), and sprintf().

fseek

(PHP 3, PHP 4 )

fseek -- Seeks on a file pointer

Description

int fseek ( resource handle, int offset [, int whence])

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, whose values are defined as follows:

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. (To move to a position before the end-of-file, you need to pass a negative value in offset.)

If whence is not specified, it is assumed to be SEEK_SET.

Upon success, returns 0; otherwise, returns -1. Note that seeking past EOF is not considered an error.

Példa 1. fseek() example

<?php

$fp = fopen('somefile.txt');

// read some data
$data = fgets($fp, 4096);

// move back to the beginning of the file
// same as rewind($fp);
fseek($fp, 0);

?>

May not be used on file pointers returned by fopen() if they use the "http://" or "ftp://" formats.

Megjegyzés: The whence argument was added after PHP 4.0.0.

See also ftell() and rewind().

fstat

(PHP 4 )

fstat -- Gets information about a file using an open file pointer

Description

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.

Returns an array with the statistics of the file; the format of the array is described in detail on the stat() manual page.

Példa 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));

?>

this will output :

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
)

Megjegyzés: Eme függvény eredményei elsőként csupán a gyorstárba kerülnek, nem lesznek azonnali hatással a fájlrendszerre. További információk a clearstatcache() oldalon olvashatók.

Megjegyzés: Ez a függvény nem fog távoli fájlokkal működni, az a szerver helyi fájlrendszerén lesz keresve.

ftell

(PHP 3, PHP 4 )

ftell -- Tells file pointer read/write position

Description

int ftell ( resource handle)

Returns the position of the file pointer referenced by handle; i.e., its offset into the file stream.

If an error occurs, returns FALSE.

The file pointer must be valid, and must point to a file successfully opened by fopen() or popen().

Példa 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);

?>

See also fopen(), popen(), fseek(), and rewind().

ftruncate

(PHP 4 )

ftruncate -- Truncates a file to a given length

Description

bool ftruncate ( resource handle, int size)

Takes the filepointer, handle, and truncates the file to length, size. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Megjegyzés: Prior to PHP 4.3.3, ftruncate() returns an integer value of 1 on success, instead of boolean TRUE.

See also fopen() and fseek().

fwrite

(PHP 3, PHP 4 )

fwrite -- Binary-safe file write

Description

int fwrite ( resource handle, string string [, int length])

fwrite() writes the contents of string to the file stream pointed to by handle. 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.

fwrite() returns the number of bytes written, or FALSE on error.

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.

Megjegyzés: On systems which differentiate between binary and text files (i.e. Windows) the file must be opened with 'b' included in fopen() mode parameter.

Példa 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)) {
        echo "Cannot write to file ($filename)";
        exit;
    }
    
    echo "Success, wrote ($somecontent) to file ($filename)";
    
    fclose($handle);
					
} else {
    echo "The file $filename is not writable";
}
?>

See also fread(), fopen(), fsockopen(), popen(), and fputs().

glob

(PHP 4 >= 4.3.0)

glob -- Find pathnames matching a pattern

Description

array glob ( string pattern [, int flags])

The glob() function searches for all the pathnames matching pattern according to the rules used by the shell. No tilde expansion or parameter substitution is done.

Returns an array containing the matched files/directories or FALSE on error.

Valid flags:

  • GLOB_MARK - Adds a slash to each item returned

  • GLOB_NOSORT - Return files as they appear in the directory (no sorting)

  • GLOB_NOCHECK - Return the search pattern if no files matching it were found

  • GLOB_NOESCAPE - Backslashes do not quote metacharacters

  • GLOB_BRACE - Expands {a,b,c} to match 'a', 'b', or 'c'

  • GLOB_ONLYDIR - Return only directory entries which match the pattern

Megjegyzés: Before PHP 4.3.3 GLOB_ONLYDIR was not available on Windows and other systems not using the GNU C library.

Példa 1. Convenient way how glob() can replace opendir() and friends.

<?php
foreach (glob("*.txt") as $filename) {
    echo "$filename size " . filesize($filename) . "\n";
}

Output will look something like:

funclist.txt size 44686
funcsummary.txt size 267625
quickref.txt size 137820

Megjegyzés: Ez a függvény nem fog távoli fájlokkal működni, az a szerver helyi fájlrendszerén lesz keresve.

See also opendir(), readdir(), closedir(), and fnmatch().

is_dir

(PHP 3, PHP 4 )

is_dir -- Tells whether the filename is a directory

Description

bool is_dir ( string filename)

Returns TRUE if the filename exists and is a directory. If filename is a relative filename, it will be checked relative to the current working directory.

Megjegyzés: Eme függvény eredményei elsőként csupán a gyorstárba kerülnek, nem lesznek azonnali hatással a fájlrendszerre. További információk a clearstatcache() oldalon olvashatók.

Példa 1. is_dir() example

<?
var_dump(is_dir('a_file.txt')) . "\n";
var_dump(is_dir('bogus_dir/abc')) . "\n";

var_dump(is_dir('..')); //one dir up
?>

The above example will output:

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

Tipp: As of PHP 5.0.0 this function can also be used with some URL wrappers. Refer to J Függelék for a listing of which wrappers support stat() family of functionality.

See also chdir(), dir, opendir(), is_file() and is_link().

is_executable

(PHP 3, PHP 4 )

is_executable -- Tells whether the filename is executable

Description

bool is_executable ( string filename)

Returns TRUE if the filename exists and is executable.

is_executable() became available with Windows in PHP version 5.0.0.

Példa 1. is_executable() example

<?php

$file = '/home/vincent/somefile.sh';

if (is_executable($file)) {
    echo $file.' is executable';
} else {
    echo $file.' is not executable';
}

?>

Megjegyzés: Eme függvény eredményei elsőként csupán a gyorstárba kerülnek, nem lesznek azonnali hatással a fájlrendszerre. További információk a clearstatcache() oldalon olvashatók.

Tipp: As of PHP 5.0.0 this function can also be used with some URL wrappers. Refer to J Függelék for a listing of which wrappers support stat() family of functionality.

See also is_file() and is_link().

is_file

(PHP 3, PHP 4 )

is_file -- Tells whether the filename is a regular file

Description

bool is_file ( string filename)

Returns TRUE if the filename exists and is a regular file.

Megjegyzés: Eme függvény eredményei elsőként csupán a gyorstárba kerülnek, nem lesznek azonnali hatással a fájlrendszerre. További információk a clearstatcache() oldalon olvashatók.

Tipp: As of PHP 5.0.0 this function can also be used with some URL wrappers. Refer to J Függelék for a listing of which wrappers support stat() family of functionality.

See also is_dir() and is_link().

is_link

(PHP 3, PHP 4 )

is_link -- Tells whether the filename is a symbolic link

Description

bool is_link ( string filename)

Returns TRUE if the filename exists and is a symbolic link.

Megjegyzés: Eme függvény eredményei elsőként csupán a gyorstárba kerülnek, nem lesznek azonnali hatással a fájlrendszerre. További információk a clearstatcache() oldalon olvashatók.

Tipp: As of PHP 5.0.0 this function can also be used with some URL wrappers. Refer to J Függelék for a listing of which wrappers support stat() family of functionality.

See also is_dir(), is_file(), and readlink().

is_readable

(PHP 3, PHP 4 )

is_readable -- Tells whether the filename is readable

Description

bool is_readable ( string filename)

Returns TRUE if the filename exists and is readable.

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.

Megjegyzés: Eme függvény eredményei elsőként csupán a gyorstárba kerülnek, nem lesznek azonnali hatással a fájlrendszerre. További információk a clearstatcache() oldalon olvashatók.

Tipp: As of PHP 5.0.0 this function can also be used with some URL wrappers. Refer to J Függelék for a listing of which wrappers support stat() family of functionality.

See also is_writable(), file_exists(), and fgets().

is_uploaded_file

(PHP 3>= 3.0.17, PHP 4 >= 4.0.3)

is_uploaded_file -- Tells whether the file was uploaded via HTTP POST

Description

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.

is_uploaded_file() is available only in versions of PHP 3 after PHP 3.0.16, and in versions of PHP 4 after 4.0.2. If you are stuck using an earlier version, you can use the following function to help protect yourself:

Megjegyzés: The following example will not work in versions of PHP 4 after 4.0.2. It depends on internal functionality of PHP which changed after that version.

<?php
/* Userland test for uploaded file. */
function is_uploaded_file($filename) 
{
    if (!$tmp_file = get_cfg_var('upload_tmp_dir')) {
        $tmp_file = dirname(tempnam('', ''));
    }
    $tmp_file .= '/' . basename($filename);
    /* User might have trailing slash in php.ini... */
    return (ereg_replace('/+', '/', $tmp_file) == $filename);
}

/* This is how to use it, since you also don't have
 * move_uploaded_file() in these older versions: */
if (is_uploaded_file($HTTP_POST_FILES['userfile'])) {
    copy($HTTP_POST_FILES['userfile'], "/place/to/put/uploaded/file");
} else {
    echo "Possible file upload attack: filename '$HTTP_POST_FILES[userfile]'.";
}
?>

See also move_uploaded_file(), and the section Handling file uploads for a simple usage example.

is_writable

(PHP 4 )

is_writable -- Tells whether the filename is writable

Description

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

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.

Megjegyzés: Eme függvény eredményei elsőként csupán a gyorstárba kerülnek, nem lesznek azonnali hatással a fájlrendszerre. További információk a clearstatcache() oldalon olvashatók.

Tipp: As of PHP 5.0.0 this function can also be used with some URL wrappers. Refer to J Függelék for a listing of which wrappers support stat() family of functionality.

See also is_readable(), file_exists(), and fwrite().

is_writeable

is_writeable -- Alias of is_writable()

Description

This function is an alias of is_writable().

link

(PHP 3, PHP 4 )

link -- Create a hard link

Description

bool link ( string target, string link)

link() creates a hard link. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Megjegyzés: Ez a függvény nem fog távoli fájlokkal működni, az a szerver helyi fájlrendszerén lesz keresve.

See also the symlink() to create soft links, and readlink() along with linkinfo().

linkinfo

(PHP 3, PHP 4 )

linkinfo -- Gets information about a link

Description

int linkinfo ( string path)

linkinfo() returns the st_dev field of the Unix C stat structure returned by the lstat system call. 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). Returns 0 or FALSE in case of error.

Példa 1. linkinfo() example

<?php

echo linkinfo('/vmlinuz'); // 835

?>

See also symlink(), link(), and readlink().

lstat

(PHP 3>= 3.0.4, PHP 4 )

lstat -- Gives information about a file or symbolic link

Description

array lstat ( string filename)

Gathers the statistics of the file or symbolic link named by filename. 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.

See the manual page for stat() for information on the structure of the array that lstat() returns.

Megjegyzés: Eme függvény eredményei elsőként csupán a gyorstárba kerülnek, nem lesznek azonnali hatással a fájlrendszerre. További információk a clearstatcache() oldalon olvashatók.

Tipp: As of PHP 5.0.0 this function can also be used with some URL wrappers. Refer to J Függelék for a listing of which wrappers support stat() family of functionality.

See also stat().

mkdir

(PHP 3, PHP 4 )

mkdir -- Makes directory

Description

bool mkdir ( string pathname [, int mode [, resource context]])

Attempts to create the directory specified by pathname.

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

Megjegyzés: Mode is ignored on Windows, and became optional in PHP 4.2.0.

The mode is 0777 by default, which means the widest possible access. For more information on modes, read the details on the chmod() page.

<?php
mkdir("/path/to/my/dir", 0700);
?>

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Megjegyzés: As of PHP 5.0.0 mkdir() can also be used with some URL wrappers. Refer to J Függelék for a listing of which wrappers support mkdir().

Megjegyzés: The context parameter was added as of PHP 5.0.0.

Megjegyzés: Ha a safe mode be van kapcsolva, a PHP ellenőrzi, hogy a könyvtár, amelyben dolgozni szeretnél, ugyanazzal a felhasználói azonosítóval (UID) rendelkezik-e, mint az éppen futó program.

See also rmdir().

move_uploaded_file

(PHP 4 >= 4.0.3)

move_uploaded_file -- Moves an uploaded file to a new location

Description

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.

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.

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.

Megjegyzés: Ha a safe mode be van kapcsolva, a PHP ellenőrzi, hogy az állományok vagy könyvtárak, amelyekkel dolgozni szeretnél, ugyanazzal a felhasználói azonosítóval (UID) rendelkeznek-e, mint az éppen futó program.

Megjegyzés: move_uploaded_file() is not affected by the normal safe mode UID-restrictions. This is not unsafe because move_uploaded_file() only operates on files uploaded via PHP.

Figyelem

If the destination file already exists, it will be overwritten.

See also is_uploaded_file(), and the section Handling file uploads for a simple usage example.

parse_ini_file

(PHP 4 )

parse_ini_file -- Parse a configuration file

Description

array parse_ini_file ( string filename [, bool process_sections])

parse_ini_file() loads in the ini file specified in filename, and returns the settings in it in an associative array. By setting the last process_sections parameter to TRUE, you get a multidimensional array, with the section names and settings included. The default for process_sections is FALSE

Megjegyzés: This function has nothing to do with the php.ini file. It is already processed, the time you run your script. This function can be used to read in your own application's configuration files.

Megjegyzés: If a value in the ini file contains any non-alphanumeric characters it needs to be enclosed in double-quotes (").

Megjegyzés: Since PHP 4.2.1 this function is also affected by safe mode and open_basedir.

Megjegyzés: There are reserved words which must not be used as keys for ini files. These include: null, yes, no, true, and false.

The structure of the ini file is similar to that of the php.ini's.

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:

Példa 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"

Példa 2. parse_ini_file() 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);

?>

Would produce:

Array
(
    [one] => 1
    [five] => 5
    [animal] => Dodo bird
    [path] => /usr/local/bin
    [URL] => http://www.example.com/~username
)
Array
(
    [first_section] => Array
        (
            [one] => 1
            [five] => 5
            [animal] = Dodo bird
        )

    [second_section] => Array
        (
            [path] => /usr/local/bin
            [URL] => http://www.example.com/~username
        )

)

pathinfo

(PHP 4 >= 4.0.3)

pathinfo -- Returns information about a file path

Description

array pathinfo ( string path)

pathinfo() returns an associative array containing information about path. The following array elements are returned: dirname, basename and extension.

Példa 1. pathinfo() Example

<?php

$path_parts = pathinfo("/www/htdocs/index.html");

echo $path_parts["dirname"] . "\n";
echo $path_parts["basename"] . "\n";
echo $path_parts["extension"] . "\n";

?>

Would produce:

/www/htdocs
index.html
html

Megjegyzés: For information on retrieving the current path info, read the section on predefined reserved variables.

See also dirname(), basename(), parse_url() and realpath().

pclose

(PHP 3, PHP 4 )

pclose -- Closes process file pointer

Description

int pclose ( resource handle)

Closes a file pointer to a pipe opened by popen().

The file pointer must be valid, and must have been returned by a successful call to popen().

Returns the termination status of the process that was run.

See also popen().

popen

(PHP 3, PHP 4 )

popen -- Opens process file pointer

Description

resource popen ( string command, string mode)

Opens a pipe to a process executed by forking the command given by command.

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

If an error occurs, returns FALSE.

Megjegyzés: If you're looking for bi-directional support (two-way), use proc_open().

Példa 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:

<?php
error_reporting(E_ALL);

/* Add redirection so we can get stderr. */
$handle = popen('/path/to/spooge 2>&1', 'r');
echo "'$handle'; " . gettype($handle) . "\n";
$read = fread($handle, 2096);
echo $read;
pclose($handle);
?>

Megjegyzés: When safe mode is enabled, 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.

See also pclose(), fopen(), and proc_open().

readfile

(PHP 3, PHP 4 )

readfile -- Outputs a file

Description

int readfile ( string filename [, bool use_include_path [, resource context]])

Reads a file and writes it to the output buffer.

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.

Tipp: URL-t is megadhatsz az állomány név paraméter helyén ha a fopen wrappers szolgáltatás be van kapcsolva. Bővebb információk az fopen() leírásánál olvashatóak arról, milyen módon adhatod meg a fájlneveket, valamint érdemes megtekinteni a J Függelék oldalt a támogatott URL típusok listájának megtekintése gyanánt.

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.

See also fpassthru(), file(), fopen(), include(), require(), virtual(), file_get_contents(), and J Függelék.

readlink

(PHP 3, PHP 4 )

readlink -- Returns the target of a symbolic link

Description

string readlink ( string path)

readlink() does the same as the readlink C function and returns the contents of the symbolic link path or 0 in case of error.

Példa 1. readlink() example

<?php

// output e.g. /boot/vmlinux-2.4.20-xfs
echo readlink('/vmlinuz');

?>

See also is_link(), symlink(), and linkinfo().

realpath

(PHP 4 )

realpath -- Returns canonicalized absolute pathname

Description

string realpath ( string path)

realpath() expands all symbolic links and resolves references to '/./', '/../' and extra '/' characters in the input path and return the canonicalized absolute pathname. The resulting path will have no symbolic link, '/./' or '/../' components.

realpath() returns FALSE on failure, e.g. if the file does not exists.

Példa 1. realpath() example

<?php
$real_path = realpath("../../index.php");
?>

See also: basename(), dirname(), and pathinfo().

rename

(PHP 3, PHP 4 )

rename -- Renames a file

Description

bool rename ( string oldname, string newname [, resource context])

Attempts to rename oldname to newname.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Példa 1. Example with rename()

<?php
rename("/tmp/tmp_file.txt", "/home/user/login/docs/my_file.txt");
?>

Megjegyzés: Prior to PHP 4.3.3, rename() could not rename files across partitions on *nix based systems.

Megjegyzés: As of PHP 5.0.0 rename() can also be used with some URL wrappers. Refer to J Függelék for a listing of which wrappers support rename().

Megjegyzés: The wrapper used in oldname MUST match the wrapper used in newname.

Megjegyzés: The context parameter was added as of PHP 5.0.0.

See also copy(), unlink(), and move_uploaded_file().

rewind

(PHP 3, PHP 4 )

rewind -- Rewind the position of a file pointer

Description

bool rewind ( resource handle)

Sets the file position indicator for handle to the beginning of the file stream.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

The file pointer must be valid, and must point to a file successfully opened by fopen().

Megjegyzés: If you have opened the file in append ("a") mode, any data you write to the file will always be appended, regardless of the file position.

See also fseek() and ftell().

rmdir

(PHP 3, PHP 4 )

rmdir -- Removes directory

Description

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. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Megjegyzés: As of PHP 5.0.0 rmdir() can also be used with some URL wrappers. Refer to J Függelék for a listing of which wrappers support rmdir().

Megjegyzés: The context parameter was added as of PHP 5.0.0.

Megjegyzés: Ha a safe mode be van kapcsolva, a PHP ellenőrzi, hogy a könyvtár, amelyben dolgozni szeretnél, ugyanazzal a felhasználói azonosítóval (UID) rendelkezik-e, mint az éppen futó program.

See also mkdir() and unlink().

set_file_buffer

set_file_buffer -- Alias of stream_set_write_buffer()

Description

This function is an alias of stream_set_write_buffer().

stat

(PHP 3, PHP 4 )

stat -- Gives information about a file

Description

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.

In case of error, stat() returns FALSE. It also will throw a warning.

Returns an array with the statistics of the file with the following elements. This array is zero-based. In addition to returning these attributes in a numeric array, they can be accessed with associative indices, as noted next to each parameter; this is available since PHP 4.0.6:

Táblázat 1. stat() and fstat() result format

NumericAssociative (since PHP 4.0.6)Description
0devdevice number
1inoinode number
2modeinode protection mode
3nlinknumber of links
4uiduserid of owner
5gidgroupid of owner
6rdevdevice type, if inode device *
7sizesize in bytes
8atimetime of last access (Unix timestamp)
9mtimetime of last modification (Unix timestamp)
10ctimetime of last change (Unix timestamp)
11blksizeblocksize of filesystem IO *
12blocksnumber of blocks allocated
* - only valid on systems supporting the st_blksize type--other systems (i.e. Windows) return -1.

Megjegyzés: Eme függvény eredményei elsőként csupán a gyorstárba kerülnek, nem lesznek azonnali hatással a fájlrendszerre. További információk a clearstatcache() oldalon olvashatók.

Tipp: As of PHP 5.0.0 this function can also be used with some URL wrappers. Refer to J Függelék for a listing of which wrappers support stat() family of functionality.

See also lstat(), fstat(), filemtime(), and filegroup().

symlink

(PHP 3, PHP 4 )

symlink -- Creates a symbolic link

Description

bool symlink ( string target, string link)

symlink() creates a symbolic link from the existing target with the specified name link.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

See also link() to create hard links, and readlink() along with linkinfo().

tempnam

(PHP 3, PHP 4 )

tempnam -- Create file with unique file name

Description

string tempnam ( string dir, string prefix)

Creates a file with a unique filename in the specified directory. If the directory does not exist, tempnam() may generate a file in the system's temporary directory, and return the name of that.

Prior to PHP 4.0.6, the behaviour of the tempnam() function was system dependent. On Windows the TMP environment variable will override the dir parameter, on Linux the TMPDIR environment variable has precedence, while SVR4 will always use your dir parameter if the directory it points to exists. Consult your system documentation on the tempnam(3) function if in doubt.

Megjegyzés: If PHP cannot create a file in the specified dir parameter, it falls back on the system default.

Returns the new temporary filename, or the FALSE string on failure.

Példa 1. tempnam() example

<?php
$tmpfname = tempnam("/tmp", "FOO");

$handle = fopen($tmpfname, "w");
fwrite($handle, "writing to tempfile");
fclose($handle);

// do here something

unlink($tmpfname);
?>

Megjegyzés: 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 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.

See also tmpfile() and unlink().

tmpfile

(PHP 3>= 3.0.13, PHP 4 )

tmpfile -- Creates a temporary file

Description

resource tmpfile ( void )

Creates a temporary file with an unique name in write mode, returning a file handle similar to the one returned by fopen(). The file is automatically removed when closed (using fclose()), or when the script ends.

For details, consult your system documentation on the tmpfile(3) function, as well as the stdio.h header file.

Példa 1. tmpfile() example

<?php
$temp = tmpfile();
fwrite($temp, "writing to tempfile");
fclose($temp); // this removes the file
?>

See also tempnam().

touch

(PHP 3, PHP 4 )

touch -- Sets access and modification time of file

Description

bool touch ( string filename [, int time [, int atime]])

Attempts to set the access and modification time of the file named by filename to the value given by time. If the option time is not given, uses the present time. This is equivalent to what utime (sometimes referred to as utimes) does. If the third option atime is present, the access time of the given filename is set to the value of atime. Note that the access time is always modified, regardless of the number of parameters.

If the file does not exist, it is created. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Példa 1. touch() example

<?php
if (touch($FileName)) {
    echo "$FileName modification time has been 
           changed to todays date and time";
} else {
    echo "Sorry Could Not change modification time of $FileName";
}
?>

umask

(PHP 3, PHP 4 )

umask -- Changes the current umask

Description

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.

umask() without arguments simply returns the current umask.

unlink

(PHP 3, PHP 4 )

unlink -- Deletes a file

Description

bool unlink ( string filename [, resource context])

Deletes filename. Similar to the Unix C unlink() function. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Megjegyzés: As of PHP 5.0.0 unlink() can also be used with some URL wrappers. Refer to J Függelék for a listing of which wrappers support unlink().

Megjegyzés: The context parameter was added as of PHP 5.0.0.

See also rmdir() for removing directories.

XXXI. Forms Data Format functions

Bevezetés

Forms Data Format (FDF) is a format for handling forms within PDF documents. You should read the documentation at http://partners.adobe.com/asn/acrobat/forms.jsp 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..


Követelmények

You need the FDF toolkit SDK available from http://partners.adobe.com/asn/acrobat/forms.jsp. As of PHP 4.3 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.


Telepítés

You must compile PHP with --with-fdftk[=DIR].

Megjegyzés: 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.

Note to Win32 Users: In order to enable this module on a Windows environment, you must copy fdftk.dll from the DLL folder of the PHP/Win32 binary package to the SYSTEM32 folder of your windows machine. (Ex: C:\WINNT\SYSTEM32 or C:\WINDOWS\SYSTEM32)


Futásidejű beállítások

Ez a kiterjesztés semmilyen konfigurációs beállításokat nem definiál a php.ini állományban.


Erőforrás típusok

fdf

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


Előre definiált állandók

Az itt listázott állandókat ez a kiterjesztés definiálja, és csak akkor elérhetőek, ha az adott kiterjesztés be van fordítva a PHP-be, vagy dinamikusan betöltött.

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)


Példák

The following examples shows just the evaluation of form data.

Példa 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);
?>

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

fdf_add_doc_javascript

(PHP 4 >= 4.3.0)

fdf_add_doc_javascript -- Adds javascript code to the FDF document

Description

bool fdf_add_doc_javascript ( resource fdfdoc, 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. It is strongly suggested to use '\r' for linebreaks within script_code.

Példa 1. Adding JavaScript code to a FDF

<?php
$fdf = fdf_create();
fdf_add_doc_javascript($fdf, "PlusOne", "function PlusOne(x)\r{\r  return x+1;\r}\r");
fdf_save($fdf);
?>

will create a FDF like this:

%FDF-1.2
%âăĎÓ
1 0 obj
<< 
/FDF << /JavaScript << /Doc [ (PlusOne)(function PlusOne\(x\)\r{\r  return x+1;\r}\r)] >> >> 
>> 
endobj
trailer
<<
/Root 1 0 R 

>>
%%EOF

fdf_add_template

(PHP 3>= 3.0.13, PHP 4 )

fdf_add_template -- Adds a template into the FDF document

Description

bool fdf_add_template ( resource fdfdoc, int newpage, string filename, string template, int rename)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

fdf_close

(PHP 3>= 3.0.6, PHP 4 )

fdf_close -- Close an FDF document

Description

bool fdf_close ( resource fdf_document)

The fdf_close() function closes the FDF document.

See also fdf_open().

fdf_create

(PHP 3>= 3.0.6, PHP 4 )

fdf_create -- Create a new FDF document

Description

resource fdf_create ( void )

The fdf_create() creates a new FDF document. This function is needed if one would like to populate input fields in a PDF document with data.

Példa 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");
?>

See also fdf_close(), fdf_save(), fdf_open().

fdf_enum_values

(PHP 4 >= 4.3.0)

fdf_enum_values -- Call a user defined function for each document value

Description

bool fdf_enum_values ( resource fdfdoc, callback function [, mixed userdata])

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

fdf_errno

(PHP 4 >= 4.3.0)

fdf_errno -- Return error code for last fdf operation

Description

int fdf_errno ( void )

fdf_errno() returns the error code set by the last fdf_...() function call. This is zero for a successfull operation or a non-zero error code on failure. A textual description may be obtained using the fdf_error() function.

See also fdf_error().

fdf_error

(PHP 4 >= 4.3.0)

fdf_error -- Return error description for fdf error code

Description

string fdf_error ( [int error_code])

fdf_error() returns a textual description for the fdf error code given in error_code. The function uses the internal error code set by the last operation if no error_code is given, so fdf_error() is a convenient shortcut for fdf_error(fdf_errno()).

See also fdf_errno().

fdf_get_ap

(PHP 4 >= 4.3.0)

fdf_get_ap -- Get the appearance of a field

Description

bool fdf_get_ap ( resource fdf_document, string field, int face, string filename)

The fdf_get_ap() function gets the appearance of a field (i.e. the value of the /AP key) and stores it in a file. The possible values of face are FDFNormalAP, FDFRolloverAP and FDFDownAP. The appearance is stored in filename.

fdf_get_attachment

(PHP 4 >= 4.3.0)

fdf_get_attachment -- Extracts uploaded file embedded in the FDF

Description

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

Megjegyzés: 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.

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

Példa 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_encoding

(PHP 4 >= 4.3.0)

fdf_get_encoding -- Get the value of the /Encoding key

Description

string fdf_get_encoding ( resource fdf_document)

The fdf_get_encoding() returns the value of the /Encoding key. An empty string is returned if the default PDFDocEncoding/Unicode scheme is used.

See also fdf_set_encoding().

fdf_get_file

(PHP 3>= 3.0.6, PHP 4 )

fdf_get_file -- Get the value of the /F key

Description

string fdf_get_file ( resource fdf_document)

The fdf_set_file() returns the value of the /F key.

See also fdf_set_file().

fdf_get_flags

(PHP 4 >= 4.3.0)

fdf_get_flags -- Gets the flags of a field

Description

fdf_get_flags ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

fdf_get_opt

(PHP 4 >= 4.3.0)

fdf_get_opt -- Gets a value from the opt array of a field

Description

mixed fdf_get_opt ( resource fdfdof, string fieldname [, int element])

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

fdf_get_status

(PHP 3>= 3.0.6, PHP 4 )

fdf_get_status -- Get the value of the /STATUS key

Description

string fdf_get_status ( resource fdf_document)

The fdf_get_status() returns the value of the /STATUS key.

See also fdf_set_status().

fdf_get_value

(PHP 3>= 3.0.6, PHP 4 )

fdf_get_value -- Get the value of a field

Description

string fdf_get_value ( resource fdf_document, string fieldname [, int which])

The fdf_get_value() function returns the value for the requested fieldname.

Elements of an array field can be retrieved by passing the optional which, starting at zero. For non-array fields the optional parameter which will be ignored.

Megjegyzés: Array support and optional which parameter were added in PHP 4.3.

See also fdf_set_value().

fdf_get_version

(PHP 4 >= 4.3.0)

fdf_get_version -- Gets version number for FDF API or file

Description

string fdf_get_version ( [resource fdf_document])

This function will return the fdf version for the given fdf_document, or the toolkit API version number if no parameter is given.

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

See also fdf_set_version().

fdf_header

(PHP 4 >= 4.3.0)

fdf_header -- Sets FDF-specific output headers

Description

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

fdf_next_field_name

(PHP 3>= 3.0.6, PHP 4 )

fdf_next_field_name -- Get the next field name

Description

string fdf_next_field_name ( resource fdf_document [, string fieldname])

The fdf_next_field_name() function returns the name of the field after the field in fieldname or the field name of the first field if the second parameter is NULL.

Példa 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";
} 
?>

See also fdf_enum_fields() and fdf_get_value().

fdf_open_string

(PHP 4 >= 4.3.0)

fdf_open_string -- Read a FDF document from a string

Description

resource fdf_open_string ( string fdf_data)

The fdf_open_string() function reads form data from a string. fdf_data must contain the data as returned from a PDF form or created using fdf_create() and fdf_save_string().

You can fdf_open_string() together with $HTTP_FDF_DATA to process fdf form input from a remote client.

Példa 1. Accessing the form data

<?php
$fdf = fdf_open_string($HTTP_FDF_DATA);
/* ... */
fdf_close($fdf);
?>

See also fdf_open(), fdf_close(), fdf_create() and fdf_save_string().

fdf_open

(PHP 3>= 3.0.6, PHP 4 )

fdf_open -- Open a FDF document

Description

resource fdf_open ( string filename)

The fdf_open() function opens a file with form data. This file must contain the data as returned from a PDF form or created using fdf_create() and fdf_save().

You can process the results of a PDF form POST request by writing the data received in $HTTP_FDF_DATA to a file and open it using fdf_open(). Starting with PHP 4.3 you can also use fdf_open_string() which handles temporary file creation and cleanup for you.

Példa 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);
?>

See also fdf_open_string(), fdf_close(), fdf_create() and fdf_save().

fdf_remove_item

(PHP 4 >= 4.3.0)

fdf_remove_item -- Sets target frame for form

Description

bool fdf_remove_item ( resource fdfdoc, string fieldname, int item)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

fdf_save_string

(PHP 4 >= 4.3.0)

fdf_save_string -- Returns the FDF document as a string

Description

string fdf_save_string ( resource fdf_document)

The fdf_save_string() function returns the FDF document as a string.

Példa 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;
?>

will output something like

%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

See also fdf_save(), fdf_open_string(), fdf_create() and fdf_close().

fdf_save

(PHP 3>= 3.0.6, PHP 4 )

fdf_save -- Save a FDF document

Description

bool fdf_save ( resource fdf_document [, string filename])

The fdf_save() function saves a FDF document. The resulting FDF will be written to filename. Without a filename fdf_save() will write the FDF to the default PHP output stream.

See also fdf_save_string(), fdf_create() and fdf_close().

fdf_set_ap

(PHP 3>= 3.0.6, PHP 4 )

fdf_set_ap -- Set the appearance of a field

Description

bool fdf_set_ap ( resource fdf_document, string field_name, int face, string filename, int page_number)

The fdf_set_ap() function sets the appearance of a field (i.e. the value of the /AP key). The possible values of face are FDFNormalAP, FDFRolloverAP and FDFDownAP.

fdf_set_encoding

(PHP 4 >= 4.1.0)

fdf_set_encoding -- Sets FDF character encoding

Description

bool fdf_set_encoding ( resource fdf_document, string encoding)

fdf_set_encoding() sets the character encoding in FDF document fdf_document. encoding should be the valid encoding name. Currently the following values are supported: "Shift-JIS", "UHC", "GBK","BigFive". An empty string resets the encoding to the default PDFDocEncoding/Unicode scheme.

fdf_set_file

(PHP 3>= 3.0.6, PHP 4 )

fdf_set_file -- Set PDF document to display FDF data in

Description

bool fdf_set_file ( resource fdf_document, string url [, string target_frame])

The fdf_set_file() selects a different PDF document to display the form results in then the form it originated from. The url needs to be given as an absolute URL.

The frame to display the document in may be selected using the optional parameter target_frame or the function fdf_set_target_frame().

Példa 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();

  /* clean up */
  fdf_close();
?>

See also fdf_get_file() and fdf_set_target_frame().

fdf_set_flags

(PHP 4 >= 4.0.2)

fdf_set_flags -- Sets a flag of a field

Description

bool fdf_set_flags ( resource fdf_document, string fieldname, int whichFlags, int newFlags)

The fdf_set_flags() sets certain flags of the given field fieldname.

See also fdf_set_opt().

fdf_set_javascript_action

(PHP 4 >= 4.0.2)

fdf_set_javascript_action -- Sets an javascript action of a field

Description

bool fdf_set_javascript_action ( resource fdf_document, string fieldname, int trigger, string script)

fdf_set_javascript_action() sets a javascript action for the given field fieldname.

See also fdf_set_submit_form_action().

fdf_set_opt

(PHP 4 >= 4.0.2)

fdf_set_opt -- Sets an option of a field

Description

bool fdf_set_opt ( resource fdf_document, string fieldname, int element, string str1, string str2)

The fdf_set_opt() sets options of the given field fieldname.

See also fdf_set_flags().

fdf_set_status

(PHP 3>= 3.0.6, PHP 4 )

fdf_set_status -- Set the value of the /STATUS key

Description

bool fdf_set_status ( resource fdf_document, string status)

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

See also fdf_get_status().

fdf_set_submit_form_action

(PHP 4 >= 4.0.2)

fdf_set_submit_form_action -- Sets a submit form action of a field

Description

bool fdf_set_submit_form_action ( resource fdf_document, string fieldname, int trigger, string script, int flags)

The fdf_set_submit_form_action() sets a submit form action for the given field fieldname.

See also fdf_set_javascript_action().

fdf_set_target_frame

(PHP 4 >= 4.3.0)

fdf_set_target_frame -- Set target frame for form display

Description

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.

See also fdf_save_file().

fdf_set_value

(PHP 3>= 3.0.6, PHP 4 )

fdf_set_value -- Set the value of a field

Description

bool fdf_set_value ( resource fdf_document, string fieldname, mixed value [, int isName])

The fdf_set_value() function sets the value for a field named fieldname. The value will be stored as a string unless it is an array. In this case all array elements will be stored as a value array.

Megjegyzés: In older versions of the fdf toolkit last parameter determined if the field value was to be converted to a PDF Name (isName = 1) or set to a PDF String (isName = 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.

Support for value arrays was added in PHP 4.3.

See also fdf_get_value() and fdf_remove_item().

fdf_set_version

(PHP 4 >= 4.3.0)

fdf_set_version -- Sets version number for a FDF file

Description

string fdf_set_version ( resource fdf_document, string version)

This function will set the fdf version for the given fdf_document. Some features supported by this extension are only available in newer fdf versions. For the current FDF toolkit 5.0 version may be either '1.2', '1.3' or '1.4'.

See also fdf_get_version().

XXXII. FriBiDi functions

Bevezetés

FriBiDi is a free implementation of the Unicode Bidirectional Algorithm.


Követelmények

You must download and install the FriBiDi package.


Telepítés

To enable FriBiDi support in PHP you must compile --with-fribidi[=DIR] where DIR is the FriBiDi install directory.


Futásidejű beállítások


Erőforrás típusok


Előre definiált állandók

Az itt listázott állandókat ez a kiterjesztés definiálja, és csak akkor elérhetőek, ha az adott kiterjesztés be van fordítva a PHP-be, vagy dinamikusan betöltött.

FRIBIDI_CHARSET_UTF8 (integer)

FRIBIDI_CHARSET_8859_6 (integer)

FRIBIDI_CHARSET_8859_8 (integer)

FRIBIDI_CHARSET_CP1255 (integer)

FRIBIDI_CHARSET_CP1256 (integer)

FRIBIDI_CHARSET_ISIRI_3342 (integer)

Tartalom
fribidi_log2vis -- Convert a logical string to a visual one

fribidi_log2vis

(4.0.4 - 4.3.2 only)

fribidi_log2vis -- Convert a logical string to a visual one

Description

string fribidi_log2vis ( string str, string direction, int charset)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

XXXIII. FTP functions

Bevezetés

The functions in this extension implement client access to file 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.


Követelmények

Az itt leírt függvények használatához semmilyen külső függvénykönyvtár megléte nem szükségeltetik.


Telepítés

In order to use FTP functions with your PHP configuration, you should add the --enable-ftp option when installing PHP 4 or --with-ftp when using PHP 3.

A PHP Windowsos változata beépített támogatással rendelkezik eme kiterjesztéshez. nincs szükség semmilyen kiterjesztés betöltésére, hogy az itt felsorolt függvnyeket használhasd.


Futásidejű beállítások

Ez a kiterjesztés semmilyen konfigurációs beállításokat nem definiál a php.ini állományban.


Erőforrás típusok

This extension uses one resource type, which is the link identifier of the FTP connection, returned by ftp_connect().


Előre definiált állandók

Az itt listázott állandókat ez a kiterjesztés definiálja, és csak akkor elérhetőek, ha az adott kiterjesztés be van fordítva a PHP-be, vagy dinamikusan betöltött.

FTP_ASCII (integer)

FTP_TEXT (integer)

FTP_BINARY (integer)

FTP_IMAGE (integer)

FTP_TIMEOUT_SEC (integer)

See ftp_set_option() for information.

The following constants were introduced in PHP 4.3.0.

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


Példák

Példa 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); 
?>

Tartalom
ftp_alloc -- Allocates space for a file to be uploaded.
ftp_cdup -- Changes to the parent directory
ftp_chdir -- Changes directories 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 program 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 -- Alias of 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 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

ftp_alloc

(no version information, might be only in CVS)

ftp_alloc -- Allocates space for a file to be uploaded.

Description

bool ftp_alloc ( resource ftp_stream, int filesize [, string &result])

Sends an ALLO command to the remote FTP server to allocate filesize bytes of space. Returns TRUE on success, or FALSE on failure.

Megjegyzés: 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.

A textual representation of the servers response will be returned by reference in result is a variable is provided.

Példa 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);

?>

See also: ftp_put(), and ftp_fput().

ftp_cdup

(PHP 3>= 3.0.13, PHP 4 )

ftp_cdup -- Changes to the parent directory

Description

bool ftp_cdup ( resource ftp_stream)

Changes to the parent directory.

Példa 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);
?>

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

See also ftp_chdir().

ftp_chdir

(PHP 3>= 3.0.13, PHP 4 )

ftp_chdir -- Changes directories on a FTP server

Description

bool ftp_chdir ( resource ftp_stream, string directory)

Changes the current directory to the specified directory.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Példa 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);
?>

See also ftp_cdup().

ftp_chmod

(PHP 5 CVS only)

ftp_chmod -- Set permissions on a file via FTP

Description

string ftp_chmod ( resource ftp_stream, int mode, string filename)

Sets the permissions on the remote file specified by filename to mode given as an octal value.

Példa 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)) {
 echo "$file cdmoded successfully to 644\n";
} else {
 echo "could not chmod $file\n";
}

// close the connection
ftp_close($conn_id);
?>

Returns the new file permissions on success or FALSE on error.

See also chmod().

ftp_close

(PHP 4 >= 4.2.0)

ftp_close -- Closes an FTP connection

Description

void ftp_close ( resource ftp_stream)

ftp_close() closes ftp_stream and releases the resource. After calling this function, you can no longer use the FTP connection and must create a new one with ftp_connect().

Példa 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);
?>

See also ftp_connect()

ftp_connect

(PHP 3>= 3.0.13, PHP 4 )

ftp_connect -- Opens an FTP connection

Description

resource ftp_connect ( string host [, int port [, int timeout]])

Returns a FTP stream on success or FALSE on error.

ftp_connect() opens an FTP connection to the specified host. host shouldn't have any trailing slashes and shouldn't be prefixed with ftp://. The port 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.

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

Megjegyzés: The timeout parameter became available in PHP 4.2.0.

Példa 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"); 

?>

See also ftp_close(), and ftp_ssl_connect().

ftp_delete

(PHP 3>= 3.0.13, PHP 4 )

ftp_delete -- Deletes a file on the FTP server

Description

bool ftp_delete ( resource ftp_stream, string path)

ftp_delete() deletes the file specified by path from the FTP server.

Példa 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);
?>

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

ftp_exec

(PHP 4 >= 4.0.3)

ftp_exec -- Requests execution of a program on the FTP server

Description

bool ftp_exec ( resource ftp_stream, string command)

Sends a SITE EXEC command request to the FTP server. Returns TRUE if the command was successful (server sent response code: 200); otherwise returns FALSE.

Példa 1. ftp_exec() example

<?php

$command = 'ls -al';

$conn_id = ftp_connect($ftp_server);

$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

if ($res = ftp_exec($conn_id, $command)) {
    echo "$command executed successfully<br />\n";
    echo nl2br($res);
} else {
    echo 'could not execute ' . $command;
}

?>

See also ftp_raw().

ftp_fget

(PHP 3>= 3.0.13, PHP 4 )

ftp_fget -- Downloads a file from the FTP server and saves to an open file

Description

bool ftp_fget ( resource ftp_stream, resource handle, string remote_file, int mode [, int resumepos])

ftp_fget() retrieves remote_file from the FTP server, and writes it to the given file pointer, handle. The transfer mode specified must be either FTP_ASCII or FTP_BINARY.

Példa 1. ftp_fget() example

<?php

// open some file for reading
$file = 'somefile.txt';
$fp = fopen($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 $file
if (ftp_fget($conn_id, $fp, $file, FTP_ASCII, 1)) {
 echo "successfully written to $file\n";
} else {
 echo "There was a problem with $file\n";
}

// close the connection and the file handler
ftp_close($conn_id);
fclose($fp);
?>

Megjegyzés: The resumepos parameter was added in PHP 4.3.0.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

See also ftp_get(), ftp_nb_get() and ftp_nb_fget().

ftp_fput

(PHP 3>= 3.0.13, PHP 4 )

ftp_fput -- Uploads from an open file to the FTP server

Description

bool ftp_fput ( resource ftp_stream, string remote_file, resource handle, int mode [, int startpos])

ftp_fput() uploads the data from the file pointer handle until the end of the file is reached. The results are stored in remote_file on the FTP server. The transfer mode specified must be either FTP_ASCII or FTP_BINARY.

Példa 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);

?>

Megjegyzés: The startpos parameter was added in PHP 4.3.0.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

See also ftp_put(), ftp_nb_fput(), and ftp_nb_put().

ftp_get_option

(PHP 4 >= 4.2.0)

ftp_get_option -- Retrieves various runtime behaviours of the current FTP stream

Description

mixed ftp_get_option ( resource ftp_stream, int option)

Returns the value on success or FALSE if the given option is not supported. In the latter case, a warning message is also thrown.

This function returns the value for the requested option from the specified ftp_stream . Currently, the following options are supported:

Táblázat 1. Supported runtime FTP options

FTP_TIMEOUT_SEC Returns the current timeout used for network related operations.

Példa 1. ftp_get_option() example

<?php
// Get the timeout of the given FTP stream
$timeout = ftp_get_option($conn_id, FTP_TIMEOUT_SEC);
?>

See also ftp_set_option().

ftp_get

(PHP 3>= 3.0.13, PHP 4 )

ftp_get -- Downloads a file from the FTP server

Description

bool ftp_get ( resource ftp_stream, string local_file, string remote_file, int mode [, int resumepos])

ftp_get() retrieves remote_file from the FTP server, and saves it to local_file locally. The transfer mode specified must be either FTP_ASCII or FTP_BINARY.

Megjegyzés: The resumepos parameter was added in PHP 4.3.0.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Példa 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);

?>

See also ftp_fget(), ftp_nb_get() and ftp_nb_fget().

ftp_login

(PHP 3>= 3.0.13, PHP 4 )

ftp_login -- Logs in to an FTP connection

Description

bool ftp_login ( resource ftp_stream, string username, string password)

Logs in to the given FTP stream.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Példa 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_mdtm

(PHP 3>= 3.0.13, PHP 4 )

ftp_mdtm -- Returns the last modified time of the given file

Description

int ftp_mdtm ( resource ftp_stream, string remote_file)

ftp_mdtm() checks the last modified time for a file, and returns it as a Unix timestamp. If an error occurs, or the file does not exist, -1 is returned.

Returns a Unix timestamp on success, or -1 on error.

Példa 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);

?>

Megjegyzés: Not all servers support this feature!

Megjegyzés: ftp_mdtm() does not work with directories.

ftp_mkdir

(PHP 3>= 3.0.13, PHP 4 )

ftp_mkdir -- Creates a directory

Description

string ftp_mkdir ( resource ftp_stream, string directory)

Creates the specified directory on the FTP server.

Returns the newly created directory name on success or FALSE on error.

Példa 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);
?>

See also ftp_rmdir().

ftp_nb_continue

(PHP 4 >= 4.3.0)

ftp_nb_continue -- Continues retrieving/sending a file (non-blocking)

Description

int ftp_nb_continue ( resource ftp_stream)

Continues retrieving/sending a file non-blocking.

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

Returns FTP_FAILED or FTP_FINISHED or FTP_MOREDATA.

ftp_nb_fget

(PHP 4 >= 4.3.0)

ftp_nb_fget -- Retrieves a file from the FTP server and writes it to an open file (non-blocking)

Description

int ftp_nb_fget ( resource ftp_stream, resource handle, string remote_file, int mode [, int resumepos])

ftp_nb_fget() retrieves remote_file from the FTP server, and writes it to the given file pointer, handle. The transfer mode specified must be either FTP_ASCII or FTP_BINARY. The difference between this function and the ftp_fget() is that this function retrieves the file asynchronously, so your program can perform other operations while the file is being downloaded.

Példa 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);
?>

Returns FTP_FAILED, FTP_FINISHED, or FTP_MOREDATA.

See also ftp_nb_get(), ftp_nb_continue(), ftp_fget(), and ftp_get().

ftp_nb_fput

(PHP 4 >= 4.3.0)

ftp_nb_fput -- Stores a file from an open file to the FTP server (non-blocking)

Description

int ftp_nb_fput ( resource ftp_stream, string remote_file, resource handle, int mode [, int startpos])

ftp_nb_fput() uploads the data from the file pointer handle until it reaches the end of the file. The results are stored in remote_file on the FTP server. The transfer mode specified must be either FTP_ASCII or FTP_BINARY. 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.

Példa 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);
?>

Returns FTP_FAILED, FTP_FINISHED, or FTP_MOREDATA.

See also ftp_nb_put(), ftp_nb_continue(), ftp_put() and ftp_fput().

ftp_nb_get

(PHP 4 >= 4.3.0)

ftp_nb_get -- Retrieves a file from the FTP server and writes it to a local file (non-blocking)

Description

int ftp_nb_get ( resource ftp_stream, string local_file, string remote_file, int mode [, int resumepos])

ftp_nb_get() retrieves remote_file from the FTP server, and saves it to local_file locally. The transfer mode specified must be either FTP_ASCII or FTP_BINARY. The difference between this function and the ftp_get() is that this function retrieves the file asynchronously, so your program can perform other operations while the file is being downloaded.

Returns FTP_FAILED, FTP_FINISHED, or FTP_MOREDATA.

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

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

Példa 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 have not have disabled FTP_AUTOSEEK, the first 100 bytes of "newfile" will be '\0'.

See also ftp_nb_fget(), ftp_nb_continue(), ftp_get(), and ftp_fget().

ftp_nb_put

(PHP 4 >= 4.3.0)

ftp_nb_put -- Stores a file on the FTP server (non-blocking)

Description

int ftp_nb_put ( resource ftp_stream, string remote_file, string local_file, int mode [, int startpos])

ftp_nb_put() stores local_file on the FTP server, as remote_file. The transfer mode specified must be either FTP_ASCII or FTP_BINARY. 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.

Returns FTP_FAILED, FTP_FINISHED, or FTP_MOREDATA.

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

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

See also ftp_nb_fput(), ftp_nb_continue(), ftp_put(), and ftp_fput().

ftp_nlist

(PHP 3>= 3.0.13, PHP 4 )

ftp_nlist -- Returns a list of files in the given directory

Description

array ftp_nlist ( resource ftp_stream, string directory)

Returns an array of filenames from the specified directory on success or FALSE on error.

Példa 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);

?>

    The above example will output something similar to:

array(3) {
  [0]=>
  string(11) "public_html"
  [1]=>
  string(10) "public_ftp"
  [2]=>
  string(3) "www"

See also ftp_rawlist().

ftp_pasv

(PHP 3>= 3.0.13, PHP 4 )

ftp_pasv -- Turns passive mode on or off

Description

bool ftp_pasv ( resource ftp_stream, bool pasv)

ftp_pasv() turns on passive mode if the pasv parameter is TRUE. It turns off passive mode if pasv is FALSE. In passive mode, data connections are initiated by the client, rather than by the server.

Példa 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);
?>

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

ftp_put

(PHP 3>= 3.0.13, PHP 4 )

ftp_put -- Uploads a file to the FTP server

Description

bool ftp_put ( resource ftp_stream, string remote_file, string local_file, int mode [, int startpos])

ftp_put() stores local_file on the FTP server, as remote_file. The transfer mode specified must be either FTP_ASCII or FTP_BINARY.

Megjegyzés: The startpos parameter was added in PHP 4.3.0.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Példa 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);
?>

See also ftp_fput(), ftp_nb_fput(), and ftp_nb_put().

ftp_pwd

(PHP 3>= 3.0.13, PHP 4 )

ftp_pwd -- Returns the current directory name

Description

string ftp_pwd ( resource ftp_stream)

Returns the current directory or FALSE on error.

Példa 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);
?>

ftp_quit

ftp_quit -- Alias of ftp_close()

Description

This function is an alias of ftp_close().

ftp_raw

(PHP 5 CVS only)

ftp_raw -- Sends an arbitrary command to an FTP server

Description

array ftp_raw ( resource ftp_stream, string command)

Sends an arbitrary command to the FTP server. 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.

Példa 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");
?>

See Also: ftp_exec()

ftp_rawlist

(PHP 3>= 3.0.13, PHP 4 )

ftp_rawlist -- Returns a detailed list of files in the given directory

Description

array ftp_rawlist ( resource ftp_stream, string directory)

ftp_rawlist() executes the FTP LIST command, and returns the result as an array. Each array element corresponds to one line of text. 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.

Példa 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);
?>

    The above example will output something similar to:    

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

See also ftp_nlist().

ftp_rename

(PHP 3>= 3.0.13, PHP 4 )

ftp_rename -- Renames a file on the FTP server

Description

bool ftp_rename ( resource ftp_stream, string from, string to)

ftp_rename() renames the file or directory that is currently named from to the new name to, using the FTP stream ftp_stream.

Példa 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 $olf_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);
?>

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

ftp_rmdir

(PHP 3>= 3.0.13, PHP 4 )

ftp_rmdir -- Removes a directory

Description

bool ftp_rmdir ( resource ftp_stream, string directory)

Removes the specified directory. directory must be either an absolute or relative path to an empty directory.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Példa 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);

?>

See also ftp_mkdir().

ftp_set_option

(PHP 4 >= 4.2.0)

ftp_set_option -- Set miscellaneous runtime FTP options

Description

bool ftp_set_option ( resource ftp_stream, int option, mixed value)

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.

This function controls various runtime options for the specified FTP stream. The value parameter depends on which option parameter is chosen to be altered. Currently, the following options are supported:

Táblázat 1. Supported runtime FTP options

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

Példa 1. ftp_set_option() example

<?php
// Set the network timeout to 10 seconds
ftp_set_option($conn_id, FTP_TIMEOUT_SEC, 10);
?>

See also ftp_get_option().

ftp_site

(PHP 3>= 3.0.15, PHP 4 )

ftp_site -- Sends a SITE command to the server

Description

bool ftp_site ( resource ftp_stream, string cmd)

ftp_site() sends the command specified by cmd 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.

Példa 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.');
}
?>

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

See Also: ftp_raw()

ftp_size

(PHP 3>= 3.0.13, PHP 4 )

ftp_size -- Returns the size of the given file

Description

int ftp_size ( resource ftp_stream, string remote_file)

ftp_size() returns the size of a remote_file in bytes. If an error occurs, or if the given file does not exist, or is a directory, -1 is returned. Not all servers support this feature.

Returns the file size on success, or -1 on error.

Példa 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);

?>

See also ftp_rawlist().

ftp_ssl_connect

(PHP 4 >= 4.3.0)

ftp_ssl_connect -- Opens an Secure SSL-FTP connection

Description

resource ftp_ssl_connect ( string host [, int port [, int timeout]])

Returns a SSL-FTP stream on success or FALSE on error.

ftp_ssl_connect() opens a SSL-FTP connection to the specified host. The port parameter specifies an alternate port to connect to. If it's omitted or set to zero then the default FTP port 21 will be used.

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

Példa 1. ftp_ssl_connect() example

<?php

// set up basic ssl connection
$conn_id = ftp_ssl_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

echo ftp_pwd($conn_id); // /

// close the ssl connection
ftp_close($conn_id);
?>

Why this function may not exist: ftp_ssl_connect() is only available if OpenSSL support is enabled into your version of PHP. If it's undefined and you've compiled FTP support then this is why.

See also ftp_connect().

ftp_systype

(PHP 3>= 3.0.13, PHP 4 )

ftp_systype -- Returns the system type identifier of the remote FTP server

Description

string ftp_systype ( resource ftp_stream)

Returns the remote system type, or FALSE on error.

Példa 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";
}

?>

The above example will output something similar to:

Example.com is powered by UNIX

XXXIV. Függvénykezelő függvények

Bevezetés

E függvények mindegyike különféle, a PHP függvényekhez szorosan kapcsolodó műveletekben segédkezik.


Követelmények

Az itt leírt függvények használatához semmilyen külső függvénykönyvtár megléte nem szükségeltetik.


Telepítés

Semmilyen telepítés nem szükséges ezen függvények használatához, a PHP alapelemei.


Futásidejű beállítások

Ez a kiterjesztés semmilyen konfigurációs beállításokat nem definiál a php.ini állományban.


Előre definiált állandók

Ez a kiterjesztés semmilyen konstans értéket nem definiál.

Tartalom
call_user_func_array --  Felhasználói függvényt hív meg a paraméterek egy tömbjével
call_user_func --  Felhasználói függvényt hív meg.
create_function -- Név nélküli (lambda típusú) függvényt definiál
func_get_arg -- Visszaadja a paraméter lista egy elemét
func_get_args --  Visszatér a függvénynek átadott paramétereket tartalmazó tömbbel
func_num_args --  Visszaadja a függvénynek átadott paraméterek számát
function_exists --  TRUE-val tér vissza, ha az adott nevű függvény definiálva van
get_defined_functions --  visszatér az összes definiált függvény nevével
register_shutdown_function --  Regiszrálja a függvényt a szkript befejezésekor történő végrehajtásra
register_tick_function --  Regisztrálja a függvényt a tick eseményhez
unregister_tick_function --  Megszünteti a függvény a tick bekövetkeztekor történő futtatását

call_user_func_array

(PHP 4 >= 4.0.4)

call_user_func_array --  Felhasználói függvényt hív meg a paraméterek egy tömbjével

Leírás

mixed call_user_func_array ( string function_name [, array paramarr])

A function_name-ban megadott nevű felhasználói függvényt hívja meg paramarr-ben megadott paraméterekkel. Például:

function debug($var, $val)
    echo "***Bogarásszunk\nVÁLTOZÓ: $var\nÉRTÉKE:";
    if (is_array($val) || is_object($val) || is_resource($val))
        print_r($val);
    else
        echo "\n$val\n";
    echo "***\n";
}

$c    = mysql_connect();
$host = $_SERVER["SERVER_NAME"];

call_user_func_array ('debug', array("host", $host));
call_user_func_array ('debug', array("c", $c));
call_user_func_array ('debug', array("_POST", $_POST));

Lásd még: call_user_func(), call_user_method() és call_user_method_array()!

Megjegyzés: Ez a függvény a PHP 4.0.4pl1 kiadása után került a CVS-be.

call_user_func

(PHP 3>= 3.0.3, PHP 4 )

call_user_func --  Felhasználói függvényt hív meg.

Leírás

mixed call_user_func ( string function_name [, mixed parameter [, mixed ...]])

A function_name-ban megadott nevű felhasználói függvényt hívja meg. Az ezután álló parameter paraméterek a megadott sorrendben lesznek átadva a meghívott függvénynek. Nézzük a kövekező példát:

function borbely ($tipus) {
    print " Szóval $tipus akar, semmi gond.";
}
call_user_func ('borbely', "gomba frizurát");
call_user_func ('borbely', "nyírást");

Lásd még: call_user_func_array(), call_user_method() és call_user_method_array()!

create_function

(PHP 4 >= 4.0.1)

create_function -- Név nélküli (lambda típusú) függvényt definiál

Leírás

string create_function ( string args, string code)

Az átadott paraméterek alapján egy anonim - név nélküli függvényt hoz létre. Az args paramétert általában egyszeres idézőjelek közt szokás átadni, és ez ajánlott a code-ra is. Ennek az az oka, hogy az egyszeres idézőjelek közé fogott sztringekre nem aktiválódik a változó-behelyettesítés, máskülönben macskakörmök használata esetén a változó neveket visszaperjelezned kellene, mint például: \$avar.

Ezzel a függvénnyel - például futási időben nyert információk alapján - definiálhatsz új függvényeket:

Példa 1. A create_function() segítségével definiált függvények

$ujfgv = create_function('$a,$b','return "ln($a) + ln($b) = ".log($a * $b);');
echo "Új névtelen függvényünk: $ujfgv\n"; // azért valami neve csak van :)
echo $ujfgv(2,M_E)."\n";
// eredményül kírja:
// Új névtelen függvényünk: lambda_1
// ln(2) + ln(2.718281828459) = 1.6931471805599
Vagy egy általános kezelőfüggvény megléte esetén műveletek sorozata alkalmazható egy adott paraméterlistára, pl:

Példa 2. Általános feldolgozó függvény létrehozása create_function()-nel.

function feldolgoz($valtozo1, $valtozo2, $fvtomb) {
    for ($f=0; $f < count($fvtomb); $f++)
    echo $fvtomb[$f]($valtozo1,$valtozo2)."\n";
}

// egy csomó matematikai függvény létrehozása
$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;}';
$fv_tomb = array(
        create_function('$x,$y', 'return "ezt nem tudom, mi: ".(sin($x) + $x*cos($y));'),
        create_function('$x,$y', 'return "az átfogó: ".sqrt($x*$x + $y*$y);'),
        create_function('$a,$b', $f1),
        create_function('$a,$b', $f2),
        create_function('$a,$b', $f3)
    );

echo "\nAz első tömb anonim függvényekkel\n";
echo "paraméterek: 2.3445, M_PI\n";
feldolgoz(2.3445, M_PI, $fv_tomb);

// most egy csomó sztringkezelő függvény létrehozása
$fv_tomb2 = array(
        create_function('$b,$a','if (strncmp($a,$b,3) == 0) return "** \"$a\" '.
        'és \"$b\"\n** nekem azonosnak tűnik! (az első 3 karakter után)";'),
        create_function('$a,$b','; return "CRCs: ".crc32($a)." , ".crc32(b);'),
        create_function('$a,$b','; return "hasonló(a,b) = ".similar_text($a,$b,&$p)."($p%)";')
    );
echo "\nA második tömb anonim függvényekkel\n";
feldolgoz("Akkor csillogó és fényes volt.", "Akkor este volt.", $fv_tomb2);
a fenti kód lefuttatása után a következő fog megjelenni:

Az első tömb anonim függvényekkel
paraméterek: 2.3445, M_PI
ezt nem tudom, mi: -1.6291725057799
az átfogó: 3.9199852871011
b*a^2 = 4.8103313314525
min(b^2+a, a^2,b) = 8.6382729035898
ln(a/b) = 0.27122299212594

A második tömb anonim függvényekkel
** "Akkor csillogó és fényes volt." és "Akkor este volt."
** nekem azonosnak tunik! (az elso 3 karakter utan)
CRCs: -725381282 , 1908338681
hasonló(a,b) = 11(45.833333333333%)

Valószínűleg az anonim függvények legáltalánosabb felhasználási módja az ún. 'callback' függvények létrehozása, pl. az array_walk() vagy az usort() számára.

Példa 3. Anonim függvények használata 'callback' függvényként

$nevelok = array("a ","egy ","az ","ez ");
array_walk($nevelok, create_function('&$v,$k','$v = $v."mangó";'));
print_r($av);  // PHP 3-soknak var_dump()
// kiírja, hogy :
// Array
// (
//   [0] => a mangó
//   [1] => egy mangó
//   [2] => az mangó
//   [3] => ez mangó
// )

// szrtinggel teli tömb a rövidebbtől a hosszabb felé rendezve
$sv = array("rovid","hosszabb","egy nagy string","ez valami sztring dolog");
print_r($sv);
// kiírja, hogy:
// Array
// (
//   [0] => rovid
//   [1] => hosszabb
//   [2] => egy nagy sztring
//   [3] => ez valami sztring dolog
// )

// hosszúság szerinti csökkenő sorrendben rendezve:
usort($sv, create_function('$a,$b','return strlen($b) - strlen($a);'));
print_r($sv);
// kiírja, hogy:
// Array
// (
//   [0] => ez valami sztring dolog
//   [1] => egy nagy sztring
//   [2] => hosszabb
//   [3] => rovid
// )

func_get_arg

(PHP 4 )

func_get_arg -- Visszaadja a paraméter lista egy elemét

Leírás

mixed func_get_arg ( int arg_num)

Visszadja a függvénynek átadott paraméterlista arg_num. helyén álló paramétert. A paraméterek számozása 0-tól kezdődik. A func_get_arg() "nem fatális" hibát (warning) jelez, ha függvényen kívül hívod meg.

Ha az arg_num a pillanatnyilag átadott paraméterek számánál nagyobb, akkor egy "nem fatális" hiba (warning) generálódik és a func_get_arg() FALSE-szal tér vissza.

<?php
function ize() {
     $parameterek_szama = func_num_args();
     echo "argumentumok száma: {$parameterek_szama}<br/>\n";
     if ($parameterek_szama >= 2) {
     echo "A második paraméter: " . func_get_arg (1) . "<br/>\n";
     }
}

ize (1, 2, 3);
?>

A func_get_arg() a func_num_args() és a func_get_args() függvényekkel együtt olyan függvények írását segítik elő, amelyek különböző hosszúságú paraméterlistákat képesek kezelni.

Megjegyzés: Ez a függvény PHP 4-től használható.

func_get_args

(PHP 4 )

func_get_args --  Visszatér a függvénynek átadott paramétereket tartalmazó tömbbel

Leírás

array func_get_args ( void )

Visszaad egy tömböt az aktuális függvénynek átadott paraméterekkel. A func_get_args() "nem fatális" hibát (warning) jelez, ha függvénydefiníción kívül hívod meg.

<?php
function ize() {
    $pm_szama = func_num_args();
    echo "A parameterek szama: {$pm_szama}<br/>\n";
    if ($pm_szama >= 2) {
    echo "A masodik parameter: " . func_get_arg (1) . "<br/>\n";
    }
    $pm_lista = func_get_args();
    for ($i = 0; $i < $pm_szama; $i++) {
    echo "$i. parameter : " . $pm_lista[$i] . "<br/>\n";
    }
}

ize (1, 2, 3);
?>

A func_get_args()-t a func_get_arg() és func_num_args() függvényekkel együtt használva a felhasználói függvények is képesek kezelni a változó hosszúságú paraméterlistákat.

Megjegyzés: Ez a függvény PHP 4-től használható.

func_num_args

(PHP 4 )

func_num_args --  Visszaadja a függvénynek átadott paraméterek számát

Leírás

int func_num_args ( void )

Visszaadja az aktuális függvénynek átadott paraméterek számát. A func_num_args() "nem fatális" hibát (warning) jelez, ha függvénydefiníción kívül hívod meg.

<?php
function ize() {
    $pm_szama = func_num_args();
    echo "A parameterek szama: {$pm_szama}\n";
}

ize (1, 2, 3);    // kiírja, hogy : 'A parameterek szama: 3'
?>

A func_num_args()-t a func_get_arg() és func_get_args() függvényekkel együtt használva a felhasználói függvények is képesek kezelni a változó hosszúságú paraméterlistákat.

function_exists

(PHP 3>= 3.0.7, PHP 4 )

function_exists --  TRUE-val tér vissza, ha az adott nevű függvény definiálva van

Leírás

bool function_exists ( string function_name)

A beépített és a felhasználó által definiált függvények között megkeresi a function_name nevűt. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

if (function_exists('imap_open')) {
    echo "IMAP függvények használhatók.<br/>\n";
} else {
    echo "IMAP függvények _nem_ használhatók.<br/>\n";
}

Vigyázat, mert egy függvény neve létezhet még akkor is, ha a függvény maga nem használható valamilyen konfigurációs vagy fordítási beálltás következtében. Ilyenek például a képkezelő függvéyek. Szintén fontos megjegyezni, hogy a function_exists() FALSE értéket fog adni a nyelvi elemekre, amilyen például az include_once() vagy az echo().

Lásd még: method_exists() és get_defined_functions()!

get_defined_functions

(PHP 4 >= 4.0.4)

get_defined_functions --  visszatér az összes definiált függvény nevével

Leírás

array get_defined_functions ( void )

Ez a függvény egy többdimenziós tömböt ad vissza, amelyben mind a beépített mind a felhasználó által definiált függvények nevei szerepelnek. A beépített függvények nevei $arr["internal"]-n keresztül érhetők el, amelyeket a felhasználó definiált, azok pedig az $arr["user"]-n keresztül. (lásd a lenti példát!)

function az_en_sorom($id, $adat) {
    return "<tr><th>$id</th><td>$adat</td></tr>\n";
}

$arr = get_defined_functions();

print_r($arr);

valami hasonlót fog kírni:

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] => az_en_sorom
        )

)

Lásd még: get_defined_vars() és get_defined_constants()!

register_shutdown_function

(PHP 3>= 3.0.4, PHP 4 )

register_shutdown_function --  Regiszrálja a függvényt a szkript befejezésekor történő végrehajtásra

Leírás

int register_shutdown_function ( string func)

A func nevű függvényt regisztrálja, hogy az majd a szkript feldolgozása után lefusson.

Ha egymás után többször is meghívásra kerül a register_shutdown_function(), akkor a paraméterként átadott függvények ebben a sorrendben lesznek regisztrálva és meghívva. Ha valamelyik regisztrált függvényben az exit()-re kerül a vezérlés, akkor a feldolgozás megszakad és az ezután következő regisztrált függvények nem kerülnek meghívásra.

Mivel a regisztrált "lezáró" függvények a kérés kiszolgálása (kimeneti tartalom elküldése) után kerülnek meghívásra , ezért nem lehet semmilyen adatot küldeni a kliensnek pl. echo() vagy print() függvényekkel, és a kimeneti tárolók tartalmát sem lehet olvasni ob_get_contents() segítségével.

Megjegyzés: A függvény neve helyett egy tömböt is átadhatsz, ami egy objektum referenciát és egy metódus nevet kell tartalmazzon.

register_tick_function

(PHP 4 >= 4.0.3)

register_tick_function --  Regisztrálja a függvényt a tick eseményhez

Leírás

void register_tick_function ( string func [, mixed arg])

Regisztrálja a func nevű függvényt, hogy az meghívásra kerüljön minden egyes tick bekövetkeztekor.

unregister_tick_function

(PHP 4 >= 4.0.3)

unregister_tick_function --  Megszünteti a függvény a tick bekövetkeztekor történő futtatását

Leírás

void unregister_tick_function ( string func [, mixed arg])

A func nevű függvényt kiiktatja, hogy az ne fusson le, amikor egy tick esemény bekövetkezik.

XXXV. GNU Gettext

A gettext függvények az NLS (Native Language Support) API-t valósítják meg, ami a PHP szkriptek nemzetközivé tételéhez használható. Lásd még a GNU gettext dokumentációt egy alaposabb leírásért ezen függvényekkel kapcsolatban.

Tartalom
bind_textdomain_codeset --  Specify the character encoding in which the messages from the DOMAIN message catalog will be returned
bindtextdomain -- Beállítja egy domain elérési útját
dcgettext -- Felülbírálja a domain-t egy lekérés erejéig
dcngettext -- Plural version of dcgettext
dgettext -- Az aktuális domain felülbírálása
dngettext -- Plural version of dgettext
gettext -- Egy üzenet lekérése az aktuális domain-ben
ngettext -- Plural version of gettext
textdomain -- Beállítja az alapértelmezett domain-t

bind_textdomain_codeset

(PHP 4 >= 4.2.0)

bind_textdomain_codeset --  Specify the character encoding in which the messages from the DOMAIN message catalog will be returned

Description

string bind_textdomain_codeset ( string domain, string codeset)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

bindtextdomain

(PHP 3>= 3.0.7, PHP 4 )

bindtextdomain -- Beállítja egy domain elérési útját

Leírás

string bindtextdomain ( string domain, string directory)

A bindtextdomain() függvény beállítja egy domain elérési útját.

dcgettext

(PHP 3>= 3.0.7, PHP 4 )

dcgettext -- Felülbírálja a domain-t egy lekérés erejéig

Leírás

string dcgettext ( string domain, string message, int category)

Ez a függvény lehetőséget ad az aktuális domain felülbírálására egy lekérés erejéig. Egy kategória megadására is módot ad.

dcngettext

(PHP 4 >= 4.2.0)

dcngettext -- Plural version of dcgettext

Description

string dcngettext ( string domain, string msgid1, string msgid2, int n, int category)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

dgettext

(PHP 3>= 3.0.7, PHP 4 )

dgettext -- Az aktuális domain felülbírálása

Leírás

string dgettext ( string domain, string message)

A dgettext() függvény lehetőséget ad az aktuális domain felülbírálására egy lekérés erejéig.

dngettext

(PHP 4 >= 4.2.0)

dngettext -- Plural version of dgettext

Description

string dngettext ( string domain, string msgid1, string msgid2, int n)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

gettext

(PHP 3>= 3.0.7, PHP 4 )

gettext -- Egy üzenet lekérése az aktuális domain-ben

Leírás

string gettext ( string message)

Ez a függvény visszaadja a lefordított stringet, ha található ilyen a fordítási táblában. Egyébként az átadott stringet változtatás adja vissza. Haználhatod az aláhúzás karaktert, mint e függvény alias-át.

Példa 1. gettext() ellenőrzés

<?php
// Németre állítjuk a nyelvet
putenv ("LANG=de");

// A fordítási táblák elérésnek megadása
bindtextdomain ("enPHPAlkalmazasom", "./locale");

// Domain kiválasztása
textdomain ("enPHPAlkalmazasom");

// Szöveges üzenet kiírása
print (gettext ("Welcome to My PHP Application"));
?>

ngettext

(PHP 4 >= 4.2.0)

ngettext -- Plural version of gettext

Description

string ngettext ( string msgid1, string msgid2, int n)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

textdomain

(PHP 3>= 3.0.7, PHP 4 )

textdomain -- Beállítja az alapértelmezett domain-t

Leírás

string textdomain ( string text_domain)

Ez a függvény beállítja, hogy melyik domain-ben kell keresni a gettext() hívások esetén. Az előző beállítást adja vissza. Ha nem adsz át paramétert, az aktuális beállításokkal tér vissza.

XXXVI. GMP functions

Bevezetés

These functions allow you to work with arbitrary-length integers using the GNU MP library.

These functions have been added in PHP 4.0.4.

Megjegyzés: Most GMP functions accept GMP number arguments, defined as resource below. However, most of these functions will also accept numeric and string arguments, given that it is possible to convert the latter to a number. Also, if there is a faster function that can operate on integer arguments, it would be used instead of the slower function when the supplied arguments are integers. This is done transparently, so the bottom line is that you can use integers in every function that expects GMP number. See also the gmp_init() function.

Figyelem

If you want to explicitly specify a large integer, specify it as a string. If you don't do that, PHP will interpret the integer-literal first, possibly resulting in loss of precision, even before GMP comes into play.

Megjegyzés: Ez a kiterjesztés nem működik Windows operációs rendszereken!


Követelmények

You can download the GMP library from http://www.swox.com/gmp/. This site also has the GMP manual available.

You will need GMP version 2 or better to use these functions. Some functions may require more recent version of the GMP library.


Telepítés

In order to have these functions available, you must compile PHP with GMP support by using the --with-gmp option.


Futásidejű beállítások

Ez a kiterjesztés semmilyen konfigurációs beállításokat nem definiál a php.ini állományban.


Erőforrás típusok

Ez a kiterjesztés semmilyen erőforrás típust nem definiál.


Előre definiált állandók

Az itt listázott állandókat ez a kiterjesztés definiálja, és csak akkor elérhetőek, ha az adott kiterjesztés be van fordítva a PHP-be, vagy dinamikusan betöltött.

GMP_ROUND_ZERO (integer)

GMP_ROUND_PLUSINF (integer)

GMP_ROUND_MINUSINF (integer)


Példák

Példa 1. Factorial function using GMP

<?php
function fact($x) 
{
    if ($x <= 1) {
        return 1;
    } else {
        return gmp_mul($x, fact($x-1));
    }
}

echo gmp_strval(fact(1000)) . "\n";
?>

This will calculate factorial of 1000 (pretty big number) very fast.


Lásd még

More mathematical functions can be found in the sections BCMath Arbitrary Precision Mathematics Functions and Mathematical Functions.

Tartalom
gmp_abs -- Absolute value
gmp_add -- Add numbers
gmp_and -- Logical AND
gmp_clrbit -- Clear bit
gmp_cmp -- Compare numbers
gmp_com -- Calculates one's complement of a
gmp_div_q -- Divide numbers
gmp_div_qr -- Divide numbers and get quotient and remainder
gmp_div_r -- Remainder of the division of numbers
gmp_div -- Alias of gmp_div_q()
gmp_divexact -- Exact division of numbers
gmp_fact -- Factorial
gmp_gcd -- Calculate GCD
gmp_gcdext -- Calculate GCD and multipliers
gmp_hamdist -- Hamming distance
gmp_init -- Create GMP number
gmp_intval -- Convert GMP number to integer
gmp_invert -- Inverse by modulo
gmp_jacobi -- Jacobi symbol
gmp_legendre -- Legendre symbol
gmp_mod -- Modulo operation
gmp_mul -- Multiply numbers
gmp_neg -- Negate number
gmp_or -- Logical OR
gmp_perfect_square -- Perfect square check
gmp_popcount -- Population count
gmp_pow -- Raise number into power
gmp_powm -- Raise number into power with modulo
gmp_prob_prime -- Check if number is "probably prime"
gmp_random -- Random number
gmp_scan0 -- Scan for 0
gmp_scan1 -- Scan for 1
gmp_setbit -- Set bit
gmp_sign -- Sign of number
gmp_sqrt -- Square root
gmp_sqrtrem --  Square root with remainder
gmp_sqrtrm -- Square root with remainder
gmp_strval -- Convert GMP number to string
gmp_sub -- Subtract numbers
gmp_xor -- Logical XOR

gmp_abs

(PHP 4 >= 4.0.4)

gmp_abs -- Absolute value

Description

resource gmp_abs ( resource a)

Returns absolute value of a.

gmp_add

(PHP 4 >= 4.0.4)

gmp_add -- Add numbers

Description

resource gmp_add ( resource a, resource b)

Add two GMP numbers. The result will be a GMP number representing the sum of the arguments.

gmp_and

(PHP 4 >= 4.0.4)

gmp_and -- Logical AND

Description

resource gmp_and ( resource a, resource b)

Calculates logical AND of two GMP numbers.

gmp_clrbit

(PHP 4 >= 4.0.4)

gmp_clrbit -- Clear bit

Description

resource gmp_clrbit ( resource &a, int index)

Clears (sets to 0) bit index in a.

gmp_cmp

(PHP 4 >= 4.0.4)

gmp_cmp -- Compare numbers

Description

int gmp_cmp ( resource a, resource b)

Returns a positive value if a > b, zero if a = b and negative value if a < b.

gmp_com

(PHP 4 >= 4.0.4)

gmp_com -- Calculates one's complement of a

Description

resource gmp_com ( resource a)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

gmp_div_q

(PHP 4 >= 4.0.4)

gmp_div_q -- Divide numbers

Description

resource gmp_div_q ( resource a, resource b [, int round])

Divides a by b and returns the integer result. 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.

This function can also be called as gmp_div().

See also gmp_div_r(), gmp_div_qr()

gmp_div_qr

(PHP 4 >= 4.0.4)

gmp_div_qr -- Divide numbers and get quotient and remainder

Description

array gmp_div_qr ( resource n, resource d [, int round])

The function divides n by d and returns 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).

See the gmp_div_q() function for description of the round argument.

Példa 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]));
?>

See also gmp_div_q(), gmp_div_r().

gmp_div_r

(PHP 4 >= 4.0.4)

gmp_div_r -- Remainder of the division of numbers

Description

resource gmp_div_r ( resource n, resource d [, int round])

Calculates remainder of the integer division of n by d. The remainder has the sign of the n argument, if not zero.

See the gmp_div_q() function for description of the round argument.

See also gmp_div_q(), gmp_div_qr()

gmp_div

gmp_div -- Alias of gmp_div_q()

Description

This function is an alias of gmp_div_q().

gmp_divexact

(PHP 4 >= 4.0.4)

gmp_divexact -- Exact division of numbers

Description

resource gmp_divexact ( resource n, resource d)

Divides n by d, using fast "exact division" algorithm. This function produces correct results only when it is known in advance that d divides n.

gmp_fact

(PHP 4 >= 4.0.4)

gmp_fact -- Factorial

Description

resource gmp_fact ( int a)

Calculates factorial (a!) of a.

gmp_gcd

(PHP 4 >= 4.0.4)

gmp_gcd -- Calculate GCD

Description

resource gmp_gcd ( resource a, resource b)

Calculate greatest common divisor of a and b. The result is always positive even if either of, or both, input operands are negative.

gmp_gcdext

(PHP 4 >= 4.0.4)

gmp_gcdext -- Calculate GCD and multipliers

Description

array gmp_gcdext ( resource a, resource b)

Calculates g, s, and t, such that a*s + b*t = g = gcd(a,b), where gcd is the greatest common divisor. Returns an array with respective elements g, s and t.

This function can be used to solve linear Diophantine equations in two variables. These are equations that allow only integer solutions and have the form: a*x + b*y = c. For more information, go to the "Diophantine Equation" page at MathWorld

Példa 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_hamdist

(PHP 4 >= 4.0.4)

gmp_hamdist -- Hamming distance

Description

int gmp_hamdist ( resource a, resource b)

Returns the hamming distance between a and b. Both operands should be non-negative.

gmp_init

(PHP 4 >= 4.0.4)

gmp_init -- Create GMP number

Description

resource gmp_init ( mixed number)

Creates a GMP number from an integer or string. String representation can be decimal or hexadecimal. In the latter case, the string should start with 0x.

Példa 1. Creating GMP number

<?php
    $a = gmp_init(123456);
    $b = gmp_init("0xFFFFDEBACDFEDF7200");
?>

Megjegyzés: It is not necessary to call this function if you want to use integer or string in place of GMP number in GMP functions, like gmp_add(). Function arguments are automatically converted to GMP numbers, if such conversion is possible and needed, using the same rules as gmp_init().

gmp_intval

(PHP 4 >= 4.0.4)

gmp_intval -- Convert GMP number to integer

Description

int gmp_intval ( resource gmpnumber)

This function allows to convert GMP number to integer.

Figyelem

This function returns a useful result only if the number actually fits the PHP integer (i.e., signed long type). If you want just to print the GMP number, use gmp_strval().

gmp_invert

(PHP 4 >= 4.0.4)

gmp_invert -- Inverse by modulo

Description

resource gmp_invert ( resource a, resource b)

Computes the inverse of a modulo b. Returns FALSE if an inverse does not exist.

gmp_jacobi

(PHP 4 >= 4.0.4)

gmp_jacobi -- Jacobi symbol

Description

int gmp_jacobi ( resource a, resource p)

Computes Jacobi symbol of a and p. p should be odd and must be positive.

gmp_legendre

(PHP 4 >= 4.0.4)

gmp_legendre -- Legendre symbol

Description

int gmp_legendre ( resource a, resource p)

Compute the Legendre symbol of a and p. p should be odd and must be positive.

gmp_mod

(PHP 4 >= 4.0.4)

gmp_mod -- Modulo operation

Description

resource gmp_mod ( resource n, resource d)

Calculates n modulo d. The result is always non-negative, the sign of d is ignored.

gmp_mul

(PHP 4 >= 4.0.4)

gmp_mul -- Multiply numbers

Description

resource gmp_mul ( resource a, resource b)

Multiplies a by b and returns the result.

gmp_neg

(PHP 4 >= 4.0.4)

gmp_neg -- Negate number

Description

resource gmp_neg ( resource a)

Returns -a.

gmp_or

(PHP 4 >= 4.0.4)

gmp_or -- Logical OR

Description

resource gmp_or ( resource a, resource b)

Calculates logical inclusive OR of two GMP numbers.

gmp_perfect_square

(PHP 4 >= 4.0.4)

gmp_perfect_square -- Perfect square check

Description

bool gmp_perfect_square ( resource a)

Returns TRUE if a is a perfect square, FALSE otherwise.

See also: gmp_sqrt(), gmp_sqrtrm().

gmp_popcount

(PHP 4 >= 4.0.4)

gmp_popcount -- Population count

Description

int gmp_popcount ( resource a)

Return the population count of a.

gmp_pow

(PHP 4 >= 4.0.4)

gmp_pow -- Raise number into power

Description

resource gmp_pow ( resource base, int exp)

Raise base into power exp. The case of 0^0 yields 1. exp cannot be negative.

gmp_powm

(PHP 4 >= 4.0.4)

gmp_powm -- Raise number into power with modulo

Description

resource gmp_powm ( resource base, resource exp, resource mod)

Calculate (base raised into power exp) modulo mod. If exp is negative, result is undefined.

gmp_prob_prime

(PHP 4 >= 4.0.4)

gmp_prob_prime -- Check if number is "probably prime"

Description

int gmp_prob_prime ( resource a [, int reps])

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

The function uses Miller-Rabin's probabilistic test.

gmp_random

(PHP 4 >= 4.0.4)

gmp_random -- Random number

Description

resource gmp_random ( int limiter)

Generate a random number. The number will be between limiter and zero in value. If limiter is negative, negative numbers are generated.

gmp_scan0

(PHP 4 >= 4.0.4)

gmp_scan0 -- Scan for 0

Description

int gmp_scan0 ( resource a, int start)

Scans a, starting with bit start, towards more significant bits, until the first clear bit is found. Returns the index of the found bit.

gmp_scan1

(PHP 4 >= 4.0.4)

gmp_scan1 -- Scan for 1

Description

int gmp_scan1 ( resource a, int start)

Scans a, starting with bit start, towards more significant bits, until the first set bit is found. Returns the index of the found bit.

gmp_setbit

(PHP 4 >= 4.0.4)

gmp_setbit -- Set bit

Description

resource gmp_setbit ( resource &a, int index [, bool set_clear])

Sets bit index in a. set_clear defines if the bit is set to 0 or 1. By default the bit is set to 1.

gmp_sign

(PHP 4 >= 4.0.4)

gmp_sign -- Sign of number

Description

int gmp_sign ( resource a)

Return sign of a - 1 if a is positive and -1 if it's negative.

gmp_sqrt

(PHP 4 >= 4.0.4)

gmp_sqrt -- Square root

Description

resource gmp_sqrt ( resource a)

Calculates square root of a.

gmp_sqrtrem

(PHP 4 >= 4.0.4)

gmp_sqrtrem --  Square root with remainder

Description

array gmp_sqrtrem ( resource a)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

gmp_sqrtrm

(no version information, might be only in CVS)

gmp_sqrtrm -- Square root with remainder

Description

array gmp_sqrtrm ( resource a)

Returns array where first element is the integer square root of a (see also gmp_sqrt()), and the second is the remainder (i.e., the difference between a and the first element squared).

gmp_strval

(PHP 4 >= 4.0.4)

gmp_strval -- Convert GMP number to string

Description

string gmp_strval ( resource gmpnumber [, int base])

Convert GMP number to string representation in base base. The default base is 10. Allowed values for the base are from 2 to 36.

Példa 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_sub

(PHP 4 >= 4.0.4)

gmp_sub -- Subtract numbers

Description

resource gmp_sub ( resource a, resource b)

Subtracts b from a and returns the result.

gmp_xor

(PHP 4 >= 4.0.4)

gmp_xor -- Logical XOR

Description

resource gmp_xor ( resource a, resource b)

Calculates logical exclusive OR (XOR) of two GMP numbers.

XXXVII. HTTP functions

Bevezetés

These functions let you manipulate the output sent back to the remote browser right down to the HTTP protocol level.


Követelmények

Az itt leírt függvények használatához semmilyen külső függvénykönyvtár megléte nem szükségeltetik.


Telepítés

Semmilyen telepítés nem szükséges ezen függvények használatához, a PHP alapelemei.


Futásidejű beállítások

Ez a kiterjesztés semmilyen konfigurációs beállításokat nem definiál a php.ini állományban.


Erőforrás típusok

Ez a kiterjesztés semmilyen erőforrás típust nem definiál.


Előre definiált állandók

Ez a kiterjesztés semmilyen konstans értéket nem definiál.

Tartalom
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
setcookie -- Send a cookie

header

(PHP 3, PHP 4 )

header -- Send a raw HTTP header

Description

void header ( string string [, bool replace [, int http_response_code]])

header() is used to send raw HTTP headers. See the HTTP/1.1 specification for more information on HTTP headers.

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

The second optional http_response_code force the HTTP response code to the specified value. (This parameter is available in PHP 4.3.0 and higher.)

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

Megjegyzés: 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.

Megjegyzés: In PHP 3, this only works when PHP is compiled as an Apache module. You can achieve the same effect using the Status header.

<?php
header("Status: 404 Not Found");
?>

The second special case is the "Location:" header. Not only does it send this header back to the browser, but it also returns a REDIRECT (302) status code to the browser unless some 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;
?>

Megjegyzés: HTTP/1.1 requires an absolute URI as argument to Location: including the scheme, hostname and absolute path, but some clients accept relative URIs. You can usually use $_SERVER['HTTP_HOST'], $_SERVER['PHP_SELF'] and dirname() to make an absolute URI from a relative one yourself:

<?php
header("Location: http://" . $_SERVER['HTTP_HOST']
                      . dirname($_SERVER['PHP_SELF'])
                      . "/" . $relative_url);
?>

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
// Date in the past
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");

// always modified
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
 
// HTTP/1.1
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);

// HTTP/1.0
header("Pragma: no-cache");
?>

Megjegyzés: 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.

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

Megjegyzés: In PHP 4, 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.

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

Megjegyzés: 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.

Megjegyzés: 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).

See also headers_sent(), setcookie(), and the section on HTTP authentication.

headers_list

(no version information, might be only in CVS)

headers_list -- Returns a list of response headers sent (or ready to send)

Description

array headers_list ( void )

headers_list() will return a numerically indexed array of headers to be sent to the browser / client. To determine whether or not these headers have been sent yet, use headers_sent().

Példa 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());

?>

this will output :

array(4) {
  [0]=>
  string(29) "X-Powered-By: PHP/5.0.0"
  [1]=>
  string(19) "Set-Cookie: foo=bar"
  [2]=>
  string(18) "X-Sample-Test: foo"
  [3]=>
  string(24) "Content-type: text/plain"
}

See Also: headers_sent(), header(), and setcookie().

headers_sent

(PHP 3>= 3.0.8, PHP 4 )

headers_sent -- Checks if or where headers have been sent

Description

bool headers_sent ( [string &file [, int &line]])

headers_sent() will return FALSE if no HTTP headers have already been sent or TRUE otherwise. 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.

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.

Megjegyzés: The optional file and line parameters where added in PHP 4.3.0.

Példa 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, as of PHP 4.3.0
// Note that $filename and $linenum are passed in for later use.
// Do not assign them values beforehand.
if (!headers_sent($filename, $linenum)) {
    header('Location: http://www.example.com/');
    exit;

// You would most likely trigger an error here.
} else {

    echo "Headers already sent in $filename on line $linenum\n" .
          "Cannot redirect, for now please click this <a " .
          "href=\"http://www.example.com\">link</a> instead\n";
    exit;
}

?>

See also ob_start(), trigger_error(), and header() for a more detailed discussion of the matters involved.

setcookie

(PHP 3, PHP 4 )

setcookie -- Send a cookie

Description

bool setcookie ( string name [, string value [, int expire [, string path [, string domain [, int secure]]]]])

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

Megjegyzés: In PHP 4, 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.

All the arguments except the name argument are optional. You may also replace an argument with an empty string ("") in order to skip that argument. Because the expire and secure arguments are integers, they cannot be skipped with an empty string, use a zero (0) instead. The following table explains each parameter of the setcookie() function, be sure to read the Netscape cookie specification for specifics on how each setcookie() parameter works and RFC 2965 for additional information on how HTTP cookies work.

Táblázat 1. setcookie() parameters explained

ParameterDescriptionExamples
name The name of the cookie. 'cookiename' is called as $_COOKIE['cookiename']
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 otherwords, 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 not set, the cookie will expire at the end of the session (when the browser closes).
path The path on the server in which the cookie will be available on. If set to '/', the cookie will be available within the entire domain. If set to '/foo/', the cookie will only be available within the /foo/ directory and all sub-directories such as /foo/bar/ of domain. The default value is the current directory that the cookie is being set in.
domain The domain that the cookie is available. To make the cookie available on all subdomains of example.com then you'd set it to '.example.com'. The . is not required but makes it compatible with more browsers. Setting it to www.example.com will make the cookie only available in the www subdomain. Refer to tail matching in the spec for details.
secure Indicates that the cookie should only be transmitted over a secure HTTPS connection. When set to 1, the cookie will only be set if a secure connection exists. The default is 0. 0 or 1

Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays. Note, autoglobals such as $_COOKIE became available in PHP 4.1.0. $HTTP_COOKIE_VARS has existed since PHP 3. Cookie values also exist in $_REQUEST.

Megjegyzés: If the PHP directive register_globals is set to on then cookie values will also be made into variables. In our examples below, $TextCookie 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 (""), and all other arguments match a previous call to setcookie, then the cookie with the specified name will be deleted from the remote client.

  • 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 users system. Consider explode() or serialize() to set one cookie with multiple names and values.

In PHP 3, multiple calls to setcookie() in the same script will be performed in reverse order. If you are trying to delete one cookie before inserting another you should put the insert before the delete. In PHP 4, multiple calls to setcookie() are performed in the order called.

Some examples follow how to send cookies:

Példa 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. To see the contents of our test cookie in a script, simply use one of the following examples:

<?php
// Print an individual cookie
echo $_COOKIE["TestCookie"];
echo $HTTP_COOKIE_VARS["TestCookie"];

// Another way to debug/test is to view all cookies
print_r($_COOKIE);
?>

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:

Példa 2. setcookie() delete example

<?php
// set the expiration date to one hour ago
setcookie ("TestCookie", "", time() - 3600);
setcookie ("TestCookie", "", time() - 3600, "/~rasmus/", ".example.com", 1);
?>

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:

Példa 3. setcookie() and arrays

<?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) {
        echo "$name : $value <br />\n";
    }
}
?>

which prints

three : cookiethree
two : cookietwo
one : cookieone

Megjegyzés: For more information on cookies, see Netscape's cookie specification at http://www.netscape.com/newsref/std/cookie_spec.html and RFC 2965.

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.

Megjegyzés: Microsoft Internet Explorer 4 with Service Pack 1 applied does not correctly deal with cookies that have their path parameter set.

Netscape Communicator 4.05 and Microsoft Internet Explorer 3.x appear to handle cookies incorrectly when the path and time are not set.

See also header() and the cookies section.

XXXVIII. Hyperwave functions

Bevezetés

Hyperwave has been developed at IICM in Graz. It started with the name Hyper-G and changed to Hyperwave when it was commercialised (in 1996).

Hyperwave is not free software. The current version, 5.5 is available at http://www.hyperwave.com/. A time limited version can be ordered for free (30 days).

See also the Hyperwave API module.

Hyperwave is an information system similar to a database (HIS, Hyperwave Information Server). Its focus is the storage and management of documents. A document can be any possible piece of data that may as well be stored in file. Each document is accompanied by its object record. The object record contains meta data for the document. The meta data is a list of attributes which can be extended by the user. Certain attributes are always set by the Hyperwave server, other may be modified by the user. An attribute is a name/value pair of the form name=value. The complete object record contains as many of those pairs as the user likes. The name of an attribute does not have to be unique, e.g. a title may appear several times within an object record. This makes sense if you want to specify a title in several languages. In such a case there is a convention, that each title value is preceded by the two letter language abbreviation followed by a colon, e.g. 'en:Title in English' or 'ge:Titel in deutsch'. Other attributes like a description or keywords are potential candidates. You may also replace the language abbreviation by any other string as long as it separated by colon from the rest of the attribute value.

Each object record has native a string representation with each name/value pair separated by a newline. The Hyperwave extension also knows a second representation which is an associated array with the attribute name being the key. Multilingual attribute values itself form another associated array with the key being the language abbreviation. Actually any multiple attribute forms an associated array with the string left to the colon in the attribute value being the key. (This is not fully implemented. Only the attributes Title, Description and Keyword are treated properly yet.)

Besides the documents, all hyper links contained in a document are stored as object records as well. Hyper links which are in a document will be removed from it and stored as individual objects, when the document is inserted into the database. The object record of the link contains information about where it starts and where it ends. In order to gain the original document you will have to retrieve the plain document without the links and the list of links and reinsert them. The functions hw_pipedocument() and hw_gettext() do this for you. The advantage of separating links from the document is obvious. Once a document to which a link is pointing to changes its name, the link can easily be modified accordingly. The document containing the link is not affected at all. You may even add a link to a document without modifying the document itself.

Saying that hw_pipedocument() and hw_gettext() do the link insertion automatically is not as simple as it sounds. Inserting links implies a certain hierarchy of the documents. On a web server this is given by the file system, but Hyperwave has its own hierarchy and names do not reflect the position of an object in that hierarchy. Therefore creation of links first of all requires a mapping from the Hyperwave hierarchy and namespace into a web hierarchy respective web namespace. The fundamental difference between Hyperwave and the web is the clear distinction between names and hierarchy in Hyperwave. The name does not contain any information about the objects position in the hierarchy. In the web the name also contains the information on where the object is located in the hierarchy. This leads to two possibles ways of mapping. Either the Hyperwave hierarchy and name of the Hyperwave object is reflected in the URL or the name only. To make things simple the second approach is used. Hyperwave object with name my_object is mapped to http://host/my_object disregarding where it resides in the Hyperwave hierarchy. An object with name parent/my_object could be the child of my_object in the Hyperwave hierarchy, though in a web namespace it appears to be just the opposite and the user might get confused. This can only be prevented by selecting reasonable object names.

Having made this decision a second problem arises. How do you involve PHP? The URL http://host/my_object will not call any PHP script unless you tell your web server to rewrite it to e.g. http://host/php_script/my_object and the script php_script evaluates the $PATH_INFO variable and retrieves the object with name my_object from the Hyperwave server. Their is just one little drawback which can be fixed easily. Rewriting any URL would not allow any access to other document on the web server. A PHP script for searching in the Hyperwave server would be impossible. Therefore you will need at least a second rewriting rule to exclude certain URLs like all e.g. starting with http://host/Hyperwave This is basically sharing of a namespace by the web and Hyperwave server.

Based on the above mechanism links are insert into documents.

It gets more complicated if PHP is not run as a server module or CGI script but as a standalone application e.g. to dump the content of the Hyperwave server on a CD-ROM. In such a case it makes sense to retain the Hyperwave hierarchy and map in onto the file system. This conflicts with the object names if they reflect its own hierarchy (e.g. by choosing names including '/'). Therefore '/' has to be replaced by another character, e.g. '_'.

The network protocol to communicate with the Hyperwave server is called HG-CSP (Hyper-G Client/Server Protocol). It is based on messages to initiate certain actions, e.g. get object record. In early versions of the Hyperwave Server two native clients (Harmony, Amadeus) were provided for communication with the server. Those two disappeared when Hyperwave was commercialised. As a replacement a so called wavemaster was provided. The wavemaster is like a protocol converter from HTTP to HG-CSP. The idea is to do all the administration of the database and visualisation of documents by a web interface. The wavemaster implements a set of placeholders for certain actions to customise the interface. This set of placeholders is called the PLACE Language. PLACE lacks a lot of features of a real programming language and any extension to it only enlarges the list of placeholders. This has led to the use of JavaScript which IMO does not make life easier.

Adding Hyperwave support to PHP should fill in the gap of a missing programming language for interface customisation. It implements all the messages as defined by the HG-CSP but also provides more powerful commands to e.g. retrieve complete documents.

Hyperwave has its own terminology to name certain pieces of information. This has widely been taken over and extended. Almost all functions operate on one of the following data types.

  • object ID: An unique integer value for each object in the Hyperwave server. It is also one of the attributes of the object record (ObjectID). Object ids are often used as an input parameter to specify an object.

  • object record: A string with attribute-value pairs of the form attribute=value. The pairs are separated by a carriage return from each other. An object record can easily be converted into an object array with hw_object2array(). Several functions return object records. The names of those functions end with obj.

  • object array: An associative array with all attributes of an object. The keys are the attribute names. If an attribute occurs more than once in an object record it will result in another indexed or associative array. Attributes which are language depended (like the title, keyword, description) will form an associative array with the keys set to the language abbreviations. All other multiple attributes will form an indexed array. PHP functions never return object arrays.

  • hw_document: This is a complete new data type which holds the actual document, e.g. HTML, PDF etc. It is somewhat optimized for HTML documents but may be used for any format.

Several functions which return an array of object records do also return an associative array with statistical information about them. The array is the last element of the object record array. The statistical array contains the following entries:

Hidden

Number of object records with attribute PresentationHints set to Hidden.

CollectionHead

Number of object records with attribute PresentationHints set to CollectionHead.

FullCollectionHead

Number of object records with attribute PresentationHints set to FullCollectionHead.

CollectionHeadNr

Index in array of object records with attribute PresentationHints set to CollectionHead.

FullCollectionHeadNr

Index in array of object records with attribute PresentationHints set to FullCollectionHead.

Total

Total: Number of object records.


Követelmények

This extension needs a Hyperwave server downloadable from http://www.hyperwave.com/.


Telepítés

To enable Hyperwave support compile PHP --with-hyperwave.


Integration with Apache

The Hyperwave extension is best used when PHP is compiled as an Apache module. In such a case the underlying Hyperwave server can be hidden from users almost completely if Apache uses its rewriting engine. The following instructions will explain this.

Since PHP with Hyperwave support built into Apache is intended to replace the native Hyperwave solution based on Wavemaster, we will assume that the Apache server will only serve as a Hyperwave web interface for these examples. This is not necessary but it simplifies the configuration. The concept is quite simple. First of all you need a PHP script which evaluates the $_ENV['PATH_INFO'] variable and treats its value as the name of a Hyperwave object. Let's call this script 'Hyperwave'. The URL http://your.hostname/Hyperwave/name_of_object would than return the Hyperwave object with the name 'name_of_object'. Depending on the type of the object the script has to react accordingly. If it is a collection, it will probably return a list of children. If it is a document it will return the mime type and the content. A slight improvement can be achieved if the Apache rewriting engine is used. From the users point of view it would be more straight forward if the URL http://your.hostname/name_of_object would return the object. The rewriting rule is quite easy:

RewriteRule ^/(.*) /usr/local/apache/htdocs/HyperWave/$1 [L]

Now every URL relates to an object in the Hyperwave server. This causes a simple to solve problem. There is no way to execute a different script, e.g. for searching, than the 'Hyperwave' script. This can be fixed with another rewriting rule like the following:

RewriteRule ^/hw/(.*) /usr/local/apache/htdocs/hw/$1 [L]

This will reserve the directory /usr/local/apache/htdocs/hw for additional scripts and other files. Just make sure this rule is evaluated before the one above. There is just a little drawback: all Hyperwave objects whose name starts with 'hw/' will be shadowed. So, make sure you don't use such names. If you need more directories, e.g. for images just add more rules or place them all in one directory. Before you put those instructions, don't forget to turn on the rewriting engine with

RewriteEngine on

You will need scripts:

  • to return the object itself

  • to allow searching

  • to identify yourself

  • to set your profile

  • one for each additional function like to show the object attributes, to show information about users, to show the status of the server, etc.

As an alternative to the Rewrite Engine, you can also consider using the Apache ErrorDocument directive, but be aware, that ErrorDocument redirected pages cannot receive POST data.


Futásidejű beállítások

Az alábbi függvények viselkedése befolyásolható a php.ini segítségével.

Táblázat 1. Hyperwave configuration options

NameDefaultChangeable
hyperwave.allow_persistent"0"PHP_INI_SYSTEM
hyperwave.default_port"418"PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().


Erőforrás típusok

Ez a kiterjesztés semmilyen erőforrás típust nem definiál.


Előre definiált állandók

Az itt listázott állandókat ez a kiterjesztés definiálja, és csak akkor elérhetőek, ha az adott kiterjesztés be van fordítva a PHP-be, vagy dinamikusan betöltött.

HW_ATTR_LANG (integer)

HW_ATTR_NR (integer)

HW_ATTR_NONE (integer)


Todo

There are still some things to do:

  • The hw_InsertDocument has to be split into hw_insertobject() and hw_putdocument().

  • The names of several functions are not fixed, yet.

  • Most functions require the current connection as its first parameter. This leads to a lot of typing, which is quite often not necessary if there is just one open connection. A default connection will improve this.

  • Conversion form object record into object array needs to handle any multiple attribute.

Tartalom
hw_Array2Objrec -- convert attributes from object array to object record
hw_changeobject --  Changes attributes of an object (obsolete)
hw_Children -- object ids of children
hw_ChildrenObj -- object records of children
hw_Close -- closes the Hyperwave connection
hw_Connect -- opens a connection
hw_connection_info --  Prints information about the connection to Hyperwave server
hw_cp -- Copies objects
hw_Deleteobject -- deletes object
hw_DocByAnchor -- object id object belonging to anchor
hw_DocByAnchorObj -- object record object belonging to anchor
hw_Document_Attributes -- object record of hw_document
hw_Document_BodyTag -- body tag of hw_document
hw_Document_Content -- returns content of hw_document
hw_Document_SetContent -- sets/replaces content of hw_document
hw_Document_Size -- size of hw_document
hw_dummy --  Hyperwave dummy function
hw_EditText -- retrieve text document
hw_Error -- error number
hw_ErrorMsg -- returns error message
hw_Free_Document -- frees hw_document
hw_GetAnchors -- object ids of anchors of document
hw_GetAnchorsObj -- object records of anchors of document
hw_GetAndLock -- return object record and lock object
hw_GetChildColl -- object ids of child collections
hw_GetChildCollObj -- object records of child collections
hw_GetChildDocColl -- object ids of child documents of collection
hw_GetChildDocCollObj -- object records of child documents of collection
hw_GetObject -- object record
hw_GetObjectByQuery -- search object
hw_GetObjectByQueryColl -- search object in collection
hw_GetObjectByQueryCollObj -- search object in collection
hw_GetObjectByQueryObj -- search object
hw_GetParents -- object ids of parents
hw_GetParentsObj -- object records of parents
hw_getrellink --  Get link from source to dest relative to rootid
hw_GetRemote -- Gets a remote document
hw_getremotechildren -- Gets children of remote document
hw_GetSrcByDestObj -- Returns anchors pointing at object
hw_GetText -- retrieve text document
hw_getusername -- name of currently logged in user
hw_Identify -- identifies as user
hw_InCollections -- check if object ids in collections
hw_Info -- info about connection
hw_InsColl -- insert collection
hw_InsDoc -- insert document
hw_insertanchors --  Inserts only anchors into text
hw_InsertDocument -- upload any document
hw_InsertObject -- inserts an object record
hw_mapid -- Maps global id on virtual local id
hw_Modifyobject -- modifies object record
hw_mv -- Moves objects
hw_New_Document -- create new document
hw_objrec2array -- Convert attributes from object record to object array
hw_Output_Document -- prints hw_document
hw_pConnect -- make a persistent database connection
hw_PipeDocument -- retrieve any document
hw_Root -- root object id
hw_setlinkroot --  Set the id to which links are calculated
hw_stat --  Returns status string
hw_Unlock -- unlock object
hw_Who -- List of currently logged in users

hw_Array2Objrec

(PHP 3>= 3.0.4, PHP 4 )

hw_Array2Objrec -- convert attributes from object array to object record

Description

string hw_array2objrec ( array object_array)

Converts an object_array into an object record. Multiple attributes like 'Title' in different languages are treated properly.

See also hw_objrec2array().

hw_changeobject

(PHP 3>= 3.0.3, PHP 4 )

hw_changeobject --  Changes attributes of an object (obsolete)

Description

void hw_changeobject ( int link, int objid, array attributes)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

hw_Children

(PHP 3>= 3.0.3, PHP 4 )

hw_Children -- object ids of children

Description

array hw_children ( int connection, int objectID)

Returns an array of object ids. Each id belongs to a child of the collection with ID objectID. The array contains all children both documents and collections.

hw_ChildrenObj

(PHP 3>= 3.0.3, PHP 4 )

hw_ChildrenObj -- object records of children

Description

array hw_childrenobj ( int connection, int objectID)

Returns an array of object records. Each object record belongs to a child of the collection with ID objectID. The array contains all children both documents and collections.

hw_Close

(PHP 3>= 3.0.3, PHP 4 )

hw_Close -- closes the Hyperwave connection

Description

int hw_close ( int connection)

Returns FALSE if connection is not a valid connection index, otherwise TRUE. Closes down the connection to a Hyperwave server with the given connection index.

hw_Connect

(PHP 3>= 3.0.3, PHP 4 )

hw_Connect -- opens a connection

Description

int hw_connect ( string host, int port, string username, string password)

Opens a connection to a Hyperwave server and returns a connection index on success, or FALSE if the connection could not be made. Each of the arguments should be a quoted string, except for the port number. The username and password arguments are optional and can be left out. In such a case no identification with the server will be done. It is similar to identify as user anonymous. This function returns a connection index that is needed by other Hyperwave functions. You can have multiple connections open at once. Keep in mind, that the password is not encrypted.

See also hw_pconnect().

hw_connection_info

(PHP 3>= 3.0.3, PHP 4 )

hw_connection_info --  Prints information about the connection to Hyperwave server

Description

void hw_connection_info ( int link)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

hw_cp

(PHP 3>= 3.0.3, PHP 4 )

hw_cp -- Copies objects

Description

int hw_cp ( int connection, array object_id_array, int destination_id)

Copies the objects with object ids as specified in the second parameter to the collection with the id destination id.

The value return is the number of copied objects.

See also hw_mv().

hw_Deleteobject

(PHP 3>= 3.0.3, PHP 4 )

hw_Deleteobject -- deletes object

Description

int hw_deleteobject ( int connection, int object_to_delete)

Deletes the object with the given object id in the second parameter. It will delete all instances of the object.

Returns TRUE if no error occurs otherwise FALSE.

See also hw_mv().

hw_DocByAnchor

(PHP 3>= 3.0.3, PHP 4 )

hw_DocByAnchor -- object id object belonging to anchor

Description

int hw_docbyanchor ( int connection, int anchorID)

Returns an th object id of the document to which anchorID belongs.

hw_DocByAnchorObj

(PHP 3>= 3.0.3, PHP 4 )

hw_DocByAnchorObj -- object record object belonging to anchor

Description

string hw_docbyanchorobj ( int connection, int anchorID)

Returns an th object record of the document to which anchorID belongs.

hw_Document_Attributes

(PHP 3>= 3.0.3, PHP 4 )

hw_Document_Attributes -- object record of hw_document

Description

string hw_document_attributes ( int hw_document)

Returns the object record of the document.

For backward compatibility, hw_documentattributes() is also accepted. This is deprecated, however.

See also hw_document_bodytag(), and hw_document_size().

hw_Document_BodyTag

(PHP 3>= 3.0.3, PHP 4 )

hw_Document_BodyTag -- body tag of hw_document

Description

string hw_document_bodytag ( int hw_document)

Returns the BODY tag of the document. If the document is an HTML document the BODY tag should be printed before the document.

See also hw_document_attributes(), and hw_document_size().

For backward compatibility, hw_documentbodytag() is also accepted. This is deprecated, however.

hw_Document_Content

(PHP 3>= 3.0.3, PHP 4 )

hw_Document_Content -- returns content of hw_document

Description

string hw_document_content ( int hw_document)

Returns the content of the document. If the document is an HTML document the content is everything after the BODY tag. Information from the HEAD and BODY tag is in the stored in the object record.

See also hw_document_attributes(), hw_document_size(), and hw_document_setcontent().

hw_Document_SetContent

(PHP 4 )

hw_Document_SetContent -- sets/replaces content of hw_document

Description

string hw_document_setcontent ( int hw_document, string content)

Sets or replaces the content of the document. If the document is an HTML document the content is everything after the BODY tag. Information from the HEAD and BODY tag is in the stored in the object record. If you provide this information in the content of the document too, the Hyperwave server will change the object record accordingly when the document is inserted. Probably not a very good idea. If this functions fails the document will retain its old content.

See also hw_document_attributes(), hw_document_size(), and hw_document_content().

hw_Document_Size

(PHP 3>= 3.0.3, PHP 4 )

hw_Document_Size -- size of hw_document

Description

int hw_document_size ( int hw_document)

Returns the size in bytes of the document.

See also hw_document_bodytag(), and hw_document_attributes().

For backward compatibility, hw_documentsize() is also accepted. This is deprecated, however.

hw_dummy

(PHP 3>= 3.0.3, PHP 4 )

hw_dummy --  Hyperwave dummy function

Description

string hw_dummy ( int link, int id, int msgid)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

hw_EditText

(PHP 3>= 3.0.3, PHP 4 )

hw_EditText -- retrieve text document

Description

int hw_edittext ( int connection, int hw_document)

Uploads the text document to the server. The object record of the document may not be modified while the document is edited. This function will only works for pure text documents. It will not open a special data connection and therefore blocks the control connection during the transfer.

See also hw_pipedocument(), hw_free_document(), hw_document_bodytag(), hw_document_size(), hw_output_document(), and hw_gettext().

hw_Error

(PHP 3>= 3.0.3, PHP 4 )

hw_Error -- error number

Description

int hw_error ( int connection)

Returns the last error number. If the return value is 0 no error has occurred. The error relates to the last command.

hw_ErrorMsg

(PHP 3>= 3.0.3, PHP 4 )

hw_ErrorMsg -- returns error message

Description

string hw_errormsg ( int connection)

Returns a string containing the last error message or 'No Error'. If FALSE is returned, this function failed. The message relates to the last command.

hw_Free_Document

(PHP 3>= 3.0.3, PHP 4 )

hw_Free_Document -- frees hw_document

Description

int hw_free_document ( int hw_document)

Frees the memory occupied by the Hyperwave document.

hw_GetAnchors

(PHP 3>= 3.0.3, PHP 4 )

hw_GetAnchors -- object ids of anchors of document

Description

array hw_getanchors ( int connection, int objectID)

Returns an array of object ids with anchors of the document with object ID objectID.

hw_GetAnchorsObj

(PHP 3>= 3.0.3, PHP 4 )

hw_GetAnchorsObj -- object records of anchors of document

Description

array hw_getanchorsobj ( int connection, int objectID)

Returns an array of object records with anchors of the document with object ID objectID.

hw_GetAndLock

(PHP 3>= 3.0.3, PHP 4 )

hw_GetAndLock -- return object record and lock object

Description

string hw_getandlock ( int connection, int objectID)

Returns the object record for the object with ID objectID. It will also lock the object, so other users cannot access it until it is unlocked.

See also hw_unlock(), and hw_getobject().

hw_GetChildColl

(PHP 3>= 3.0.3, PHP 4 )

hw_GetChildColl -- object ids of child collections

Description

array hw_getchildcoll ( int connection, int objectID)

Returns an array of object ids. Each object ID belongs to a child collection of the collection with ID objectID. The function will not return child documents.

See also hw_children(), and hw_getchilddoccoll().

hw_GetChildCollObj

(PHP 3>= 3.0.3, PHP 4 )

hw_GetChildCollObj -- object records of child collections

Description

array hw_getchildcollobj ( int connection, int objectID)

Returns an array of object records. Each object records belongs to a child collection of the collection with ID objectID. The function will not return child documents.

See also hw_childrenobj(), and hw_getchilddoccollobj().

hw_GetChildDocColl

(PHP 3>= 3.0.3, PHP 4 )

hw_GetChildDocColl -- object ids of child documents of collection

Description

array hw_getchilddoccoll ( int connection, int objectID)

Returns array of object ids for child documents of a collection.

See also hw_children(), and hw_getchildcoll().

hw_GetChildDocCollObj

(PHP 3>= 3.0.3, PHP 4 )

hw_GetChildDocCollObj -- object records of child documents of collection

Description

array hw_getchilddoccollobj ( int connection, int objectID)

Returns an array of object records for child documents of a collection.

See also hw_childrenobj(), and hw_getchildcollobj().

hw_GetObject

(PHP 3>= 3.0.3, PHP 4 )

hw_GetObject -- object record

Description

array hw_getobject ( int connection, mixed objectID, string query)

Returns the object record for the object with ID objectID if the second parameter is an integer. If the second parameter is an array of integer the function will return an array of object records. In such a case the last parameter is also evaluated which is a query string.

The query string has the following syntax:

<expr> ::= "(" <expr> ")" |

"!" <expr> | /* NOT */

<expr> "||" <expr> | /* OR */

<expr> "&&" <expr> | /* AND */

<attribute> <operator> <value>

<attribute> ::= /* any attribute name (Title, Author, DocumentType ...) */

<operator> ::= "=" | /* equal */

"<" | /* less than (string compare) */

">" | /* greater than (string compare) */

"~" /* regular expression matching */

The query allows to further select certain objects from the list of given objects. Unlike the other query functions, this query may use not indexed attributes. How many object records are returned depends on the query and if access to the object is allowed.

See also hw_getandlock(), and hw_getobjectbyquery().

hw_GetObjectByQuery

(PHP 3>= 3.0.3, PHP 4 )

hw_GetObjectByQuery -- search object

Description

array hw_getobjectbyquery ( int connection, string query, int max_hits)

Searches for objects on the whole server and returns an array of object ids. The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.

The query will only work with indexed attributes.

See also hw_getobjectbyqueryobj().

hw_GetObjectByQueryColl

(PHP 3>= 3.0.3, PHP 4 )

hw_GetObjectByQueryColl -- search object in collection

Description

array hw_getobjectbyquerycoll ( int connection, int objectID, string query, int max_hits)

Searches for objects in collection with ID objectID and returns an array of object ids. The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.

The query will only work with indexed attributes.

See also hw_getobjectbyquerycollobj().

hw_GetObjectByQueryCollObj

(PHP 3>= 3.0.3, PHP 4 )

hw_GetObjectByQueryCollObj -- search object in collection

Description

array hw_getobjectbyquerycollobj ( int connection, int objectID, string query, int max_hits)

Searches for objects in collection with ID objectID and returns an array of object records. The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.

The query will only work with indexed attributes.

See also hw_getobjectbyquerycoll().

hw_GetObjectByQueryObj

(PHP 3>= 3.0.3, PHP 4 )

hw_GetObjectByQueryObj -- search object

Description

array hw_getobjectbyqueryobj ( int connection, string query, int max_hits)

Searches for objects on the whole server and returns an array of object records. The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.

The query will only work with indexed attributes.

See also hw_getobjectbyquery().

hw_GetParents

(PHP 3>= 3.0.3, PHP 4 )

hw_GetParents -- object ids of parents

Description

array hw_getparents ( int connection, int objectID)

Returns an indexed array of object ids. Each object id belongs to a parent of the object with ID objectID.

hw_GetParentsObj

(PHP 3>= 3.0.3, PHP 4 )

hw_GetParentsObj -- object records of parents

Description

array hw_getparentsobj ( int connection, int objectID)

Returns an indexed array of object records plus an associated array with statistical information about the object records. The associated array is the last entry of the returned array. Each object record belongs to a parent of the object with ID objectID.

hw_getrellink

(PHP 3>= 3.0.3, PHP 4 )

hw_getrellink --  Get link from source to dest relative to rootid

Description

string hw_getrellink ( int link, int rootid, int sourceid, int destid)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

hw_GetRemote

(PHP 3>= 3.0.3, PHP 4 )

hw_GetRemote -- Gets a remote document

Description

int hw_getremote ( int connection, int objectID)

Returns a remote document. Remote documents in Hyperwave notation are documents retrieved from an external source. Common remote documents are for example external web pages or queries in a database. In order to be able to access external sources through remote documents Hyperwave introduces the HGI (Hyperwave Gateway Interface) which is similar to the CGI. Currently, only ftp, http-servers and some databases can be accessed by the HGI. Calling hw_getremote() returns the document from the external source. If you want to use this function you should be very familiar with HGIs. You should also consider to use PHP instead of Hyperwave to access external sources. Adding database support by a Hyperwave gateway should be more difficult than doing it in PHP.

See also hw_getremotechildren().

hw_getremotechildren

(PHP 3>= 3.0.3, PHP 4 )

hw_getremotechildren -- Gets children of remote document

Description

int hw_getremotechildren ( int connection, string object_record)

Returns the children of a remote document. Children of a remote document are remote documents itself. This makes sense if a database query has to be narrowed and is explained in Hyperwave Programmers' Guide. If the number of children is 1 the function will return the document itself formated by the Hyperwave Gateway Interface (HGI). If the number of children is greater than 1 it will return an array of object record with each maybe the input value for another call to hw_getremotechildren(). Those object records are virtual and do not exist in the Hyperwave server, therefore they do not have a valid object ID. How exactly such an object record looks like is up to the HGI. If you want to use this function you should be very familiar with HGIs. You should also consider to use PHP instead of Hyperwave to access external sources. Adding database support by a Hyperwave gateway should be more difficult than doing it in PHP.

See also hw_getremote().

hw_GetSrcByDestObj

(PHP 3>= 3.0.3, PHP 4 )

hw_GetSrcByDestObj -- Returns anchors pointing at object

Description

array hw_getsrcbydestobj ( int connection, int objectID)

Returns the object records of all anchors pointing to the object with ID objectID. The object can either be a document or an anchor of type destination.

See also hw_getanchors().

hw_GetText

(PHP 3>= 3.0.3, PHP 4 )

hw_GetText -- retrieve text document

Description

int hw_gettext ( int connection, int objectID [, mixed rootID/prefix])

Returns the document with object ID objectID. If the document has anchors which can be inserted, they will be inserted already. The optional parameter rootID/prefix can be a string or an integer. If it is an integer it determines how links are inserted into the document. The default is 0 and will result in links that are constructed from the name of the link's destination object. This is useful for web applications. If a link points to an object with name 'internet_movie' the HTML link will be <A HREF="/internet_movie">. The actual location of the source and destination object in the document hierarchy is disregarded. You will have to set up your web browser, to rewrite that URL to for example '/my_script.php3/internet_movie'. 'my_script.php3' will have to evaluate $PATH_INFO and retrieve the document. All links will have the prefix '/my_script.php3/'. If you do not want this you can set the optional parameter rootID/prefix to any prefix which is used instead. Is this case it has to be a string.

If rootID/prefix is an integer and unequal to 0 the link is constructed from all the names starting at the object with the id rootID/prefix separated by a slash relative to the current object. If for example the above document 'internet_movie' is located at 'a-b-c-internet_movie' with '-' being the separator between hierarchy levels on the Hyperwave server and the source document is located at 'a-b-d-source' the resulting HTML link would be: <A HREF="../c/internet_movie">. This is useful if you want to download the whole server content onto disk and map the document hierarchy onto the file system.

This function will only work for pure text documents. It will not open a special data connection and therefore blocks the control connection during the transfer.

See also hw_pipedocument(), hw_free_document(), hw_document_bodytag(), hw_document_size(), and hw_output_document().

hw_getusername

(PHP 3>= 3.0.3, PHP 4 )

hw_getusername -- name of currently logged in user

Description

string hw_getusername ( int connection)

Returns the username of the connection.

hw_Identify

(PHP 3>= 3.0.3, PHP 4 )

hw_Identify -- identifies as user

Description

int hw_identify ( string username, string password)

Identifies as user with username and password. Identification is only valid for the current session. I do not thing this function will be needed very often. In most cases it will be easier to identify with the opening of the connection.

See also hw_connect().

hw_InCollections

(PHP 3>= 3.0.3, PHP 4 )

hw_InCollections -- check if object ids in collections

Description

array hw_incollections ( int connection, array object_id_array, array collection_id_array, int return_collections)

Checks whether a set of objects (documents or collections) specified by the object_id_array is part of the collections listed in collection_id_array. When the fourth parameter return_collections is 0, the subset of object ids that is part of the collections (i.e., the documents or collections that are children of one or more collections of collection ids or their subcollections, recursively) is returned as an array. When the fourth parameter is 1, however, the set of collections that have one or more objects of this subset as children are returned as an array. This option allows a client to, e.g., highlight the part of the collection hierarchy that contains the matches of a previous query, in a graphical overview.

hw_Info

(PHP 3>= 3.0.3, PHP 4 )

hw_Info -- info about connection

Description

string hw_info ( int connection)

Returns information about the current connection. The returned string has the following format: <Serverstring>, <Host>, <Port>, <Username>, <Port of Client>, <Byte swapping>

hw_InsColl

(PHP 3>= 3.0.3, PHP 4 )

hw_InsColl -- insert collection

Description

int hw_inscoll ( int connection, int objectID, array object_array)

Inserts a new collection with attributes as in object_array into collection with object ID objectID.

hw_InsDoc

(PHP 3>= 3.0.3, PHP 4 )

hw_InsDoc -- insert document

Description

int hw_insdoc ( int connection, int parentID, string object_record, string text)

Inserts a new document with attributes as in object_record into collection with object ID parentID. This function inserts either an object record only or an object record and a pure ascii text in text if text is given. If you want to insert a general document of any kind use hw_insertdocument() instead.

See also hw_insertdocument(), and hw_inscoll().

hw_insertanchors

(PHP 4 >= 4.0.4)

hw_insertanchors --  Inserts only anchors into text

Description

string hw_insertanchors ( int hwdoc, array anchorecs, array dest [, array urlprefixes])

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

hw_InsertDocument

(PHP 3>= 3.0.3, PHP 4 )

hw_InsertDocument -- upload any document

Description

int hw_insertdocument ( int connection, int parent_id, int hw_document)

Uploads a document into the collection with parent_id. The document has to be created before with hw_new_document(). Make sure that the object record of the new document contains at least the attributes: Type, DocumentType, Title and Name. Possibly you also want to set the MimeType. The functions returns the object id of the new document or FALSE.

See also hw_pipedocument().

hw_InsertObject

(PHP 3>= 3.0.3, PHP 4 )

hw_InsertObject -- inserts an object record

Description

int hw_insertobject ( int connection, string object_rec, string parameter)

Inserts an object into the server. The object can be any valid hyperwave object. See the HG-CSP documentation for a detailed information on how the parameters have to be.

Note: If you want to insert an Anchor, the attribute Position has always been set either to a start/end value or to 'invisible'. Invisible positions are needed if the annotation has no corresponding link in the annotation text.

See also hw_pipedocument(), hw_insertdocument(), hw_insdoc(), and hw_inscoll().

hw_mapid

(PHP 3>= 3.0.13, PHP 4 )

hw_mapid -- Maps global id on virtual local id

Description

int hw_mapid ( int connection, int server_id, int object_id)

Maps a global object id on any hyperwave server, even those you did not connect to with hw_connect(), onto a virtual object id. This virtual object id can then be used as any other object id, e.g. to obtain the object record with hw_getobject(). The server id is the first part of the global object id (GOid) of the object which is actually the IP number as an integer.

Note: In order to use this function you will have to set the F_DISTRIBUTED flag, which can currently only be set at compile time in hg_comm.c. It is not set by default. Read the comment at the beginning of hg_comm.c

hw_Modifyobject

(PHP 3>= 3.0.7, PHP 4 )

hw_Modifyobject -- modifies object record

Description

int hw_modifyobject ( int connection, int object_to_change, array remove, array add, int mode)

This command allows to remove, add, or modify individual attributes of an object record. The object is specified by the Object ID object_to_change. The first array remove is a list of attributes to remove. The second array add is a list of attributes to add. In order to modify an attribute one will have to remove the old one and add a new one. hw_modifyobject() will always remove the attributes before it adds attributes unless the value of the attribute to remove is not a string or array.

The last parameter determines if the modification is performed recursively. 1 means recursive modification. If some of the objects cannot be modified they will be skipped without notice. hw_error() may not indicate an error though some of the objects could not be modified.

The keys of both arrays are the attributes name. The value of each array element can either be an array, a string or anything else. If it is an array each attribute value is constructed by the key of each element plus a colon and the value of each element. If it is a string it is taken as the attribute value. An empty string will result in a complete removal of that attribute. If the value is neither a string nor an array but something else, e.g. an integer, no operation at all will be performed on the attribute. This is necessary if you want to to add a completely new attribute not just a new value for an existing attribute. If the remove array contained an empty string for that attribute, the attribute would be tried to be removed which would fail since it doesn't exist. The following addition of a new value for that attribute would also fail. Setting the value for that attribute to e.g. 0 would not even try to remove it and the addition will work.

If you would like to change the attribute 'Name' with the current value 'books' into 'articles' you will have to create two arrays and call hw_modifyobject().

Példa 1. modifying an attribute

<?php
       // $connect is an existing connection to the Hyperwave server
       // $objid is the ID of the object to modify
       $remarr = array("Name" => "books");
       $addarr = array("Name" => "articles");
       $hw_modifyobject($connect, $objid, $remarr, $addarr);
?>
In order to delete/add a name=value pair from/to the object record just pass the remove/add array and set the last/third parameter to an empty array. If the attribute is the first one with that name to add, set attribute value in the remove array to an integer.

Példa 2. adding a completely new attribute

<?php
       // $connect is an existing connection to the Hyperwave server
       // $objid is the ID of the object to modify
       $remarr = array("Name" => 0);
       $addarr = array("Name" => "articles");
       $hw_modifyobject($connect, $objid, $remarr, $addarr);
?>

Megjegyzés: Multilingual attributes, e.g. 'Title', can be modified in two ways. Either by providing the attributes value in its native form 'language':'title' or by providing an array with elements for each language as described above. The above example would than be:

Példa 3. modifying Title attribute

<?php
       $remarr = array("Title" => "en:Books");
       $addarr = array("Title" => "en:Articles");
       $hw_modifyobject($connect, $objid, $remarr, $addarr);
?>
or

Példa 4. modifying Title attribute

<?php
       $remarr = array("Title" => array("en" => "Books"));
       $addarr = array("Title" => array("en" => "Articles", "ge"=>"Artikel"));
       $hw_modifyobject($connect, $objid, $remarr, $addarr);
?>
This removes the English title 'Books' and adds the English title 'Articles' and the German title 'Artikel'.

Példa 5. removing attribute

<?php
       $remarr = array("Title" => "");
       $addarr = array("Title" => "en:Articles");
       $hw_modifyobject($connect, $objid, $remarr, $addarr);
?>

Megjegyzés: This will remove all attributes with the name 'Title' and adds a new 'Title' attribute. This comes in handy if you want to remove attributes recursively.

Megjegyzés: If you need to delete all attributes with a certain name you will have to pass an empty string as the attribute value.

Megjegyzés: Only the attributes 'Title', 'Description' and 'Keyword' will properly handle the language prefix. If those attributes don't carry a language prefix, the prefix 'xx' will be assigned.

Megjegyzés: The 'Name' attribute is somewhat special. In some cases it cannot be complete removed. You will get an error message 'Change of base attribute' (not clear when this happens). Therefore you will always have to add a new Name first and than remove the old one.

Megjegyzés: You may not surround this function by calls to hw_getandlock() and hw_unlock(). hw_modifyobject() does this internally.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

hw_mv

(PHP 3>= 3.0.3, PHP 4 )

hw_mv -- Moves objects

Description

int hw_mv ( int connection, array object_id_array, int source_id, int destination_id)

Moves the objects with object ids as specified in the second parameter from the collection with id source_id to the collection with the id destination_id. If the destination id is 0 the objects will be unlinked from the source collection. If this is the last instance of that object it will be deleted. If you want to delete all instances at once, use hw_deleteobject().

The value returned is the number of moved objects.

See also hw_cp(), and hw_deleteobject().

hw_New_Document

(PHP 3>= 3.0.3, PHP 4 )

hw_New_Document -- create new document

Description

int hw_new_document ( string object_record, string document_data, int document_size)

Returns a new Hyperwave document with document data set to document_data and object record set to object_record. The length of the document_data has to passed in document_sizeThis function does not insert the document into the Hyperwave server.

See also hw_free_document(), hw_document_size(), hw_document_bodytag(), hw_output_document(), and hw_insertdocument().

hw_objrec2array

(PHP 3>= 3.0.3, PHP 4 )

hw_objrec2array -- Convert attributes from object record to object array

Description

array hw_objrec2array ( string object_record [, array format])

Converts an object_record into an object array. The keys of the resulting array are the attributes names. Multi-value attributes like 'Title' in different languages form its own array. The keys of this array are the left part to the colon of the attribute value. This left part must be two characters long. Other multi-value attributes without a prefix form an indexed array. If the optional parameter is missing the attributes 'Title', 'Description' and 'Keyword' are treated as language attributes and the attributes 'Group', 'Parent' and 'HtmlAttr' as non-prefixed multi-value attributes. By passing an array holding the type for each attribute you can alter this behaviour. The array is an associated array with the attribute name as its key and the value being one of HW_ATTR_LANG or HW_ATTR_NONE.

See also hw_array2objrec().

hw_Output_Document

(PHP 3>= 3.0.3, PHP 4 )

hw_Output_Document -- prints hw_document

Description

int hw_output_document ( int hw_document)

Prints the document without the BODY tag.

For backward compatibility, hw_outputdocument() is also accepted. This is deprecated, however.

hw_pConnect

(PHP 3>= 3.0.3, PHP 4 )

hw_pConnect -- make a persistent database connection

Description

int hw_pconnect ( string host, int port, string username, string password)

Returns a connection index on success, or FALSE if the connection could not be made. Opens a persistent connection to a Hyperwave server. Each of the arguments should be a quoted string, except for the port number. The username and password arguments are optional and can be left out. In such a case no identification with the server will be done. It is similar to identify as user anonymous. This function returns a connection index that is needed by other Hyperwave functions. You can have multiple persistent connections open at once.

See also hw_connect().

hw_PipeDocument

(PHP 3>= 3.0.3, PHP 4 )

hw_PipeDocument -- retrieve any document

Description

int hw_pipedocument ( int connection, int objectID)

Returns the Hyperwave document with object ID objectID. If the document has anchors which can be inserted, they will have been inserted already. The document will be transferred via a special data connection which does not block the control connection.

See also hw_gettext() for more on link insertion, hw_free_document(), hw_document_size(), hw_document_bodytag(), and hw_output_document().

hw_Root

(PHP 3>= 3.0.3, PHP 4 )

hw_Root -- root object id

Description

int hw_root ( )

Returns the object ID of the hyperroot collection. Currently this is always 0. The child collection of the hyperroot is the root collection of the connected server.

hw_setlinkroot

(PHP 3>= 3.0.3, PHP 4 )

hw_setlinkroot --  Set the id to which links are calculated

Description

void hw_setlinkroot ( int link, int rootid)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

hw_stat

(PHP 3>= 3.0.3, PHP 4 )

hw_stat --  Returns status string

Description

string hw_stat ( int link)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

hw_Unlock

(PHP 3>= 3.0.3, PHP 4 )

hw_Unlock -- unlock object

Description

int hw_unlock ( int connection, int objectID)

Unlocks a document, so other users regain access.

See also hw_getandlock().

hw_Who

(PHP 3>= 3.0.3, PHP 4 )

hw_Who -- List of currently logged in users

Description

int hw_who ( int connection)

Returns an array of users currently logged into the Hyperwave server. Each entry in this array is an array itself containing the elements id, name, system, onSinceDate, onSinceTime, TotalTime and self. 'self' is 1 if this entry belongs to the user who initiated the request.

XXXIX. Hyperwave API functions

Bevezetés

Hyperwave has been developed at IICM in Graz. It started with the name Hyper-G and changed to Hyperwave when it was commercialised (in 1996).

Hyperwave is not free software. The current version, 5.5, is available at http://www.hyperwave.com/. A time limited version can be ordered for free (30 days).

See also the Hyperwave module.

Hyperwave is an information system similar to a database (HIS, Hyperwave Information Server). Its focus is the storage and management of documents. A document can be any possible piece of data that may as well be stored in file. Each document is accompanied by its object record. The object record contains meta data for the document. The meta data is a list of attributes which can be extended by the user. Certain attributes are always set by the Hyperwave server, other may be modified by the user.


Követelmények

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.


Telepítés

After installing the Hyperwave SDK, configure PHP with --with-hwapi[=DIR].


Integration with Apache

The integration with Apache and possible other servers is already described in the Hyperwave module which has been the first extension to connect a Hyperwave Server.


Futásidejű beállítások

Az alábbi függvények viselkedése befolyásolható a php.ini segítségével.

Táblázat 1. Hyperwave API configuration options

NameDefaultChangeable
hwapi.allow_persistent"0"PHP_INI_SYSTEM
For further details and definition of the PHP_INI_* constants see ini_set().


Erőforrás típusok

Ez a kiterjesztés semmilyen erőforrás típust nem definiál.


Előre definiált állandók

Ez a kiterjesztés semmilyen konstans értéket nem definiál.


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

Tartalom
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_attribute -- Creates instance of class hw_api_attribute
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->mimetype -- Returns mimetype
hw_api_content->read -- Read content
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->dstofsrcanchors -- Returns destination of a source anchor
hw_api_error->count -- Returns number of reasons
hw_api_error->reason -- Returns reason of error
hw_api->find -- Search for objects
hw_api->ftstat -- Returns statistics about fulltext server
hwapi_hgcsp -- Returns object of class hw_api
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_content -- Create new instance of class hw_api_content
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 -- Creates a new instance of class hw_api_object
hw_api_object->remove -- Removes attribute
hw_api_object->title -- Returns the title attribute
hw_api_object->value -- Returns value of attribute
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_reason->description -- Returns description of reason
hw_api_reason->type -- Returns type of reason
hw_api->remove -- Delete an object
hw_api->replace -- Replaces an object
hw_api->setcommitedversion -- 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

(no version information, might be only in CVS)

hw_api_attribute->key -- Returns key of the attribute

Description

string key ( void )

Returns the name of the attribute.

See also hwapi_attribute_value().

hw_api_attribute->langdepvalue

(no version information, might be only in CVS)

hw_api_attribute->langdepvalue -- Returns value for a given language

Description

string langdepvalue ( string language)

Returns the value in the given language of the attribute.

See also hwapi_attribute_value().

hw_api_attribute->value

(no version information, might be only in CVS)

hw_api_attribute->value -- Returns value of the attribute

Description

string value ( void )

Returns the value of the attribute.

See also hwapi_attribute_key(), hwapi_attribute_values().

hw_api_attribute->values

(no version information, might be only in CVS)

hw_api_attribute->values -- Returns all values of the attribute

Description

array values ( void )

Returns all values of the attribute as an array of strings.

See also hwapi_attribute_value().

hw_api_attribute

(no version information, might be only in CVS)

hw_api_attribute -- Creates instance of class hw_api_attribute

Description

object attribute ( [string name [, string value]])

Creates a new instance of hw_api_attribute with the given name and value.

hw_api->checkin

(no version information, might be only in CVS)

hw_api->checkin -- Checks in an object

Description

object checkin ( array parameter)

This function checks in an object or a whole hiearchie 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.

See also hwapi_checkout().

hw_api->checkout

(no version information, might be only in CVS)

hw_api->checkout -- Checks out an object

Description

object checkout ( array parameter)

This function checks out an object or a whole hiearchie of objects. 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.

See also hwapi_checkin().

hw_api->children

(no version information, might be only in CVS)

hw_api->children -- Returns children of an object

Description

array 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. The parameter array contains the required elements 'objectIdentifier' and the optional elements 'attributeSelector' and 'objectQuery'.

The return value is an array of objects of type HW_API_Object or HW_API_Error.

See also hwapi_parents().

hw_api_content->mimetype

(no version information, might be only in CVS)

hw_api_content->mimetype -- Returns mimetype

Description

string mimetype ( void )

Returns the mimetype of the content.

hw_api_content->read

(no version information, might be only in CVS)

hw_api_content->read -- Read content

Description

string read ( string buffer, integer len)

Reads len bytes from the content into the given buffer.

hw_api->content

(no version information, might be only in CVS)

hw_api->content -- Returns content of an object

Description

object content ( array parameter)

This function returns the content of a document as an object of type hw_api_content. 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 hw_api_content() to insert only reachable links and HW_API_CONTENT_PLAIN will lead to document without any links.

hw_api->copy

(no version information, might be only in CVS)

hw_api->copy -- Copies physically

Description

object 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. The parameter array contains the required elements 'objectIdentifier' and 'destinationParentIdentifier'. The optional parameter is 'attributeSelector'`

See also hwapi_move(), hwapi_link().

hw_api->dbstat

(no version information, might be only in CVS)

hw_api->dbstat -- Returns statistics about database server

Description

object dbstat ( array parameter)

See also hwapi_dcstat(), hwapi_hwstat(), hwapi_ftstat().

hw_api->dcstat

(no version information, might be only in CVS)

hw_api->dcstat -- Returns statistics about document cache server

Description

object dcstat ( array parameter)

See also hwapi_hwstat(), hwapi_dbstat(), hwapi_ftstat().

hw_api->dstanchors

(no version information, might be only in CVS)

hw_api->dstanchors -- Returns a list of all destination anchors

Description

object dstanchors ( array parameter)

Retrieves all destination anchors of an object. The parameter array contains the required element 'objectIdentifier' and the optional elements 'attributeSelector' and 'objectQuery'.

See also hwapi_srcanchors().

hw_api->dstofsrcanchors

(no version information, might be only in CVS)

hw_api->dstofsrcanchors -- Returns destination of a source anchor

Description

object dstofsrcanchors ( 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. The parameters array contains the required element 'objectIdentifier' and the optional element 'attributeSelector'.

See also hwapi_srcanchors(), hwapi_dstanchors(), hwapi_objectbyanchor().

hw_api_error->count

(no version information, might be only in CVS)

hw_api_error->count -- Returns number of reasons

Description

int count ( void )

Returns the number of error reasons.

See also hwapi_error_reason().

hw_api_error->reason

(no version information, might be only in CVS)

hw_api_error->reason -- Returns reason of error

Description

object reason ( void )

Returns the first error reason.

See also hwapi_error_count().

hw_api->find

(no version information, might be only in CVS)

hw_api->find -- Search for objects

Description

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

hw_api->ftstat

(no version information, might be only in CVS)

hw_api->ftstat -- Returns statistics about fulltext server

Description

object ftstat ( array parameter)

See also hwapi_dcstat(), hwapi_dbstat(), hwapi_hwstat().

hwapi_hgcsp

(no version information, might be only in CVS)

hwapi_hgcsp -- Returns object of class hw_api

Description

object hwapi_hgcsp ( string hostname [, int port])

Opens a connection to the Hyperwave server on host hostname. The protocol used is HGCSP. If you do not pass a port number, 418 is used.

See also hwapi_hwtp().

hw_api->hwstat

(no version information, might be only in CVS)

hw_api->hwstat -- Returns statistics about Hyperwave server

Description

object hwstat ( array parameter)

See also hwapi_dcstat(), hwapi_dbstat(), hwapi_ftstat().

hw_api->identify

(no version information, might be only in CVS)

hw_api->identify -- Log into Hyperwave Server

Description

object identify ( array parameter)

Logs into the Hyperwave Server. The parameter array must contain the elements 'username' and 'password'.

The return value will be an object of type HW_API_Error if identification failed or TRUE if it was successful.

hw_api->info

(no version information, might be only in CVS)

hw_api->info -- Returns information about server configuration

Description

object info ( array parameter)

See also hwapi_dcstat(), hwapi_dbstat(), hwapi_ftstat(), hwapi_hwstat().

hw_api->insert

(no version information, might be only in CVS)

hw_api->insert -- Inserts a new object

Description

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

See also hwapi_replace().

hw_api->insertanchor

(no version information, might be only in CVS)

hw_api->insertanchor -- Inserts a new object of type anchor

Description

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

See also hwapi_insertdocument(), hwapi_insertcollection(), hwapi_insert().

hw_api->insertcollection

(no version information, might be only in CVS)

hw_api->insertcollection -- Inserts a new object of type collection

Description

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

See also hwapi_insertdocument(), hwapi_insertanchor(), hwapi_insert().

hw_api->insertdocument

(no version information, might be only in CVS)

hw_api->insertdocument -- Inserts a new object of type document

Description

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

See also hwapi_insert() hwapi_insertanchor(), hwapi_insertcollection().

hw_api->link

(no version information, might be only in CVS)

hw_api->link -- Creates a link to an object

Description

object link ( array parameter)

Creates a link to an object. Accessing this link is like accessing the object to links points to. The parameter array contains the required elements 'objectIdentifier' and 'destinationParentIdentifier'. 'destinationParentIdentifier' is the target collection.

The function returns TRUE on success or an error object.

See also hwapi_copy().

hw_api->lock

(no version information, might be only in CVS)

hw_api->lock -- Locks an object

Description

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

See also hwapi_unlock().

hw_api->move

(no version information, might be only in CVS)

hw_api->move -- Moves object between collections

Description

object move ( array parameter)

See also hw_objrec2array().

hw_api_content

(no version information, might be only in CVS)

hw_api_content -- Create new instance of class hw_api_content

Description

string content ( string content, string mimetype)

Creates a new content object from the string content. The mimetype is set to mimetype.

hw_api_object->assign

(no version information, might be only in CVS)

hw_api_object->assign -- Clones object

Description

object assign ( array parameter)

Clones the attributes of an object.

hw_api_object->attreditable

(no version information, might be only in CVS)

hw_api_object->attreditable -- Checks whether an attribute is editable

Description

bool attreditable ( array parameter)

hw_api_object->count

(no version information, might be only in CVS)

hw_api_object->count -- Returns number of attributes

Description

int count ( array parameter)

hw_api_object->insert

(no version information, might be only in CVS)

hw_api_object->insert -- Inserts new attribute

Description

bool insert ( object attribute)

Adds an attribute to the object. Returns TRUE on success and otherwise FALSE.

See also hwapi_object_remove().

hw_api_object

(no version information, might be only in CVS)

hw_api_object -- Creates a new instance of class hw_api_object

Description

object hw_api_object ( array parameter)

See also hwapi_lock().

hw_api_object->remove

(no version information, might be only in CVS)

hw_api_object->remove -- Removes attribute

Description

bool remove ( string name)

Removes the attribute with the given name. Returns TRUE on success and otherwise FALSE.

See also hwapi_object_insert().

hw_api_object->title

(no version information, might be only in CVS)

hw_api_object->title -- Returns the title attribute

Description

string title ( array parameter)

hw_api_object->value

(no version information, might be only in CVS)

hw_api_object->value -- Returns value of attribute

Description

string value ( string name)

Returns the value of the attribute with the given name or FALSE if an error occurred.

hw_api->object

(no version information, might be only in CVS)

hw_api->object -- Retrieve attribute information

Description

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. The parameter array contains the required elements 'objectIdentifier' and the optional elements 'attributeSelector' and 'version'.

The returned object is an instance of class HW_API_Object on success or HW_API_Error if an error occurred.

This simple example retrieves an object and checks for errors.

Példa 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);
?>

See also hwapi_content().

hw_api->objectbyanchor

(no version information, might be only in CVS)

hw_api->objectbyanchor -- Returns the object an anchor belongs to

Description

object objectbyanchor ( array parameter)

This function retrieves an object the specified anchor belongs to. The parameter array contains the required element 'objectIdentifier' and the optional element 'attributeSelector'.

See also hwapi_dstofsrcanchor(), hwapi_srcanchors(), hwapi_dstanchors().

hw_api->parents

(no version information, might be only in CVS)

hw_api->parents -- Returns parents of an object

Description

array parents ( array parameter)

Retrieves the parents of an object. The parents can be further filtered by specifying an object query. The parameter array contains the required elements 'objectidentifier' and the optional elements 'attributeselector' and 'objectquery'.

The return value is an array of objects of type HW_API_Object or HW_API_Error.

See also hwapi_children().

hw_api_reason->description

(no version information, might be only in CVS)

hw_api_reason->description -- Returns description of reason

Description

string description ( void )

Returns the description of a reason

hw_api_reason->type

(no version information, might be only in CVS)

hw_api_reason->type -- Returns type of reason

Description

object type ( void )

Returns the type of a reason.

hw_api->remove

(no version information, might be only in CVS)

hw_api->remove -- Delete an object

Description

object remove ( array parameter)

Removes an object from the specified parent. Collections will be removed recursively. 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.

See also hwapi_move().

hw_api->replace

(no version information, might be only in CVS)

hw_api->replace -- Replaces an object

Description

object replace ( array parameter)

Replaces the attributes and the content of an object 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

See also hwapi_insert().

hw_api->setcommitedversion

(no version information, might be only in CVS)

hw_api->setcommitedversion -- Commits version other than last version

Description

object setcommitedversion ( 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.

See also hwapi_checkin(), hwapi_checkout(), hwapi_revert().

hw_api->srcanchors

(no version information, might be only in CVS)

hw_api->srcanchors -- Returns a list of all source anchors

Description

object srcanchors ( array parameter)

Retrieves all source anchors of an object. The parameter array contains the required element 'objectIdentifier' and the optional elements 'attributeSelector' and 'objectQuery'.

See also hwapi_dstanchors().

hw_api->srcsofdst

(no version information, might be only in CVS)

hw_api->srcsofdst -- Returns source of a destination object

Description

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

See also hwapi_dstofsrcanchor().

hw_api->unlock

(no version information, might be only in CVS)

hw_api->unlock -- Unlocks a locked object

Description

object unlock ( array parameter)

Unlocks a locked object. Only the user who has locked the object and the system user may unlock an object. 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().

Returns TRUE on success or an object of class HW_API_Error.

See also hwapi_lock().

hw_api->user

(no version information, might be only in CVS)

hw_api->user -- Returns the own user object

Description

object user ( array parameter)

See also hwapi_userlist().

hw_api->userlist

(no version information, might be only in CVS)

hw_api->userlist -- Returns a list of all logged in users

Description

object userlist ( array parameter)

See also hwapi_user().

XL. iconv functions

Bevezetés

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


Követelmények

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.


Telepítés

To use functions provided by this module, the PHP binary must be built with the following configure line: --with-iconv[=DIR].

Note to Windows® Users: In order to enable this module on a Windows® environment, you need to put a DLL file named iconv.dll or iconv-1.3.dll (prior to 4.2.1) which is bundled with the PHP/Win32 binary package into a directory specified by the PATH environment variable or one of the system directories of your Windows® installation.


Futásidejű beállítások

Az alábbi függvények viselkedése befolyásolható a php.ini segítségével.

Táblázat 1. Iconv configuration options

NameDefaultChangeable
iconv.input_encodingICONV_INPUT_ENCODINGPHP_INI_ALL
iconv.output_encodingICONV_OUTPUT_ENCODINGPHP_INI_ALL
iconv.internal_encodingICONV_INTERNAL_ENCODINGPHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().


Erőforrás típusok

Ez a kiterjesztés semmilyen erőforrás típust nem definiál.


Előre definiált állandók

Since PHP 4.3.0 it is possible to identify at runtime which iconv implementation is adopted by this extension.

Táblázat 2. iconv constants

NameTypeDescription
ICONV_IMPLstringThe implementation name
ICONV_VERSIONstringThe implementation version

Megjegyzés: Writing implementation-dependent scripts with these constants is strongly discouraged.

Since PHP 5.0.0, the following constants are also available:

Táblázat 3. iconv constants available since PHP 5.0.0

NameTypeDescription
ICONV_MIME_DECODE_STRICTintegerA bitmask used for iconv_mime_decode()
ICONV_MIME_DECODE_CONTINUE_ON_ERRORintegerA bitmask used for iconv_mime_decode()


Lásd még

See also GNU Recode functions.

Tartalom
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 the specified range of 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

iconv_get_encoding

(PHP 4 >= 4.0.5)

iconv_get_encoding -- Retrieve internal configuration variables of iconv extension

Description

mixed iconv_get_encoding ( [string type])

iconv_get_encoding() returns the current value of the internal configuration variable if successful, or FALSE on failure.

The value of the optional type can be:

all
input_encoding
output_encoding
internal_encoding

If type is omitted or set to "all", iconv_get_encoding() returns an array that stores all these variables.

Példa 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>

The printout of the above program will be:

Array
(
    [input_encoding] => ISO-8859-1
    [output_encoding] => ISO-8859-1
    [internal_encoding] => UTF-8
)

See also iconv_set_encoding() and ob_iconv_handler().

iconv_mime_decode_headers

(no version information, might be only in CVS)

iconv_mime_decode_headers --  Decodes multiple MIME header fields at once

Description

array iconv_mime_decode_headers ( string encoded_headers [, int mode [, string charset]])

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.

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.

Táblázat 1. Bitmasks acceptable to iconv_mime_decode_headers()

ValueConstantDescription
1ICONV_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.
2ICONV_MIME_DECODE_CONTINUE_ON_ERROR If set, iconv_mime_decode_headers() attempts to ignore any grammatical errors and continue to process a given header.

The optional charset parameter specifies the character set to represent the result by. If omitted, iconv.internal_charset will be used.

Példa 1. iconv_mime_decode_function() 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);
?>

The output of this script should look like:

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
        )

)

See also iconv_mime_decode(), mb_decode_mimeheader(), imap_mime_header_decode(), imap_base64() and imap_qprint().

iconv_mime_decode

(PHP 5 CVS only)

iconv_mime_decode --  Decodes a MIME header field

Description

string iconv_mime_decode ( string encoded_header [, int mode [, string charset]])

Returns a decoded MIME field on success, or FALSE if an error occurs during the decoding.

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.

Táblázat 1. Bitmasks acceptable to iconv_mime_decode()

ValueConstantDescription
1ICONV_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.
2ICONV_MIME_DECODE_CONTINUE_ON_ERROR If set, iconv_mime_decode() attempts to continue to process the given header even though an error occurs.

The optional charset parameter specifies the character set to represent the result by. If omitted, iconv.internal_charset will be used.

Példa 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");
?>

See also iconv_mime_decode_headers(), mb_decode_mimeheader(), imap_mime_header_decode(), imap_base64() and imap_qprint().

iconv_mime_encode

(PHP 5 CVS only)

iconv_mime_encode --  Composes a MIME header field

Description

string iconv_mime_encode ( string field_name, string field_value [, array preferences])

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.

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.

Táblázat 1. Configuration items supported by iconv_mime_encode()

ItemTypeDescriptionDefault valueExample
schemeboolean 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. BB
input-charsetstring 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_charset ini setting. iconv.internal_charset ISO-8859-1
output-charsetstring Specifies the character set to use to compose the MIME header. If not given, the same value as input-charset will be used. the same value as input-charset UTF-8
line-lengthinteger 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. 76996
line-break-charsstring 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

Példa 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_Pr=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);
?>

See also imap_binary(), mb_encode_mimeheader() and imap_8bit().

iconv_set_encoding

(PHP 4 >= 4.0.5)

iconv_set_encoding -- Set current setting for character encoding conversion

Description

bool iconv_set_encoding ( string type, string charset)

iconv_set_encoding() changes the value of the internal configuration variable specified by type to charset. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

The value of type can be any one of those:

input_encoding
output_encoding
internal_encoding

Példa 1. iconv_set_encoding() example:

<?php
iconv_set_encoding("internal_encoding", "UTF-8");
iconv_set_encoding("output_encoding", "ISO-8859-1");
?>

See also iconv_get_encoding() and ob_iconv_handler().

iconv_strlen

(PHP 5 CVS only)

iconv_strlen --  Returns the character count of string

Description

int iconv_strlen ( string str [, string charset])

Returns the character count of str.

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.

If charset parameter is omitted, str is assumed to be encoded in iconv.internal_charset.

See also strlen() and mb_strlen().

iconv_strpos

(PHP 5 CVS only)

iconv_strpos --  Finds position of first occurrence of a needle within a haystack.

Description

int iconv_strpos ( string haystack, string needle, int offset [, string charset])

Returns the numeric position of the first occurrence of needle in haystack.

The optional offset parameter specifies the position from which the search should be performed.

If needle is not found, iconv_strpos() will return FALSE.

Figyelem

Ez a függvény a logikai típusú FALSE értékkel is visszatérhet, olyan nem logikai típusú értékek mellett, amik szintén FALSE értékként jelenhetnek meg (mint pl. 0 vagy ""). Olvasd el a Logikai típusról szóló részt további információkért. Használd a === operátort a visszatérési érték ellenőrzésére.

If haystack or needle is not a string, it is converted to a string and applied as the ordinal value of a character.

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.

If charset parameter is omitted, string are assumed to be encoded in iconv.internal_charset.

See also strpos(), iconv_strrpos() and mb_strpos().

iconv_strrpos

(PHP 5 CVS only)

iconv_strrpos --  Finds the last occurrence of a needle within the specified range of haystack.

Description

string iconv_strrpos ( string haystack, string needle [, string charset])

Returns the numeric position of the last occurrence of needle in haystack.

If needle is not found, iconv_strrpos() will return FALSE.

Figyelem

Ez a függvény a logikai típusú FALSE értékkel is visszatérhet, olyan nem logikai típusú értékek mellett, amik szintén FALSE értékként jelenhetnek meg (mint pl. 0 vagy ""). Olvasd el a Logikai típusról szóló részt további információkért. Használd a === operátort a visszatérési érték ellenőrzésére.

If haystack or needle is not a string, it is converted to a string and applied as the ordinal value of a character.

In contrast to strpos(), 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.

See also strrpos(), iconv_strpos() and mb_strrpos().

iconv_substr

(PHP 5 CVS only)

iconv_substr --  Cut out part of a string

Description

string iconv_substr ( string str, int offset [, int length [, string charset]])

Returns the portion of str specified by the start and length parameters.

If start is non-negative, iconv_substr() cuts the portion out of str beginning at start'th character, counting from zero.

If start is negative, iconv_substr() cuts out the portion beginning at the position, start characters away from the end of str.

If length is given and is positive, the return value will contain at most length characters of the portion that begins at start (depending on the length of string). If str is shorter than start characters long, FALSE will be returned.

If negative length is passed, iconv_substr() cuts the portion out of str from the start'th character up to the character that is length characters away from the end of the string. In case start is also negative, the start position is calculated beforehand according to the rule explained above.

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. If charset is not given, the character set is determined by the iconv.internal_charset ini setting.

See also substr(), mb_substr() and mb_strcut().

iconv

(PHP 4 >= 4.0.5)

iconv -- Convert string to requested character encoding

Description

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. Returns the converted string or FALSE on failure.

Példa 1. iconv() example:

<?php
echo iconv("ISO-8859-1", "UTF-8", "This is a test.");
?>

ob_iconv_handler

(PHP 4 >= 4.0.5)

ob_iconv_handler -- Convert character encoding as output buffer handler

Description

array ob_iconv_handler ( string contents, int status)

It converts the string encoded in internal_encoding to output_encoding.

internal_encoding and output_encoding should be defined by iconv_set_encoding() or in the configuration file php.ini.

Példa 1. ob_iconv_handler() example:

<?php
ob_start("ob_iconv_handler"); // start output buffering
?>

See also iconv_get_encoding(), iconv_set_encoding() and output-control functions.

XLI. Képmanipuláló függvények

A PHP képmanipuláló függvényeit használhatod JPEG, GIF, PNG és SWF képek méreteinek lekérdezésére, és ha van GD könyvtárad, mely a http://www.boutell.com/gd/ címen érhető el, tudsz vele képeket készíteni és manipulálni.

Tartalom
exif_imagetype -- Determine the type of an image
exif_read_data -- Reads the EXIF headers from JPEG or TIFF. This way you can read meta data generated by digital cameras.
exif_thumbnail -- Retrieve the embedded thumbnail of a TIFF or JPEG image
gd_info -- Retrieve information about the currently installed GD library
GetImageSize -- Egy GIF, JPEG, PNG vagy SWF kép méretét adja vissza
image_type_to_mime_type -- Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype
image2wbmp -- Output image to browser or file
imagealphablending -- Set the blending mode for an image
imageantialias --  Should antialias functions be used or not
ImageArc -- Egy ellipszisdarabot rajzol
ImageChar -- Egy karaktert rajzol vízszintesen
ImageCharUp -- Egy karaktert rajzol függőlegesen
ImageColorAllocate -- Egy színt foglal le egy képben
imagecolorallocatealpha -- Allocate a color for an image
ImageColorAt -- Egy képpont színének indexét adja vissza
ImageColorClosest --  Az adott színhez legközelebb álló szín indexét adja vissza
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 nearest to the given color
ImageColorDeAllocate --  Egy színt szabadít fel egy képből
ImageColorExact -- A megadott szín palettabeli indexét adja vissza
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 --  Az adott szín, vagy ahhoz legközelebbi szín palettaindexét adja vissza.
imagecolorresolvealpha --  Get the index of the specified color + alpha or its closest possible alternative
ImageColorSet --  Adott indexű palettaszín megváltoztatása
ImageColorsForIndex -- Adott indexű szín RGB komponensei
ImageColorsTotal --  A kép palettájában levő színek számát adja
ImageColorTransparent -- Egy színt átlátszónak definiál
ImageCopy --  Kép egy részét másolja
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 -- Másolja és átméretezni egy kép részletét
ImageCreate -- Egy új képet hoz létre
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 -- Fileból vagy URL-ből új képet hoz létre
ImageCreateFromJpeg -- Fileból vagy URL-ből új képet hoz létre
ImageCreateFromPng -- Fájlból vagy URL-ből új képet hoz létre
imagecreatefromstring -- Create a new image from the image stream in the string
imagecreatefromwbmp -- Create a new image from file or URL
imagecreatefromxbm -- Create a new image from file or URL
imagecreatefromxpm -- Create a new image from file or URL
imagecreatetruecolor -- Create a new true color image
ImageDashedLine -- Szaggatott vonalat rajzol
ImageDestroy -- Megsemmisít egy képet
imageellipse -- Draw an ellipse
ImageFill -- Zárt terület kifestése
imagefilledarc -- Draw a partial ellipse and fill it
imagefilledellipse -- Draw a filled ellipse
ImageFilledPolygon -- Kitöltött sokszöget rajzol
ImageFilledRectangle -- Kitöltött téglalapot rajzol
ImageFillToBorder -- Kitöltés adott határoló színig
ImageFontHeight -- Adott betűtípus magassága
ImageFontWidth -- Adott betűtípus szélessége
imageftbbox -- Give the bounding box of a text using fonts via freetype2
imagefttext -- Write text to the image using fonts using FreeType 2
ImageGammaCorrect --  A GD képre gamma korrekciót alkalmaz
imagegd2 -- Output GD2 image
imagegd -- Output GD image to browser or file
ImageGIF -- Kirajzol egy képet, vagy fájlba menti
ImageInterlace -- Interlace bit állítása
imageistruecolor -- Finds whether an image is a truecolor image.
ImageJPEG -- Kirajzol egy képet, vagy fájlba menti
ImageLine -- Vonalat rajzol
ImageLoadFont -- Betölt egy betűkészletet
imagepalettecopy -- Copy the palette from one image to another
ImagePng --  Kirajzol PNG egy képet, vagy fájlba menti
ImagePolygon -- Sokszöget rajzol
ImagePSBBox --  Szöveg köré rajzolt legkisebb téglalap méreteit adja PostScript Type1 betűkészletet használva
ImagePSCopyFont --  Make a copy of an already loaded font for further modification
ImagePSEncodeFont --  Megváltoztatja a betűkészlet egy karakterkódolási vektorát
ImagePsExtendFont --  Széthúz vagy zsugorít egy betűkészletet
ImagePSFreeFont -- Egy PostScript Type 1 betűtípus által használt memóriát szabadít fel
ImagePSLoadFont -- Fájlból betölt egy PostScript Type 1 betűtípust
ImagePsSlantFont --  Dönt egy betűkészletet
ImagePSText --  Egy képbe PostScript Type1 típusú szöveget ír
ImageRectangle -- Téglalapot rajzol
imagerotate -- Rotate an image with a given angle
imagesavealpha --  Set the flag to save full alpha channel information (as opposed to single-color transparency) when saving PNG images.
imagesetbrush -- Set the brush image for line drawing
ImageSetPixel -- Egy pont színét megváltoztatja
imagesetstyle -- Set the style for line drawing
imagesetthickness -- Set the thickness for line drawing
imagesettile -- Set the tile image for filling
ImageString -- Karakterláncot ír ki (vízszintesen)
ImageStringUp -- Kiír egy karakterláncot lentről fel [mint ahogy a :-)-t kell nézni]
ImageSX -- Kép szélessége
ImageSY -- Kép magassága
imagetruecolortopalette -- Convert a true color image to a palette image
ImageTTFBBox --  TruType betűtípusú szöveg befoglaló téglalapját adja vissza.
ImageTTFText --  TrueType típusú szöveget ír ki egy képre
imagetypes -- Return the image types supported by this PHP build
imagewbmp -- Output image to browser or file
iptcembed -- Embed binary IPTC data into a JPEG image
iptcparse --  Parse a binary IPTC http://www.iptc.org/ 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 -- Alias of exif_read_data()

exif_imagetype

(PHP 4 >= 4.3.0)

exif_imagetype -- Determine the type of an image

Description

int exif_imagetype ( string filename)

exif_imagetype() reads the first bytes of an image and checks its signature. When a correct signature is found a constant will be returned otherwise the return value is FALSE. The return value is the same value that getimagesize() returns in index 2 but this function is much faster.

The following constants are defined:

Táblázat 1. Imagetype Constants

ValueConstant
1IMAGETYPE_GIF
2IMAGETYPE_JPEG
3IMAGETYPE_PNG
4IMAGETYPE_SWF
5IMAGETYPE_PSD
6IMAGETYPE_BMP
7IMAGETYPE_TIFF_II (intel byte order)
8 IMAGETYPE_TIFF_MM (motorola byte order)
9IMAGETYPE_JPC
10IMAGETYPE_JP2
11IMAGETYPE_JPX
12IMAGETYPE_JB2
13IMAGETYPE_SWC
14IMAGETYPE_IFF
15IMAGETYPE_WBMP
16IMAGETYPE_XBM

Megjegyzés: Support for JPC, JP2, JPX, JB2, XBM, and WBMP became available in PHP 4.3.2. Support for SWC as of PHP 4.3.0.

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

Megjegyzés: This function is only available if PHP is compiled using --enable-exif.

Megjegyzés: This function does not require the GD image library.

Példa 1. exif_imagetype() example

<?php

if (exif_imagetype("image.gif") != IMAGETYPE_GIF) {
    echo "The picture is not a gif";
}

?>

See also getimagesize().

exif_read_data

(PHP 4 >= 4.2.0)

exif_read_data -- Reads the EXIF headers from JPEG or TIFF. This way you can read meta data generated by digital cameras.

Description

array exif_read_data ( string filename [, string sections [, bool arrays [, bool thumbnail]]])

The exif_read_data() function reads the EXIF headers from a JPEG or TIFF image file. It returns an associative array where the indexes are the header names and the values are the values associated with those headers. If no data can be returned the result is FALSE.

filename is the name of the file to read. This cannot be a 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.

FILEFileName, FileSize, FileDateTime, SectionsFound
COMPUTEDhtml, Width, Height, IsColor and some more if available.
ANY_TAGAny information that has a Tag e.g. IFD0, EXIF, ...
IFD0All tagged data of IFD0. In normal imagefiles this contains image size and so forth.
THUMBNAILA 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.
COMMENTComment headers of JPEG images.
EXIFThe 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 allways become arrays as they may contain values whose names are conflict with other sections.

thumbnail whether or not to read the thumbnail itself and not only its tagged data.

Megjegyzés: 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.

Windows ME/XP both can wipe the Exif headers when connecting to a camera. More information available at http://www.canon-asia.com/products/digital_cameras/winxp_problems.html.

Példa 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 />";

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

Megjegyzés: 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. This was added in PHP 4.3.

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 contain also an entry Copyright Which is either the original copyright string or it is a comma separated list of photo and editor copyright.

Megjegyzés: 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.

If the user comment uses Unicode or JIS encoding and the module mbstring is available this encoding will automatically changed according to the exif ini settings in the php.ini. This was added in PHP 4.3.

Megjegyzés: 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.

Megjegyzés: Starting from PHP 4.3 the function can read all embedded IFD data including arrays (returned as such). Also the size of an embedded thumbnail is returned in THUMBNAIL subarray and the function exif_read_data() can return thumbnails in TIFF format. Last but not least there is no longer a maximum length for returned values (not until memory limit is reached).

Megjegyzés: This function is only available in PHP 4 compiled using --enable-exif. Its functionality and behaviour has changed in PHP 4.2. Earlier versions are very unstable.

Since PHP 4.3 user comment can automatically change encoding if PHP 4 was compiled using --enable-mbstring.

This function does not require the GD image library.

See also exif_thumbnail() and getimagesize().

exif_thumbnail

(PHP 4 >= 4.2.0)

exif_thumbnail -- Retrieve the embedded thumbnail of a TIFF or JPEG image

Description

string exif_thumbnail ( string filename [, int &width [, int &height [, int &imagetype]]])

exif_thumbnail() reads the embedded thumbnail of a TIFF or JPEG image. If the image contains no thumbnail FALSE will be returned.

The parameters width, height and imagetype are available since PHP 4.3.0 and return the size of the thumbnail as well as its type. 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.

If you want to deliver thumbnails through this function, you should send the mimetype information using the header() function. The following example demonstrates this:

Példa 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";
}
?>

Starting from version PHP 4.3.0, the function exif_thumbnail() can return thumbnails in TIFF format.

Megjegyzés: This function is only available in PHP 4 compiled using --enable-exif. Its functionality and behaviour has changed in PHP 4.2.0

Megjegyzés: This function does not require the GD image library.

See also exif_read_data() and image_type_to_mime_type().

gd_info

(PHP 4 >= 4.3.0)

gd_info -- Retrieve information about the currently installed GD library

Description

array gd_info ( void )

Returns an associative array describing the version and capabilities of the installed GD library.

Táblázat 1. Elements of array returned by gd_info()

AttributeMeaning
GD Versionstring value describing the installed libgd version.
Freetype Supportboolean value. TRUE if Freetype Support is installed.
Freetype Linkagestring 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 Supportboolean value. TRUE if T1Lib support is included.
GIF Read Supportboolean value. TRUE if support for reading GIF images is included.
GIF Create Supportboolean value. TRUE if support for creating GIF images is included.
JPG Supportboolean value. TRUE if JPG support is included.
PNG Supportboolean value. TRUE if PNG support is included.
WBMP Supportboolean value. TRUE if WBMP support is included.
XBM Supportboolean value. TRUE if XBM support is included.

Példa 1. Using gd_info()

<?php
var_dump(gd_info());
?>

The typical output is :

array(9) {
  ["GD Version"]=>
  string(24) "bundled (2.0 compatible)"
  ["FreeType Support"]=>
  bool(false)
  ["T1Lib Support"]=>
  bool(false)
  ["GIF Read Support"]=>
  bool(true)
  ["GIF Create Support"]=>
  bool(false)
  ["JPG Support"]=>
  bool(false)
  ["PNG Support"]=>
  bool(true)
  ["WBMP Support"]=>
  bool(true)
  ["XBM Support"]=>
  bool(false)
}

See also imagepng(), imagejpeg(), imagegif(), imagewbmp(), and imagetypes().

GetImageSize

(PHP 3, PHP 4 )

GetImageSize -- Egy GIF, JPEG, PNG vagy SWF kép méretét adja vissza

Leírás

array getimagesize ( string filename [, array imageinfo])

A GetImageSize() függvény megállapítja a méretét bármely GIF, JPG, PNG vagy SWF filenak és visszaadja a kép méreteit along with a file type and a height/width text string to be used inside a normal HTML <IMG> tag.

Egy 4 elemű tömbbel tér vissza. A tömb első eleme (indexe 0) a kép szélessége pixelben. A következő a kép magassága. A harmadik pedig egy flag, amely a kép típusára utal. 1 = GIF, 2 = JPG, 3 = PNG, 4 = SWF. A negyedik pedig egy string, amely tartalmazza a megfelelő "height=xxx width=xxx" string, amit egy az egyben bele tudsz írni egy IMG tagbe.

Példa 1. GetImageSize

<?php $size = GetImageSize ("img/flag.jpg"); ?>
<IMG SRC="img/flag.jpg" <?php echo $size[3]; ?>

Az opcionális imageinfo paraméter lehetővé teszi néhány plusz információ kinyerését a fileból. Jelenleg ez a különböző JPG APP jelzéseket asszociatív tömb formájában adja vissza. Néhány program ezeket az APP jelzéseket használja, hogy szöveges információt rejtsen a képekbe. A legismertebb az IPTC http://www.iptc.org/ információ belarakása az APP13 jelzésbe. Az iptcparse() funkciót használhatod arra, hogy a bináris APP13 jelzést valami olvashatóvá alakítsd.

Példa 2. IPTC információ kinyerése a GetImageSize segítségével

<?php 
    $size = GetImageSize ("testimg.jpg",&$info);
    if (isset ($info["APP13"])) {
        $iptc = iptcparse ($info["APP13"]);
        var_dump ($iptc);
    }
?>

Megjegyzés: Ehhez a függvényhez nem kell a GD könyvtár.

image_type_to_mime_type

(PHP 4 >= 4.3.0)

image_type_to_mime_type -- Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype

Description

string image_type_to_mime_type ( int imagetype)

The image_type_to_mime_type() function will determine the Mime-Type for an IMAGETYPE constant.

Példa 1. image_type_to_mime_type (file)

<?php
header("Content-type: " . image_type_to_mime_type(IMAGETYPE_PNG));
?>

The returned values are as follows

Táblázat 1. Returned values Constants

imagetypeReturned value
IMAGETYPE_GIFimage/gif
IMAGETYPE_JPEGimage/jpeg
IMAGETYPE_PNGimage/png
IMAGETYPE_SWFapplication/x-shockwave-flash
IMAGETYPE_PSDimage/psd
IMAGETYPE_BMPimage/bmp
IMAGETYPE_TIFF_II (intel byte order)image/tiff
IMAGETYPE_TIFF_MM (motorola byte order) image/tiff
IMAGETYPE_JPCapplication/octet-stream
IMAGETYPE_JP2image/jp2
IMAGETYPE_JPXapplication/octet-stream
IMAGETYPE_JB2application/octet-stream
IMAGETYPE_SWCapplication/x-shockwave-flash
IMAGETYPE_IFFimage/iff
IMAGETYPE_WBMPimage/vnd.wap.wbmp
IMAGETYPE_XBMimage/xbm

Megjegyzés: This function does not require the GD image library.

See also getimagesize(), exif_imagetype(), exif_read_data() and exif_thumbnail().

image2wbmp

(PHP 4 >= 4.0.5)

image2wbmp -- Output image to browser or file

Description

int image2wbmp ( resource image [, string filename [, int threshold]])

image2wbmp() creates the WBMP file in filename from the image image. The image argument is the return from imagecreate().

The filename argument is optional, and if left off, the raw image stream will be output directly. By sending an image/vnd.wap.wbmp content-type using header(), you can create a PHP script that outputs WBMP images directly.

Példa 1. image2wbmp() example

<?php

$file = 'php.jpg';

header('Content-type: ' . image_type_to_mime_type(IMAGETYPE_WBMP));
image2wbmp($file); // output the stream directly

?>

Megjegyzés: WBMP support is only available if PHP was compiled against GD-1.8 or later.

See also imagewbmp().

imagealphablending

(PHP 4 >= 4.0.6)

imagealphablending -- Set the blending mode for an image

Description

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. If blendmode is TRUE, then blending mode is enabled, otherwise disabled. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Megjegyzés: This function was added in PHP 4.0.6 and requires GD 2.0.1

imageantialias

(PHP 4 >= 4.3.2)

imageantialias --  Should antialias functions be used or not

Description

bool imageantialias ( resource im, bool on)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

See also imagecreatetruecolor().

ImageArc

(PHP 3, PHP 4 )

ImageArc -- Egy ellipszisdarabot rajzol

Leírás

int imagearc ( int im, int cx, int cy, int w, int h, int s, int e, int col)

Az ImageArc() függvény egy ellipszisdarabot rajzol az im-mel azonosított képre cx, cy középponttal (a kép bal felső széle a 0, 0). A w és a h paraméterek az ellipszis szélességét illetve magasságát határozzák meg. Az ellipszisdarab kezdő és végpontját fokban a s és az e adják meg.

ImageChar

(PHP 3, PHP 4 )

ImageChar -- Egy karaktert rajzol vízszintesen

Leírás

int imagechar ( int im, int font, int x, int y, string c, int col)

Az ImageChar() függvény megrajzolja a c string első betűjét col színnel az id-vel azonosított képen a betű bal felső sarkát az x,y koordinátához igazítva (a kép bal felső széle a 0, 0 pont). with a color . Ha font értéke 1, 2, 3, 4 vagy 5, egy beépített betűtípus kerül használatra (nagyobb szám nagyobb fontot jelent).

Lásd még az imageloadfont() funkciót.

ImageCharUp

(PHP 3, PHP 4 )

ImageCharUp -- Egy karaktert rajzol függőlegesen

Leírás

int imagechar ( int im, int font, int x, int y, string c, int col)

Az ImageChar() függvény megrajzolja a c string első betűjét col színnel az id-vel azonosított képen a betű bal felső sarkát az x,y koordinátához igazítva (a kép bal felső széle a 0, 0 pont). with a color . Ha font értéke 1, 2, 3, 4 vagy 5, egy beépített font kerül használatra (nagyobb szám nagyobb fontot jelent).

Lásd még az imageloadfont() funkciót.

ImageColorAllocate

(PHP 3, PHP 4 )

ImageColorAllocate -- Egy színt foglal le egy képben

Leírás

int imagecolorallocate ( int im, int red, int green, int blue)

Az ImageColorAllocate() egy színkóddal tér vissza, amely a megadotott RGB komponensekből áll. Az im paraméter az imagecreate() funkció által visszaadott érték. A red, green és blue paraméterek a szín vörös, zöld és a kék komponenseit határozzák meg. A komponensek értékei 0 és 255 közötti egész számok. Az ImageColorAllocate() függvényt meg kell hívnod az összes olyan színre, amelyet az im-mel azonosított képben használni akarsz.

$feher = ImageColorAllocate ($im, 255, 255, 255);
$fekete = ImageColorAllocate ($im, 0, 0, 0);

imagecolorallocatealpha

(PHP 4 >= 4.3.2)

imagecolorallocatealpha -- Allocate a color for an image

Description

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 which may have a value between 0 and 127. 0 indicates completely opaque while 127 indicates completely transparent.

Returns FALSE if the allocation failed.

Példa 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);
?>

See also imagecolorallocate() and imagecolordeallocate().

ImageColorAt

(PHP 3, PHP 4 )

ImageColorAt -- Egy képpont színének indexét adja vissza

Leírás

int imagecolorat ( int im, int x, int y)

A paraméterek által meghatározott képen és helyen lévő képpont színének indexével tér vissza.

Lásd még a imagecolorset() és a imagecolorsforindex() függvényeket.

ImageColorClosest

(PHP 3, PHP 4 )

ImageColorClosest --  Az adott színhez legközelebb álló szín indexét adja vissza

Leírás

int imagecolorclosest ( int im, int red, int green, int blue)

A kép palettájának azon indexét adja vissza, amely a paraméterekben megadott RGB értékhez a "legközelebb" van.

A "távolság" a kívánt szín és a többi palettaszín között úgy kerül meghatározásra, mintha a színek RGB komponensét egy háromdimenziós térben ábrázolnánk, s a köztük levő távolságot mérnénk.

Lásd még a imagecolorexact() függvényt.

imagecolorclosestalpha

(PHP 4 >= 4.0.6)

imagecolorclosestalpha -- Get the index of the closest color to the specified color + alpha

Description

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.

Megjegyzés: This function was added in PHP 4.0.6 and requires GD 2.0.1

See also imagecolorexactalpha().

imagecolorclosesthwb

(PHP 4 >= 4.0.1)

imagecolorclosesthwb --  Get the index of the color which has the hue, white and blackness nearest to the given color

Description

int imagecolorclosesthwb ( resource image, int red, int green, int blue)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ImageColorDeAllocate

(PHP 3>= 3.0.6, PHP 4 )

ImageColorDeAllocate --  Egy színt szabadít fel egy képből

Leírás

int imagecolordeallocate ( int im, int index)

Az ImageColorDeAllocate() funkció felszabadít egy korábban az ImageColorAllocate() által lefoglalt színt.

$feher = ImageColorAllocate($im, 255, 255, 255);
ImageColorDeAllocate($im, $feher);

ImageColorExact

(PHP 3, PHP 4 )

ImageColorExact -- A megadott szín palettabeli indexét adja vissza

Leírás

int imagecolorexact ( resource image, int red, int green, int blue)

Az adott szín palettabeli indexét adja vissza. image.

Ha a szín nem szerepel a kép palettájában, -1-gyel tér vissza.

Lásd még a imagecolorclosest() függvényt.

imagecolorexactalpha

(PHP 4 >= 4.0.6)

imagecolorexactalpha -- Get the index of the specified color + alpha

Description

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.

If the color does not exist in the image's palette, -1 is returned.

See also imagecolorclosestalpha().

Megjegyzés: This function was added in PHP 4.0.6 and requires GD 2.0.1 or later

imagecolormatch

(PHP 4 >= 4.3.0)

imagecolormatch --  Makes the colors of the palette version of an image more closely match the true color version

Description

bool imagecolormatch ( resource image1, resource image2)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

image1 must be Truecolor, image2 must be Palette, and both image1 and image2 must be the same size.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

See also imagecreatetruecolor().

ImageColorResolve

(PHP 3>= 3.0.2, PHP 4 )

ImageColorResolve --  Az adott szín, vagy ahhoz legközelebbi szín palettaindexét adja vissza.

Leírás

int imagecolorresolve ( int im, int red, int green, int blue)

A függvény garantáltan visszaad egy indexet a kívánt színre válaszul, vagy a szín palettaindexét, vagy a legközelebbi lehetséges alternatíváét.

Lásd még a imagecolorclosest() függvényt.

imagecolorresolvealpha

(PHP 4 >= 4.0.6)

imagecolorresolvealpha --  Get the index of the specified color + alpha or its closest possible alternative

Description

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.

See also imagecolorclosestalpha().

Megjegyzés: This function was added in PHP 4.0.6 and requires GD 2.0.1

ImageColorSet

(PHP 3, PHP 4 )

ImageColorSet --  Adott indexű palettaszín megváltoztatása

Leírás

bool imagecolorset ( int im, int index, int red, int green, int blue)

A függvény az adott palettaindexű színt a paraméterekben megadott színűvé változtatja. Hasznos kitöltésszerű műveletekhez indexelt szervezésű képekben, mert nem kell a tényleges kitöltéshez szükséges plusz műveleteket végrehajtani.

Lásd még a imagecolorat() függvényt.

ImageColorsForIndex

(PHP 3, PHP 4 )

ImageColorsForIndex -- Adott indexű szín RGB komponensei

Leírás

array imagecolorsforindex ( int im, int index)

Egy asszociatív tömbbel tér vissza, mely az adott indexű paletta vörös, zöld és kék komponenseit tartalmazza.

Lásd még a imagecolorat() és imagecolorexact() függvényeket.

ImageColorsTotal

(PHP 3, PHP 4 )

ImageColorsTotal --  A kép palettájában levő színek számát adja

Leírás

int imagecolorstotal ( int im)

A megadott kép színeinek számát adja vissza.

Lásd még a imagecolorat() és a imagecolorsforindex() függvényeket.

ImageColorTransparent

(PHP 3, PHP 4 )

ImageColorTransparent -- Egy színt átlátszónak definiál

Leírás

int imagecolortransparent ( int im [, int col])

Az ImageColorTransparent() az im képben az átlátszó színt col-ra állítja. Az im az ImageCreate() által visszaadott érték és col pedig egy ImageColorAllocate() által visszaadott azonosító.

Az új vagy az aktuális átlátszó szín azonosítójával tér vissza.

ImageCopy

(PHP 3>= 3.0.6, PHP 4 )

ImageCopy --  Kép egy részét másolja

Leírás

int ImageCopy ( int dst_im, int src_im, int dst_x, int dst_y, int src_x, int src_y, int src_w, int src_h)

A src_im kép egy részét dst_im-be másolja, a részlet másolását a src_x, src_y koordinátákkal kezdődik, a képrészlet szélessége src_w, magassága src_h. A részlet bal felső sarka a dst_x, dst_y koordinátára kerül.

imagecopymerge

(PHP 4 >= 4.0.1)

imagecopymerge -- Copy and merge part of an image

Description

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

Megjegyzés: This function was added in PHP 4.0.6

imagecopymergegray

(PHP 4 >= 4.0.6)

imagecopymergegray -- Copy and merge part of an image with gray scale

Description

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

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.

Megjegyzés: This function was added in PHP 4.0.6

imagecopyresampled

(PHP 4 >= 4.0.6)

imagecopyresampled -- Copy and resize part of an image with resampling

Description

bool imagecopyresampled ( resource dst_im, resource src_im, int dstX, int dstY, int srcX, int srcY, int dstW, int dstH, int srcW, int srcH)

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. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad. dst_im is the destination image, src_im is the source image identifier. 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_im is the same as src_im) but if the regions overlap the results will be unpredictable.

Megjegyzés: 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().

Megjegyzés: imagecopyresampled() requires GD 2.0.l or greater.

See also imagecopyresized().

ImageCopyResized

(PHP 3, PHP 4 )

ImageCopyResized -- Másolja és átméretezni egy kép részletét

Leírás

int imagecopyresized ( int dst_im, int src_im, int dstX, int dstY, int srcX, int srcY, int dstW, int dstH, int srcW, int srcH)

Az ImageCopyResized() függvény egy kép téglalap alakú részét másolja át egy másik képbe. Dst_im a tárgykép, src_im a forráskép azonosítója. Ha a forrás és a célkép koordinátái, szélessége, magassága különbözik, a képdarabon nyújtás, összenyomás hajtódik végre. A koordináták a képdarabok bal felső koordinátái. Ezt a funkciót egyazon képen belüli másolásra is lehet használni (ha a dst_im és a src_im prarméter azonos), de ha az egyes részletek átfedik egymást, az eredmény kiszámíthatatlan.

ImageCreate

(PHP 3, PHP 4 )

ImageCreate -- Egy új képet hoz létre

Leírás

int imagecreate ( int x_size, int y_size)

Az ImageCreate() függvény egy képazonosítóval tér vissza, mely üres, és mérete x_size * y_size.

imagecreatefromgd2

(PHP 4 >= 4.1.0)

imagecreatefromgd2 -- Create a new image from GD2 file or URL

Description

resource imagecreatefromgd2 ( string filename)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

Tipp: URL-t is megadhatsz az állomány név paraméter helyén ha a fopen wrappers szolgáltatás be van kapcsolva. Bővebb információk az fopen() leírásánál olvashatóak arról, milyen módon adhatod meg a fájlneveket, valamint érdemes megtekinteni a J Függelék oldalt a támogatott URL típusok listájának megtekintése gyanánt.

Figyelem

A PHP Windows rendszeren futó verziója a 4.3.0-ásnál régebbi változataiban nem támogatja a távoli állomány elérést e függvény használatakor, még akkor sem, ha az allow_url_fopen engedélyezett.

imagecreatefromgd2part

(PHP 4 >= 4.1.0)

imagecreatefromgd2part -- Create a new image from a given part of GD2 file or URL

Description

resource imagecreatefromgd2part ( string filename, int srcX, int srcY, int width, int height)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

Tipp: URL-t is megadhatsz az állomány név paraméter helyén ha a fopen wrappers szolgáltatás be van kapcsolva. Bővebb információk az fopen() leírásánál olvashatóak arról, milyen módon adhatod meg a fájlneveket, valamint érdemes megtekinteni a J Függelék oldalt a támogatott URL típusok listájának megtekintése gyanánt.

Figyelem

A PHP Windows rendszeren futó verziója a 4.3.0-ásnál régebbi változataiban nem támogatja a távoli állomány elérést e függvény használatakor, még akkor sem, ha az allow_url_fopen engedélyezett.

imagecreatefromgd

(PHP 4 >= 4.1.0)

imagecreatefromgd -- Create a new image from GD file or URL

Description

resource imagecreatefromgd ( string filename)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

Tipp: URL-t is megadhatsz az állomány név paraméter helyén ha a fopen wrappers szolgáltatás be van kapcsolva. Bővebb információk az fopen() leírásánál olvashatóak arról, milyen módon adhatod meg a fájlneveket, valamint érdemes megtekinteni a J Függelék oldalt a támogatott URL típusok listájának megtekintése gyanánt.

Figyelem

A PHP Windows rendszeren futó verziója a 4.3.0-ásnál régebbi változataiban nem támogatja a távoli állomány elérést e függvény használatakor, még akkor sem, ha az allow_url_fopen engedélyezett.

ImageCreateFromGif

(PHP 3, PHP 4 )

ImageCreateFromGif -- Fileból vagy URL-ből új képet hoz létre

Leírás

int imagecreatefromgif ( string filename)

Az ImageCreateFromGif() egy képazonosítóval tér vissza, mely az adott filenévből létrehozott képet tartalmazza.

Az ImageCreateFromGif() üres stringgel tér vissza hiba esetén. Hibaüzenetet is ad, amit hibás linkként látunk a böngészőben A nyomkövetés megkönnyítésére a következő példa egy hibát jelző GIF-et állít elő.

Példa 1. Létrehozás közbeni hiba kezelése (vic@zymsys.com jóvoltából)

function LoadGif ($imgname) {
    $im = @imagecreatefromgif ($imgname); /* Kísérlet a megnyitásra */
    if ($im == "") { /* Megnézzük, hogy sikerült-e */
        $im = ImageCreate (150, 30); /* Üres kép létrehozása */
        $bgc = ImageColorAllocate ($im, 255, 255, 255);
        $tc  = ImageColorAllocate ($im, 0, 0, 0);
        ImageFilledRectangle ($im, 0, 0, 150, 30, $bgc); 
        /* Hibaüzenet */
        ImageString($im, 1, 5, 5, "Hiba $imgname kép betöltésénél", $tc); 
    }
    return $im;
}

Megjegyzés: Mivel mindenféle GIF támogatást az 1.6-os verzióban töröltek, ez a funkció nem elérhető, ha épp azt a verziót használod.

ImageCreateFromJpeg

(PHP 3>= 3.0.16, PHP 4 )

ImageCreateFromJpeg -- Fileból vagy URL-ből új képet hoz létre

Leírás

int imagecreatefromjpeg ( string filename)

Az ImageCreateFromJpeg() egy képazonosítóval tér vissza, mely az adott filenévből létrehozott képet tartalmazza.

Az ImageCreateFromJpeg() üres stringgel tér vissza hiba esetén. Hibaüzenetet is ad, amit hibás linkként látunk a böngészőben A nyomkövetés megkönnyítésére a következő példa egy hibát jelző JPEG-et állít elő.

Példa 1. Létrehozás közbeni hiba kezelése (vic@zymsys.com jóvoltából)

function LoadJpeg ($imgname) {
    $im = @imagecreatefromjpeg ($imgname); /* Kísérlet a megnyitásra */
    if ($im == "") { /* Megnézzük, hogy sikerült-e */
        $im = ImageCreate (150, 30); /* Üres kép létrehozása */
        $bgc = ImageColorAllocate ($im, 255, 255, 255);
        $tc  = ImageColorAllocate ($im, 0, 0, 0);
        ImageFilledRectangle ($im, 0, 0, 150, 30, $bgc); 
        /* Hibaüzenet */
        ImageString($im, 1, 5, 5, "Hiba $imgname kép betöltésénél", $tc); 
    }
    return $im;
}

ImageCreateFromPng

(PHP 3>= 3.0.13, PHP 4 )

ImageCreateFromPng -- Fájlból vagy URL-ből új képet hoz létre

Leírás

int imagecreatefrompng ( string filename)

Az ImageCreateFromPng() egy képazonosítóval tér vissza, mely az adott filenévből létrehozott képet tartalmazza.

Az ImageCreateFromPng() üres stringgel tér vissza hiba esetén. Hibaüzenetet is ad, amit hibás linkként látunk a böngészőben A nyomkövetés megkönnyítésére a következő példa egy hibát jelző PNG-t állít elő.

Példa 1. Létrehozás közbeni hiba kezelése (vic@zymsys.com jóvoltából)

function LoadPNG ($imgname) {
    $im = @imagecreatefrompng ($imgname); /* Kísérlet a megnyitásra */
    if ($im == "") { /* Megnézzük, hogy sikerült-e */
        $im = ImageCreate (150, 30); /* Üres kép létrehozása */
        $bgc = ImageColorAllocate ($im, 255, 255, 255);
        $tc  = ImageColorAllocate ($im, 0, 0, 0);
        ImageFilledRectangle ($im, 0, 0, 150, 30, $bgc); 
        /* Hibaüzenet */
        ImageString($im, 1, 5, 5, "Hiba $imgname kép betöltésénél", $tc); 
    }
    return $im;
}

imagecreatefromstring

(PHP 4 >= 4.0.4)

imagecreatefromstring -- Create a new image from the image stream in the string

Description

resource imagecreatefromstring ( string image)

imagecreatefromstring() returns an image identifier representing the image obtained from the given string.

imagecreatefromwbmp

(PHP 4 >= 4.0.1)

imagecreatefromwbmp -- Create a new image from file or URL

Description

resource imagecreatefromwbmp ( string filename)

imagecreatefromwbmp() returns an image identifier representing the image obtained from the given filename.

imagecreatefromwbmp() returns an empty string on failure. It also outputs an error message, which unfortunately displays as a broken link in a browser. To ease debugging the following example will produce an error WBMP:

Példa 1. Example to handle an error during creation (courtesy vic at zymsys dot com)

<?php
function LoadWBMP($imgname) 
{
    $im = @imagecreatefromwbmp($imgname); /* Attempt to open */
    if (!$im) { /* See if it failed */
        $im  = imagecreate (20, 20); /* Create a blank image */
        $bgc = imagecolorallocate($im, 255, 255, 255);
        $tc  = imagecolorallocate($im, 0, 0, 0);
        imagefilledrectangle($im, 0, 0, 10, 10, $bgc);
        /* Output an errmsg */
        imagestring($im, 1, 5, 5, "Error loading $imgname", $tc);
    }
    return $im;
}
?>

Megjegyzés: WBMP support is only available if PHP was compiled against GD-1.8 or later.

Tipp: URL-t is megadhatsz az állomány név paraméter helyén ha a fopen wrappers szolgáltatás be van kapcsolva. Bővebb információk az fopen() leírásánál olvashatóak arról, milyen módon adhatod meg a fájlneveket, valamint érdemes megtekinteni a J Függelék oldalt a támogatott URL típusok listájának megtekintése gyanánt.

Figyelem

A PHP Windows rendszeren futó verziója a 4.3.0-ásnál régebbi változataiban nem támogatja a távoli állomány elérést e függvény használatakor, még akkor sem, ha az allow_url_fopen engedélyezett.

imagecreatefromxbm

(PHP 4 >= 4.0.1)

imagecreatefromxbm -- Create a new image from file or URL

Description

resource imagecreatefromxbm ( string filename)

imagecreatefromxbm() returns an image identifier representing the image obtained from the given filename.

Tipp: URL-t is megadhatsz az állomány név paraméter helyén ha a fopen wrappers szolgáltatás be van kapcsolva. Bővebb információk az fopen() leírásánál olvashatóak arról, milyen módon adhatod meg a fájlneveket, valamint érdemes megtekinteni a J Függelék oldalt a támogatott URL típusok listájának megtekintése gyanánt.

Figyelem

A PHP Windows rendszeren futó verziója a 4.3.0-ásnál régebbi változataiban nem támogatja a távoli állomány elérést e függvény használatakor, még akkor sem, ha az allow_url_fopen engedélyezett.

imagecreatefromxpm

(PHP 4 >= 4.0.1)

imagecreatefromxpm -- Create a new image from file or URL

Description

resource imagecreatefromxpm ( string filename)

imagecreatefromxpm() returns an image identifier representing the image obtained from the given filename.

Tipp: URL-t is megadhatsz az állomány név paraméter helyén ha a fopen wrappers szolgáltatás be van kapcsolva. Bővebb információk az fopen() leírásánál olvashatóak arról, milyen módon adhatod meg a fájlneveket, valamint érdemes megtekinteni a J Függelék oldalt a támogatott URL típusok listájának megtekintése gyanánt.

Figyelem

A PHP Windows rendszeren futó verziója a 4.3.0-ásnál régebbi változataiban nem támogatja a távoli állomány elérést e függvény használatakor, még akkor sem, ha az allow_url_fopen engedélyezett.

imagecreatetruecolor

(PHP 4 >= 4.0.6)

imagecreatetruecolor -- Create a new true color image

Description

resource imagecreatetruecolor ( int x_size, int y_size)

imagecreatetruecolor() returns an image identifier representing a black image of size x_size by y_size.

Példa 1. Creating a new GD image stream and outputting an image.

<?php
header ("Content-type: image/png");
$im = @imagecreatetruecolor(50, 100)
      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);
?>

Megjegyzés: This function was added in PHP 4.0.6 and requires GD 2.0.1 or later.

Megjegyzés: This function will not work with GIF file formats.

See also imagedestroy() and imagecreate().

ImageDashedLine

(PHP 3, PHP 4 )

ImageDashedLine -- Szaggatott vonalat rajzol

Leírás

int imagedashedline ( int im, int x1, int y1, int x2, int y2, int col)

Az ImageDashedLine() függvény szaggatott vonalat rajzol az x1, y1 pontból az x2, y2 pontba az im képen col színnel. (A kép bal felső sarka a 0, 0 koordinátájú pont.)

Lásd még az ImageLine() függvényt.

ImageDestroy

(PHP 3, PHP 4 )

ImageDestroy -- Megsemmisít egy képet

Leírás

int imagedestroy ( int im)

Az ImageDestroy() függvény felszabadítja az im kép által lefoglalt memóriát. Im egy ImageCreate() függvény által visszaadott kép azonosító.

imageellipse

(PHP 4 >= 4.0.6)

imageellipse -- Draw an ellipse

Description

int imageellipse ( resource image, int cx, int cy, int w, int h, int color)

imageellipse() draws an ellipse centered at cx, cy (top left is 0, 0) in the image represented by image. W and h specifies the ellipse's width and height respectively. The color of the ellipse is specified by color.

Megjegyzés: This function was added in PHP 4.0.6 and requires GD 2.0.2 or later which can be obtained at http://www.boutell.com/gd/

Példa 1. imageellipse() example

<?php

// create a blank image
$image = imagecreate(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 ellipse
imageellipse($image, 200, 150, 300, 200, $col_ellipse);

// output the picture
header("Content-type: image/png");
imagepng($image);

?>

See also imagefilledellipse() and imagearc().

ImageFill

(PHP 3, PHP 4 )

ImageFill -- Zárt terület kifestése

Leírás

int imagefill ( int im, int x, int y, int col)

Az ImageFill() függvény az x, y koordinátától kezdve átszínez egy zárt területet az im képen col színűvé. (A kép bal felső sarka a 0, 0 koordinátájú pont.)

imagefilledarc

(PHP 4 >= 4.0.6)

imagefilledarc -- Draw a partial ellipse and fill it

Description

bool imagefilledarc ( resource image, int cx, int cy, int w, int h, int s, int e, int color, int style)

imagefilledarc() draws a partial ellipse centered at cx, cy (top left is 0, 0) in the image represented by image. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad. W and h specifies the ellipse's width and height respectively while the start and end points are specified in degrees indicated by the s and e arguments. style is 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'.

Példa 1. Creating a 3D looking pie

<?php

// this example is provided by poxy at klam dot is

// create image
$image = imagecreate(100, 100);

// allocate some solors
$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);
?>

Megjegyzés: This function was added in PHP 4.0.6 and requires GD 2.0.1

imagefilledellipse

(PHP 4 >= 4.0.6)

imagefilledellipse -- Draw a filled ellipse

Description

bool imagefilledellipse ( resource image, int cx, int cy, int w, int h, int color)

imagefilledellipse() draws an ellipse centered at cx, cy (top left is 0, 0) in the image represented by image. W and h specifies the ellipse's width and height respectively. The ellipse is filled using color. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Megjegyzés: This function was added in PHP 4.0.6 and requires GD 2.0.1 or later

Példa 1. imagefilledellipse() example

<?php

// create a blank image
$image = imagecreate(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);

?>

See also imageellipse() and imagefilledarc().

ImageFilledPolygon

(PHP 3, PHP 4 )

ImageFilledPolygon -- Kitöltött sokszöget rajzol

Leírás

int imagefilledpolygon ( int im, array points, int num_points, int col)

Az ImageFilledPolygon() függvény az im képre egy kitöltött sokszöget rajzol. A points egy PHP tömb, amely a sokszög csúcspontjait tartalmazza. Például: points[0] = x0, points[1] = y0, points[2] = x1, points[3] = y1, stb. Num_points a sokszög csúcsainak száma.

ImageFilledRectangle

(PHP 3, PHP 4 )

ImageFilledRectangle -- Kitöltött téglalapot rajzol

Leírás

int imagefilledrectangle ( int im, int x1, int y1, int x2, int y2, int col)

Az ImageFilledRectangle() függvény egy col() színű kitöltött téglalapot rajzol az im képre. A téglalap bal felső koordinátája x1, y1, jobb alsó koordinátája pedig x2, y2. (A kép bal felső sarka a 0, 0 koordinátájú pont.)

Megjegyzés: Ha nem bal felső és jobb alsó koordinátákat adsz meg, akkor lehal a program, és a képből semmit sem fogsz látni (lehet, hogy bug...)!!! [angol doksiba!]

ImageFillToBorder

(PHP 3, PHP 4 )

ImageFillToBorder -- Kitöltés adott határoló színig

Leírás

int imagefilltoborder ( int im, int x, int y, int border, int col)

Az ImageFillToBorder() függvény a border szín eléréséig kitölt egy területet. A kitöltést az x, y koordinátában kezdi, a kitöltés színe col lesz. (A kép bal felső sarka a 0, 0 koordinátájú pont.)

ImageFontHeight

(PHP 3, PHP 4 )

ImageFontHeight -- Adott betűtípus magassága

Leírás

int imagefontheight ( int font)

A függvény a megadott betűkészlet egy karakterének magasságát adja vissza pixelben.

Lásd még a ImageFontWidth() és a ImageLoadFont() függvényeket!

ImageFontWidth

(PHP 3, PHP 4 )

ImageFontWidth -- Adott betűtípus szélessége

Leírás

int imagefontwidth ( int font)

A függvény a megadott betűkészlet egy karakterének szélességét adja vissza pixelben.

Lásd még a ImageFontHeight() és a ImageLoadFont() függvényeket.

imageftbbox

(PHP 4 >= 4.1.0)

imageftbbox -- Give the bounding box of a text using fonts via freetype2

Description

array imageftbbox ( int size, int angle, string font_file, string text [, array extrainfo])

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

imagefttext

(PHP 4 >= 4.1.0)

imagefttext -- Write text to the image using fonts using FreeType 2

Description

array imagefttext ( resource image, int size, int angle, int x, int y, int col, string font_file, string text [, array extrainfo])

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ImageGammaCorrect

(PHP 3>= 3.0.13, PHP 4 )

ImageGammaCorrect --  A GD képre gamma korrekciót alkalmaz

Leírás

int imagegammacorrect ( int im, double inputgamma, double outputgamma)

A ImageGammaCorrect() függvény gamma korrekciót alkalmaz egy gd képfolyamra (im). A korrekció mértékét a bemeneti és a kimeneti gamma értéke határozza meg (inputgamma és az outputgamma).

imagegd2

(PHP 4 >= 4.1.0)

imagegd2 -- Output GD2 image

Description

int imagegd2 ( resource image [, string filename [, int chunk_size [, int type]]])

imagegd2() outputs GD2 image to browser or file.

The optional type parameter is either IMG_GD2_RAW or IMG_GD2_COMPRESSED. Default is IMG_GD2_RAW.

Megjegyzés: The optional chunk_size and type parameters became available in PHP 4.3.2.

imagegd

(PHP 4 >= 4.1.0)

imagegd -- Output GD image to browser or file

Description

int imagegd ( resource image [, string filename])

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ImageGIF

(PHP 3, PHP 4 )

ImageGIF -- Kirajzol egy képet, vagy fájlba menti

Leírás

int imagegif ( int im [, string filename])

Az ImageGIF() függvény egy filename nevű GIF fájlt hoz létre az im képből. Az im paraméter az imagecreate() függvény által visszaadott azonosító.

A kép formátuma GIF87a lesz, ha a kép nem tartalmaz ImageColorTransparent() függvénnyel létrehozott átlátszó színt és GIF89a formátumú, ha tartalmaz átlátszó színt.

A filename paraméter opcionális, ha nem adod meg, akkor a kép közvetlenül a kimenetre kerül. Ha a lap tartalmát a header() függvénnyel image/gif-re állítod, akkor a PHP lap közvetlenül egy GIF típusú képet jelenít meg.

Megjegyzés: Mivel minden GIF támogatást a GD könyvtár 1.6-os verziójából eltávolítottak, így ez a függvény nem elérhető, ha a GD e változatát használod.

ImageInterlace

(PHP 3, PHP 4 )

ImageInterlace -- Interlace bit állítása

Leírás

int imageinterlace ( int im [, int interlace])

Az ImageInterlace() függvény az interlace bitet hivatott állítani. Ha értéke 1, az image "interlaced" lesz, ha 0, akkor nem lesz az.

A függvény visszatérési értéke az interlace bit aktuális értéke.

imageistruecolor

(PHP 4 >= 4.3.2)

imageistruecolor -- Finds whether an image is a truecolor image.

Description

bool imageistruecolor ( resource image)

imageistruecolor() finds whether the image image is a truecolor image.

See also imagecreatetruecolor().

ImageJPEG

(PHP 3>= 3.0.16, PHP 4 )

ImageJPEG -- Kirajzol egy képet, vagy fájlba menti

Leírás

int imagejpeg ( int im [, string filename [, int quality]])

Az ImageJPEG() függvény egy JPEG fájlt hoz létre az im képből. Az im paraméter a ImageCreate() függvény által visszaadott azonosító.

Ha a filename paraméter elmarad, akkor a kép a szabványos kimenetre kerül. Ha szeretnéd megadni a kép minőségét akkor, amikor a képet a kimenetre szeretnéd küldeni, akkor a kép nevének üres karakterláncot ('') adj meg! Ha egy image/jpg értékű content-type fejlécet írsz ki a header() függvénnyel, akkor a JPEG típusú kép közvetlenül a kimenetre küldhető.

Megjegyzés: A JPEG támogatás csak akkor elérhető, ha a PHP-t GD-1.8 (vagy későbbi) változatával fordítod.

ImageLine

(PHP 3, PHP 4 )

ImageLine -- Vonalat rajzol

Leírás

int imageline ( int im, int x1, int y1, int x2, int y2, int col)

Az ImageLine() függvény vonalat rajzol az x1, y1 pontból az x2, y2 pontba col színnel. (A kép bal felső sarka a 0, 0 koordinátájú pont.)

Lásd még az ImageCreate() és a ImageColorAllocate() függvényeket!

ImageLoadFont

(PHP 3, PHP 4 )

ImageLoadFont -- Betölt egy betűkészletet

Leírás

int imageloadfont ( string file)

Az ImageLoadFont() függvény egy felhasználói pixelgrafikus betűkészletet tölt be és a betöltött betűtípus azonosítóját adja vissza. (Ez mindig nagyobb, mint 5, hogy a beépített betűkészletekkel ne ütközzön.)

A font file formátuma jelenleg bináris és gépfüggő. Ez azt jelenti, hogy a betűkészletet azon a gépen kell létrehozni, mint amilyen típusú CPU-n fog futni a PHP, ami a betűkészletet használja.

Táblázat 1. Betűkészletek formátuma

byte pozícióC adattípusleírás
byte 0-3inta betűtípusban levő karakterek száma
byte 4-7int az első karakter kódja (gyakran 32, ez a szóköz kódja)
byte 8-11integy karakter szélessége
byte 12-15integy karakter magassága
byte 16-char tömb, amely az egyes karakterek adatait tartalmazza. Minden karakter egy pontot reprezentál, így az egész tömb hossza (nchars*width*height) byte hosszú.

Lásd még az ImageFontWidth() és a ImageFontHeight() függvényeket!

imagepalettecopy

(PHP 4 >= 4.0.1)

imagepalettecopy -- Copy the palette from one image to another

Description

int imagepalettecopy ( resource destination, resource source)

imagepalettecopy() copies the palette from the source image to the destination image.

ImagePng

(PHP 3>= 3.0.13, PHP 4 )

ImagePng --  Kirajzol PNG egy képet, vagy fájlba menti

Leírás

int imagepng ( int im [, string filename])

Az ImagePng() függvény az im képet írja ki a szabványos kimenetre (a böngészőbe), vagy, ha filename paramétert is megadtál, akkor a kép tartalma abba a fájlba kerül.

$im = ImageCreateFromPng("test.png");
ImagePng($im);

ImagePolygon

(PHP 3, PHP 4 )

ImagePolygon -- Sokszöget rajzol

Leírás

int imagepolygon ( int im, array points, int num_points, int col)

Az ImagePolygon() függvény az id azonosítójú képre egy sokszöget rajzol. A Points tömb tartalmazza a sokszög csúcsait a következőképp: points[0] = x0, points[1] = y0, points[2] = x1, points[3] = y1, stb. A Num_points adja meg a csúcspontok számát.

Lásd még az imagecreate() függvényt!

ImagePSBBox

(PHP 3>= 3.0.9, PHP 4 )

ImagePSBBox --  Szöveg köré rajzolt legkisebb téglalap méreteit adja PostScript Type1 betűkészletet használva

Leírás

array imagepsbbox ( string text, int font, int size [, int space [, int tightness [, float angle]]])

A Size pixelben értendő.

A Space paraméter segítségével megváltoztathatjuk a betűtípus alapértelmezett szóközét. Ez az érték a normál értékhez hozzáadódik, így van értelme negatív értéket is megadni.

A Tightness paraméterrel pedig a betűk közötti távolságot változtathatjuk. A paraméter értéke a karakter méretéhez hozzáadódik, így lehet negatív is.

Az Angle paramétert fokban kell megadni.

A space és a tightness paraméterek mértékegysége egy ezred em. (ennek az em-nek az m betű magasságához van köze)

A space, tightness és a angle paraméterek elhagyhatók.

A határoló doboz méreteit a függvény a fontból számítja, és sajnos néha eléggé különbözik ez az érték a ténylegesen megrajzolt szöveg méretétől. Ha a megadott szög 0 fok, akkor előfordulhat, hogy a szöveg a valóságban 1 pixelllel nagyobb lesz mindkét irányban.

A függvény egy tömböt ad vissza, melynek elemei:

0bal alsó x-koordináta
1bal alsó y-koordináta
2jobb felső x-koordináta
3jobb felső y-koordináta

Lásd még az imagepstext() függvényt!

ImagePSCopyFont

(PHP 3>= 3.0.9, PHP 4 )

ImagePSCopyFont --  Make a copy of an already loaded font for further modification

Leírás

int imagepscopyfont ( int fontindex)

Use this function if you need make further modifications to a font, for example extending/condensing, slanting it or changing it's character encoding vector, but need to keep a original along as well. Note that a font you want to copy must be one obtained using ImagePSLoadFont(), not a font that is itself a copied one. You can although make modifications to it before copying.

If you use this function, you must free a fonts obtained this way yourself and in reverse order. Otherwise your script will hang.

In a case everything went right, a valid font index will be returned and can be used for further purposes. Otherwise a function returns false and prints a message describing what went wrong.

Lásd még a ImagePSLoadFont().

ImagePSEncodeFont

(PHP 3>= 3.0.9, PHP 4 )

ImagePSEncodeFont --  Megváltoztatja a betűkészlet egy karakterkódolási vektorát

Leírás

int imagepsencodefont ( string encodingfile)

Fájlból betölt egy karakter-kódolási vektort és a font kódolási-vektorát erre változtatja. Mivel a PostScript betűkészletek alapértelmezett vektorában a legtöbb 127 feletti karakter máshol van, mint szeretnéd, így muszáj lesz megváltoztatnod, hacsak nem az angol nyelvet használod [nem azt használod, mert ezt a magyar leírást használod]. Ennek a betöltendő fájlnak a pontos formátuma megtalálható a T1libs dokumentációjában. [Aki nem hiszi, annak utánajárunk :)] A T1lib két használható fájllal rukkolt ki: az IsoLatin1.enc és az IsoLatin2.enc nevűekkel. [Ékes anyanyelvünk lelkes híveinek az utóbbit ajánlom!]

Ha azon kapod magad, hogy folyton ezt a függvényt használod, akkor jobban jársz, ha a kódolást a ps.default_encoding-ot a konfigurációs fájlban a megfelelő kódolási fájlra állítod, így betűkészleteid automatikusan jó kódolásúak lesznek.

ImagePsExtendFont

(PHP 3>= 3.0.9, PHP 4 )

ImagePsExtendFont --  Széthúz vagy zsugorít egy betűkészletet

Leírás

bool imagepsextendfont ( int font_index, double extend)

Széthúz vagy zsugorít egy betűkészletet (a font_index paraméterben megadottat). Ha az extend paraméter értéke egynél kisebb, a betűkészletet összenyomja.

ImagePSFreeFont

(PHP 3>= 3.0.9, PHP 4 )

ImagePSFreeFont -- Egy PostScript Type 1 betűtípus által használt memóriát szabadít fel

Leírás

void imagepsfreefont ( int fontindex)

Lásd még a ImagePSLoadFont() függvényt!

ImagePSLoadFont

(PHP 3>= 3.0.9, PHP 4 )

ImagePSLoadFont -- Fájlból betölt egy PostScript Type 1 betűtípust

Leírás

int imagepsloadfont ( string filename)

Ha minden jól megy, akkor egy érvényes betűtípus-azonosítót kapsz vissza. Ha nincs szerencséd, a függvény hamissal tér vissza, és kiírja, hogy mi a baj. [ennek nem sok hasznát veszed, hiszen a kimenet típusa kép...]

Lásd még a ImagePSFreeFont() függvényt!

ImagePsSlantFont

(PHP 3>= 3.0.9, PHP 4 )

ImagePsSlantFont --  Dönt egy betűkészletet

Leírás

bool imagepsslantfont ( int font_index, double slant)

A font_index paraméterben megadott betűkészletet dönti a slant parametérben megadott értékkel.

ImagePSText

(PHP 3>= 3.0.9, PHP 4 )

ImagePSText --  Egy képbe PostScript Type1 típusú szöveget ír

Leírás

array imagepstext ( int image, string text, int font, int size, int foreground, int background, int x, int y [, int space [, int tightness [, float angle [, int antialias_steps]]]])

Size pixelben.

A foreground az a szín, amivel a szöveg kiíródik. A background az a szín, amelyet háttérszínnek feltételez a rajzolóalgoritmus (antialiasing miatt kell). A függvény egyetlen background színű pontot sem fog rajzolni, így a háttérnek nem kell egyszínűnek lennie.

Az x, y által adott paraméterek fogják a szöveg kezdetét meghatározni (durván az első karakter bal alsó sarkát). Ez egy különbség a ImageString(), függvénytől, ahol az x, y paraméterek az első karakter jobb felső [vagy bal felső] sarkát határozzák meg. Ha nem érted, hogy miért úgy rajzol a függvény, olvasd a PostScript dokumentációját a betűkészletekkel meg a koordinátarendszerekkel kapcsolatban!

A space paraméter segítségével a betűkészlet alapértelmezett térközének méretét tudod szabályozni. A megadott mennyiség a normál térközhöz hozzáadódik, így van értelme negatív térközt is megadni.

A tightness paraméter segítségével a betűk közötti térköz nagyságán tudsz változtatni. A megadott mennyiség a normál térközhöz hozzáadódik, így negatív is lehet.

A angle paraméter fokban értendő.

Az antialias_steps paraméter segítségével az antialiasing-hoz használt színek számát tudod szabályozni. A megengedett értékek: 4 és 16. 20-nál kisebb betűméret esetén a nagyobb értéket célszerű használni. Nagyobb betűkre használj 4-et, mert így gyorsabb a betűk rajzolása!

A space és a tightness paraméterek egysége a "karakter távolság egység", ami ezrede az em-nek [0.001em, jól mondom?].

A space, tightness, angle és a antialias paraméterek elhagyhatók.

A függvény egy tömbbel tér vissza, melynek az alábbi elemei vannak:

0bal alsó x-koordináta
1bal alsó y-koordináta
2jobb felső x-koordináta
3jobb felső y-koordináta

Lásd még az imagepsbbox() függvényt!

ImageRectangle

(PHP 3, PHP 4 )

ImageRectangle -- Téglalapot rajzol

Leírás

int imagerectangle ( int im, int x1, int y1, int x2, int y2, int col)

A ImageRectangle() függvény egy col színű téglalapot rajzol az im képre. A téglalap bal felső koordinátái x1, y1, a jobb alsó koordináták pedig x2, y2. A kép bal felső sarka a 0,0 koordináta.

imagerotate

(PHP 4 >= 4.3.0)

imagerotate -- Rotate an image with a given angle

Description

resource imagerotate ( resource src_im, float angle, int bgd_color)

Rotates the src_im image using a given angle in degree. bgd_color specifies the color of the uncovered zone after the rotation.

imagesavealpha

(PHP 4 >= 4.3.2)

imagesavealpha --  Set the flag to save full alpha channel information (as opposed to single-color transparency) when saving PNG images.

Description

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.

See also imagealphablending().

imagesetbrush

(PHP 4 >= 4.0.6)

imagesetbrush -- Set the brush image for line drawing

Description

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

Megjegyzés: 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!

Megjegyzés: This function was added in PHP 4.0.6

ImageSetPixel

(PHP 3, PHP 4 )

ImageSetPixel -- Egy pont színét megváltoztatja

Leírás

int imagesetpixel ( int im, int x, int y, int col)

A ImageSetPixel() függvény az im képben x, y pont (A kép bal felső sarka a 0,0 pont) színét a col színűre változtatja.

Lásd még a ImageCreate() és a ImageColorAllocate() függvényeket.

imagesetstyle

(PHP 4 >= 4.0.6)

imagesetstyle -- Set the style for line drawing

Description

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. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

The style parameter is an array of pixels. Following example script draws a dashed line from upper left to lower right corner of the canvas:

Példa 1. imagesetstyle() example

<?php
header("Content-type: image/jpeg");
$im  = imagecreate(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);
?>

See also imagesetbrush(), imageline().

Megjegyzés: This function was added in PHP 4.0.6

imagesetthickness

(PHP 4 >= 4.0.6)

imagesetthickness -- Set the thickness for line drawing

Description

bool imagesetthickness ( resource image, int thickness)

imagesetthickness() sets the thickness of the lines drawn when drawing rectangles, polygons, ellipses etc. etc. to thickness pixels. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Megjegyzés: This function was added in PHP 4.0.6 and requires GD 2.0.1 or later

imagesettile

(PHP 4 >= 4.0.6)

imagesettile -- Set the tile image for filling

Description

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

Megjegyzés: 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!

ImageString

(PHP 3, PHP 4 )

ImageString -- Karakterláncot ír ki (vízszintesen)

Leírás

int imagestring ( int im, int font, int x, int y, string s, int col)

Az ImageString() függvény kiírja az s karakterláncot az im képen az x, y (a bal felső sarok a 0, 0 pont) ponttól col színnel. Ha a font értéke 1, 2, 3, 4 vagy 5, egy beépített betűkészlet kerül felhasználásra.

Lásd még az ImageLoadFont() függvényt!

ImageStringUp

(PHP 3, PHP 4 )

ImageStringUp -- Kiír egy karakterláncot lentről fel [mint ahogy a :-)-t kell nézni]

Leírás

int imagestringup ( int im, int font, int x, int y, string s, int col)

Az ImageStringUp() függvény kiírja az s karakterláncot függőlegesen az im képen az x, y (a bal felső sarok a 0, 0 pont) ponttól col színnel. Ha a font értéke 1, 2, 3, 4 vagy 5, egy beépített betűkészlet kerül felhasználásra.

Lásd még az ImageLoadFont() függvényt!

ImageSX

(PHP 3, PHP 4 )

ImageSX -- Kép szélessége

Leírás

int imagesx ( int im)

Az ImageSX() függvény az im álala azonosított kép szélességét adja vissza.

Lásd még a ImageCreate() és a ImageSY() függvényeket!

ImageSY

(PHP 3, PHP 4 )

ImageSY -- Kép magassága

Leírás

int imagesy ( int im)

Az ImageSY() függvény az im álala azonosított kép magasságát adja vissza.

Lásd még a ImageCreate() és a ImageSX() függvényeket!

imagetruecolortopalette

(PHP 4 >= 4.0.6)

imagetruecolortopalette -- Convert a true color image to a palette image

Description

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

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.

Megjegyzés: This function was added in PHP 4.0.6 and requires GD 2.0.1 or later

ImageTTFBBox

(PHP 3>= 3.0.1, PHP 4 )

ImageTTFBBox --  TruType betűtípusú szöveg befoglaló téglalapját adja vissza.

Leírás

array imagettfbbox ( int size, int angle, string fontfile, string text)

A függvény kiszámítja és visszaadja a TrueType szöveg befoglaló téglalap méretét (képpontban).

text

a megmérendő szöveg

size

a betűk nagysága

fontfile

A TrueType betűtípus fájl neve. (Lehet URL is)

angle

Szög fokban, amiben a text paramétert mérjük. [???]

Az ImageTTFBBox() függvény egy 8-elemű tömbbel tér vissza, amely a befoglaló négy pont koordinátáit tartalmazza:

0bal alsó sarok, X koordináta
1bal alsó sarok, Y koordináta
2jobb alsó sarok, X koordináta
3jobb alsó sarok, Y koordináta
4jobb felső sarok, X koordináta
5jobb felső sarok, Y koordináta
6bal felső sarok, X koordináta
7bal felső sarok, Y koordináta

A pontok a szöveghez képest értendők, tehát a "bal felső" azt jelenti, hogy a szöveget normálisan nézve bal felső.

E függvény használatához a GD és a FreeType könyvtárak is kellenek.

Lásd még az ImageTTFText() függvényt!

ImageTTFText

(PHP 3, PHP 4 )

ImageTTFText --  TrueType típusú szöveget ír ki egy képre

Leírás

array imagettftext ( int im, int size, int angle, int x, int y, int col, string fontfile, string text)

A ImageTTFText() függvény az im képre írja ki a text szöveget az x, y koordinátákra angle szöggel elforgatva col színnel a fontfile betűtípust felhasználva.

Az x, y által adott paraméterek fogják a szöveg kezdetét meghatározni (durván az első karakter bal alsó sarkát). Ez egy különbség a ImageString(), függvénytől, ahol az x, y paraméterek az első karakter jobb felső [talán bal felső] sarkát határozzák meg.

Az angle paraméter értéke fokban értendő. Ha értéke 0, a szöveg "normális" balról-jobbra olvasható szöveg. Pozitív értékek a szöveget pozitív (óramutató járásával ellentétes) irányba forgatja. (Pl.: 90-es elforgatásnál a szöveget lentről felfelé kell olvasni)

A fontfile paraméter egy TrueType betűtípus teljes elérési útvonala.

A text paraméter a szöveg, mely tartalmazhat UTF-8 karaktersorozatokat (&#123; formában) a 255 feletti kódú karakterek eléréséhez.

A col paraméter egy szín-index. Ha értéke negatív, az kikapcsolja az antialiasing-ot.

Az ImageTTFText() függvény egy 8-elemű tömböt ad vissza, mely a szöveget befoglaló 4 pont koordinátáit tartalmazza. A pontok sorrendje: bal felső, jobb felső, jobb alsó, bal alsó. A pontok a szöveghez képest relatívok, vagyis a szöveget olvasva értendők.

Az alábbi példaprogram egy fekete 400x30-as GIF képet eredményez egy fehér Arial típusú "Próba" kezdetű szöveggel. [Feltéve, ha nem túl új a GD-d mert a gif támogatást kiszedték :(]

Példa 1. ImageTTFText

<?php
Header ("Content-type: image/gif");
$im = imagecreate (400, 30);
$black = ImageColorAllocate ($im, 0, 0, 0);
$white = ImageColorAllocate ($im, 255, 255, 255);
ImageTTFText ($im, 20, 0, 10, 20, $white, "/path/arial.ttf", 
              "Próba Omega: &#937;");
ImageGif ($im);
ImageDestroy ($im);
?>

A függvény használatához a GD könyvtáron kívül a FreeType könyvtár is szükséges.

Lásd még a ImageTTFBBox() függvényt!

imagetypes

(PHP 3 CVS only, PHP 4 >= 4.0.2)

imagetypes -- Return the image types supported by this PHP build

Description

int imagetypes ( void )

This function returns a bit-field corresponding to the image formats supported by the version of GD linked into PHP. The following bits are returned, IMG_GIF | IMG_JPG | IMG_PNG | IMG_WBMP. To check for PNG support, for example, do this:

Példa 1. imagetypes() example

<?php
if (imagetypes() & IMG_PNG) {
    echo "PNG Support is enabled";
}
?>

imagewbmp

(PHP 3>= 3.0.15, PHP 4 >= 4.0.1)

imagewbmp -- Output image to browser or file

Description

int imagewbmp ( resource image [, string filename [, int foreground]])

imagewbmp() creates the WBMP file in filename from the image image. The image argument is the return from the imagecreate() function.

The filename argument is optional, and if left off, the raw image stream will be output directly. By sending an image/vnd.wap.wbmp content-type using header(), you can create a PHP script that outputs WBMP images directly.

Megjegyzés: WBMP support is only available if PHP was compiled against GD-1.8 or later.

Using the optional foreground parameter, you can set the foreground color. Use an identifier obtained from imagecolorallocate(). The default foreground color is black.

See also image2wbmp(), imagepng(), imagegif(), imagejpeg(), imagetypes().

iptcembed

(PHP 3>= 3.0.7, PHP 4 )

iptcembed -- Embed binary IPTC data into a JPEG image

Description

array iptcembed ( string iptcdata, string jpeg_file_name [, int spool])

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

iptcparse

(PHP 3>= 3.0.6, PHP 4 )

iptcparse --  Parse a binary IPTC http://www.iptc.org/ block into single tags.

Description

array iptcparse ( string iptcblock)

This function parses a binary IPTC block into its single tags. It 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. See getimagesize() for a sample.

jpeg2wbmp

(PHP 4 >= 4.0.5)

jpeg2wbmp -- Convert JPEG image file to WBMP image file

Description

int jpeg2wbmp ( string jpegname, string wbmpname, int d_height, int d_width, int threshold)

Converts the jpegname JPEG file to WBMP format, and saves it as wbmpname. With the d_height and d_width you specify the height and width of the destination image.

Megjegyzés: WBMP support is only available if PHP was compiled against GD-1.8 or later.

See also png2wbmp().

png2wbmp

(PHP 4 >= 4.0.5)

png2wbmp -- Convert PNG image file to WBMP image file

Description

int png2wbmp ( string pngname, string wbmpname, int d_height, int d_width, int threshold)

Converts the pngname PNG file to WBMP format, and saves it as wbmpname. With the d_height and d_width you specify the height and width of the destination image.

Megjegyzés: WBMP support is only available if PHP was compiled against GD-1.8 or later.

See also jpeg2wbmp().

read_exif_data

read_exif_data -- Alias of exif_read_data()

Description

This function is an alias of exif_read_data().

XLII. IMAP, POP3 and NNTP functions

Bevezetés

These functions are not limited to the IMAP protocol, despite their name. The underlying c-client library also supports NNTP, POP3 and local mailbox access methods.


Követelmények

This extension requires the c-client library to be installed. Grab the latest version from ftp://ftp.cac.washington.edu/imap/ and compile it.

It's important that you do not copy the IMAP source files directly into the system include directory as there may be conflicts. Instead, create a new directory inside the system include directory, such as /usr/local/imap-2000b/ (location and name depend on your setup and IMAP version), and inside this new directory create additional directories named lib/ and include/. From the c-client directory from your IMAP source tree, copy all the *.h files into include/ and all the *.c files into lib/. Additionally when you compiled IMAP, a file named c-client.a was created. Also put this in the lib/ directory but rename it as libc-client.a.

Megjegyzés: To build the c-client library with SSL or/and Kerberos support read the docs supplied with the package.


Telepítés

To get these functions to work, you have to compile PHP with --with-imap[=DIR], where DIR is the c-client install prefix. From our example above, you would use --with-imap=/usr/local/imap-2000b. This location depends on where you created this directory according to the description above. Windows users may include the php_imap.dll DLL in php.ini

Megjegyzés: Depending how the c-client was configured, you might also need to add --with-imap-ssl=/path/to/openssl/ and/or --with-kerberos=/path/to/kerberos into the PHP configure line.

Figyelem

Az IMAP kiterjesztés nem használható együtt a recode és YAZ kiterjesztésekkel. Ennek oka az, hogy C forrás szinten ugyanazt a beépített szimbólumot használják.


Futásidejű beállítások

Ez a kiterjesztés semmilyen konfigurációs beállításokat nem definiál a php.ini állományban.


Erőforrás típusok


Előre definiált állandók

Az itt listázott állandókat ez a kiterjesztés definiálja, és csak akkor elérhetőek, ha az adott kiterjesztés be van fordítva a PHP-be, vagy dinamikusan betöltött.

NIL (integer)

OP_DEBUG (integer)

OP_READONLY (integer)

OP_ANONYMOUS (integer)

OP_SHORTCACHE (integer)

OP_SILENT (integer)

OP_PROTOTYPE (integer)

OP_HALFOPEN (integer)

OP_EXPUNGE (integer)

OP_SECURE (integer)

CL_EXPUNGE (integer)

FT_UID (integer)

FT_PEEK (integer)

FT_NOT (integer)

FT_INTERNAL (integer)

FT_PREFETCHTEXT (integer)

ST_UID (integer)

ST_SILENT (integer)

ST_SET (integer)

CP_UID (integer)

CP_MOVE (integer)

SE_UID (integer)

SE_FREE (integer)

SE_NOPREFETCH (integer)

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)

LATT_NOSELECT (integer)

LATT_MARKED (integer)

LATT_UNMARKED (integer)

SORTDATE (integer)

SORTARRIVAL (integer)

SORTFROM (integer)

SORTSUBJECT (integer)

SORTTO (integer)

SORTCC (integer)

SORTSIZE (integer)

TYPETEXT (integer)

TYPEMULTIPART (integer)

TYPEMESSAGE (integer)

TYPEAPPLICATION (integer)

TYPEAUDIO (integer)

TYPEIMAGE (integer)

TYPEVIDEO (integer)

TYPEOTHER (integer)

ENC7BIT (integer)

ENC8BIT (integer)

ENCBINARY (integer)

ENCBASE64 (integer)

ENCQUOTEDPRINTABLE (integer)

ENCOTHER (integer)


Lásd még

This document can't go into detail on all the topics touched by the provided functions. Further information is provided by the documentation of the c-client library source (docs/internal.txt). and the following RFC documents:

  • RFC2821: Simple Mail Transfer Protocol (SMTP).

  • RFC2822: Standard for ARPA internet text messages.

  • RFC2060: Internet Message Access Protocol (IMAP) Version 4rev1.

  • RFC1939: Post Office Protocol Version 3 (POP3).

  • RFC977: Network News Transfer Protocol (NNTP).

  • RFC2076: Common Internet Message Headers.

  • RFC2045 , RFC2046 , RFC2047 , RFC2048 & RFC2049: Multipurpose Internet Mail Extensions (MIME).

A detailed overview is also available in the books Programming Internet Email by David Wood and Managing IMAP by Dianna Mullet & Kevin Mullet.

Tartalom
imap_8bit --  Convert an 8bit string to a quoted-printable string
imap_alerts --  This function returns all IMAP alert messages (if any) that have occurred during this page request or since the alert stack was reset
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_createmailbox -- Create a new mailbox
imap_delete --  Mark a message for deletion from current mailbox
imap_deletemailbox -- Delete a mailbox
imap_errors --  This function returns all of the IMAP errors (if any) that have occurred during this page request or since the error stack was reset.
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_fetchstructure --  Read the structure of a particular message
imap_get_quota --  Retrieve the quota level settings, and usage statics per mailbox
imap_get_quotaroot --  Retrieve the quota settings per user
imap_getacl --  Gets the ACL for a given mailbox
imap_getmailboxes --  Read the list of mailboxes, returning detailed information on each one
imap_getsubscribed -- List all the subscribed mailboxes
imap_header -- Alias of imap_headerinfo()
imap_headerinfo -- Read the header of the message
imap_headers --  Returns headers for all messages in a mailbox
imap_last_error --  This function returns the last IMAP error (if any) that occurred during this page request
imap_list -- Read the list of mailboxes
imap_listmailbox -- Alias of imap_list()
imap_listscan --  Read the list of mailboxes, takes a string to search for in the text of the mailbox
imap_listsubscribed -- Alias of 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 --  This function returns the message sequence number for the given UID
imap_num_msg --  Gives the number of messages in the current mailbox
imap_num_recent -- Gives 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_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_scanmailbox -- Alias of imap_listscan()
imap_search --  This function returns an array of messages matching the given search criteria
imap_set_quota -- Sets a quota for a given mailbox
imap_setacl --  Sets the ACL for a giving mailbox
imap_setflag_full -- Sets flags on messages
imap_sort -- Sort an array of message headers
imap_status --  This function returns status information on a mailbox other than the current one
imap_subscribe -- Subscribe to a mailbox
imap_thread --  Return threaded by REFERENCES tree
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

imap_8bit

(PHP 3, PHP 4 )

imap_8bit --  Convert an 8bit string to a quoted-printable string

Description

string imap_8bit ( string string)

Convert an 8bit string to a quoted-printable string (according to RFC2045, section 6.7).

Returns a quoted-printable string.

See also imap_qprint().

imap_alerts

(PHP 3>= 3.0.12, PHP 4 )

imap_alerts --  This function returns all IMAP alert messages (if any) that have occurred during this page request or since the alert stack was reset

Description

array imap_alerts ( void )

This function returns an array of all of the IMAP alert messages generated since the last imap_alerts() call, or the beginning of the page. When imap_alerts() is called, the alert stack is subsequently cleared. The IMAP specification requires that these messages be passed to the user.

imap_append

(PHP 3, PHP 4 )

imap_append --  Append a string message to a specified mailbox

Description

bool imap_append ( resource imap_stream, string mbox, string message [, string options])

imap_append() appends a string message to the specified mailbox mbox. If the optional options is specified, writes the options to that mailbox also.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

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.

Példa 1. imap_append() example

<?php
$stream = imap_open("{your.imap.host}INBOX.Drafts", "username", "password");

$check = imap_check($stream);
echo "Msg Count before append: ". $check->Nmsgs."\n";

imap_append($stream, "{your.imap.host}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_base64

(PHP 3, PHP 4 )

imap_base64 -- Decode BASE64 encoded text

Description

string imap_base64 ( string text)

imap_base64() function decodes BASE-64 encoded text (see RFC2045, Section 6.8). The decoded message is returned as a string.

See also imap_binary(), base64_encode() and base64_decode().

imap_binary

(PHP 3>= 3.0.2, PHP 4 )

imap_binary --  Convert an 8bit string to a base64 string

Description

string imap_binary ( string string)

Convert an 8bit string to a base64 string (according to RFC2045, Section 6.8).

Returns a base64 string.

See also imap_base64().

imap_body

(PHP 3, PHP 4 )

imap_body -- Read the message body

Description

string imap_body ( resource imap_stream, int msg_number [, int options])

imap_body() returns the body of the message, numbered msg_number in the current mailbox. The optional flags are a bit mask with one or more of the following:

  • FT_UID - The msgno 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.

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.

imap_bodystruct

(PHP 3>= 3.0.4, PHP 4 )

imap_bodystruct --  Read the structure of a specified body section of a specific message

Description

object imap_bodystruct ( resource stream_id, int msg_no, int section)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

imap_check

(PHP 3, PHP 4 )

imap_check -- Check current mailbox

Description

object imap_check ( resource imap_stream)

Returns information about the current mailbox. Returns FALSE on failure.

The imap_check() function checks the current mailbox status on the server and returns the information in an object with following properties:

  • Date - current system time formatted according to RFC822

  • 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

Példa 1. imap_check() example

<?php

$imap_obj = imap_check($imap_stream);
var_dump($imap_obj);

?>

this will output :

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_clearflag_full

(PHP 3>= 3.0.3, PHP 4 )

imap_clearflag_full -- Clears flags on messages

Description

bool imap_clearflag_full ( resource stream, string sequence, string flag, string options)

This function causes a store to delete the specified flag to the flags set for the messages in the specified sequence. The flags which you can unset are "\\Seen", "\\Answered", "\\Flagged", "\\Deleted", and "\\Draft" (as defined by RFC2060).

The options are a bit mask with one or more of the following:


ST_UID          The sequence argument contains UIDs instead of
                sequence numbers
      

imap_close

(PHP 3, PHP 4 )

imap_close -- Close an IMAP stream

Description

bool imap_close ( resource imap_stream [, int flag])

Closes the imap stream. Takes an optional flag CL_EXPUNGE, which will silently expunge the mailbox before closing, removing all messages marked for deletion.

imap_createmailbox

(PHP 3, PHP 4 )

imap_createmailbox -- Create a new mailbox

Description

bool imap_createmailbox ( resource imap_stream, string mbox)

imap_createmailbox() creates a new mailbox specified by mbox. Names containing international characters should be encoded by imap_utf7_encode()

Returns TRUE on success and FALSE on error.

See also imap_renamemailbox(), imap_deletemailbox() and imap_open() for the format of mbox names.

Példa 1. imap_createmailbox() example

<?php
$mbox = imap_open("{your.imap.host}", "username", "password", OP_HALFOPEN)
     or die("can't connect: " . imap_last_error());

$name1 = "phpnewbox";
$name2 = imap_utf7_encode("phpnewb&ouml;x");

$newname = $name1;

echo "Newname will be '$name1'<br />\n";

# we will now create a new mailbox "phptestbox" in your inbox folder,
# check its status after creation and finaly remove it to restore
# your inbox to its initial state 
if (@imap_createmailbox($mbox, imap_utf7_encode("{your.imap.host}INBOX.$newname"))) {
  $status = @imap_status($mbox, "{your.imap.host}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, "{your.imap.host}INBOX.$newname", "{your.imap.host}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, "{your.imap.host}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);
?>

imap_delete

(PHP 3, PHP 4 )

imap_delete --  Mark a message for deletion from current mailbox

Description

bool imap_delete ( int imap_stream, int msg_number [, int options])

Returns TRUE.

imap_delete() marks messages listed in msg_number for deletion. The optional flags parameter only has a single option, FT_UID, which tells the function to treat the msg_number argument as a UID. 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.

Megjegyzés: POP3 mailboxes do not have their message flags saved between connections, so imap_expunge() must be called during the same connection in order for messages marked for deletion to actually be purged.

Példa 1. imap_delete() example

<?php
$mbox = imap_open("{your.imap.host}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);
?>

imap_deletemailbox

(PHP 3, PHP 4 )

imap_deletemailbox -- Delete a mailbox

Description

bool imap_deletemailbox ( resource imap_stream, string mbox)

imap_deletemailbox() deletes the specified mailbox (see imap_open() for the format of mbox names).

Returns TRUE on success and FALSE on error.

See also imap_createmailbox(), imap_renamemailbox(), and imap_open() for the format of mbox.

imap_errors

(PHP 3>= 3.0.12, PHP 4 )

imap_errors --  This function returns all of the IMAP errors (if any) that have occurred during this page request or since the error stack was reset.

Description

array imap_errors ( void )

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. When imap_errors() is called, the error stack is subsequently cleared.

imap_expunge

(PHP 3, PHP 4 )

imap_expunge -- Delete all messages marked for deletion

Description

bool imap_expunge ( resource imap_stream)

imap_expunge() deletes all the messages marked for deletion by imap_delete(), imap_mail_move(), or imap_setflag_full().

Returns TRUE.

imap_fetch_overview

(PHP 3>= 3.0.4, PHP 4 )

imap_fetch_overview --  Read an overview of the information in the headers of the given message

Description

array imap_fetch_overview ( resource imap_stream, string sequence [, int options])

This function fetches mail headers for the given sequence and returns an overview of their contents. sequence will contain a sequence of message indices or UIDs, if flags contains FT_UID. The returned value is an array of objects describing one message header each:

  • subject - the messages subject

  • from - who sent it

  • date - when was it sent

  • message_id - Message-ID

  • references - is a reference to this message id

  • size - size in bytes

  • uid - UID the message has in the mailbox

  • msgno - message sequence number in the maibox

  • 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

Példa 1. imap_fetch_overview() example

<?php
$mbox = imap_open("{your.imap.host:143}", "username", "password")
     or die("can't connect: " . imap_last_error());
 
$overview = imap_fetch_overview($mbox, "2,4:6", 0);
 
if (is_array($overview)) {
        reset($overview);
        while (list($key, $val) = each($overview)) {
                echo      $val->msgno
                . " - " . $val->date
                . " - " . $val->subject
                . "\n";
        }
}
 
imap_close($mbox);
?>

imap_fetchbody

(PHP 3, PHP 4 )

imap_fetchbody --  Fetch a particular section of the body of the message

Description

string imap_fetchbody ( resource imap_stream, int msg_number, string part_number [, flags options])

This function causes a fetch of a particular section of the body of the specified messages as a text string and returns that text string. The section specification is a string of integers delimited by period which index into a body part list as per the IMAP4 specification. Body parts are not decoded by this function.

The options for imap_fetchbody() is 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, without any attempt to canonicalize CRLF.

See also: imap_fetchstructure().

imap_fetchheader

(PHP 3>= 3.0.3, PHP 4 )

imap_fetchheader -- Returns header for a message

Description

string imap_fetchheader ( resource imap_stream, int msgno, int options)

This function causes a fetch of the complete, unfiltered RFC2822 format header of the specified message as a text string and returns that text string.

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

imap_fetchstructure

(PHP 3, PHP 4 )

imap_fetchstructure --  Read the structure of a particular message

Description

object imap_fetchstructure ( resource imap_stream, int msg_number [, int options])

This function fetches all the structured information for a given message. The optional flags parameter only has a single option, FT_UID, which tells the function to treat the msg_number argument as a UID. The returned 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:

Táblázat 1. Returned Objects for imap_fetchstructure()

typePrimary body type
encodingBody transfer encoding
ifsubtypeTRUE if there is a subtype string
subtypeMIME subtype
ifdescriptionTRUE if there is a description string
descriptionContent description string
ifidTRUE if there is an identification string
idIdentification string
linesNumber of lines
bytesNumber of bytes
ifdispositionTRUE if there is a disposition string
dispositionDisposition string
ifdparametersTRUE if the dparameters array exists
dparametersAn array of objects where each object has an "attribute" and a "value" property corresponding to the parameters on the Content-disposition MIMEheader.
ifparametersTRUE if the parameters array exists
parametersAn array of objects where each object has an "attribute" and a "value" property.
partsAn array of objects identical in structure to the top-level object, each of which corresponds to a MIME body part.

Táblázat 2. Primary body type

0text
1multipart
2message
3application
4audio
5image
6video
7other

Táblázat 3. Transfer encodings

07BIT
18BIT
2BINARY
3BASE64
4QUOTED-PRINTABLE
5OTHER

See also: imap_fetchbody().

imap_get_quota

(PHP 4 >= 4.0.5)

imap_get_quota --  Retrieve the quota level settings, and usage statics per mailbox

Description

array imap_get_quota ( resource imap_stream, string quota_root)

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.

This function is currently only available to users of the c-client2000 or greater library.

NOTE: For this function to work, the mail stream is required to be opened as the mail-admin user. For a non-admin user version of this function, please see the imap_get_quotaroot() function of PHP.

imap_stream should be the value returned from an imap_open() call. NOTE: This stream is required to be opened as the mail admin user for the get_quota function to work. quota_root should normally be in the form of user.name where name is the mailbox you wish to retrieve information about.

Példa 1. imap_get_quota() example

<?php
$mbox = imap_open("{your.imap.host}", "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); 
?>

As of PHP version 4.3, the function more properly reflects the functionality as dictated by the RFC 2087. 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. The example below shows the updated returned output.

For backwards compatibility reasons, the originial access methods are still available for use, although it is suggested to update.

Példa 2. imap_get_quota() 4.3 or greater example

<?php
$mbox = imap_open("{your.imap.host}", "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); 
?>

See also imap_open(), imap_set_quota() and imap_get_quotaroot().

imap_get_quotaroot

(PHP 4 >= 4.3.0)

imap_get_quotaroot --  Retrieve the quota settings per user

Description

array imap_get_quotaroot ( resource imap_stream, string quota_root)

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.

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

This function is currently only available to users of the c-client2000 or greater library.

imap_stream should be the value returned from an imap_open() call. This stream should be opened as the user whose mailbox you wish to check. quota_root should normally be in the form of which mailbox (i.e. INBOX).

Példa 1. imap_get_quotaroot() example

<?php
$mbox = imap_open("{your.imap.host}", "kalowsky", "password", OP_HALFOPEN)
      or die("can't connect: " . imap_last_error());
 
$quota = imap_get_quotaroot($mbox, "INBOX");
if (is_array($quota)) {
   $storage = $quota_values['STORAGE'];
   echo "STORAGE usage level is: " .  $storage['usage'];
   echo "STORAGE limit level is: " .  $storage['limit'];

   $message = $quota_values['MESSAGE']; 
   echo "MESSAGE usage level is: " .  $message['usage'];
   echo "MESSAGE usage level is: " .  $message['limit'];

   /* ...  */ 

} 
 
imap_close($mbox); 
?>

See also imap_open(), imap_set_quota() and imap_get_quota().

imap_getacl

(PHP 5 CVS only)

imap_getacl --  Gets the ACL for a given mailbox

Description

array imap_getacl ( resource stream_id, string mailbox)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

imap_getmailboxes

(PHP 3>= 3.0.12, PHP 4 )

imap_getmailboxes --  Read the list of mailboxes, returning detailed information on each one

Description

array imap_getmailboxes ( resource imap_stream, string ref, string pattern)

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.

Mailbox names containing international Characters outside the printable ASCII range will be encoded and may be decoded by imap_utf7_decode().

ref should normally be just the server specification as described in imap_open(), and pattern specifies where in the mailbox hierarchy to start searching. If you want all mailboxes, pass '*' for pattern.

There are two special characters you can pass as part of the pattern: '*' and '%'. '*' means to return all mailboxes. If you pass pattern as '*', you will get a list of the entire mailbox hierarchy. '%' means to return the current level only. '%' as the pattern parameter will return only the top level mailboxes; '~/mail/%' on UW_IMAPD will return every mailbox in the ~/mail directory, but none in subfolders of that directory.

Példa 1. imap_getmailboxes() example

<?php
$mbox = imap_open("{your.imap.host}", "username", "password", OP_HALFOPEN)
      or die("can't connect: " . imap_last_error());
 
$list = imap_getmailboxes($mbox, "{your.imap.host}", "*");
if (is_array($list)) {
  reset($list);
  while (list($key, $val) = each($list)) {
    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);
?>

See also imap_getsubscribed().

imap_getsubscribed

(PHP 3>= 3.0.12, PHP 4 )

imap_getsubscribed -- List all the subscribed mailboxes

Description

array imap_getsubscribed ( resource imap_stream, string ref, string pattern)

This function is identical to imap_getmailboxes(), except that it only returns mailboxes that the user is subscribed to.

imap_header

imap_header -- Alias of imap_headerinfo()

Description

This function is an alias of imap_headerinfo().

imap_headerinfo

(PHP 3, PHP 4 )

imap_headerinfo -- Read the header of the message

Description

object imap_headerinfo ( resource imap_stream, int msg_number [, int fromlength [, int subjectlength [, string defaulthost]]])

This function returns an object of various header elements.


       remail, date, Date, subject, Subject, in_reply_to, message_id,
       newsgroups, followup_to, references

message flags:
   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
   Answered -'A' if answered, 
             ' ' if unanswered
   Deleted - 'D' if deleted, 
             ' ' if not deleted
   Draft -   'X' if draft, 
             ' ' if not draft
   Flagged - 'F' if flagged, 
             ' ' if not flagged

NOTE that the Recent/Unseen behavior is a little odd. If you want to
know if a message is Unseen, you must check for

Unseen == 'U' || Recent == 'N'

toaddress (full to: line, up to 1024 characters)

to[] (returns an array of objects from the To line, containing):
   personal
   adl
   mailbox
   host

fromaddress (full from: line, up to 1024 characters)

from[] (returns an array of objects from the From line, containing):
   personal
   adl
   mailbox
   host

ccaddress (full cc: line, up to 1024 characters)
cc[] (returns an array of objects from the Cc line, containing):
   personal
   adl
   mailbox
   host

bccaddress (full bcc line, up to 1024 characters)
bcc[] (returns an array of objects from the Bcc line, containing):
   personal
   adl
   mailbox
   host

reply_toaddress (full reply_to: line, up to 1024 characters)
reply_to[] (returns an array of objects from the Reply_to line,
containing):
   personal
   adl
   mailbox
   host

senderaddress (full sender: line, up to 1024 characters)
sender[] (returns an array of objects from the sender line, containing):
   personal
   adl
   mailbox
   host

return_path (full return-path: line, up to 1024 characters)
return_path[] (returns an array of objects from the return_path line,
containing):
   personal
   adl
   mailbox
   host

udate (mail message date in unix time)

fetchfrom (from line formatted to fit fromlength 
characters)

fetchsubject (subject line formatted to fit subjectlength characters)
      

imap_headers

(PHP 3, PHP 4 )

imap_headers --  Returns headers for all messages in a mailbox

Description

array imap_headers ( resource imap_stream)

Returns an array of string formatted with header info. One element per mail message.

imap_last_error

(PHP 3>= 3.0.12, PHP 4 )

imap_last_error --  This function returns the last IMAP error (if any) that occurred during this page request

Description

string imap_last_error ( void )

This function returns 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.

imap_list

(PHP 3>= 3.0.4, PHP 4 )

imap_list -- Read the list of mailboxes

Description

array imap_list ( resource imap_stream, string ref, string pattern)

Returns an array containing the names of the mailboxes. See imap_getmailboxes() for a description of ref and pattern.

Példa 1. imap_list() example

<?php
$mbox = imap_open("{your.imap.host}", "username", "password", OP_HALFOPEN)
      or die("can't connect: " . imap_last_error());
 
$list = imap_list($mbox, "{your.imap.host}", "*");
if (is_array($list)) {
  reset($list);
  while (list($key, $val) = each($list))
    echo imap_utf7_decode($val) . "<br />\n";
} else {
  echo "imap_list failed: " . imap_last_error() . "\n";
}

imap_close($mbox);
?>

imap_listmailbox

imap_listmailbox -- Alias of imap_list()

Description

This function is an alias of imap_list().

imap_listscan

(no version information, might be only in CVS)

imap_listscan --  Read the list of mailboxes, takes a string to search for in the text of the mailbox

Description

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. See imap_getmailboxes() for a description of ref and pattern.

imap_listsubscribed

imap_listsubscribed -- Alias of imap_lsub()

Description

This function is an alias of imap_lsub().

imap_lsub

(PHP 3>= 3.0.4, PHP 4 )

imap_lsub -- List all the subscribed mailboxes

Description

array imap_lsub ( resource imap_stream, string ref, string pattern)

Returns an array of all the mailboxes that you have subscribed.

imap_mail_compose

(PHP 3>= 3.0.5, PHP 4 )

imap_mail_compose --  Create a MIME message based on given envelope and body sections

Description

string imap_mail_compose ( array envelope, array body)

Példa 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_mail_copy

(PHP 3, PHP 4 )

imap_mail_copy -- Copy specified messages to a mailbox

Description

bool imap_mail_copy ( resource imap_stream, string msglist, string mbox [, int options])

Returns TRUE on success and FALSE on error.

Copies mail messages specified by msglist to specified mailbox. msglist is a range not just message numbers (as described in RFC2060).

Flags 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

imap_mail_move

(PHP 3, PHP 4 )

imap_mail_move -- Move specified messages to a mailbox

Description

bool imap_mail_move ( resource imap_stream, string msglist, string mbox [, int options])

Moves mail messages specified by msglist to specified mailbox mbox. msglist is a range not just message numbers (as described in RFC2060).

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

options is a bitmask and may contain the single option

  • CP_UID - the sequence numbers contain UIDS

imap_mail

(PHP 3>= 3.0.14, PHP 4 )

imap_mail --  Send an email message

Description

bool imap_mail ( string to, string subject, string message [, string additional_headers [, string cc [, string bcc [, string rpath]]]])

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. The receivers specified in bcc will get the mail, but are excluded from the headers. Use the rpath parameter to specify return path. This is useful when using PHP as a mail client for multiple users.

imap_mailboxmsginfo

(PHP 3>= 3.0.2, PHP 4 )

imap_mailboxmsginfo -- Get information about the current mailbox

Description

object imap_mailboxmsginfo ( resource imap_stream)

Returns information about the current mailbox. Returns FALSE on failure.

The imap_mailboxmsginfo() function 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. It returns the information in an object with following properties.

Táblázat 1. Mailbox properties

Datedate of last change
Driverdriver
Mailboxname of the mailbox
Nmsgsnumber of messages
Recentnumber of recent messages
Unreadnumber of unread messages
Deletednumber of deleted messages
Sizemailbox size

Példa 1. imap_mailboxmsginfo() example

<?php

$mbox = imap_open("{your.imap.host}INBOX", "username", "password")
      or die("can't connect: " . imap_last_error());
 
$check = imap_mailboxmsginfo($mbox);
 
if ($check) {
    echo "Date: "     . $check->Date    . "<br />\n" ;
    echo "Driver: "   . $check->Driver  . "<br />\n" ;
    echo "Mailbox: "  . $check->Mailbox . "<br />\n" ;
    echo "Messages: " . $check->Nmsgs   . "<br />\n" ;
    echo "Recent: "   . $check->Recent  . "<br />\n" ;
    echo "Unread: "   . $check->Unread  . "<br />\n" ;
    echo "Deleted: "  . $check->Deleted . "<br />\n" ;
    echo "Size: "     . $check->Size    . "<br />\n" ;
} else {
    echo "imap_check() failed: " . imap_last_error() . "<br />\n";
}
 
imap_close($mbox);

?>

imap_mime_header_decode

(PHP 3>= 3.0.17, PHP 4 )

imap_mime_header_decode -- Decode MIME header elements

Description

array imap_mime_header_decode ( string text)

imap_mime_header_decode() function decodes MIME message header extensions that are non ASCII text (see RFC2047) The decoded elements are returned in an array of objects, where each object has two properties, "charset" & "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".

Példa 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";
}
?>

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.

imap_msgno

(PHP 3>= 3.0.3, PHP 4 )

imap_msgno --  This function returns the message sequence number for the given UID

Description

int imap_msgno ( resource imap_stream, int uid)

This function returns the message sequence number for the given UID. It is the inverse of imap_uid().

imap_num_msg

(PHP 3, PHP 4 )

imap_num_msg --  Gives the number of messages in the current mailbox

Description

int imap_num_msg ( resource imap_stream)

Return the number of messages in the current mailbox.

See also: imap_num_recent() and imap_status().

imap_num_recent

(PHP 3, PHP 4 )

imap_num_recent -- Gives the number of recent messages in current mailbox

Description

int imap_num_recent ( resource imap_stream)

Returns the number of recent messages in the current mailbox.

See also: imap_num_msg() and imap_status().

imap_open

(PHP 3, PHP 4 )

imap_open -- Open an IMAP stream to a mailbox

Description

resource imap_open ( string mailbox, string username, string password [, int options])

Returns an IMAP stream on success and FALSE on error. 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.

A mailbox name consists of a server part and a mailbox path on this server. The special name INBOX stands for the current users personal mailbox. 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. Mailbox names that contain international characters besides those in the printable ASCII space have to be encoded with imap_utf7_encode().

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

To connect to an IMAP server running on port 143 on the local machine, do the following:

<?php
$mbox = imap_open("{localhost:143}INBOX", "user_id", "password");
?>

To connect to a POP3 server on port 110 on the local server, use:

<?php
$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:

<?php
$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:

<?php
$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:

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

Példa 1. imap_open() example

<?php
$mbox = imap_open("{your.imap.host:143}", "username", "password");

echo "<p><h1>Mailboxes</h1>\n";
$folders = imap_listmailbox($mbox, "{your.imap.host:143}", "*");

if ($folders == false) {
    echo "Call failed<br />\n";
} else {
    while (list ($key, $val) = each($folders)) {
        echo $val . "<br />\n";
    }
}

echo "<p><h1>Headers in INBOX</h1>\n";
$headers = imap_headers($mbox);

if ($headers == false) {
    echo "Call failed<br />\n";
} else {
    while (list ($key, $val) = each ($headers)) {
        echo $val . "<br />\n";
    }
}

imap_close($mbox);
?>

imap_ping

(PHP 3, PHP 4 )

imap_ping -- Check if the IMAP stream is still active

Description

bool imap_ping ( resource imap_stream)

Returns TRUE if the stream is still alive, FALSE otherwise.

imap_ping() function pings the stream to see it is 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. (As PHP scripts do not tend to run that long, I can hardly imagine that this function will be useful to anyone.)

imap_qprint

(PHP 3, PHP 4 )

imap_qprint -- Convert a quoted-printable string to an 8 bit string

Description

string imap_qprint ( string string)

Convert a quoted-printable string to an 8 bit string (according to RFC2045, section 6.7).

Returns an 8 bit (binary) string.

See also imap_8bit().

imap_renamemailbox

(PHP 3, PHP 4 )

imap_renamemailbox -- Rename an old mailbox to new mailbox

Description

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

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

See also imap_createmailbox(), imap_deletemailbox(), and imap_open() for the format of mbox.

imap_reopen

(PHP 3, PHP 4 )

imap_reopen -- Reopen IMAP stream to new mailbox

Description

bool imap_reopen ( resource imap_stream, string mailbox [, string options])

This function reopens the specified stream to a new mailbox on an IMAP or NNTP server.

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

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

imap_rfc822_parse_adrlist

(PHP 3>= 3.0.2, PHP 4 )

imap_rfc822_parse_adrlist -- Parses an address string

Description

array imap_rfc822_parse_adrlist ( string address, string default_host)

This function parses the address string as defined in RFC2822 and for each address, 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

Példa 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 $val) {
  echo "mailbox : " . $val->mailbox . "<br />\n";
  echo "host    : " . $val->host . "<br />\n";
  echo "personal: " . $val->personal . "<br />\n";
  echo "adl     : " . $val->adl . "<br />\n";
} 
?>

imap_rfc822_parse_headers

(PHP 4 )

imap_rfc822_parse_headers -- Parse mail headers from a string

Description

object imap_rfc822_parse_headers ( string headers [, string defaulthost])

This function returns an object of various header elements, similar to imap_header(), except without the flags and other elements that come from the IMAP server.

imap_rfc822_write_address

(PHP 3>= 3.0.2, PHP 4 )

imap_rfc822_write_address --  Returns a properly formatted email address given the mailbox, host, and personal info.

Description

string imap_rfc822_write_address ( string mailbox, string host, string personal)

Returns a properly formatted email address as defined in RFC2822 given the mailbox, host, and personal info.

Példa 1. imap_rfc822_write_address() example

<?php
echo imap_rfc822_write_address("hartmut", "cvs.php.net", "Hartmut Holzgraefe") . "\n";      
?>

imap_scanmailbox

imap_scanmailbox -- Alias of imap_listscan()

Description

This function is an alias of imap_listscan().

imap_search

(PHP 3>= 3.0.12, PHP 4 )

imap_search --  This function returns an array of messages matching the given search criteria

Description

array imap_search ( resource imap_stream, string criteria, int options)

This function performs a search on the mailbox currently opened in the given imap stream. criteria is a string, delimited by spaces, in which the following keywords are allowed. Any multi-word arguments (e.g. FROM "joey smith") must be quoted.

  • 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

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

Valid values for flags are SE_UID, which causes the returned array to contain UIDs instead of messages sequence numbers.

imap_set_quota

(PHP 4 >= 4.0.5)

imap_set_quota -- Sets a quota for a given mailbox

Description

bool imap_set_quota ( resource imap_stream, string quota_root, int quota_limit)

Sets an upper limit quota on a per mailbox basis. This function requires the imap_stream to have been opened as the mail administrator account. It will not work if opened as any other user.

This function is currently only available to users of the c-client2000 or greater library.

imap_stream is the stream pointer returned from a imap_open() call. This stream must be opened as the mail administrator, other wise this function will fail. quota_root is the mailbox to have a quota set. This should follow the IMAP standard format for a mailbox, 'user.name'. quota_limit is the maximum size (in KB) for the quota_root.

Returns TRUE on success and FALSE on error.

Példa 1. imap_set_quota() example

<?php
$mbox = imap_open("{your.imap.host:143}", "mailadmin", "password");

if (!imap_set_quota($mbox, "user.kalowsky", 3000)) {
    echo "Error in setting quota\n";
    return;
}

imap_close($mbox);
?>

See also imap_open() and imap_set_quota().

imap_setacl

(PHP 4 >= 4.1.0)

imap_setacl --  Sets the ACL for a giving mailbox

Description

bool imap_setacl ( resource stream_id, string mailbox, string id, string rights)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

imap_setflag_full

(PHP 3>= 3.0.3, PHP 4 )

imap_setflag_full -- Sets flags on messages

Description

bool imap_setflag_full ( resource stream, string sequence, string flag, string options)

This function causes a store to add the specified flag to the flags set for the messages in the specified sequence.

The flags which you can set are "\\Seen", "\\Answered", "\\Flagged", "\\Deleted", and "\\Draft" (as defined by RFC2060).

The options are a bit mask with one or more of the following:


ST_UID          The sequence argument contains UIDs instead of
                sequence numbers
      

Példa 1. imap_setflag_full() example

<?php
$mbox = imap_open("{your.imap.host: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);
?>

imap_sort

(PHP 3>= 3.0.3, PHP 4 )

imap_sort -- Sort an array of message headers

Description

array imap_sort ( resource stream, int criteria, int reverse [, int options [, string search_criteria]])

Returns an array of message numbers sorted by the given parameters.

Reverse is 1 for reverse-sorting.

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
      

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

imap_status

(PHP 3>= 3.0.4, PHP 4 )

imap_status --  This function returns status information on a mailbox other than the current one

Description

object imap_status ( resource imap_stream, string mailbox, int options)

This function returns an object containing status information. 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

status->flags is also set, which contains a bitmask which can be checked against any of the above constants.

Példa 1. imap_status() example

<?php
$mbox = imap_open("{your.imap.host}", "username", "password", OP_HALFOPEN)
      or die("can't connect: " . imap_last_error());
 
$status = imap_status($mbox, "{your.imap.host}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_subscribe

(PHP 3, PHP 4 )

imap_subscribe -- Subscribe to a mailbox

Description

bool imap_subscribe ( resource imap_stream, string mbox)

Subscribe to a new mailbox.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

imap_thread

(PHP 4 >= 4.1.0)

imap_thread --  Return threaded by REFERENCES tree

Description

array imap_thread ( resource stream_id [, int options])

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

imap_timeout

(no version information, might be only in CVS)

imap_timeout --  Set or fetch imap timeout

Description

mixed imap_timeout ( int timeout_type [, int timeout])

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

imap_uid

(PHP 3>= 3.0.3, PHP 4 )

imap_uid --  This function returns the UID for the given message sequence number

Description

int imap_uid ( resource imap_stream, int msgno)

This function returns the UID for the given message sequence number. An UID is an 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().

Megjegyzés: This is not supported by POP3 mailboxes.

imap_undelete

(PHP 3, PHP 4 )

imap_undelete --  Unmark the message which is marked deleted

Description

bool imap_undelete ( resource imap_stream, int msg_number)

This function removes the deletion flag for a specified message, which is set by imap_delete() or imap_mail_move().

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

imap_unsubscribe

(PHP 3, PHP 4 )

imap_unsubscribe -- Unsubscribe from a mailbox

Description

bool imap_unsubscribe ( string imap_stream, string mbox)

Unsubscribe from a specified mailbox.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

imap_utf7_decode

(PHP 3>= 3.0.15, PHP 4 )

imap_utf7_decode --  Decodes a modified UTF-7 encoded string.

Description

string imap_utf7_decode ( string text)

Decodes modified UTF-7 text into ISO-8859-1 string.

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. This function is needed to decode mailbox names that contain certain characters which are not in range of printable ASCII characters. The modified UTF-7 encoding is defined in RFC 2060, section 5.1.3 (original UTF-7 was defined in RFC1642).

imap_utf7_encode

(PHP 3>= 3.0.15, PHP 4 )

imap_utf7_encode --  Converts ISO-8859-1 string to modified UTF-7 text.

Description

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. Note that data is expected to be encoded in ISO-8859-1. The modified UTF-7 encoding is defined in RFC 2060, section 5.1.3 (original UTF-7 was defined in RFC1642).

Returns the modified UTF-7 text.

imap_utf8

(PHP 3>= 3.0.13, PHP 4 )

imap_utf8 --  Converts MIME-encoded text to UTF-8

Description

string imap_utf8 ( string mime_encoded_text)

Converts the given mime_encoded_text to UTF-8. MIME encoding method and the UTF-8 specification are described in RFC2047 and RFC2044 respectively.

XLIII. Informix functions

Bevezetés

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


Követelmények

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.


Telepítés

To be able to use the functions defined in this module you must compile your PHP interpreter using the configure line --with_informix[=DIR], where DIR is the Informix base install directory, defaults to nothing.


Futásidejű beállítások

Az alábbi függvények viselkedése befolyásolható a php.ini segítségével.

Megjegyzés: 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).

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

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

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.

Táblázat 1. Informix configuration options

NameDefaultChangeable
ifx.allow_persistent"1"PHP_INI_SYSTEM
ifx.max_persistent"-1"PHP_INI_SYSTEM
ifx.max_links"-1"PHP_INI_SYSTEM
ifx.default_hostNULLPHP_INI_SYSTEM
ifx.default_userNULLPHP_INI_SYSTEM
ifx.default_passwordNULLPHP_INI_SYSTEM
ifx.blobinfile"1"PHP_INI_ALL
ifx.textasvarchar"0"PHP_INI_ALL
ifx.byteasvarchar"0"PHP_INI_ALL
ifx.charasvarchar"0"PHP_INI_ALL
ifx.nullformat"0"PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().

Here's a short explanation of the configuration directives.

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

ifx.default_user string

The default user id to use when none is specified in ifx_connect() or ifx_pconnect(). Doesn't apply in safe mode.

ifx.default_password string

The default password to use when none is specified in ifx_connect() or ifx_pconnect(). Doesn't apply in safe mode.

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


Erőforrás típusok


Előre definiált állandók

Ez a kiterjesztés semmilyen konstans értéket nem definiál.

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

ifx_affected_rows

(PHP 3>= 3.0.3, PHP 4 )

ifx_affected_rows -- Get number of rows affected by a query

Description

int ifx_affected_rows ( int result_id)

result_id is a valid result id returned by ifx_query() or ifx_prepare().

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.

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

See also ifx_num_rows().

ifx_blobinfile_mode

(PHP 3>= 3.0.4, PHP 4 )

ifx_blobinfile_mode -- Set the default blob mode for all select queries

Description

void ifx_blobinfile_mode ( int mode)

Set the default blob mode for all select queries. Mode "0" means save Byte-Blobs in memory, and mode "1" means save Byte-Blobs in a file.

ifx_byteasvarchar

(PHP 3>= 3.0.4, PHP 4 )

ifx_byteasvarchar -- Set the default byte mode

Description

void ifx_byteasvarchar ( int mode)

Sets the default byte mode for all select-queries. Mode "0" will return a blob id, and mode "1" will return a varchar with text content.

ifx_close

(PHP 3>= 3.0.3, PHP 4 )

ifx_close -- Close Informix connection

Description

int ifx_close ( [int link_identifier])

Returns: always TRUE.

ifx_close() closes the link to an Informix 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.

ifx_close() will not close persistent links generated by ifx_pconnect().

Példa 1. Closing a Informix connection

<?php
$conn_id = ifx_connect ("mydb@ol_srv", "itsme", "mypassword");
/* ... some queries and stuff ... */
ifx_close($conn_id);
?>

See also ifx_connect() and ifx_pconnect().

ifx_connect

(PHP 3>= 3.0.3, PHP 4 )

ifx_connect -- Open Informix server connection

Description

int ifx_connect ( [string database [, string userid [, string password]]])

Returns a connection identifier on success, or FALSE on error.

ifx_connect() establishes a connection to an Informix server. All of the arguments are optional, and if they're missing, defaults are taken from values supplied in configuration file (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).

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

Példa 1. Connect to a Informix database

<?php
$conn_id = ifx_connect ("mydb@ol_srv1", "imyself", "mypassword");
?>

See also ifx_pconnect() and ifx_close().

ifx_copy_blob

(PHP 3>= 3.0.4, PHP 4 )

ifx_copy_blob -- Duplicates the given blob object

Description

int ifx_copy_blob ( int bid)

Duplicates the given blob object. bid is the ID of the blob object.

Returns FALSE on error otherwise the new blob object-id.

ifx_create_blob

(PHP 3>= 3.0.4, PHP 4 )

ifx_create_blob -- Creates an blob object

Description

int ifx_create_blob ( int type, int mode, string param)

Creates an blob object.

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.

Return FALSE on error, otherwise the new blob object-id.

ifx_create_char

(PHP 3>= 3.0.6, PHP 4 )

ifx_create_char -- Creates an char object

Description

int ifx_create_char ( string param)

Creates an char object. param should be the char content.

ifx_do

(PHP 3>= 3.0.4, PHP 4 )

ifx_do --  Execute a previously prepared SQL-statement

Description

int ifx_do ( int result_id)

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

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

See also: ifx_prepare().

ifx_error

(PHP 3>= 3.0.3, PHP 4 )

ifx_error -- Returns error code of last Informix call

Description

string ifx_error ( void )

The Informix error codes (SQLSTATE & SQLCODE) formatted as follows :

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

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. The format of the string is "(char) [SQLSTATE=(two digits) (three digits) SQLCODE=(one digit)]". The first character can be ' ' (space) (success), 'W' (the statement caused some warning), 'E' (an error happened when executing the statement) or 'N' (the statement didn't return any data).

See also: ifx_errormsg()

ifx_errormsg

(PHP 3>= 3.0.4, PHP 4 )

ifx_errormsg -- Returns error message of last Informix call

Description

string ifx_errormsg ( [int errorcode])

Returns the Informix error message associated with the most recent Informix error, or, when the optional "errorcode" parameter is present, the error message corresponding to "errorcode".

Példa 1. ifx_errormsg() example

printf("%s\n&lt;br>", ifx_errormsg(-201));

See also ifx_error().

ifx_fetch_row

(PHP 3>= 3.0.3, PHP 4 )

ifx_fetch_row -- Get row as enumerated array

Description

array ifx_fetch_row ( int result_id [, mixed position])

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. Returns FALSE on error

result_id is a valid resultid returned by ifx_query() or ifx_prepare() (select type queries only!).

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

ifx_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, with the column name as key.

Subsequent calls to ifx_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.

Példa 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_fieldproperties

(PHP 3>= 3.0.3, PHP 4 )

ifx_fieldproperties -- List of SQL fieldproperties

Description

array ifx_fieldproperties ( int result_id)

Returns an associative array with fieldnames as key and the SQL fieldproperties as data for a query with result_id. Returns FALSE on error.

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

Példa 1. Informix SQL fieldproperties

<?php
$properties = ifx_fieldproperties ($resultid);
if (! isset($properties)) {
    /* ... error ... */
}
for ($i = 0; $i < count($properties); $i++) {
    $fname = key ($properties);
    printf ("%s:\t type =  %s\n", $fname, $properties[$fname]);
    next ($properties);
}
?>

ifx_fieldtypes

(PHP 3>= 3.0.3, PHP 4 )

ifx_fieldtypes -- List of Informix SQL fields

Description

array ifx_fieldtypes ( int result_id)

Returns an associative array with fieldnames as key and the SQL fieldtypes as data for query with result_id. Returns FALSE on error.

Példa 1. Fieldnames and SQL fieldtypes

<?php
$types = ifx_fieldtypes ($resultid);
if (! isset ($types)) {
    /* ... error ... */
}
for ($i = 0; $i < count($types); $i++) {
    $fname = key($types);
    printf("%s :\t type =  %s\n", $fname, $types[$fname]);
    next($types);
}
?>

ifx_free_blob

(PHP 3>= 3.0.4, PHP 4 )

ifx_free_blob -- Deletes the blob object

Description

int ifx_free_blob ( int bid)

Deletes the blobobject for the given blob object-id bid. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

ifx_free_char

(PHP 3>= 3.0.6, PHP 4 )

ifx_free_char -- Deletes the char object

Description

int ifx_free_char ( int bid)

Deletes the charobject for the given char object-id bid. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

ifx_free_result

(PHP 3>= 3.0.3, PHP 4 )

ifx_free_result -- Releases resources for the query

Description

int ifx_free_result ( int result_id)

Releases resources for the query associated with result_id. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

ifx_get_blob

(PHP 3>= 3.0.4, PHP 4 )

ifx_get_blob -- Return the content of a blob object

Description

int ifx_get_blob ( int bid)

Returns the content of the blob object for the given blob object-id bid.

ifx_get_char

(PHP 3>= 3.0.6, PHP 4 )

ifx_get_char -- Return the content of the char object

Description

int ifx_get_char ( int bid)

Returns the content of the char object for the given char object-id bid.

ifx_getsqlca

(PHP 3>= 3.0.8, PHP 4 )

ifx_getsqlca --  Get the contents of sqlca.sqlerrd[0..5] after a query

Description

array ifx_getsqlca ( int result_id)

result_id is a valid result id returned by ifx_query() or ifx_prepare().

Returns a pseudo-row (associative array) 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.

Példa 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_htmltbl_result

(PHP 3>= 3.0.3, PHP 4 )

ifx_htmltbl_result --  Formats all rows of a query into a HTML table

Description

int ifx_htmltbl_result ( int result_id [, string html_table_options])

Returns the number of rows fetched or FALSE on error.

Formats all rows of the result_id query into a HTML table. The optional second argument is a string of <table> tag options

Példa 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_nullformat

(PHP 3>= 3.0.4, PHP 4 )

ifx_nullformat --  Sets the default return value on a fetch row

Description

void ifx_nullformat ( int mode)

Sets the default return value of a NULL-value on a fetch row. Mode "0" returns "", and mode "1" returns "NULL".

ifx_num_fields

(PHP 3>= 3.0.3, PHP 4 )

ifx_num_fields -- Returns the number of columns in the query

Description

int ifx_num_fields ( int result_id)

Returns the number of columns in query for result_id or FALSE on error

After preparing or executing a query, this call gives you the number of columns in the query.

ifx_num_rows

(PHP 3>= 3.0.3, PHP 4 )

ifx_num_rows -- Count the rows already fetched from a query

Description

int ifx_num_rows ( int result_id)

Gives the number of rows fetched so far for a query with result_id after a ifx_query() or ifx_do() query.

ifx_pconnect

(PHP 3>= 3.0.3, PHP 4 )

ifx_pconnect -- Open persistent Informix connection

Description

int ifx_pconnect ( [string database [, string userid [, string password]]])

Returns: A positive Informix persistent link identifier on success, or FALSE on error

ifx_pconnect() acts very much like ifx_connect() with two major differences.

This function behaves exactly like ifx_connect() when PHP is not running as an Apache module. 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'.

See also: ifx_connect().

ifx_prepare

(PHP 3>= 3.0.4, PHP 4 )

ifx_prepare -- Prepare an SQL-statement for execution

Description

int ifx_prepare ( string query, int conn_id [, int cursor_def, mixed blobidarray])

Returns an integer result_id for use by ifx_do(). Sets affected_rows for retrieval by the ifx_affected_rows() function.

Prepares query on connection conn_id. For "select-type" queries a cursor is declared and opened. The optional cursor_type 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.

For either query type the estimated number of affected rows is saved for retrieval by ifx_affected_rows().

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.

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

See also: ifx_do().

ifx_query

(PHP 3>= 3.0.3, PHP 4 )

ifx_query -- Send Informix query

Description

int ifx_query ( string query, int link_identifier [, int cursor_type [, mixed blobidarray]])

Returns a positive Informix result identifier on success, or FALSE on error.

A "result_id" resource used by other functions to retrieve the query results. Sets "affected_rows" for retrieval by the ifx_affected_rows() function.

ifx_query() sends a query to the currently active database on the server that's associated with the specified link identifier.

Executes query on connection conn_id. For "select-type" queries a cursor is declared and opened. The optional cursor_type 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. Non-select queries are "execute immediate". IFX_SCROLL and IFX_HOLD are symbolic constants and as such shouldn't be between quotes. I you omit this parameter the cursor is a normal sequential cursor.

For either query type the number of (estimated or real) affected rows is saved for retrieval by ifx_affected_rows().

If you have BLOB (BYTE or TEXT) columns in an update query, you can add a blobidarray parameter containing the corresponding "blob ids", and you should replace those columns with a "?" in the query text.

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

Példa 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);
?>

Példa 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);
?>

See also ifx_connect().

ifx_textasvarchar

(PHP 3>= 3.0.4, PHP 4 )

ifx_textasvarchar -- Set the default text mode

Description

void ifx_textasvarchar ( int mode)

Sets the default text mode for all select-queries. Mode "0" will return a blob id, and mode "1" will return a varchar with text content.

ifx_update_blob

(PHP 3>= 3.0.4, PHP 4 )

ifx_update_blob -- Updates the content of the blob object

Description

bool ifx_update_blob ( int bid, string content)

Updates the content of the blob object for the given blob object bid. content is a string with new data. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

ifx_update_char

(PHP 3>= 3.0.6, PHP 4 )

ifx_update_char -- Updates the content of the char object

Description

int ifx_update_char ( int bid, string content)

Updates the content of the char object for the given char object bid. content is a string with new data. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

ifxus_close_slob

(PHP 3>= 3.0.4, PHP 4 )

ifxus_close_slob -- Deletes the slob object

Description

int ifxus_close_slob ( int bid)

Deletes the slob object on the given slob object-id bid. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

ifxus_create_slob

(PHP 3>= 3.0.4, PHP 4 )

ifxus_create_slob -- Creates an slob object and opens it

Description

int ifxus_create_slob ( int mode)

Creates an slob object and opens it. Modes: 1 = LO_RDONLY, 2 = LO_WRONLY, 4 = LO_APPEND, 8 = LO_RDWR, 16 = LO_BUFFER, 32 = LO_NOBUFFER -> or-mask. You can also use constants named IFX_LO_RDONLY, IFX_LO_WRONLY etc. Return FALSE on error otherwise the new slob object-id.

ifxus_free_slob

(PHP 3>= 3.0.4, PHP 4 )

ifxus_free_slob -- Deletes the slob object

Description

int ifxus_free_slob ( int bid)

Deletes the slob object. bid is the Id of the slob object. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

ifxus_open_slob

(PHP 3>= 3.0.4, PHP 4 )

ifxus_open_slob -- Opens an slob object

Description

int ifxus_open_slob ( long bid, int mode)

Opens an slob object. bid should be an existing slob id. Modes: 1 = LO_RDONLY, 2 = LO_WRONLY, 4 = LO_APPEND, 8 = LO_RDWR, 16 = LO_BUFFER, 32 = LO_NOBUFFER -> or-mask. Returns FALSE on error otherwise the new slob object-id.

ifxus_read_slob

(PHP 3>= 3.0.4, PHP 4 )

ifxus_read_slob -- Reads nbytes of the slob object

Description

int ifxus_read_slob ( long bid, long nbytes)

Reads nbytes of the slob object. bid is a existing slob id and nbytes is the number of bytes read. Return FALSE on error otherwise the string.

ifxus_seek_slob

(PHP 3>= 3.0.4, PHP 4 )

ifxus_seek_slob -- Sets the current file or seek position

Description

int ifxus_seek_slob ( long bid, int mode, long offset)

Sets the current file or seek position of an open slob object. bid should be an existing slob id. Modes: 0 = LO_SEEK_SET, 1 = LO_SEEK_CUR, 2 = LO_SEEK_END and offset is an byte offset. Return FALSE on error otherwise the seek position.

ifxus_tell_slob

(PHP 3>= 3.0.4, PHP 4 )

ifxus_tell_slob -- Returns the current file or seek position

Description

int ifxus_tell_slob ( long bid)

Returns the current file or seek position of an open slob object bid should be an existing slob id. Return FALSE on error otherwise the seek position.

ifxus_write_slob

(PHP 3>= 3.0.4, PHP 4 )

ifxus_write_slob -- Writes a string into the slob object

Description

int ifxus_write_slob ( long bid, string content)

Writes a string into the slob object. bid is an existing slob id and content the content to write. Return FALSE on error otherwise bytes written.

XLIV. InterBase functions

Bevezetés

InterBase is a popular database put out by Borland/Inprise. More information about InterBase is available at http://www.interbase.com/. Oh, by the way, InterBase just joined the open source movement!

Megjegyzés: Full support for InterBase 6 was added in PHP 4.0.

This database uses a single quote (') character for escaping, a behavior similar to the Sybase database, add to your php.ini the following directive:

magic_quotes_sybase = On


Követelmények


Telepítés

To enable InterBase support configure PHP --with-interbase[=DIR], where DIR is the InterBase base install directory, which defaults to /usr/interbase.

Note to Win32 Users: In order to enable this module on a Windows environment, you must copy gds32.dll from the DLL folder of the PHP/Win32 binary package to the SYSTEM32 folder of your windows machine. (Ex: C:\WINNT\SYSTEM32 or C:\WINDOWS\SYSTEM32). In case you installed the InterBase database server on the same machine PHP is running on, you will have this DLL already. Therefore you don't need to copy gds32.dll from the DLL folder.


Futásidejű beállítások

Az alábbi függvények viselkedése befolyásolható a php.ini segítségével.

Táblázat 1. InterBase configuration options

NameDefaultChangeable
ibase.allow_persistent"1"PHP_INI_SYSTEM
ibase.max_persistent"-1"PHP_INI_SYSTEM
ibase.max_links"-1"PHP_INI_SYSTEM
ibase.default_userNULLPHP_INI_ALL
ibase.default_passwordNULLPHP_INI_ALL
ibase.timestampformat"%m/%d/%Y%H:%M:%S"PHP_INI_ALL
ibase.dateformat"%m/%d/%Y"PHP_INI_ALL
ibase.timeformat"%H:%M:%S"PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().


Erőforrás típusok


Előre definiált állandók

Az itt listázott állandókat ez a kiterjesztés definiálja, és csak akkor elérhetőek, ha az adott kiterjesztés be van fordítva a PHP-be, vagy dinamikusan betöltött.

IBASE_DEFAULT (integer)

IBASE_TEXT (integer)

IBASE_UNIXTIME (integer)

IBASE_WRITE (integer)

Access mode

IBASE_READ (integer)

Access mode

IBASE_COMMITTED (integer)

Isolation level

IBASE_CONSISTENCY (integer)

Isolation level

IBASE_CONCURRENCY (integer)

Isolation level (default)

IBASE_REC_VERSION (integer)

IBASE_REC_NO_VERSION (integer)

IBASE_NOWAIT (integer)

Lock resolution

IBASE_WAIT (integer)

Lock resolution (default)

IBASE_TIMESTAMP (integer)

IBASE_DATE (integer)

IBASE_TIME (integer)

Tartalom
ibase_add_user --  Add a user to a security database (only for IB6 or later)
ibase_affected_rows --  Return the number of rows that were affected by the previous query
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 an InterBase database
ibase_delete_user --  Delete a user from a security database (only for IB6 or later)
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_modify_user --  Modify a user to a security database (only for IB6 or later)
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_rollback_ret -- Roll back a transaction without closing it
ibase_rollback -- Roll back a transaction
ibase_set_event_handler --  Register a callback function to be called when events are posted
ibase_timefmt --  Sets the format of timestamp, date and time type columns returned from queries
ibase_trans -- Begin a transaction
ibase_wait_event --  Wait for an event to be posted by the database

ibase_add_user

(PHP 4 >= 4.2.0)

ibase_add_user --  Add a user to a security database (only for IB6 or later)

Description

bool ibase_add_user ( string server, string dba_user_name, string dba_user_password, string user_name, string password [, string first_name [, string middle_name [, string last_name]]])

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

See also ibase_modify_user() and ibase_delete_user().

ibase_affected_rows

(no version information, might be only in CVS)

ibase_affected_rows --  Return the number of rows that were affected by the previous query

Description

int ibase_affected_rows ( resource link_identifier)

This function returns the number of rows that were affected by the previous query that was executed from within the transaction context specified by link_identifier. If link_identifier is a connection resource, its default transaction is used.

See also ibase_query() and ibase_execute().

ibase_blob_add

(PHP 3>= 3.0.7, PHP 4 )

ibase_blob_add --  Add data into a newly created blob

Description

bool ibase_blob_add ( resource blob_handle, string data)

ibase_blob_add() adds data into a blob created with ibase_blob_create(). Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

See also ibase_blob_cancel(), ibase_blob_close(), ibase_blob_create() and ibase_blob_import().

ibase_blob_cancel

(PHP 3>= 3.0.7, PHP 4 )

ibase_blob_cancel --  Cancel creating blob

Description

bool ibase_blob_cancel ( resource blob_handle)

This function will discard a BLOB created by ibase_create_blob() if it has not yet been closed by ibase_blob_close(). Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

See also ibase_blob_close(), ibase_blob_create() and ibase_blob_import().

ibase_blob_close

(PHP 3>= 3.0.7, PHP 4 )

ibase_blob_close --  Close blob

Description

mixed ibase_blob_close ( resource blob_handle)

This function closes a BLOB that has either been opened for reading by ibase_open_blob() or has been opened for writing by ibase_create_blob(). 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.

See also ibase_blob_cancel() and ibase_blob_open().

ibase_blob_create

(PHP 3>= 3.0.7, PHP 4 )

ibase_blob_create --  Create a new blob for adding data

Description

resource ibase_blob_create ( [resource link_identifier])

ibase_blob_create() creates a new BLOB for filling with data. It returns a BLOB handle for later use with ibase_blob_add() or FALSE on failure.

See also ibase_blob_add(), ibase_blob_cancel(), ibase_blob_close() and ibase_blob_import().

ibase_blob_echo

(PHP 3>= 3.0.7, PHP 4 )

ibase_blob_echo --  Output blob contents to browser

Description

bool ibase_blob_echo ( string blob_id)

This function opens a BLOB for reading and sends its contents directly to standard output (the browser, in most cases). Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

See also ibase_blob_open(), ibase_blob_close() and ibase_blob_get().

ibase_blob_get

(PHP 3>= 3.0.7, PHP 4 )

ibase_blob_get --  Get len bytes data from open blob

Description

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(). Returns FALSE on failure.

<?php
    $sql       = "SELECT blob_value FROM table";
    $result    = ibase_query($sql);
    $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.

Megjegyzés: It is not possible to read from a BLOB that has been opened for writing by ibase_blob_create().

See also ibase_blob_open(), ibase_blob_close() and ibase_blob_echo().

ibase_blob_import

(PHP 3>= 3.0.7, PHP 4 )

ibase_blob_import --  Create blob, copy file in it, and close it

Description

string ibase_blob_import ( [resource link_identifier, resource file_handle])

This function creates a BLOB, reads an entire file into it, closes it and returns the assigned BLOB id. The file handle is a handle returned by fopen(). Returns FALSE on failure.

See also ibase_blob_add(), ibase_blob_cancel(), ibase_blob_close() and ibase_blob_create().

ibase_blob_info

(PHP 3>= 3.0.7, PHP 4 )

ibase_blob_info --  Return blob length and other useful info

Description

array ibase_blob_info ( string blob_id)

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_open

(PHP 3>= 3.0.7, PHP 4 )

ibase_blob_open --  Open blob for retrieving data parts

Description

resource ibase_blob_open ( string blob_id)

ibase_blob_open() opens an existing BLOB for reading. It returns a BLOB handle for later use with ibase_blob_get() or FALSE on failure.

See also ibase_blob_close(), ibase_blob_echo() and ibase_blob_get().

ibase_close

(PHP 3>= 3.0.6, PHP 4 )

ibase_close --  Close a connection to an InterBase database

Description

bool ibase_close ( [resource connection_id])

Closes the link to an InterBase database that's associated with a connection id returned from ibase_connect(). If the connection id is omitted, the last opened link is assumed. Default transaction on link is committed, other transactions are rolled back. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

See also ibase_connect() and ibase_pconnect().

ibase_commit_ret

(no version information, might be only in CVS)

ibase_commit_ret -- Commit a transaction without closing it

Description

bool ibase_commit_ret ( [resource link_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. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

ibase_commit

(PHP 3>= 3.0.7, PHP 4 )

ibase_commit -- Commit a transaction

Description

bool ibase_commit ( [resource link_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. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

ibase_connect

(PHP 3>= 3.0.6, PHP 4 )

ibase_connect --  Open a connection to an InterBase database

Description

resource ibase_connect ( string database [, string username [, string password [, string charset [, int buffers [, int dialect [, string role]]]]]])

Establishes a connection to an InterBase server. 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 and password can also be specified with PHP configuration directives ibase.default_user and ibase.default_password. charset is the default character set for a database. buffers is the number of database buffers to allocate for the server-side cache. If 0 or omitted, server chooses its own default. dialect selects the default SQL dialect for any statement executed within a connection, and it defaults to the highest one supported by client libraries.

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

Példa 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);
?>

Megjegyzés: The optional buffers parameter was added in PHP 4.0.0.

Megjegyzés: The optional dialect parameter was added in PHP 4.0.0 and is functional only with InterBase 6 and up.

Megjegyzés: The optional role parameter was added in PHP 4.0.0 and is functional only with InterBase 5 and up.

Megjegyzés: 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).

See also ibase_pconnect() and ibase_close().

ibase_delete_user

(PHP 4 >= 4.2.0)

ibase_delete_user --  Delete a user from a security database (only for IB6 or later)

Description

bool ibase_delete_user ( string server, string dba_user_name, string dba_user_password, string user_name)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

See also ibase_add_user() and ibase_modify_user().

ibase_drop_db

(no version information, might be only in CVS)

ibase_drop_db --  Drops a database

Description

bool ibase_drop_db ( resource connection)

This functions drops a database that was opened by either ibase_connect() or ibase_pconnect(). The database is closed and deleted from the server. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

See also ibase_connect() and ibase_pconnect().

ibase_errcode

(no version information, might be only in CVS)

ibase_errcode --  Return an error code

Description

int ibase_errcode ( void )

Returns the error code that resulted from the most recent InterBase function call. Returns FALSE if no error occurred.

See also ibase_errmsg().

ibase_errmsg

(PHP 3>= 3.0.7, PHP 4 )

ibase_errmsg --  Return error messages

Description

string ibase_errmsg ( void )

Returns the error message that resulted from the most recent InterBase function call. Returns FALSE if no error occurred.

See also ibase_errcode().

ibase_execute

(PHP 3>= 3.0.6, PHP 4 )

ibase_execute -- Execute a previously prepared query

Description

resource ibase_execute ( resource query [, int bind_args])

Execute a query prepared by ibase_prepare(). 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.

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.

Példa 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 = ?");

    while (list($baz, $bar) = each($updates)) {
        ibase_execute($query, $bar, $baz);
    }
?>

Megjegyzés: In PHP 5.0.0 and up, 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.

See also ibase_query().

ibase_fetch_assoc

(PHP 4 >= 4.3.0)

ibase_fetch_assoc --  Fetch a result row from a query as an associative array

Description

array ibase_fetch_assoc ( resource result [, int fetch_flag])

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

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.

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.

See also ibase_fetch_row() and ibase_fetch_object().

ibase_fetch_object

(PHP 3>= 3.0.7, PHP 4 )

ibase_fetch_object -- Get an object from a InterBase database

Description

object ibase_fetch_object ( resource result_id [, int fetch_flag])

Fetches a row as a pseudo-object from a result_id obtained either by ibase_query() or ibase_execute().

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

Subsequent calls to ibase_fetch_object() return the next row in the result set, or FALSE if there are no more rows.

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.

See also ibase_fetch_row() and ibase_fetch_assoc().

ibase_fetch_row

(PHP 3>= 3.0.6, PHP 4 )

ibase_fetch_row -- Fetch a row from an InterBase database

Description

array ibase_fetch_row ( resource result_identifier [, int fetch_flag])

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

ibase_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 calls to ibase_fetch_row() return the next row in the result set, or FALSE if there are no more rows.

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.

See also ibase_fetch_assoc() and ibase_fetch_object().

ibase_field_info

(PHP 3>= 3.0.7, PHP 4 )

ibase_field_info --  Get information about a field

Description

array ibase_field_info ( resource result, int field_number)

Returns an array with information about a field after a select query has been run. The array is in the form of name, alias, relation, length, type.

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

See also: ibase_num_fields().

ibase_free_event_handler

(no version information, might be only in CVS)

ibase_free_event_handler --  Cancels a registered event handler

Description

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. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

See also ibase_set_event_handler().

ibase_free_query

(PHP 3>= 3.0.6, PHP 4 )

ibase_free_query --  Free memory allocated by a prepared query

Description

bool ibase_free_query ( resource query)

Free a query prepared by ibase_prepare(). Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

ibase_free_result

(PHP 3>= 3.0.6, PHP 4 )

ibase_free_result -- Free a result set

Description

bool ibase_free_result ( resource result_identifier)

Frees a result set that has been created by ibase_query() or ibase_execute(). Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

ibase_gen_id

(no version information, might be only in CVS)

ibase_gen_id --  Increments the named generator and returns its new value

Description

int ibase_gen_id ( [resource link_identifier [, string generator [, int increment]]])

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ibase_modify_user

(PHP 4 >= 4.2.0)

ibase_modify_user --  Modify a user to a security database (only for IB6 or later)

Description

bool ibase_modify_user ( string server, string dba_user_name, string dba_user_password, string user_name, string password [, string first_name [, string middle_name [, string last_name]]])

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

See also ibase_add_user() and ibase_delete_user().

ibase_name_result

(no version information, might be only in CVS)

ibase_name_result --  Assigns a name to a result set

Description

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. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

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

See also ibase_prepare() and ibase_execute().

ibase_num_fields

(PHP 3>= 3.0.7, PHP 4 )

ibase_num_fields --  Get the number of fields in a result set

Description

int ibase_num_fields ( resource result_id)

Returns an integer containing the number of fields in a result set.

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

See also: ibase_field_info().

ibase_num_params

(no version information, might be only in CVS)

ibase_num_params --  Return the number of parameters in a prepared query

Description

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

See also ibase_prepare() and ibase_param_info().

ibase_param_info

(no version information, might be only in CVS)

ibase_param_info --  Return information about a parameter in a prepared query

Description

array ibase_param_info ( resource query, int param_number)

Returns an array with information about a parameter after a query has been prepared. The array is in the form of name, alias, relation, length, type.

See also ibase_field_info() and ibase_num_params().

ibase_pconnect

(PHP 3>= 3.0.6, PHP 4 )

ibase_pconnect --  Open a persistent connection to an InterBase database

Description

resource ibase_pconnect ( string database [, string username [, string password [, string charset [, int buffers [, int dialect [, string role]]]]]])

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

Megjegyzés: buffers was added in PHP4-RC2.

Megjegyzés: dialect was added in PHP4-RC2. It is functional only with InterBase 6 and versions higher than that.

Megjegyzés: role was added in PHP4-RC2. It is functional only with InterBase 5 and versions higher than that.

See also ibase_close() and ibase_connect() for the meaning of parameters passed to this function. They are exactly the same.

ibase_prepare

(PHP 3>= 3.0.6, PHP 4 )

ibase_prepare --  Prepare a query for later binding of parameter placeholders and execution

Description

resource ibase_prepare ( [resource link_identifier, string query])

Prepare a query for later binding of parameter placeholders and execution (via ibase_execute()).

ibase_query

(PHP 3>= 3.0.6, PHP 4 )

ibase_query -- Execute a query on an InterBase database

Description

resource ibase_query ( [resource link_identifier, string query [, int bind_args]])

Performs a query on an InterBase database. 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.

Példa 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());

?>

Megjegyzés: 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.

Megjegyzés: 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).

See also ibase_errmsg(), ibase_fetch_row(), ibase_fetch_object(), and ibase_free_result().

ibase_rollback_ret

(no version information, might be only in CVS)

ibase_rollback_ret -- Roll back a transaction without closing it

Description

bool ibase_rollback_ret ( [resource link_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. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

ibase_rollback

(PHP 3>= 3.0.7, PHP 4 )

ibase_rollback -- Roll back a transaction

Description

bool ibase_rollback ( [resource link_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. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

ibase_set_event_handler

(no version information, might be only in CVS)

ibase_set_event_handler --  Register a callback function to be called when events are posted

Description

resource ibase_set_event_handler ( [resource connection, callback event_handler, string event_name1 [, string event_name2 [, string ...]]])

This function registers a PHP user function as event handler for the specified events. 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.

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

The return value is an event resource. This resource can be used to free the event handler using ibase_free_event_handler().

See also ibase_free_event_handler() and ibase_wait_event().

ibase_timefmt

(PHP 3>= 3.0.6, PHP 4 )

ibase_timefmt --  Sets the format of timestamp, date and time type columns returned from queries

Description

int ibase_timefmt ( string format [, int columntype])

Sets the format of timestamp, date or time type columns returned from queries. Internally, the columns are formatted by c-function strftime(), so refer to it's documentation regarding to the format of the string. columntype is one of the constants IBASE_TIMESTAMP, IBASE_DATE and IBASE_TIME. If omitted, defaults to IBASE_TIMESTAMP for backwards compatibility.

<?php
    /* InterBase 6 TIME-type columns will be returned in
     * the form '05 hours 37 minutes'. */
    ibase_timefmt("%H hours %M minutes", IBASE_TIME);
?>

You can also set defaults for these formats with PHP configuration directives ibase.timestampformat, ibase.dateformat and ibase.timeformat.

Megjegyzés: columntype was added in PHP 4.0. It has any meaning only with InterBase version 6 and higher.

Megjegyzés: A backwards incompatible change happened in PHP 4.0 when PHP configuration directive ibase.timeformat was renamed to ibase.timestampformat and directives ibase.dateformat and ibase.timeformat were added, so that the names would match better their functionality.

ibase_trans

(PHP 3>= 3.0.7, PHP 4 )

ibase_trans -- Begin a transaction

Description

resource ibase_trans ( [int trans_args [, resource link_identifier]])

Begins a transaction.

trans_args can be a combination of IBASE_READ, IBASE_WRITE, IBASE_COMMITED, IBASE_CONSISTENCY, IBASE_CONCURRENCY, IBASE_REC_VERSION, IBASE_REC_NO_VERSION, IBASE_WAIT and IBASE_NOWAIT.

Megjegyzés: The behaviour of this function has been changed in PHP 5.0.0. 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().

Megjegyzés: In PHP 5.0.0. and up, 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().

ibase_wait_event

(no version information, might be only in CVS)

ibase_wait_event --  Wait for an event to be posted by the database

Description

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.

See also ibase_set_event_handler() and ibase_free_event_handler().

XLV. Ingres II functions

Bevezetés

These functions allow you to access Ingres II database servers.

Megjegyzés: If you already used PHP extensions to access other database servers, note that Ingres doesn't allow concurrent queries and/or transaction over one connection, thus you won't find any result or transaction handle in this extension. The result of a query must be treated before sending another query, and a transaction must be committed or rolled back before opening another transaction (which is automatically done when sending the first query).

Figyelem

Ez a kiterjesztés KÍSÉRLETI JELLEGGEL MŰKÖDIK. Ez azt jelenti, hogy minden itt dokumentált működés, beleértve a függvények nevét, működését vagy bármi más, amit a kiterjesztés kapcsán leírtunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a kiterjesztést csak a saját felelősségedre használd!


Követelmények

To compile PHP with Ingres support, you need the Open API library and header files included with Ingres II.


Telepítés

In order to have these functions available, you must compile PHP with Ingres support by using the --with-ingres[=DIR] option, where DIR is the Ingres base directory, which defaults to /II/ingres. If the II_SYSTEM environment variable isn't correctly set you may have to use --with-ingres=DIR to specify your Ingres installation directory.

When using this extension with Apache, if Apache does not start and complains with "PHP Fatal error: Unable to start ingres_ii module in Unknown on line 0" then make sure the environment variable II_SYSTEM is correctly set. Adding "export II_SYSTEM="/home/ingres/II" in the script that starts Apache, just before launching httpd, should be fine.


Futásidejű beállítások

Az alábbi függvények viselkedése befolyásolható a php.ini segítségével.

Táblázat 1. Ingres II configuration options

NameDefaultChangeable
ingres.allow_persistent"1"PHP_INI_SYSTEM
ingres.max_persistent"-1"PHP_INI_SYSTEM
ingres.max_links"-1"PHP_INI_SYSTEM
ingres.default_databaseNULLPHP_INI_ALL
ingres.default_userNULLPHP_INI_ALL
ingres.default_passwordNULLPHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().


Erőforrás típusok

Ez a kiterjesztés semmilyen erőforrás típust nem definiál.


Előre definiált állandók

Az itt listázott állandókat ez a kiterjesztés definiálja, és csak akkor elérhetőek, ha az adott kiterjesztés be van fordítva a PHP-be, vagy dinamikusan betöltött.

INGRES_ASSOC (integer)

INGRES_NUM (integer)

INGRES_BOTH (integer)

Tartalom
ingres_autocommit -- Switch autocommit on or off
ingres_close -- Close an Ingres II database connection
ingres_commit -- Commit a transaction
ingres_connect --  Open a connection to an Ingres II database
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_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_num_fields --  Get the number of fields returned by the last query
ingres_num_rows --  Get the number of rows affected or returned by the last query
ingres_pconnect --  Open a persistent connection to an Ingres II database
ingres_query -- Send a SQL query to Ingres II
ingres_rollback -- Roll back a transaction

ingres_autocommit

(PHP 4 >= 4.0.2)

ingres_autocommit -- Switch autocommit on or off

Description

bool ingres_autocommit ( [resource link])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

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 the autocommit mode is on, every query is automatically committed by the server, as if ingres_commit() was called after every call to ingres_query().

See also ingres_query(), ingres_rollback(), and ingres_commit().

ingres_close

(PHP 4 >= 4.0.2)

ingres_close -- Close an Ingres II database connection

Description

bool ingres_close ( [resource link])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Returns TRUE on success, or FALSE on failure.

ingres_close() closes the connection to the Ingres server that's associated with the specified link. If the link parameter isn't specified, the last opened link is used.

ingres_close() isn't usually necessary, as it won't close persistent connections and all non-persistent connections are automatically closed at the end of the script.

See also ingres_connect() and ingres_pconnect().

ingres_commit

(PHP 4 >= 4.0.2)

ingres_commit -- Commit a transaction

Description

bool ingres_commit ( [resource link])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

ingres_commit() commits the currently open transaction, making all changes made to the database permanent.

This closes the transaction. A new one can be open 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.

See also ingres_query(), ingres_rollback(), and ingres_autocommit().

ingres_connect

(PHP 4 >= 4.0.2)

ingres_connect --  Open a connection to an Ingres II database

Description

resource ingres_connect ( [string database [, string username [, string password]]])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Returns a Ingres II link resource on success, or FALSE on failure.

ingres_connect() opens a connection with the Ingres database designated by database, which follows the syntax [node_id::]dbname[/svr_class].

If some parameters are missing, ingres_connect() uses the values in php.ini for ingres.default_database, ingres.default_user, and ingres.default_password.

The connection is closed when the script ends or when ingres_close() is called on this link.

All the other ingres functions use the last opened link as a default, so you need to store the returned value only if you use more than one link at a time.

Példa 1. ingres_connect() example

<?php
    $link = ingres_connect("mydb", "user", "pass")
        or die("Could not connect");
    echo "Connected successfully";
    ingres_close($link);
?>

Példa 2. ingres_connect() example using default link

<?php
    ingres_connect("mydb", "user", "pass")
        or die("Could not connect");
    echo "Connected successfully";
    ingres_close();
?>

See also ingres_pconnect() and ingres_close().

ingres_fetch_array

(PHP 4 >= 4.0.2)

ingres_fetch_array -- Fetch a row of result into an array

Description

array ingres_fetch_array ( [int result_type [, resource link]])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

ingres_fetch_array() Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

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 other column(s) of the same name, you must use the numeric index of the column or make an alias for the column.

<?php

ingres_query("select t1.f1 as foo t2.f1 as bar from t1, t2");
$result = ingres_fetch_array();
$foo = $result["foo"];
$bar = $result["bar"];

?>

result_type can be INGRES_NUM for enumerated array, INGRES_ASSOC for associative array, or INGRES_BOTH (default).

Speed-wise, the function is identical to ingres_fetch_object(), and almost as quick as ingres_fetch_row() (the difference is insignificant).

Példa 1. ingres_fetch_array() example

<?php
ingres_connect($database, $user, $password);

ingres_query("select * from table");
while ($row = ingres_fetch_array()) {
    echo $row["user_id"];  // using associative array
    echo $row["fullname"];
    echo $row[1];          // using enumerated array
    echo $row[2];
}
?>

See also ingres_query(), ingres_num_fields(), ingres_field_name(), ingres_fetch_object(), and ingres_fetch_row().

ingres_fetch_object

(PHP 4 >= 4.0.2)

ingres_fetch_object -- Fetch a row of result into an object.

Description

object ingres_fetch_object ( [int result_type [, resource link]])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

ingres_fetch_object() Returns an object that corresponds to the fetched row, or FALSE if there are no more rows.

This function is similar to ingres_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).

The optional argument result_type is a constant and can take the following values: INGRES_ASSOC, INGRES_NUM, and INGRES_BOTH.

Speed-wise, the function is identical to ingres_fetch_array(), and almost as quick as ingres_fetch_row() (the difference is insignificant).

Példa 1. ingres_fetch_object() example

<?php
ingres_connect($database, $user, $password);
ingres_query("select * from table");
while ($row = ingres_fetch_object()) {
    echo $row->user_id;
    echo $row->fullname;
}
?>

See also ingres_query(), ingres_num_fields(), ingres_field_name(), ingres_fetch_array(), and ingres_fetch_row().

ingres_fetch_row

(PHP 4 >= 4.0.2)

ingres_fetch_row --  Fetch a row of result into an enumerated array

Description

array ingres_fetch_row ( [resource link])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

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 call to ingres_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.

Példa 1. ingres_fetch_row() example

<?php
ingres_connect($database, $user, $password);

ingres_query("select * from table");
while ($row = ingres_fetch_row()) {
    echo $row[1];
    echo $row[2];
}
?>

See also ingres_num_fields(), ingres_query(), ingres_fetch_array(), and ingres_fetch_object().

ingres_field_length

(PHP 4 >= 4.0.2)

ingres_field_length -- Get the length of a field

Description

int ingres_field_length ( int index [, resource link])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

ingres_field_length() returns the length of a field. This is the number of bytes used by the server to store the field. For detailed information, see the Ingres/OpenAPI User Guide - Appendix C.

index is the number of the field and must be between 1 and the value given by ingres_num_fields().

See also ingres_query(), ingres_fetch_array(), ingres_fetch_object(), and ingres_fetch_row().

ingres_field_name

(PHP 4 >= 4.0.2)

ingres_field_name -- Get the name of a field in a query result.

Description

string ingres_field_name ( int index [, resource link])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

ingres_field_name() returns the name of a field in a query result, or FALSE on failure.

index is the number of the field and must be between 1 and the value given by ingres_num_fields().

See also ingres_query(), ingres_fetch_array(), ingres_fetch_object() and ingres_fetch_row().

ingres_field_nullable

(PHP 4 >= 4.0.2)

ingres_field_nullable -- Test if a field is nullable

Description

bool ingres_field_nullable ( int index [, resource link])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

ingres_field_nullable() returns TRUE if the field can be set to the NULL value and FALSE if it can't.

index is the number of the field and must be between 1 and the value given by ingres_num_fields().

See also ingres_query(), ingres_fetch_array(), ingres_fetch_object(), and ingres_fetch_row().

ingres_field_precision

(PHP 4 >= 4.0.2)

ingres_field_precision -- Get the precision of a field

Description

int ingres_field_precision ( int index [, resource link])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

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

index is the number of the field and must be between 1 and the value given by ingres_num_fields().

See also ingres_query(), ingres_fetch_array(), ingres_fetch_object(), and ingres_fetch_row().

ingres_field_scale

(PHP 4 >= 4.0.2)

ingres_field_scale -- Get the scale of a field

Description

int ingres_field_scale ( int index [, resource link])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

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

index is the number of the field and must be between 1 and the value given by ingres_num_fields().

See also ingres_query(), ingres_fetch_array(), ingres_fetch_object(), and ingres_fetch_row().

ingres_field_type

(PHP 4 >= 4.0.2)

ingres_field_type --  Get the type of a field in a query result

Description

string ingres_field_type ( int index [, resource link])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

ingres_field_type() returns the type of a field in a query result, or FALSE on failure. 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 C.

index is the number of the field and must be between 1 and the value given by ingres_num_fields().

See also ingres_query(), ingres_fetch_array(), ingres_fetch_object(), and ingres_fetch_row().

ingres_num_fields

(PHP 4 >= 4.0.2)

ingres_num_fields --  Get the number of fields returned by the last query

Description

int ingres_num_fields ( [resource link])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

ingres_num_fields() returns the number of fields in the results returned by the Ingres server after a call to ingres_query()

See also ingres_query(), ingres_fetch_array(), ingres_fetch_object(), and ingres_fetch_row().

ingres_num_rows

(PHP 4 >= 4.0.2)

ingres_num_rows --  Get the number of rows affected or returned by the last query

Description

int ingres_num_rows ( [resource link])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

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.

Megjegyzés: This function is mainly meant to get the number of rows modified in the database. If 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 won't be able to get them.

You should instead 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.

See also ingres_query(), ingres_fetch_array(), ingres_fetch_object(), and ingres_fetch_row().

ingres_pconnect

(PHP 4 >= 4.0.2)

ingres_pconnect --  Open a persistent connection to an Ingres II database

Description

resource ingres_pconnect ( [string database [, string username [, string password]]])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Returns a Ingres II link resource on success, or FALSE on failure.

See ingres_connect() for parameters details and examples. There are only 2 differences between ingres_pconnect() and ingres_connect() : 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 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'.

See also ingres_connect() and ingres_close().

ingres_query

(PHP 4 >= 4.0.2)

ingres_query -- Send a SQL query to Ingres II

Description

bool ingres_query ( string query [, resource link])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Returns TRUE on success, or FALSE on failure.

ingres_query() sends the given query to the Ingres server. This query must be a valid SQL query (see the Ingres SQL reference guide)

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

Some types of SQL queries can't be sent with this function:

Példa 1. ingres_query() example

<?php
ingres_connect($database, $user, $password);

ingres_query("select * from table");
while ($row = ingres_fetch_row()) {
    echo $row[1];
    echo $row[2];
}
?>

See also ingres_fetch_array(), ingres_fetch_object(), ingres_fetch_row(), ingres_commit(), ingres_rollback(), and ingres_autocommit().

ingres_rollback

(PHP 4 >= 4.0.2)

ingres_rollback -- Roll back a transaction

Description

bool ingres_rollback ( [resource link])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

ingres_rollback() rolls back the currently open transaction, actually canceling all changes made to the database during the transaction.

This closes the transaction. A new one can be open by sending a query with ingres_query().

See also ingres_query(), ingres_commit(), and ingres_autocommit().

XLVI. IRC Gateway Functions

Bevezetés

With IRCG you can rapidly stream XML data to thousands of concurrently connected users. This can be used to build powerful, extensible interactive platforms such as online games and webchats. IRCG also features support for a non-streaming mode where a helper application reformats incoming data and supplies static file snippets in special formats such as cHTML (i-mode) or WML (WAP). These static files are then delivered by the high-performance web server.

Up to v4, IRCG runs under these platforms:

  • AIX

  • FreeBSD

  • HP-UX

  • Irix

  • Linux

  • Solaris

  • Tru64

  • Windows


Telepítés

Detailed installation instructions can be found at http://www.schumann.cx/ircg/. We urge you to use the provided installation script.

It is not recommended, but you can try enable IRCG support yourself. Provide the path to the ircg-config script, --with-ircg-config=path/to/irc-config and in addition add --with-ircg to your configure line.


Futásidejű beállítások

Ez a kiterjesztés semmilyen konfigurációs beállításokat nem definiál a php.ini állományban.


Erőforrás típusok


Előre definiált állandók

Ez a kiterjesztés semmilyen konstans értéket nem definiál.

Tartalom
ircg_channel_mode --  Set channel mode flags for user
ircg_disconnect --  Close connection to server
ircg_fetch_error_msg --  Returns the error from previous IRCG operation
ircg_get_username --  Get username for connection
ircg_html_encode --  Encodes HTML preserving output
ircg_ignore_add --  Add a user to your ignore list on a server
ircg_ignore_del --  Remove a user from your ignore list on a server
ircg_invite -- Invites nickname to channel
ircg_is_conn_alive --  Check connection status
ircg_join --  Join a channel on a connected server
ircg_kick --  Kick a user out of a channel on server
ircg_list -- List topic/user count of channel(s)
ircg_lookup_format_messages --  Check for the existence of a format message set
ircg_lusers -- IRC network statistics
ircg_msg --  Send message to channel or user on server
ircg_nick --  Change nickname on server
ircg_nickname_escape --  Encode special characters in nickname to be IRC-compliant
ircg_nickname_unescape --  Decodes encoded nickname
ircg_notice --  Send a notice to a user on server
ircg_oper -- Elevates privileges to IRC OPER
ircg_part --  Leave a channel on server
ircg_pconnect --  Connect to an IRC server
ircg_register_format_messages --  Register a format message set
ircg_set_current --  Set current connection for output
ircg_set_file --  Set logfile for connection
ircg_set_on_die --  Set action to be executed when connection dies
ircg_topic --  Set topic for channel on server
ircg_who -- Queries server for WHO information
ircg_whois --  Query server for user information

ircg_channel_mode

(PHP 4 >= 4.0.5)

ircg_channel_mode --  Set channel mode flags for user

Description

bool ircg_channel_mode ( resource connection, string channel, string mode_spec, string nick)

Set channel mode flags for channel on server connected to by connection. Mode flags are passed in mode_spec and are applied to the user specified by nick.

Mode flags are set or cleared by specifying a mode character and prepending it with a plus or minus character, respectively. E.g. operator mode is granted by '+o' and revoked by '-o', as passed as mode_spec.

ircg_disconnect

(PHP 4 >= 4.0.4)

ircg_disconnect --  Close connection to server

Description

bool ircg_disconnect ( resource connection, string reason)

ircg_disconnect() will close a connection to a server previously established with ircg_pconnect().

See also: ircg_pconnect().

ircg_fetch_error_msg

(PHP 4 >= 4.1.0)

ircg_fetch_error_msg --  Returns the error from previous IRCG operation

Description

array ircg_fetch_error_msg ( resource connection)

ircg_fetch_error_msg() returns the error from a failed connection.

Megjegyzés: Error code is stored in first array element, error text in second. The error code is equivalent to IRC reply codes as defined by RFC 2812.

Példa 1. ircg_fetch_error_msg() example

<?php
if (!ircg_join ($id, "#php")) {
    $error = ircg_fetch_error_msg($id);
    echo "Can't join channel #php. Error code: 
          $error[0] Description: $error[1]";
}
?>

ircg_get_username

(PHP 4 >= 4.1.0)

ircg_get_username --  Get username for connection

Description

string ircg_get_username ( resource connection)

Function ircg_get_username() returns the username for the specified connection connection. Returns FALSE if connection died or is not valid.

ircg_html_encode

(PHP 4 >= 4.0.5)

ircg_html_encode --  Encodes HTML preserving output

Description

bool ircg_html_encode ( string html_string)

Encodes a HTML string html_string for output. This exposes the interface which the IRCG extension uses internally to reformat data coming from an IRC link. The function causes IRC color/font codes to be encoded in HTML and escapes certain entities.

ircg_ignore_add

(PHP 4 >= 4.0.5)

ircg_ignore_add --  Add a user to your ignore list on a server

Description

bool ircg_ignore_add ( resource connection, string nick)

This function adds user nick to the ignore list of connection connection. Afterwards, IRCG will suppress all messages from this user through the associated connection.

See also: ircg_ignore_del().

ircg_ignore_del

(PHP 4 >= 4.0.5)

ircg_ignore_del --  Remove a user from your ignore list on a server

Description

bool ircg_ignore_del ( resource connection, string nick)

This function removes user nick from the IRCG ignore list associated with connection.

See also: ircg_ignore_add().

ircg_invite

(PHP 5 CVS only)

ircg_invite -- Invites nickname to channel

Description

bool ircg_invite ( resource connection, string channel, string nickname)

ircg_invite() will send an invitation to the user nickname, prompting him to join channel. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

ircg_is_conn_alive

(PHP 4 >= 4.0.5)

ircg_is_conn_alive --  Check connection status

Description

bool ircg_is_conn_alive ( resource connection)

ircg_is_conn_alive() returns TRUE if connection is still alive and working or FALSE, if the connection has died for some reason.

ircg_join

(PHP 4 >= 4.0.4)

ircg_join --  Join a channel on a connected server

Description

bool ircg_join ( resource connection, string channel [, string key])

Join the channel channel on the server connected to by connection. IRCG will optionally pass the room key key.

ircg_kick

(PHP 4 >= 4.0.5)

ircg_kick --  Kick a user out of a channel on server

Description

bool ircg_kick ( resource connection, string channel, string nick, string reason)

Kick user nick from channel on server connected to by connection. reason should give a short message describing why this action was performed.

ircg_list

(no version information, might be only in CVS)

ircg_list -- List topic/user count of channel(s)

Description

bool ircg_list ( resource connection, string channel)

ircg_list() will request a list of users in the channel. The answer is sent to the output defined by ircg_set_file() or ircg_set_current(). Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Példa 1. ircg_list() example

<?php

// connect to server
$id = ircg_pconnect($nickname, $ip, $port);

// set to output to a file
ircg_set_file($id, 'irc_output.html');

// try to join a channel
if (!ircg_join($id, $channel)) {
    echo "Cannot /join $channel<br />";
}

// send list command
ircg_list($id, $channel);

// wait for output to arrive
sleep(5);

// disconnect
ircg_disconnect($id,'Bye World');

// output everything
readfile('irc_output.html');

?>

This example will output something similar to:

...
Channel #channel has n users and the topic is 'Topic'
End of LIST
...

See also: ircg_set_file(), ircg_set_current(), and ircg_who().

ircg_lookup_format_messages

(PHP 4 >= 4.0.5)

ircg_lookup_format_messages --  Check for the existence of a format message set

Description

bool ircg_lookup_format_messages ( string name)

Check for the existence of the format message set name. Sets may be registered with ircg_register_format_messages(), a default set named ircg is always available. Returns TRUE, if the set exists and FALSE otherwise.

See also: ircg_register_format_messages()

ircg_lusers

(no version information, might be only in CVS)

ircg_lusers -- IRC network statistics

Description

bool ircg_lusers ( resource connection)

ircg_lusers() will request a statistical breakdown of users on the network connected to on connection. The answer is sent to the output defined by ircg_set_file() or ircg_set_current(). Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

See also: ircg_set_file(), and ircg_set_current().

ircg_msg

(PHP 4 >= 4.0.4)

ircg_msg --  Send message to channel or user on server

Description

bool ircg_msg ( resource connection, string recipient, string message [, boolean suppress])

ircg_msg() will send the message to a channel or user on the server connected to by connection. A recipient starting with # or & will send the message to a channel, anything else will be interpreted as a username.

Setting the optional parameter suppress to a TRUE value will suppress output of your message to your own connection. This so-called loopback is necessary, because the IRC server does not echo PRIVMSG commands back to us.

ircg_nick

(PHP 4 >= 4.0.5)

ircg_nick --  Change nickname on server

Description

bool ircg_nick ( resource connection, string nick)

Change your nickname on the given connection to the one given in nick, if possible.

Will return TRUE on success and FALSE on failure.

ircg_nickname_escape

(PHP 4 >= 4.0.6)

ircg_nickname_escape --  Encode special characters in nickname to be IRC-compliant

Description

string ircg_nickname_escape ( string nick)

Function ircg_nickname_escape() returns an encoded nickname specified by nick which is IRC-compliant.

See also: ircg_nickname_unescape()

ircg_nickname_unescape

(PHP 4 >= 4.0.6)

ircg_nickname_unescape --  Decodes encoded nickname

Description

string ircg_nickname_unescape ( string nick)

Function ircg_nickname_unescape() returns a decoded nickname, which is specified in nick.

See also: ircg_nickname_escape()

ircg_notice

(PHP 4 >= 4.0.5)

ircg_notice --  Send a notice to a user on server

Description

bool ircg_notice ( resource connection, string , string message)

This function will send the message text to the user nick on the server connected to by connection. IRC servers and other software will not automatically generate replies to NOTICEs in contrast to other message types.

ircg_oper

(no version information, might be only in CVS)

ircg_oper -- Elevates privileges to IRC OPER

Description

bool ircg_oper ( resource connection, string name, string password)

ircg_oper() will authenticate the logged in user on connection as an IRC operator. name and password must match a registered IRC operator account. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

ircg_part

(PHP 4 >= 4.0.4)

ircg_part --  Leave a channel on server

Description

bool ircg_part ( resource connection, string channel)

Leave the channel channel on the server connected to by connection.

ircg_pconnect

(PHP 4 >= 4.0.4)

ircg_pconnect --  Connect to an IRC server

Description

resource ircg_pconnect ( string username [, string server_ip [, int server_port [, string msg_format [, array ctcp_messages [, array user_settings]]]]])

ircg_pconnect() will try to establish a connection to an IRC server and return a connection resource handle for further use.

The only mandatory parameter is username, this will set your initial nickname on the server. server_ip and server_port are optional and default to 127.0.0.1 and 6667.

Megjegyzés: For now parameter server_ip will not do any hostname lookups and will only accept IP addresses in numerical form. DNS lookups are expensive and should be done in the context of IRCG.

You can customize the output of IRC messages and events by selecting a format message set previously created with ircg_register_format_messages() by specifying the set's name in msg_format.

If you want to handle CTCP messages such as ACTION (/me), you need to define a mapping from CTCP type (e.g. ACTION) to a custom format string. Do this by passing an associative array as ctcp_messages. The keys of the array are the CTCP type and the respective value is the format message.

You can define "ident", "password", and "realname" tokens which are sent to the IRC server by setting these in an associative array. Pass that array as user_settings.

See also: ircg_disconnect(), ircg_is_conn_alive(), ircg_register_format_messages().

ircg_register_format_messages

(PHP 4 >= 4.0.5)

ircg_register_format_messages --  Register a format message set

Description

bool ircg_register_format_messages ( string name, array messages)

With ircg_register_format_messages() you can customize the way your IRC output looks like or which script functions are invoked on the client side.

  • Plain channel message

  • Private message received

  • Private message sent

  • Some user leaves channel

  • Some user enters channel

  • Some user was kicked from the channel

  • Topic has been changed

  • Error

  • Fatal error

  • Join list end(?)

  • Self part(?)

  • Some user changes his nick

  • Some user quits his connection

  • Mass join begin

  • Mass join element

  • Mass join end

  • Whois user

  • Whois server

  • Whois idle

  • Whois channel

  • Whois end

  • Voice status change on user

  • Operator status change on user

  • Banlist

  • Banlist end

  • %f - from

  • %t - to

  • %c - channel

  • %r - plain message

  • %m - encoded message

  • %j - js encoded message

  • 1 - mod encode

  • 2 - nickname decode

See also: ircg_lookup_format_messages().

ircg_set_current

(PHP 4 >= 4.0.4)

ircg_set_current --  Set current connection for output

Description

bool ircg_set_current ( resource connection)

Select the current HTTP connection for output in this execution context. Every output sent from the server connected to by connection will be copied to standard output while using default formatting or a format message set specified by ircg_register_format_messages().

See also: ircg_register_format_messages().

ircg_set_file

(PHP 4 >= 4.2.0)

ircg_set_file --  Set logfile for connection

Description

bool ircg_set_file ( resource connection, string path)

Function ircg_set_file() specifies a logfile path in which all output from connection connection will be logged. Returns TRUE on success, otherwise FALSE.

ircg_set_on_die

(PHP 4 >= 4.2.0)

ircg_set_on_die --  Set action to be executed when connection dies

Description

bool ircg_set_on_die ( resource connection, string host, int port, string data)

In case of the termination of connection connection IRCG will connect to host at port (Note: host must be an IPv4 address, IRCG does not resolve host-names due to blocking issues), send data to the new host connection and will wait until the remote part closes connection. This can be used to trigger a PHP script for example.

This feature requires IRCG 3.

ircg_topic

(PHP 4 >= 4.0.5)

ircg_topic --  Set topic for channel on server

Description

bool ircg_topic ( resource connection, string channel, string new_topic)

Change the topic for channel channel on the server connected to by connection to new_topic.

ircg_who

(PHP 5 CVS only)

ircg_who -- Queries server for WHO information

Description

bool ircg_who ( resource connection, string mask [, bool ops_only])

ircg_who() will request a list of users whose nickname is matching mask on connected network connection. The optional parameter ops_only will shrink the list to server operators only.

The answer is sent to the output defined by ircg_set_file() or ircg_set_current(). Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

See also: ircg_set_file(), and ircg_set_current().

ircg_whois

(PHP 4 >= 4.0.5)

ircg_whois --  Query server for user information

Description

bool ircg_whois ( resource connection, string nick)

Sends a query to the connected server connection to ask for information about the specified user nick.

XLVII. PHP / Java Integration

Bevezetés

There are two possible ways to bridge PHP and Java: you can either integrate PHP into a Java Servlet environment, which is the more stable and efficient solution, or integrate Java support into PHP. The former is provided by a SAPI module that interfaces with the Servlet server, the latter by this Java extension.

The Java extension provides a simple and effective means for creating and invoking methods on Java objects from PHP. The JVM is created using JNI, and everything runs in-process.

Figyelem

Ez a kiterjesztés KÍSÉRLETI JELLEGGEL MŰKÖDIK. Ez azt jelenti, hogy minden itt dokumentált működés, beleértve a függvények nevét, működését vagy bármi más, amit a kiterjesztés kapcsán leírtunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a kiterjesztést csak a saját felelősségedre használd!


Követelmények

You need a Java VM installed on your machine to use this extension.


Telepítés

To include Java support in your PHP build you must add the option --with-java[=DIR] where DIR points to the base install directory of your JDK. This extension can only be built as a shared dl. More build instructions for this extension can be found in php4/ext/java/README.

Note to Win32 Users: In order to enable this module on a Windows environment with PHP <= 4.0.6, you must copy jvm.dll from the DLL folder of the PHP/Win32 binary package to the SYSTEM32 folder of your windows machine. (Ex: C:\WINNT\SYSTEM32 or C:\WINDOWS\SYSTEM32). For PHP > 4.0.6 you do not need any additional dll file.


Futásidejű beállítások

Az alábbi függvények viselkedése befolyásolható a php.ini segítségével.

Táblázat 1. Java configuration options

NameDefaultChangeable
java.class.pathNULLPHP_INI_ALL
java.homeNULLPHP_INI_ALL
java.library.pathNULLPHP_INI_ALL
java.libraryJAVALIBPHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().


Erőforrás típusok

Ez a kiterjesztés semmilyen erőforrás típust nem definiál.


Előre definiált állandók

Ez a kiterjesztés semmilyen konstans értéket nem definiál.


Példák

Példa 1. Java Example

<?php
  // get instance of Java class java.lang.System in PHP
  $system = new Java('java.lang.System');

  // demonstrate property access
  echo 'Java version=' . $system->getProperty('java.version') . '<br />';
  echo 'Java vendor=' . $system->getProperty('java.vendor') . '<br />';
  echo 'OS=' . $system->getProperty('os.name') . ' ' .
              $system->getProperty('os.version') . ' on ' .
              $system->getProperty('os.arch') . ' <br />';

  // java.util.Date example
  $formatter = new Java('java.text.SimpleDateFormat',
                        "EEEE, MMMM dd, yyyy 'at' h:mm:ss a zzzz");

  echo $formatter->format(new Java('java.util.Date'));
?>

Példa 2. AWT Example

<?php
  // This example is only intended to be run as a CGI.

  $frame  = new Java('java.awt.Frame', 'PHP');
  $button = new Java('java.awt.Button', 'Hello Java World!');

  $frame->add('North', $button);
  $frame->validate();
  $frame->pack();
  $frame->visible = True;

  $thread = new Java('java.lang.Thread');
  $thread->sleep(10000);

  $frame->dispose();
?>
Notes:

  • new Java() will create an instance of a class if a suitable constructor is available. If no parameters are passed and the default constructor is useful as it provides access to classes like java.lang.System which expose most of their functionallity through static methods.

  • Accessing a member of an instance will first look for bean properties then public fields. In other words, print $date.time will first attempt to be resolved as $date.getTime(), then as $date.time.

  • Both static and instance members can be accessed on an object with the same syntax. Furthermore, if the java object is of type java.lang.Class, then static members of the class (fields and methods) can be accessed.

  • Exceptions raised result in PHP warnings, and NULL results. The warnings may be eliminated by prefixing the method call with an "@" sign. The following APIs may be used to retrieve and reset the last error:

  • Overload resolution is in general a hard problem given the differences in types between the two languages. The PHP Java extension employs a simple, but fairly effective, metric for determining which overload is the best match.

    Additionally, method names in PHP are not case sensitive, potentially increasing the number of overloads to select from.

    Once a method is selected, the parameters are coerced if necessary, possibly with a loss of data (example: double precision floating point numbers will be converted to boolean).

  • In the tradition of PHP, arrays and hashtables may pretty much be used interchangably. Note that hashtables in PHP may only be indexed by integers or strings; and that arrays of primitive types in Java can not be sparse. Also note that these constructs are passed by value, so may be expensive in terms of memory and time.


Java Servlet SAPI

The Java Servlet SAPI builds upon the mechanism defined by the Java extension to enable the entire PHP processor to be run as a servlet. The primary advanatage of this from a PHP perspective is that web servers which support servlets typically take great care in pooling and reusing JVMs. Build instructions for the Servlet SAPI module can be found in php4/sapi/README. Notes:

  • While this code is intended to be able to run on any servlet engine, it has only been tested on Apache's Jakarta/tomcat to date. Bug reports, success stories and/or patches required to get this code to run on other engines would be appreciated.

  • PHP has a habit of changing the working directory. sapi/servlet will eventually change it back, but while PHP is running the servlet engine may not be able to load any classes from the CLASSPATH which are specified using a relative directory syntax, or find the work directory used for administration and JSP compilation tasks.

Tartalom
java_last_exception_clear -- Clear last Java exception
java_last_exception_get -- Get last Java exception

java_last_exception_clear

(PHP 4 >= 4.0.2)

java_last_exception_clear -- Clear last Java exception

Description

void java_last_exception_clear ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

See java_last_exception_get() for an example.

java_last_exception_get

(PHP 4 >= 4.0.2)

java_last_exception_get -- Get last Java exception

Description

exception java_last_exception_get ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

The following example demonstrates the usage of Java's exception handler from within PHP:

Példa 1. Java exception handler

<?php
  $stack = new Java('java.util.Stack');
  $stack->push(1);

  // This should succeed
  $result = $stack->pop();
  $ex = java_last_exception_get();
  if (!$ex) {
    echo "$result\n";
  }

  // This should fail (error suppressed by @)
  $result = @$stack->pop();
  $ex = java_last_exception_get();
  if ($ex) {
    echo $ex->toString();
  }

  // Clear last exception
  java_last_exception_clear();
?>

XLVIII. LDAP functions

Bevezetés

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

The Netscape SDK contains a helpful Programmer's Guide in HTML format.


Követelmények

You will need to get and compile LDAP client libraries from either the University of Michigan ldap-3.3 package, Netscape Directory SDK 3.0 or OpenLDAP to compile PHP with LDAP support.


Telepítés

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.

Note to Win32 Users: In order to enable this module on a Windows environment, you must copy several files from the DLL folder of the PHP/Win32 binary package to the SYSTEM folder of your windows machine. (Ex: C:\WINNT\SYSTEM32, or C:\WINDOWS\SYSTEM). For PHP <= 4.2.0 copy libsasl.dll, for PHP >= 4.3.0 copy libeay32.dll and ssleay32.dll to your SYSTEM folder.


Futásidejű beállítások

Az alábbi függvények viselkedése befolyásolható a php.ini segítségével.

Táblázat 1. LDAP configuration options

NameDefaultChangeable
ldap.max_links"-1"PHP_INI_SYSTEM
For further details and definition of the PHP_INI_* constants see ini_set().


Erőforrás típusok

Ez a kiterjesztés semmilyen erőforrás típust nem definiál.


Előre definiált állandók

Az itt listázott állandókat ez a kiterjesztés definiálja, és csak akkor elérhetőek, ha az adott kiterjesztés be van fordítva a PHP-be, vagy dinamikusan betöltött.

LDAP_DEREF_NEVER (integer)

LDAP_DEREF_SEARCHING (integer)

LDAP_DEREF_FINDING (integer)

LDAP_DEREF_ALWAYS (integer)

LDAP_OPT_DEREF (integer)

LDAP_OPT_SIZELIMIT (integer)

LDAP_OPT_TIMELIMIT (integer)

LDAP_OPT_PROTOCOL_VERSION (integer)

LDAP_OPT_ERROR_NUMBER (integer)

LDAP_OPT_REFERRALS (integer)

LDAP_OPT_RESTART (integer)

LDAP_OPT_HOST_NAME (integer)

LDAP_OPT_ERROR_STRING (integer)

LDAP_OPT_MATCHED_DN (integer)

LDAP_OPT_SERVER_CONTROLS (integer)

LDAP_OPT_CLIENT_CONTROLS (integer)

LDAP_OPT_DEBUG_LEVEL (integer)

GSLC_SSL_NO_AUTH (integer)

GSLC_SSL_ONEWAY_AUTH (integer)

GSLC_SSL_TWOWAY_AUTH (integer)


Példák

Retrieve information for all entries where the surname starts with "S" from a directory server, displaying an extract with name and email address.

Példa 1. LDAP search example

<?php
// basic sequence with LDAP is connect, bind, search, interpret search
// result, close connection

echo "<h3>LDAP query test</h3>";
echo "Connecting ...";
$ds=ldap_connect("localhost");  // must be a valid LDAP server!
echo "connect result is " . $ds . "<br />";

if ($ds) { 
    echo "Binding ..."; 
    $r=ldap_bind($ds);     // this is an "anonymous" bind, typically
                           // read-only access
    echo "Bind result is " . $r . "<br />";

    echo "Searching for (sn=S*) ...";
    // Search surname entry
    $sr=ldap_search($ds, "o=My Company, c=US", "sn=S*");  
    echo "Search result is " . $sr . "<br />";

    echo "Number of entires returned is " . ldap_count_entries($ds, $sr) . "<br />";

    echo "Getting entries ...<p>";
    $info = ldap_get_entries($ds, $sr);
    echo "Data for " . $info["count"] . " items returned:<p>";

    for ($i=0; $i<$info["count"]; $i++) {
        echo "dn is: " . $info[$i]["dn"] . "<br />";
        echo "first cn entry is: " . $info[$i]["cn"][0] . "<br />";
        echo "first email entry is: " . $info[$i]["mail"][0] . "<br /><hr />";
    }

    echo "Closing connection";
    ldap_close($ds);

} else {
    echo "<h4>Unable to connect to LDAP server</h4>";
}
?>

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"

Tartalom
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 -- Close link to LDAP server
ldap_compare -- Compare value of attribute found in entry specified with DN
ldap_connect -- Connect to an LDAP server
ldap_count_entries -- Count the number of entries in a search
ldap_delete -- Delete an entry from a directory
ldap_dn2ufn -- Convert DN to User Friendly Naming format
ldap_err2str --  Convert LDAP error number into string error message
ldap_errno --  Return the LDAP error number of the last LDAP command
ldap_error --  Return the LDAP error message of the last LDAP command
ldap_explode_dn -- Splits DN into its component parts
ldap_first_attribute -- Return first attribute
ldap_first_entry -- Return first result id
ldap_first_reference --  Return first reference
ldap_free_result -- Free result memory
ldap_get_attributes -- Get attributes from a search result entry
ldap_get_dn -- Get the DN of a result entry
ldap_get_entries -- Get all result entries
ldap_get_option -- Get the current value for given option
ldap_get_values_len -- Get all binary values from a result entry
ldap_get_values -- Get all values from a result entry
ldap_list -- Single-level search
ldap_mod_add -- Add attribute values to current attributes
ldap_mod_del -- Delete attribute values from current attributes
ldap_mod_replace -- Replace attribute values with new ones
ldap_modify -- Modify an LDAP entry
ldap_next_attribute -- Get the next attribute in result
ldap_next_entry -- Get next result entry
ldap_next_reference --  Get next reference
ldap_parse_reference --  Extract information from reference entry
ldap_parse_result --  Extract information from result
ldap_read -- Read an entry
ldap_rename -- Modify the name of an entry
ldap_search -- Search LDAP tree
ldap_set_option -- Set the value of the given option
ldap_set_rebind_proc --  Set a callback function to do re-binds on referral chasing.
ldap_sort --  Sort LDAP result entries
ldap_start_tls --  Start TLS
ldap_t61_to_8859 --  Translate t61 characters to 8859 characters
ldap_unbind -- Unbind from LDAP directory

ldap_8859_to_t61

(PHP 4 >= 4.0.2)

ldap_8859_to_t61 --  Translate 8859 characters to t61 characters

Description

string ldap_8859_to_t61 ( string value)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ldap_add

(PHP 3, PHP 4 )

ldap_add -- Add entries to LDAP directory

Description

bool ldap_add ( resource link_identifier, string dn, array entry)

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

The ldap_add() function is used to add entries in the LDAP directory. The DN of the entry to be added is specified by dn. Array entry 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.


    entry["attribute1"] = value
    entry["attribute2"][0] = value1
    entry["attribute2"][1] = value2

Példa 1. Complete example with authenticated bind

<?php
$ds=ldap_connect("localhost");  // assuming the LDAP server is on this host

if ($ds) {
    // bind with appropriate dn to give update access
    $r=ldap_bind($ds, "cn=root, o=My Company, c=US", "secret");

    // prepare data
    $info["cn"]="John Jones";
    $info["sn"]="Jones";
    $info["mail"]="jonj@example.com";
    $info["objectclass"]="person";

    // add data to directory
    $r=ldap_add($ds, "cn=John Jones, o=My Company, c=US", $info);

    ldap_close($ds);
} else {
    echo "Unable to connect to LDAP server"; 
}
?>

ldap_bind

(PHP 3, PHP 4 )

ldap_bind -- Bind to LDAP directory

Description

bool ldap_bind ( resource link_identifier [, string bind_rdn [, string bind_password]])

Binds to the LDAP directory with specified RDN and password. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

ldap_bind() does a bind operation on the directory. bind_rdn and bind_password are optional. If not specified, anonymous bind is attempted.

Példa 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...";
    }
        
}

?>

Példa 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...";
    }
 
}
    
?>

ldap_close

(PHP 3, PHP 4 )

ldap_close -- Close link to LDAP server

Description

bool ldap_close ( resource link_identifier)

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

ldap_close() closes the link to the LDAP server that's associated with the specified link_identifier.

This call is internally identical to ldap_unbind(). The LDAP API uses the call ldap_unbind(), so perhaps you should use this in preference to ldap_close().

Megjegyzés: This function is an alias of ldap_unbind().

ldap_compare

(PHP 4 >= 4.0.2)

ldap_compare -- Compare value of attribute found in entry specified with DN

Description

bool ldap_compare ( resource link_identifier, string dn, string attribute, string value)

Returns TRUE if value matches otherwise returns FALSE. Returns -1 on error.

ldap_compare() is used to compare value of attribute to value of same attribute in LDAP directory entry specified with dn.

The following example demonstrates how to check whether or not given password matches the one defined in DN specified entry.

Példa 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.";
}
?>

Figyelem

ldap_compare() can NOT be used to compare BINARY values!

Megjegyzés: This function was added in 4.0.2.

ldap_connect

(PHP 3, PHP 4 )

ldap_connect -- Connect to an LDAP server

Description

resource ldap_connect ( [string hostname [, int port]])

Returns a positive LDAP link identifier on success, or FALSE on error.

ldap_connect() establishes a connection to a LDAP server on a specified hostname and port. Both the arguments are optional. If no arguments are specified then the link identifier of the already opened link will be returned. If only hostname is specified, then the port defaults to 389.

If you are using OpenLDAP 2.x.x you can specify a URL instead of the hostname. To use LDAP with SSL, compile OpenLDAP 2.x.x with SSL support, configure PHP with SSL, and use ldaps://hostname/ as host parameter. The port parameter is not used when using URLs.

Megjegyzés: URL and SSL support were added in 4.0.4.

Példa 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");

?>

Példa 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}");

?>

ldap_count_entries

(PHP 3, PHP 4 )

ldap_count_entries -- Count the number of entries in a search

Description

int ldap_count_entries ( resource link_identifier, resource result_identifier)

Returns number of entries in the result or FALSE on error.

ldap_count_entries() returns the number of entries stored in the result of previous search operations. result_identifier identifies the internal ldap result.

ldap_delete

(PHP 3, PHP 4 )

ldap_delete -- Delete an entry from a directory

Description

bool ldap_delete ( resource link_identifier, string dn)

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

ldap_delete() function delete a particular entry in LDAP directory specified by dn.

ldap_dn2ufn

(PHP 3, PHP 4 )

ldap_dn2ufn -- Convert DN to User Friendly Naming format

Description

string ldap_dn2ufn ( string dn)

ldap_dn2ufn() function is used to turn a DN, specified by dn, into a more user-friendly form, stripping off type names.

ldap_err2str

(PHP 3>= 3.0.13, PHP 4 )

ldap_err2str --  Convert LDAP error number into string error message

Description

string ldap_err2str ( int errno)

Returns string error message.

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

See also ldap_errno() and ldap_error().

Példa 1. Enumerating all LDAP error messages

<?php
  for ($i=0; $i<100; $i++) {
    printf("Error $i: %s<br />\n", ldap_err2str($i));
  }
?>

ldap_errno

(PHP 3>= 3.0.12, PHP 4 )

ldap_errno --  Return the LDAP error number of the last LDAP command

Description

int ldap_errno ( resource link_identifier)

Return the LDAP error number of the last LDAP command for this link.

This function returns the standardized error number returned by the last LDAP command for the given link_identifier. This number can be converted into a textual error message using ldap_err2str().

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.

Példa 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";
?>

See also ldap_err2str() and ldap_error().

ldap_error

(PHP 3>= 3.0.12, PHP 4 )

ldap_error --  Return the LDAP error message of the last LDAP command

Description

string ldap_error ( resource link_identifier)

Returns string error message.

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

See also ldap_err2str() and ldap_errno().

ldap_explode_dn

(PHP 3, PHP 4 )

ldap_explode_dn -- Splits DN into its component parts

Description

array ldap_explode_dn ( string dn, int with_attrib)

ldap_explode_dn() function is used to split 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. ldap_explode_dn() returns an array of all those components. with_attrib is 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.

ldap_first_attribute

(PHP 3, PHP 4 )

ldap_first_attribute -- Return first attribute

Description

string ldap_first_attribute ( resource link_identifier, resource result_entry_identifier, int ber_identifier)

Returns the first attribute in the entry on success and FALSE on error.

Similar to reading entries, attributes are also read one by one from a particular entry. ldap_first_attribute() returns the first attribute in the entry pointed by the result_entry_identifier. Remaining attributes are retrieved by calling ldap_next_attribute() successively. ber_identifier is the identifier to internal memory location pointer. It is passed by reference. The same ber_identifier is passed to the ldap_next_attribute() function, which modifies that pointer.

See also ldap_get_attributes()

ldap_first_entry

(PHP 3, PHP 4 )

ldap_first_entry -- Return first result id

Description

resource ldap_first_entry ( resource link_identifier, resource result_identifier)

Returns the result entry identifier for the first entry on success and FALSE on error.

Entries in the LDAP result are read sequentially using the ldap_first_entry() and ldap_next_entry() functions. ldap_first_entry() 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.

See also ldap_get_entries().

ldap_first_reference

(PHP 4 >= 4.0.5)

ldap_first_reference --  Return first reference

Description

resource ldap_first_reference ( resource link, resource result)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ldap_free_result

(PHP 3, PHP 4 )

ldap_free_result -- Free result memory

Description

bool ldap_free_result ( resource result_identifier)

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

ldap_free_result() frees up the memory allocated internally to store the result and pointed by the result_identifier. 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.

ldap_get_attributes

(PHP 3, PHP 4 )

ldap_get_attributes -- Get attributes from a search result entry

Description

array ldap_get_attributes ( resource link_identifier, resource result_entry_identifier)

Returns a complete entry information in a multi-dimensional array on success and FALSE on error.

ldap_get_attributes() function is used to simplify reading the attributes and values from an entry in the search result. The return value is a multi-dimensional array of attributes and values.

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

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

See also ldap_first_attribute() and ldap_next_attribute().

ldap_get_dn

(PHP 3, PHP 4 )

ldap_get_dn -- Get the DN of a result entry

Description

string ldap_get_dn ( resource link_identifier, resource result_entry_identifier)

Returns the DN of the result entry and FALSE on error.

ldap_get_dn() function is used to find out the DN of an entry in the result.

ldap_get_entries

(PHP 3, PHP 4 )

ldap_get_entries -- Get all result entries

Description

array ldap_get_entries ( resource link_identifier, resource result_identifier)

Returns a complete result information in a multi-dimensional array on success and FALSE on error.

ldap_get_entries() function is used to simplify reading multiple entries from the result, specified with result_identifier, and then reading the attributes and multiple values. The entire information is returned by one function call in a multi-dimensional array. 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] = 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

See also ldap_first_entry() and ldap_next_entry()

ldap_get_option

(PHP 4 >= 4.0.4)

ldap_get_option -- Get the current value for given option

Description

bool ldap_get_option ( resource link_identifier, int option, mixed retval)

Sets retval to the value of the specified option. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

The parameter option can be one of: LDAP_OPT_DEREF, LDAP_OPT_SIZELIMIT, LDAP_OPT_TIMELIMIT, LDAP_OPT_PROTOCOL_VERSION, LDAP_OPT_ERROR_NUMBER, LDAP_OPT_REFERRALS, LDAP_OPT_RESTART, LDAP_OPT_HOST_NAME, LDAP_OPT_ERROR_STRING, LDAP_OPT_MATCHED_DN. These are described in draft-ietf-ldapext-ldap-c-api-xx.txt

Megjegyzés: This function is only available when using OpenLDAP 2.x.x OR Netscape Directory SDK x.x, and was added in PHP 4.0.4

Példa 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";
}
?>

See also ldap_set_option().

ldap_get_values_len

(PHP 3>= 3.0.13, PHP 4 )

ldap_get_values_len -- Get all binary values from a result entry

Description

array ldap_get_values_len ( resource link_identifier, resource result_entry_identifier, string attribute)

Returns an array of values for the attribute on success and FALSE on error.

ldap_get_values_len() function is used to read all the values of the attribute in the entry in the result. entry is specified by the result_entry_identifier. 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.

This function is used exactly like ldap_get_values() except that it handles binary data and not string data.

Megjegyzés: This function was added in 4.0.

ldap_get_values

(PHP 3, PHP 4 )

ldap_get_values -- Get all values from a result entry

Description

array ldap_get_values ( resource link_identifier, resource result_entry_identifier, string attribute)

Returns an array of values for the attribute on success and FALSE on error.

ldap_get_values() function is used to read all the values of the attribute in the entry in the result. entry is specified by the result_entry_identifier. 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.

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.

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

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

ldap_list

(PHP 3, PHP 4 )

ldap_list -- Single-level search

Description

resource ldap_list ( resource link_identifier, string base_dn, string filter [, array attributes [, int attrsonly [, int sizelimit [, int timelimit [, int deref]]]]])

Returns a search result identifier or FALSE on error.

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

This call takes 5 optional parameters. See ldap_search() notes.

Megjegyzés: These optional parameters were added in 4.0.2: attrsonly, sizelimit, timelimit, deref.

Példa 1. Produce a list of all organizational units of an organization

// $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] ;
}

Megjegyzés: From 4.0.5 on it's also possible to do parallel searches. See ldap_search() for details.

ldap_mod_add

(PHP 3>= 3.0.8, PHP 4 )

ldap_mod_add -- Add attribute values to current attributes

Description

bool ldap_mod_add ( resource link_identifier, string dn, array entry)

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

This function adds attribute(s) 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.

ldap_mod_del

(PHP 3>= 3.0.8, PHP 4 )

ldap_mod_del -- Delete attribute values from current attributes

Description

bool ldap_mod_del ( resource link_identifier, string dn, array entry)

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

This function removes attribute(s) 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.

ldap_mod_replace

(PHP 3>= 3.0.8, PHP 4 )

ldap_mod_replace -- Replace attribute values with new ones

Description

bool ldap_mod_replace ( resource link_identifier, string dn, array entry)

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

This function replaces attribute(s) 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.

ldap_modify

(PHP 3, PHP 4 )

ldap_modify -- Modify an LDAP entry

Description

bool ldap_modify ( resource link_identifier, string dn, array entry)

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

ldap_modify() function is used to modify the existing entries in the LDAP directory. The structure of the entry is same as in ldap_add().

ldap_next_attribute

(PHP 3, PHP 4 )

ldap_next_attribute -- Get the next attribute in result

Description

string ldap_next_attribute ( resource link_identifier, resource result_entry_identifier, resource ber_identifier)

Returns the next attribute in an entry on success and FALSE on error.

ldap_next_attribute() is called to retrieve the attributes in an entry. The internal state of the pointer is maintained by the ber_identifier. It is passed by reference to the function. The first call to ldap_next_attribute() is made with the result_entry_identifier returned from ldap_first_attribute().

See also ldap_get_attributes()

ldap_next_entry

(PHP 3, PHP 4 )

ldap_next_entry -- Get next result entry

Description

resource ldap_next_entry ( resource link_identifier, resource result_entry_identifier)

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.

ldap_next_entry() function is used to 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().

See also ldap_get_entries()

ldap_next_reference

(PHP 4 >= 4.0.5)

ldap_next_reference --  Get next reference

Description

resource ldap_next_reference ( resource link, resource entry)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ldap_parse_reference

(PHP 4 >= 4.0.5)

ldap_parse_reference --  Extract information from reference entry

Description

bool ldap_parse_reference ( resource link, resource entry, array referrals)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ldap_parse_result

(PHP 4 >= 4.0.5)

ldap_parse_result --  Extract information from result

Description

bool ldap_parse_result ( resource link, resource result, int errcode, string matcheddn, string errmsg, array referrals)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ldap_read

(PHP 3, PHP 4 )

ldap_read -- Read an entry

Description

resource ldap_read ( resource link_identifier, string base_dn, string filter [, array attributes [, int attrsonly [, int sizelimit [, int timelimit [, int deref]]]]])

Returns a search result identifier or FALSE on error.

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

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

This call takes 5 optional parameters. See ldap_search() notes.

Megjegyzés: These optional parameters were added in 4.0.2: attrsonly, sizelimit, timelimit, deref.

From 4.0.5 on it's also possible to do parallel searches. See ldap_search() for details.

ldap_rename

(PHP 4 >= 4.0.5)

ldap_rename -- Modify the name of an entry

Description

bool ldap_rename ( resource link_identifier, string dn, string newrdn, string newparent, bool deleteoldrdn)

The entry specified by dn is renamed/moved. The new RDN is specified by newrdn and the new parent/superior entry is specified by newparent. If the parameter deleteoldrdn is TRUE the old RDN value(s) is removed, else the old RDN value(s) is retained as non-distinguished values of the entry. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Megjegyzés: 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, and was added in PHP 4.0.5.

ldap_search

(PHP 3, PHP 4 )

ldap_search -- Search LDAP tree

Description

resource ldap_search ( resource link_identifier, string base_dn, string filter [, array attributes [, int attrsonly [, int sizelimit [, int timelimit [, int deref]]]]])

Returns a search result identifier or FALSE on error.

ldap_search() 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. base_dn specifies the base DN for the directory.

There is an optional fourth parameter, that can be added to restrict the attributes and values returned by the server to just those required. This is much more efficient than the default action (which is to return all attributes and their associated values). The use of the fourth parameter should therefore be considered good practice.

The fourth parameter is a standard PHP string 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.

Note too that 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 occurs also if the sixth parameter sizelimit has been used to limit the count of fetched entries.

The fifth parameter 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.

With the sixth parameter sizelimit it is possible to limit the count of entries fetched. Setting this to 0 means no limit. NOTE: This parameter can NOT override server-side preset sizelimit. You can set it lower though.

The seventh parameter timelimit sets the number of seconds how long is spend on the search. Setting this to 0 means no limit. NOTE: This parameter can NOT override server-side preset timelimit. You can set it lower though.

The eighth parameter 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.

Megjegyzés: These optional parameters were added in 4.0.2: attrsonly, sizelimit, timelimit, deref.

The search filter can be simple or advanced, using boolean operators in the format described in the LDAP documentation (see the Netscape Directory SDK for full information on filters).

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.

Példa 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";
?>

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.

ldap_set_option

(PHP 4 >= 4.0.4)

ldap_set_option -- Set the value of the given option

Description

bool ldap_set_option ( resource link_identifier, int option, mixed newval)

Sets the value of the specified option to be newval. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad. on error.

The parameter option can be one of: LDAP_OPT_DEREF, LDAP_OPT_SIZELIMIT, LDAP_OPT_TIMELIMIT, LDAP_OPT_PROTOCOL_VERSION, LDAP_OPT_ERROR_NUMBER, LDAP_OPT_REFERRALS, LDAP_OPT_RESTART, LDAP_OPT_HOST_NAME, LDAP_OPT_ERROR_STRING, LDAP_OPT_MATCHED_DN, LDAP_OPT_SERVER_CONTROLS, LDAP_OPT_CLIENT_CONTROLS. Here's a brief description, see draft-ietf-ldapext-ldap-c-api-xx.txt for details.

The options LDAP_OPT_DEREF, LDAP_OPT_SIZELIMIT, LDAP_OPT_TIMELIMIT, LDAP_OPT_PROTOCOL_VERSION and LDAP_OPT_ERROR_NUMBER have integer value, LDAP_OPT_REFERRALS and LDAP_OPT_RESTART have boolean value, and the options LDAP_OPT_HOST_NAME, LDAP_OPT_ERROR_STRING and LDAP_OPT_MATCHED_DN have string value. The first example illustrates their use. The options 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 also the second example below.

Megjegyzés: This function is only available when using OpenLDAP 2.x.x OR Netscape Directory SDK x.x, and was added in PHP 4.0.4.

Példa 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";
}
?>

Példa 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";
?>

See also ldap_get_option().

ldap_set_rebind_proc

(PHP 4 >= 4.2.0)

ldap_set_rebind_proc --  Set a callback function to do re-binds on referral chasing.

Description

bool ldap_set_rebind_proc ( resource link, string callback)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ldap_sort

(PHP 4 >= 4.2.0)

ldap_sort --  Sort LDAP result entries

Description

bool ldap_sort ( resource link, resource result, string sortfilter)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ldap_start_tls

(PHP 4 >= 4.2.0)

ldap_start_tls --  Start TLS

Description

bool ldap_start_tls ( resource link)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ldap_t61_to_8859

(PHP 4 >= 4.0.2)

ldap_t61_to_8859 --  Translate t61 characters to 8859 characters

Description

string ldap_t61_to_8859 ( string value)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ldap_unbind

(PHP 3, PHP 4 )

ldap_unbind -- Unbind from LDAP directory

Description

bool ldap_unbind ( resource link_identifier)

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

ldap_unbind() function unbinds from the LDAP directory.

XLIX. LZF Functions

Bevezetés

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.


Telepítés

LZF is currently available through PECL http://pecl.php.net/package/lzf.

If PEAR is available on your *nix-like system you can use the pear installer to install the LZF extension, by the following command: pear -v install lzf.

You can always download the tar.gz package and install LZF by hand:

Példa 1. LZF install by hand

gunzip lzf-xxx.tgz
tar -xvf lzf-xxx.tar
cd lzf-xxx
phpize
./configure && make && make install

You can pass --enable-lzf-better-compression to optimize LZF for space rather then speed.

Windows users can download the extension dll php_lzf.dll from http://snaps.php.net/win32/PECL_STABLE/.

Tartalom
lzf_compress --  LZF compression.
lzf_decompress --  LZF decompression.
lzf_optimized_for --  Determines what LZF extension was optimized for.

lzf_compress

(no version information, might be only in CVS)

lzf_compress --  LZF compression.

Description

string lzf_compress ( string arg)

lzf_compress() compresses data in arg parameter.

Returns compressed data or FALSE if an error occured.

See also lzf_decompress().

lzf_decompress

(no version information, might be only in CVS)

lzf_decompress --  LZF decompression.

Description

string lzf_decompress ( string arg)

lzf_decompress() decompresses data from parameter arg.

Returns decompressed data or FALSE if an error occured.

See also lzf_compress().

lzf_optimized_for

(no version information, might be only in CVS)

lzf_optimized_for --  Determines what LZF extension was optimized for.

Description

int lzf_optimized_for ( void )

Returns 1 if LZF was optimized for speed, 0 for compression.

L. Mail függvények

A mail() függvény ad lehetőséget email küldésére.

Levelezés beállítási lehetőségei

SMTP string

A DNS neve vagy IP címe annak az SMTP szervernek, amit a PHP Windows alatt a mail küldésre használ, amikor a mail() függvényt hívod meg.

sendmail_from string

Megadja, hogy milyen "From:" email címet használjon a PHP mail küldésekor Windows alatt.

sendmail_path string

Megadja, hogy hol található a sendmail program. Ez általában /usr/sbin/sendmail vagy /usr/lib/sendmail. A configure megpróbálja megtalálni, és beállítani, de ha ez nem sikerül, itt te is beállíthatod.

Azokon a rendszereken, ahol nem a sendmail használatos, ez a beállítás a sendmail wrapper/helyettesítő beállítására szolgál, ha van ilyen. Például a Qmail használók általában a /var/qmail/bin/sendmail beállítást használják.

Tartalom
ezmlm_hash -- Kiszámítja a hash értéket, amit az EZMLM vár
mail -- Levelet küld

ezmlm_hash

(PHP 3>= 3.0.17, PHP 4 >= 4.0.2)

ezmlm_hash -- Kiszámítja a hash értéket, amit az EZMLM vár

Leírás

int ezmlm_hash ( string addr)

Az ezmlm_hash() kiszámítja a szükséges hash értékeket, amik az EZMLM levelezőlisták MySQL adatbázisban való tárolásához szükségesek.

Példa 1. A hash kiszámítása és a felhasználó felírása a listára

$felhasznalo = "joecool@example.com";
$hash = ezmlm_hash ($felhasznalo);
$query = sprintf ("INSERT INTO minta VALUES (%s, '%s')", $hash, $felhasznalo);
$db->query($query); // itt éppen a PHPLIB db felületet használjuk

mail

(PHP 3, PHP 4 )

mail -- Levelet küld

Leírás

bool mail ( string to, string subject, string message [, string additional_headers])

A mail() automatikusan a message paraméterben megadott levelet a to paraméterben megadott címzettnek. A levél témamegjelölését a subject határozza meg. Több címzettet is megadhatsz, ha vesszőt teszel a címzettek listájában az email címek közé a to paraméterében. Levélmellékletek és egyéb különleges tartalmú levelek küldésére is használható ez a függvény. Ezeket a MIME kódolással érhetők el, amelyről részletesebb leírást egy Zend cikkben vagy a PEAR Mime Classes c. található.

A követkeő RFC-k is számos segítséget nyújthatnak: RFC 1896, RFC 2045, RFC 2046, RFC 2047, RFC 2048 és RFC 2049.

A mail() TRUE-val tér vissza, ha levelet sikeresen elküldte máskülönben FALSE-szal.

Példa 1. Email küldése

mail("joecool@example.com", "Témamegjelölés", "Első sor\nMásodik sor\nHarmadik sor");

A negyedik paraméter megadott szöveg az email fejléc végére kerül. Ez nagyon gyakran újabb fejlécek elküldésére használható, több ilyen esetén azokat az újsorkarakterrel kell elválasztani.

Megjegyzés: A fejlécek elválasztására a \r\n karaktersorozatot kell használni még akkor is, ha néhány Unix levéltovábbító elem az egyszerű újsorkarakterrel (\n) is beéri. A Cc: fejléc kis- és nagy betűre érzékeny, így Cc: kell írni Win32 rendszereken. A Bcc: fejlécet nem támogatják a Win32 rendszerek.

Példa 2. e-mail küldése kiegészítő fejlécekkel

mail("nobody@example.com", "Téma", $uzenet,
     "From: webmaster@$SERVER_NAME\r\n".
     "Reply-To: webmaster@$SERVER_NAME\r\n".
     "X-Mailer: PHP/" . phpversion());

Az additional_parameters paraméter használható arra, hogy a levélküldőként beállított program számára további paramétereket lehessen átadni, lásd: sendmail_path). Ezzel például a levél mellé a feladó 'borítékot' is küldhet a sendmail-t használva. Szükség lehet a webszervert futtató felhasználót sendmail beállításai közé felvenni, hogy a levelekbe ne kerüljenek X-Warning fejlécek, ha ezzel a módszerrel küldesz 'borítékot' a levél mellé.

Példa 3. Kiegészítő fejléces levél küldése és további parancssori paraméterek átadása

mail("nobody@example.com", "a tárgy", $uzenet,
     "From: webmaster@$SERVER_NAME", "-fwebmaster@$SERVER_NAME");

Megjegyzés: Az ötödik paraméter PHP 4.0.5-től elérhető.

Egyszerű sztring kezelő módszerekkel lehet összetettebb e-mail üzenetek összeállításához:

Példa 4. Komplexebb email küldése

/* címzettek */
$kinek  = "Mari <mari@example.com>" . ", " ; // figyelj a vesszőre!
$kinek .= "Kolos <kolos@example.com>";

/* tárgy */
$targy = "Augusztusi Születésnapi Emlékeztető";

/* üzenet */
$uzenet = '
<html>
<head>
 <title>Augusztusi Születésnapi Emlékeztető</title>
</head>
<body>
<p>Itt van az augusztusi születésnapok listája!</p>
<table>
 <tr>
  <th>Személy</th><th>Év</th><th>Hónap</th><th>Nap</th>
 </tr>
 <tr>
  <td>Jocó</td><td>1970</td><td>augusztus</td><td>3.</td>
  <td>Saci</td><td>1973</td><td>augusztus</td><td>17.</td>
 </tr>
</table>
</body>
</html>
';

/* HTML levél küldése a Content-type fejléc megadásával */
$fejlec  = "MIME-Version: 1.0\r\n";
$fejlec .= "Content-type: text/html; charset=iso-8859-2\r\n";

/* további fejlécek */
$fejlec .= "From: Szuletesnapi Emlekezteto <szulinap@example.com>\r\n";

$fejlec .= "Cc: szulinaptar@example.com\r\n";
$fejlec .= "Bcc: szulinapell@example.com\r\n";

/* és most küldjük el! */
mail($kinek, $targy, $uzenet, $fejlec);

Megjegyzés: Biztosítani kell, hogy a ne legyen egyetlen újsorkarakter sem a to vagy a subject fejlécben, mert különben nem megfelelően lesz kiküldve a levél.

LI. mailparse functions

Bevezetés

Figyelem

Ez a kiterjesztés KÍSÉRLETI JELLEGGEL MŰKÖDIK. Ez azt jelenti, hogy minden itt dokumentált működés, beleértve a függvények nevét, működését vagy bármi más, amit a kiterjesztés kapcsán leírtunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a kiterjesztést csak a saját felelősségedre használd!

This extension has been moved from PHP as of PHP 4.2.0 and now mailparse lives in PECL.


Telepítés

These functions are only available if PHP was configured with --enable-mailparse.

Tartalom
mailparse_determine_best_xfer_encoding --  Figures out the best way of encoding the content read from the file pointer fp, which must be seek-able
mailparse_msg_create -- Returns a handle that can be used to parse a message
mailparse_msg_extract_part_file -- Extracts/decodes a message section, decoding the transfer encoding
mailparse_msg_extract_part --  Extracts/decodes a message section. If callbackfunc is not specified, the contents will be sent to "stdout"
mailparse_msg_free -- Frees a handle allocated by mailparse_msg_create()
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 -- Parse file and return a resource representing the structure
mailparse_msg_parse -- Incrementally parse data into buffer
mailparse_rfc822_parse_addresses --  Parse addresses and returns a hash containing that data
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. Returns an array listing filename information

mailparse_determine_best_xfer_encoding

(4.1.0 - 4.1.2 only)

mailparse_determine_best_xfer_encoding --  Figures out the best way of encoding the content read from the file pointer fp, which must be seek-able

Description

int mailparse_determine_best_xfer_encoding ( resource fp)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mailparse_msg_create

(4.1.0 - 4.1.2 only)

mailparse_msg_create -- Returns a handle that can be used to parse a message

Description

int mailparse_msg_create ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mailparse_msg_extract_part_file

(4.1.0 - 4.1.2 only)

mailparse_msg_extract_part_file -- Extracts/decodes a message section, decoding the transfer encoding

Description

string mailparse_msg_extract_part_file ( resource rfc2045, string filename [, string callbackfunc])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mailparse_msg_extract_part

(4.1.0 - 4.1.2 only)

mailparse_msg_extract_part --  Extracts/decodes a message section. If callbackfunc is not specified, the contents will be sent to "stdout"

Description

void mailparse_msg_extract_part ( resource rfc2045, string msgbody [, string callbackfunc])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mailparse_msg_free

(4.1.0 - 4.1.2 only)

mailparse_msg_free -- Frees a handle allocated by mailparse_msg_create()

Description

void mailparse_msg_free ( resource rfc2045buf)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mailparse_msg_get_part_data

(4.1.0 - 4.1.2 only)

mailparse_msg_get_part_data -- Returns an associative array of info about the message

Description

array mailparse_msg_get_part_data ( resource rfc2045)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mailparse_msg_get_part

(4.1.0 - 4.1.2 only)

mailparse_msg_get_part -- Returns a handle on a given section in a mimemessage

Description

int mailparse_msg_get_part ( resource rfc2045, string mimesection)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mailparse_msg_get_structure

(4.1.0 - 4.1.2 only)

mailparse_msg_get_structure -- Returns an array of mime section names in the supplied message

Description

array mailparse_msg_get_structure ( resource rfc2045)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mailparse_msg_parse_file

(4.1.0 - 4.1.2 only)

mailparse_msg_parse_file -- Parse file and return a resource representing the structure

Description

resource mailparse_msg_parse_file ( string filename)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mailparse_msg_parse

(4.1.0 - 4.1.2 only)

mailparse_msg_parse -- Incrementally parse data into buffer

Description

void mailparse_msg_parse ( resource rfc2045buf, string data)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mailparse_rfc822_parse_addresses

(4.1.0 - 4.1.2 only)

mailparse_rfc822_parse_addresses --  Parse addresses and returns a hash containing that data

Description

array mailparse_rfc822_parse_addresses ( string addresses)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mailparse_stream_encode

(4.1.0 - 4.1.2 only)

mailparse_stream_encode --  Streams data from source file pointer, apply encoding and write to destfp

Description

bool mailparse_stream_encode ( resource sourcefp, resource destfp, string encoding)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mailparse_uudecode_all

(no version information, might be only in CVS)

mailparse_uudecode_all --  Scans the data from fp and extract each embedded uuencoded file. Returns an array listing filename information

Description

array mailparse_uudecode_all ( resource fp)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

LII. Matematikai függvények

Bevezetés

Ezek a matematikai függvények csak a gépeden ábrázolható integer és float típusok értéktartományába eső értékeket képes kezelni (ez jelenleg azonos a C beli long és double típusokéval). Ha nagyobb számokat kell kezelni, akkor a nézd meg a BCMath tetszőleges pontosságú matematikai függvényeket..


Követelmények

Az itt leírt függvények használatához semmilyen külső függvénykönyvtár megléte nem szükségeltetik.


Telepítés

Semmilyen telepítés nem szükséges ezen függvények használatához, a PHP alapelemei.


Futásidejű beállítások

Ez a kiterjesztés semmilyen konfigurációs beállításokat nem definiál a php.ini állományban.


Erőforrás típusok

Ez a kiterjesztés semmilyen erőforrás típust nem definiál.


Előre definiált állandók

Az itt felsorolt konstansok mindig elérthetőek, mivel részei a PHP alaptelepítésének.

Táblázat 1. Matematikai állandók

ÁllandóÉrtékLeírás
M_PI3.14159265358979323846Pi
M_E2.7182818284590452354e
M_LOG2E1.4426950408889634074log_2 e
M_LOG10E0.43429448190325182765log_10 e
M_LN20.69314718055994530942log_e 2
M_LN102.30258509299404568402log_e 10
M_PI_21.57079632679489661923pi/2
M_PI_40.78539816339744830962pi/4
M_1_PI0.318309886183790671541/pi
M_2_PI0.636619772367581343082/pi
M_SQRTPI1.77245385090551602729sqrt(pi) [4.0.2]
M_2_SQRTPI1.128379167095512573902/sqrt(pi)
M_SQRT21.41421356237309504880sqrt(2)
M_SQRT31.73205080756887729352sqrt(3) [4.0.2]
M_SQRT1_20.707106781186547524401/sqrt(2)
M_LNPI1.14472988584940017414log_e(pi) [4.0.2]
M_EULER0.57721566490153286061Euler constant [4.0.2]
PHP 4.0.0 verziójáig csak az M_PI használható. Minden más állandó PHP 4.0.0-tól kezdve elérhető, kivéve amelyiknél a [4.0.2] címke olvasható: ezek csak PHP 4.0.2-tól kezdve.

Tartalom
abs -- abszolút érték
acos -- arkusz koszinusz
acosh -- area hiperbolikus koszinusz
asin -- arkusz szinusz
asinh -- area hiperbolikus szinusz
atan2 -- két változó arkusz tangense
atan -- arkusz tangens
atanh -- area hiperbolikus tangens
base_convert -- tetszőleges számrendszerbe vált át egy számot
bindec -- binárisból tizes számrendszerbe vált át
ceil -- törtrésszel bíró számot felfelé kerekíti
cos -- koszinusz
cosh -- hiperbolikus koszinusz
decbin -- tízes számrendszerből kettesbe vált át
dechex -- tízes számrendszerből tizenhatosba vált át
decoct -- tízes számrendszerből nyolcasba vált át
deg2rad -- fokból radiánba vált át
exp -- e a(z) ... -re emelve
expm1 --  exp(number) - 1 pontos értéke, még ha a number 0-hoz közeli értékű is
floor -- lefelé kerekíti a törtrésszel bíró számot
fmod -- Returns the floating point remainder (modulo) of the division of the arguments
getrandmax -- a legnagyobb lehetséges véletlen számot adja vissza
hexdec -- tizenhatos számrendszerből tízesbe vált át
hypot --  a sqrt( num1*num1 + num2*num2) értékét adja vissza
is_finite -- 
is_infinite -- 
is_nan -- 
lcg_value -- Kombinált lineáris kongruencia generátor
log10 -- tízes alapú logaritmus
log1p --  log(1 + number) pontos értékét adja vissza, akkor is ha a paraméter értéke 0-hoz közeli
log -- természetes alapú logaritmus
max -- megkeresi a legnagyobb értéket
min -- megkeresi a legkisebb értéket
mt_getrandmax -- visszaadja a lehetséges legnagyobb véletlenszámot
mt_rand -- véletlenszámot generál - jobban :)
mt_srand --  beállítja a "jobbik" véletlenszám generátor kiinduló értékét
octdec -- nyolcas számrendszerből tízesbe vált át
pi -- visszaadja pi értékét
pow -- hatványozás
rad2deg -- radiánból fokokra vált
rand -- véletlenszámot generál
round -- lebegőpontos számot kerekít
sin -- szinusz
sinh -- hiperbolikus szinusz
sqrt -- négyzetgyököt von
srand -- a véletlenszámgenerátor kiinduló értékét állítja be
tan -- tangens
tanh -- hiperbolikus tangens

abs

(PHP 3, PHP 4 )

abs -- abszolút érték

Leírás

mixed abs ( mixed number)

A number szám abszolút értékével tér vissza. Ha a number paraméterben átadott szám float típusú,akkor a visszaadott érték is float típusú lesz, egyébként integer. (Mivel egy float-nak általában nagyobb az értéke, mint egy integer-nek.)

Példa 1. abs() példa

$abs  = abs(-4.2); // $abs  = 4.2; (double/float) 
$abs2 = abs(5);    // $abs2 = 5; (integer) 
$abs3 = abs(-5);   // $abs3 = 5; (integer)

acos

(PHP 3, PHP 4 )

acos -- arkusz koszinusz

Leírás

float acos ( float arg)

Az arg arkusz koszinuszát adja vissza radiánban. Az acos() a cos() függvény inverzfüggvénye, ami azt jelenti, hogy fennáll az a==cos(acos(a)) minden olyan a értékre, amely az acos() értelmezési tartományába esik.

Lásd még: acosh(), asin() és atan()!

acosh

(PHP 4 >= 4.1.0)

acosh -- area hiperbolikus koszinusz

Leírás

float acosh ( float arg)

Az arg area hiperbolikus koszinuszát adja vissza, azt az értéket, amelynek hiperbolikus koszinusza egyenlő az arg paraméterrel.

Megjegyzés: Ez a függvény nem működik Windows operációs rendszereken!

Lásd még: acos(), asinh() és atanh()!

asin

(PHP 3, PHP 4 )

asin -- arkusz szinusz

Leírás

float asin ( float arg)

Az arg arkusz szinuszát adja vissza radiánban. Az asin() a sin() inverzfüggvénye, ami azt jelenti, hogy a==sin(asin(a)) fennáll minden olyan a értékre, amely a asin() értelmezési tartományába esik.

Lásd még: acos() és atan()!

asinh

(PHP 4 >= 4.1.0)

asinh -- area hiperbolikus szinusz

Leírás

float asinh ( float arg)

Az arg area hiperbolikus szinuszával tér vissza, azzal az értékkel, amelynnek hiperbolikus szinusza egyenlő az arg paraméterrel.

Megjegyzés: Ez a függvény nem működik Windows operációs rendszereken!

Lásd még: asin(), acosh() és atanh()!

atan2

(PHP 3>= 3.0.5, PHP 4 )

atan2 -- két változó arkusz tangense

Leírás

float atan2 ( float y, float x)

Ez a függvény az x és y által meghatározott érték arkusz tangensét adja vissza radiánban. Ez hasonló az y / x arkusz tangenséhez, attól eltekintve hogy a paraméterek előjele meghatározza, hogy az eredmény melyik körnegyedbe esik.

A függvény eredményét radiánban adja vissza, ami -PI és +PI közé esik (beleértve a határokat is).

Lásd még: acos() és atan()!

atan

(PHP 3, PHP 4 )

atan -- arkusz tangens

Leírás

float atan ( float arg)

A arg arkusz tangensét adja vissza radiánban. Az atan() a tan() inverzfüggvénye, ami azt jelenti, hogy a==tan(atan(a)) fennáll minden olyan a értékre, amely a atan() értelmezési tartományába esik.

Lásd még: asin() és acos()!

atanh

(PHP 4 >= 4.1.0)

atanh -- area hiperbolikus tangens

Leírás

float atanh ( float arg)

Az arg area hiperbolikus tangensével tér vissza, azzal az értékkel, amelynek hiiperbolikus tangense egyenlő az arg paraméterrel.

Megjegyzés: Ez a függvény nem működik Windows operációs rendszereken!

Lásd még: atan(), asinh() és acosh()!

base_convert

(PHP 3>= 3.0.6, PHP 4 )

base_convert -- tetszőleges számrendszerbe vált át egy számot

Leírás

string base_convert ( string number, int frombase, int tobase)

A number-ben átadott számot váltja át a tobase-ben megadott alapszámú számrendszerbe, és ezzel tér vissza. A number alapszáma a frombase-ben adható meg. Mind a frombase és tobase paraméternek 2 és 36 közé kell esnie. A 10-nél nagyobb értékű számjegyeket betűkkel ábrázoljuk, ahol az "a" 10-et jelent, a "b" 11-et és a "z" 35-öt.

Példa 1. base_convert()

$binaris = base_convert ($hexadecimalis, 16, 2);

bindec

(PHP 3, PHP 4 )

bindec -- binárisból tizes számrendszerbe vált át

Leírás

int bindec ( string binary_string)

A binary_string kettes számrendszerbeli (bináris) szám tizes számrendszerbeli (decimális) megfelelőjét adja vissza.

A bindec() függvény integer típusúvá konvertálja át a bináris számot. A legnagyobb konvertálható szám a 31 db 1 bitből álló szám, vagyis 2147483647 (10-es számrendszerben).

Lásd még: decbin()!

ceil

(PHP 3, PHP 4 )

ceil -- törtrésszel bíró számot felfelé kerekíti

Leírás

float ceil ( float value)

Ha szükséges, akkor a következő legnagyobb egész számmal tér vissza a value-t felfelé kerekítve. A ceil() által visszadott érték float típusú, mivel a float értékészlete általában nagyobb, mint int-é.

Példa 1. ceil() példák

echo ceil(4.3);   //  5
echo ceil(9.999); // 10

Lásd még: floor() és round()!

cos

(PHP 3, PHP 4 )

cos -- koszinusz

Leírás

float cos ( float arg)

A radiában megadott arg koszinuszát adja vissza.

Lásd még: acos(), sin(), tan() és deg2rad()!

cosh

(PHP 4 >= 4.1.0)

cosh -- hiperbolikus koszinusz

Leírás

float cosh ( float arg)

Az arg hiperbolikus koszinuszát adja vissza, amelyet a (exp(arg) + exp(-arg))/2 kifejezéssel határozható meg.

Lásd még: cos(), acosh(), sin() és tan()!

decbin

(PHP 3, PHP 4 )

decbin -- tízes számrendszerből kettesbe vált át

Leírás

string decbin ( int number)

A number kettes számrendszerbeli ábrázolását sztringként adja vissza. A legnagyobb átváltható szám 4294967295 (tízes számrendszerben), ami 31 db 1-esből álló sztringet eredményez.

Lásd még: bindec()!

dechex

(PHP 3, PHP 4 )

dechex -- tízes számrendszerből tizenhatosba vált át

Leírás

string dechex ( int number)

A number tizenhatos számrendszerbeli ábrázolását sztringként adja vissza. A legnagyobb átváltható szám 2147483647 (tízes számrendszerben), ami "7fffffff"-et ad eredményül.

Lásd még: hexdec()!

decoct

(PHP 3, PHP 4 )

decoct -- tízes számrendszerből nyolcasba vált át

Leírás

string decoct ( int number)

A number nyolcas számrendszerbeli ábrázolását sztringként adja vissza. A legnagyobb átváltható szám 2147483647 (tízes számrendszerben), ami "17777777777"-et ad eredményül.

Lásd még: octdec()!

deg2rad

(PHP 3>= 3.0.4, PHP 4 )

deg2rad -- fokból radiánba vált át

Leírás

float deg2rad ( float number)

Ez a függvény a number paraméterben megadott fokokat radiánba váltja át.

Lásd még: rad2deg()!

exp

(PHP 3, PHP 4 )

exp -- e a(z) ... -re emelve

Leírás

float exp ( float arg)

Visszaadja, hogy mennyivel egyenlő az e az arg-ban megadott hatványon.

Lásd még: pow()!

expm1

(PHP 4 >= 4.1.0)

expm1 --  exp(number) - 1 pontos értéke, még ha a number 0-hoz közeli értékű is

Leírás

float expm1 ( float number)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

floor

(PHP 3, PHP 4 )

floor -- lefelé kerekíti a törtrésszel bíró számot

Leírás

float floor ( float value)

Ha szükséges, akkor a megelőző legkisebb egész számmal tér vissza a value-t lefelé kerekítve. A floor() által visszadott érték float típusú, mivel a float értékészlete általában nagyobb, mint int-é.

Példa 1. floor() példa

echo floor(4.3);   // 4
echo floor(9.999); // 9

Lásd még: ceil() és round()!

fmod

(PHP 4 >= 4.2.0)

fmod -- Returns the floating point remainder (modulo) of the division of the arguments

Description

float fmod ( float x, float y)

Returns the floating point remainder of dividing the dividend (x) by the divisor (y). The reminder (r) is defined as: x = i * y + r, for some integer i. If y is non-zero, r has the same sign as x and a magnitude less than the magnitude of y.

Példa 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
?>

getrandmax

(PHP 3, PHP 4 )

getrandmax -- a legnagyobb lehetséges véletlen számot adja vissza

Leírás

int getrandmax ( void )

A legnagyobb lehetséges véletlen számot adja vissza, amit a rand() a meghívásakor visszaadhat.

Lásd még: rand(), srand() és mt_getrandmax()!

hexdec

(PHP 3, PHP 4 )

hexdec -- tizenhatos számrendszerből tízesbe vált át

Leírás

int hexdec ( string hex_string)

A tizenhatos számrendszerbeli hex_string tízes számrendszerbeli megfelelőjével tér vissza. A legnagyobb átváltható szám a 7fffffff, azaz 2147483647 (tízes számrendszerben).

A hexdec() a hex_string nem hexadecimális karaktereit 0-ra cseréli, és minden baloldali nullát figyelmen kívül hagy, de a jobboldaliak beszámítanak az eredménybe.

Példa 1. hexdec() példa

var_dump(hexdec("hee"));
var_dump(hexdec("ee"));
// mindkettő: int(238)

var_dump(hexdec("az"));
var_dump(hexdec("a0"));
// mindkettő: int(160)

Lásd még: dechex()!

hypot

(PHP 4 >= 4.1.0)

hypot --  a sqrt( num1*num1 + num2*num2) értékét adja vissza

Leírás

float hypot ( float num1, float num2)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

is_finite

(PHP 4 >= 4.2.0)

is_finite -- 

Leírás

bool is_finite ( float val)

TRUE-val tér vissza, ha a val olan érvényes véges számot, amely belefér a PHP-t futtató platform lebegőpontos ábrázolási tartományába.

is_infinite

(PHP 4 >= 4.2.0)

is_infinite -- 

Description

bool is_infinite ( float val)

TRUE-val tér vissza, ha a val pozitív vagy negatív végtelen, mint pl. a log(0) értéke, vagy bármely más érték, amely nem belefér a PHP-t futtató platform lebegőpontos ábrázolási tartományába.

is_nan

(PHP 4 >= 4.2.0)

is_nan -- 

Leírás

bool is_nan ( float val)

TRUE-val tér vissza, ha val nem szám, mint pl. a acos(1.01) eredménye.

Megjegyzés: Az előző példából láthatóan ez akkor fordulhat elő, ha például valamilyen matematikai műveletnek értelmezési tartományán kívüli értéket adunk át, pl. arkusza csak -1 és +1 közé eső számoknak lehet.

lcg_value

(PHP 4 )

lcg_value -- Kombinált lineáris kongruencia generátor

Leírás

float lcg_value ( void )

A lcg_value() ál véletlenszámot ad vissza a (0,1) intervallumból. A függvény két, 2^31 - 85 és 2^31 - 249 periódusú CG-t kombinál, és a periódusa ennek a két prímnek a szorzatával egyenlő.

log10

(PHP 3, PHP 4 )

log10 -- tízes alapú logaritmus

Leírás

float log10 ( float arg)

Az arg tízes alapú logaritmusát adja vissza.

log1p

(PHP 4 >= 4.1.0)

log1p --  log(1 + number) pontos értékét adja vissza, akkor is ha a paraméter értéke 0-hoz közeli

Leírás

float log1p ( float number)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

log

(PHP 3, PHP 4 )

log -- természetes alapú logaritmus

Leírás

float log ( float arg)

Az arg természetes (e) alapú logaritmusát adja vissza.

max

(PHP 3, PHP 4 )

max -- megkeresi a legnagyobb értéket

Leírás

mixed max ( mixed arg1, mixed arg2, mixed argn)

A max() a paraméterként átadott, számként értelmezett értékek legnagyobbjával tér vissza.

Ha az első paraméter tömb típusú, akkor a tömbbeli legnagyobb értéket adja vissza. Ha az első paraméter integer, float vagy string típusú, akkor legalább két paraméterrel kell meghívni a függvényt, és az a legnagyobb értékű számmal tér vissza. Korlátlan számú paraméterrel hívható meg ez a függvény.

Ha legalább egy összehasonlítandó érték float típusú, akkor mindegyik float-ként lesz kezelve és a visszatérési érték is float lesz. Ha egyik sem float, akkor mindegyik integer-ként lesz kezelve, és a visszatérési érték is integer lesz.

min

(PHP 3, PHP 4 )

min -- megkeresi a legkisebb értéket

Leírás

number min ( number arg1, number arg2 [, ...])

number min ( array numbers)

A min() a paraméterként átadott, számként értelmezett értékek legkisebbjével tér vissza. ha ezek közül valamelyik értéke nem meghatározott, akkor a min() hibát jelez.

Ha az első paraméter tömb típusú, akkor a tömbbeli legkisebb értéket adja vissza. Ha az első paraméter integer, float vagy string típusú, akkor legalább két paraméterrel kell meghívni a függvényt, és az a legkisebb értékű számmal tér vissza. Korlátlan számú paraméterrel hívható meg ez a függvény.

Ha legalább egy összehasonlítandó érték float típusú, akkor mindegyik float-ként lesz kezelve és a visszatérési érték is float lesz. Ha egyik sem float, akkor mindegyik integer-ként lesz kezelve, és a visszatérési érték is integer lesz. Hiba esetén a min() NULL értékkel tér vissza, és E_WARNING szintű hibát generál.

<?php
$a = 4;
$b = 9;
$c = 3;
$arr = array(99, 34, 11);
// Saját hiba ellenőrzéssel elejét lehet venni a lehetséges hibáknak
// (pl. egy változó nincs létrehozva)
if (!$min_value = @min($a, $b, $c)) {
    echo "Nem lehet meghatározni a legkisebb értéket, próbáld újra.";
} else {
    echo "A legkisebb értk: $min_value.";
}
print min($arr);  // 11
?>

Lásd még: max()!

mt_getrandmax

(PHP 3>= 3.0.6, PHP 4 )

mt_getrandmax -- visszaadja a lehetséges legnagyobb véletlenszámot

Leírás

int mt_getrandmax ( void )

Visszaadja azt a legnagyobb véletlenszámot, amit az mt_rand() a meghívásakor visszadhat.

Lásd még: mt_rand(), mt_srand() és getrandmax()!

mt_rand

(PHP 3>= 3.0.6, PHP 4 )

mt_rand -- véletlenszámot generál - jobban :)

Leírás

int mt_rand ( [int min, int max])

A régebbi libc-k véletlenszám generátorai kétes vagy bizonytalan jellegűek és lassúak voltak. Alapértelmezés szerint, a PHP a libc véletlenszám generátorát használja a rand() függvényben. A mt_rand() függvény egy "beugrós" helyettesítése ennek. Ez egy ismert jellemvonásokkal bíró véletlenszám generátor, a Mersenne Twister, ami többféle kriptogáfiai eljárás inicializálásához (seeding) is megfelelő véletlenszámokat generál kb. négyszer gyorsabban, mint az átlagos libc rand függvények. (Részletesebb információkért nézd meg a Mersenne Twister honlapját).

Ha a min és max paraméterek nélkül hívod meg az mt_rand() függvényt, akkor az ál véletlenszám értéke 0 és RAND_MAX közé fog esni. Ha pl. 5 és 15 közé (bezárólag) eső véletlen számot akarsz kapni, akkor mt_rand(5, 15) kell írni.

Régebbi PHP verziókban a véletlenszám generátor kiinduló értékét a mt_srand() függvénnyel kell beállítani, de a 4.2.0-tól ez már nem szükséges.

Megjegyzés: A 3.0.7 verziók előtt a max paraméter helyett range (tartomány) szerepelt. Ezekben a verziókban az előző példával egyenértékű megoldás a mt_rand (5, 11), hogy 5 és 15 közé eső véletlen számot kapj.

Lásd még: mt_srand(), mt_getrandmax() és rand()!

mt_srand

(PHP 3>= 3.0.6, PHP 4 )

mt_srand --  beállítja a "jobbik" véletlenszám generátor kiinduló értékét

Leírás

void mt_srand ( int seed)

Beállítja a véletlenszám generátor kiinduló értékét seed-re.

// beállítás ezredmásodpercekkel
function make_seed() {
    list($usec, $sec) = explode(' ', microtime());
    return (float) $sec + ((float) $usec * 100000);
}
mt_srand(make_seed());
$randval = mt_rand();

Megjegyzés: PHP 4.2.0 verziótól kezdve nem szükséges a véletlenszám-generátort beállítani a használata előtt.

Lásd még: mt_getrandmax(), srand() és mt_rand()!

octdec

(PHP 3, PHP 4 )

octdec -- nyolcas számrendszerből tízesbe vált át

Leírás

int octdec ( string octal_string)

A nyolcas számrendszerbeli octal_string tízes számrendszerbeli megfelelőjével tér vissza. A legnagyobb átváltható szám "17777777777", ami 2147483647-et (tízes számrendszerben) ad eredményül.

Lásd még: decoct()!

pi

(PHP 3, PHP 4 )

pi -- visszaadja pi értékét

Leírás

float pi ( void )

PI megközelítőleg pontos értékét adja vissza. A visszaadott float érték pontossága a php.ini-ben megadott precision beállítástól függ, amely alapértelmezésben 14. A M_PI állandó használata ugyanazt az eredményt adja, mint a pi() függvény.

echo pi(); // 3.1415926535898
echo M_PI; // 3.1415926535898

pow

(PHP 3, PHP 4 )

pow -- hatványozás

Leírás

number pow ( number base, number exp)

A base-t az exp hatványra emelt értékével tér vissza. Ha lehetséges, akkor a függvény visszatérési értéke integer lesz.

Ha a hatványérték nem számítható ki, akkor egy "nem fatális" (warning) hibát jelez a pow() függvény, és FALSE-szal tér vissza.

Példa 1. Néhány példa a pow() alkalmazására

<?php

var_dump( pow(2,8) ); // int(256)
echo pow(-1,20); // 1
echo pow( 0, 0); // 1

echo pow(-1, 5.5); // hiba

?>

Figyelem

PHP 4.0.6-ban és korábbi verziókban a pow() mindig float típussal tért vissza, és soha nem jelzett hibát.

Lásd még: exp() és sqrt()!

rad2deg

(PHP 3>= 3.0.4, PHP 4 )

rad2deg -- radiánból fokokra vált

Leírás

float rad2deg ( float number)

Ez a függvény a radiánban értlemezett number paramétert fokokba váltja.

Lásd még: deg2rad()!

rand

(PHP 3, PHP 4 )

rand -- véletlenszámot generál

Leírás

int rand ( void )

int rand ( [int min, int max])

Ha a min és max paraméterek nélkül hívod meg az mt_rand() függvényt, akkor az ál véletlenszám értéke 0 és RAND_MAX közé fog esni. Ha pl. 5 és 15 közé (bezárólag) eső véletlen számot akarsz kapni, akkor mt_rand(5, 15) kell írni.

Régebbi PHP verziókban a véletlenszám-generátor kiinduló értékét a srand() függvénnyel kell beállítani, de a 4.2.0-tól ez már nem szükséges.

Megjegyzés: A 3.0.7 verziók előtt a max paraméter helyett range (tartomány) szerepelt. Ezekben a verziókban az előző példával egyenértékű megoldás a mt_rand (5, 11), hogy 5 és 15 közé eső véletlen számot kapj.

Lásd még: srand(), getrandmax() és mt_rand()!

round

(PHP 3, PHP 4 )

round -- lebegőpontos számot kerekít

Leírás

float round ( float val [, int precision])

A val paraméter precision-ben megadott pontosságra kerekített értékével tér vissza. A precision a tizedespont után (ill. előtte) álló számjegyek számát jelenti. A precision nulla vagy negatív szám is lehet.

Figyelem

PHP nem kezeli megfelelően a "12,300.2"-hez hasonló sztringeket alapértelmezés szerint. Lásd string konverziók!

echo round(3.4);  // 3
echo round(3.5);  // 4
echo round(3.6);  // 4
echo round(3.6, 0);      // a fentivel azonos
echo round(1.95583, 2);  // 1.96
echo round(1241757, -3); // 1242000

Megjegyzés: A precision paraméter csak PHP 4-től használható.

Lásd még: ceil() és floor()!

sin

(PHP 3, PHP 4 )

sin -- szinusz

Leírás

float sin ( float arg)

A radiánban megadott arg szinuszát adja vissza.

<?php
// a pontosság függ a precision konfigurációs direktívától
print sin(deg2rad(60));  //  0.866025403...
print sin(60);           // -0.304810621...
?>

Lásd még: cos() és tan()!

sinh

(PHP 4 >= 4.1.0)

sinh -- hiperbolikus szinusz

Leírás

float sinh ( float arg)

Az arg hiperbolikus szinuszát adja vissza, amelyet a (exp(arg) - exp(-arg))/2 kifejezés határoz meg.

Lásd még: sin(), asinh(), cos() és tan()!

sqrt

(PHP 3, PHP 4 )

sqrt -- négyzetgyököt von

Leírás

float sqrt ( float arg)

Az arg négyzetgyökét adja vissza.

<?php
// a pontosság függ a precision konfigurációs direktívától
echo sqrt(9);  // 3
echo sqrt(10); // 3.16227766 ...
?>

Lásd még: pow()!

srand

(PHP 3, PHP 4 )

srand -- a véletlenszámgenerátor kiinduló értékét állítja be

Leírás

void srand ( int seed)

Beállítja a véletlenszám generátor kiinduló értékét seed-re.

// beállítás ezredmásodpercekkel
function make_seed() {
    list($usec, $sec) = explode(' ', microtime());
    return (float) $sec + ((float) $usec * 100000);
}
srand(make_seed());
$randval = rand();

Megjegyzés: PHP 4.2.0 verziótól kezdve nem szükséges a véletlenszám-generátort beállítani a használata előtt.

Lásd még: rand(), getrandmax() és mt_srand()!

tan

(PHP 3, PHP 4 )

tan -- tangens

Leírás

float tan ( float arg)

A radiánban megadott arg tangensét adja vissza.

Lásd még: atan(), sin(), cos() és deg2rad()!

tanh

(PHP 4 >= 4.1.0)

tanh -- hiperbolikus tangens

Leírás

float tanh ( float arg)

Az arg hiperbolikus tangensét adja vissza, amelyet a sinh(arg)/cosh(arg) kifejezés definiál.

Lásd még: tan(), atanh(), sin() és cos()!

LIII. Multi-Byte String Functions

Bevezetés

There are many languages in which all characters can be expressed by single byte. Multi-byte character codes are used to express many characters for many languages. mbstring is developed to handle Japanese characters. However, many mbstring functions are able to handle character encoding other than Japanese.

A multi-byte character encoding represents single character with consecutive bytes. Some character encoding has shift(escape) sequences to start/end multi-byte character strings. Therefore, a multi-byte character string may be destroyed when it is divided and/or counted unless multi-byte character encoding safe method is used. This module provides multi-byte character safe string functions and other utility functions such as conversion functions.

Since PHP is basically designed for ISO-8859-1, some multi-byte character encoding does not work well with PHP. Therefore, it is important to set mbstring.language to appropriate language (i.e. "Japanese" for Japanese) and mbstring.internal_encoding to a character encoding that works with PHP.

PHP 4 Character Encoding Requirements

  • Per byte encoding

  • Single byte characters in range of 00h-7fh which is compatible with ASCII

  • Multi-byte characters without 00h-7fh

These are examples of internal character encoding that works with PHP and does NOT work with PHP.

Character encodings work with PHP: 
ISO-8859-*, EUC-JP, UTF-8

Character encodings do NOT work with PHP:
JIS, SJIS

Character encoding, that does not work with PHP, may be converted with mbstring's HTTP input/output conversion feature/function.

Megjegyzés: SJIS should not be used for internal encoding unless the reader is familiar with parser/compiler, character encoding and character encoding issues.

Megjegyzés: If you use databases with PHP, it is recommended that you use the same character encoding for both database and internal encoding for ease of use and better performance.

If you are using PostgreSQL, it supports character encoding that is different from backend character encoding. See the PostgreSQL manual for details.


Telepítés

mbstring is an extended module. You must enable the module with the configure script. Refer to the Install section for details.

The following configure options are related to the mbstring module.

  • --enable-mbstring=LANG: Enable mbstring functions. This option is required to use mbstring functions.

    As of PHP 4.3.0, mbstring extension provides enhanced support for Simplified Chinese, Traditional Chinese, Korean, and Russian in addition to Japanese. To enable that feature, you will have to supply either one of the following options to the LANG parameter; --enable-mbstring=cn for Simplified Chinese support, --enable-mbstring=tw for Traditional Chinese support, --enable-mbstring=kr for Korean support, --enable-mbstring=ru for Russian support, and --enable-mbstring=ja for Japanese support.

    Also --enable-mbstring=all is convenient for you to enable all the supported languages listed above.

    Megjegyzés: Japanese language support is also enabled by --enable-mbstring without any options for the sake of backwards compatibility.

  • --enable-mbstr-enc-trans : Enable HTTP input character encoding conversion using mbstring conversion engine. If this feature is enabled, HTTP input character encoding may be converted to mbstring.internal_encoding automatically.

    Megjegyzés: As of PHP 4.3.0, the option --enable-mbstr-enc-trans will be eliminated and replaced with mbstring.encoding_translation. HTTP input character encoding conversion is enabled when this is set to On (the default is Off).

  • --enable-mbregex: Enable regular expression functions with multibyte character support.


Futásidejű beállítások

Az alábbi függvények viselkedése befolyásolható a php.ini segítségével.

Táblázat 1. Multi-Byte String configuration options

NameDefaultChangeable
mbstring.language"neutral"PHP_INI_SYSTEM | PHP_INI_PERDIR
mbstring.detect_orderNULLPHP_INI_ALL
mbstring.http_input"pass"PHP_INI_ALL
mbstring.http_output"pass"PHP_INI_ALL
mbstring.internal_encodingNULLPHP_INI_ALL
mbstring.script_encodingNULLPHP_INI_ALL
mbstring.substitute_characterNULLPHP_INI_ALL
mbstring.func_overload"0"PHP_INI_SYSTEM | PHP_INI_PERDIR
mbstring.encoding_translation"0"PHP_INI_SYSTEM | PHP_INI_PERDIR
For further details and definition of the PHP_INI_* constants see ini_set().

Here's a short explanation of the configuration directives.

  • mbstring.language defines default language used in mbstring. Note that this option defines mbstring.internal_encoding and mbstring.internal_encoding should be placed after mbstring.language in php.ini

  • mbstring.encoding_translation enables HTTP input character encoding detection and translation into internal character encoding.

  • mbstring.internal_encoding defines default internal character encoding.

  • mbstring.http_input defines default HTTP input character encoding.

  • mbstring.http_output defines default HTTP output character encoding.

  • mbstring.detect_order defines default character code detection order. See also mb_detect_order().

  • mbstring.substitute_character defines character to substitute for invalid character encoding.

  • mbstring.func_overloadoverload(replace) single byte functions by mbstring functions. mail(), ereg(), etc. are overloaded by mb_send_mail(), mb_ereg(), etc. Possible values are 0, 1, 2, 4 or a combination of them. For example, 7 for overload everything. 0: No overload, 1: Overload mail() function, 2: Overload str*() functions, 4: Overload ereg*() functions.

Web Browsers are supposed to use the same character encoding when submitting form. However, browsers may not use the same character encoding. See mb_http_input() to detect character encoding used by browsers.

If enctype is set to multipart/form-data in HTML forms, mbstring does not convert character encoding in POST data. The user must convert them in the script, if conversion is needed.

Although, browsers are smart enough to detect character encoding in HTML. charset is better to be set in HTTP header. Change default_charset according to character encoding.

Példa 1. php.ini setting example

; Set default language
mbstring.language        = Neutral; Set default language to Neutral(UTF-8) (default)
mbstring.language        = English; Set default language to English 
mbstring.language        = Japanese; Set default language to Japanese

;; Set default internal encoding
;; Note: Make sure to use character encoding works with PHP
mbstring.internal_encoding    = UTF-8  ; Set internal encoding to UTF-8

;; HTTP input encoding translation is enabled.
mbstring.encoding_translation = On

;; Set default HTTP input character encoding
;; Note: Script cannot change http_input setting.
mbstring.http_input           = pass    ; No conversion. 
mbstring.http_input           = auto    ; Set HTTP input to auto
                                ; "auto" is expanded to "ASCII,JIS,UTF-8,EUC-JP,SJIS"
mbstring.http_input           = SJIS    ; Set HTTP2 input to  SJIS
mbstring.http_input           = UTF-8,SJIS,EUC-JP ; Specify order

;; Set default HTTP output character encoding 
mbstring.http_output          = pass    ; No conversion
mbstring.http_output          = UTF-8   ; Set HTTP output encoding to UTF-8

;; Set default character encoding detection order
mbstring.detect_order         = auto    ; Set detect order to auto
mbstring.detect_order         = ASCII,JIS,UTF-8,SJIS,EUC-JP ; Specify order

;; Set default substitute character
mbstring.substitute_character = 12307   ; Specify Unicode value
mbstring.substitute_character = none    ; Do not print character
mbstring.substitute_character = long    ; Long Example: U+3000,JIS+7E7E

Példa 2. php.ini setting for EUC-JP users

;; Disable Output Buffering
output_buffering      = Off

;; Set HTTP header charset
default_charset       = EUC-JP    

;; Set default language to Japanese
mbstring.language = Japanese

;; HTTP input encoding translation is enabled.
mbstring.encoding_translation = On

;; Set HTTP input encoding conversion to auto
mbstring.http_input   = auto 

;; Convert HTTP output to EUC-JP
mbstring.http_output  = EUC-JP    

;; Set internal encoding to EUC-JP
mbstring.internal_encoding = EUC-JP    

;; Do not print invalid characters
mbstring.substitute_character = none

Példa 3. php.ini setting for SJIS users

;; Enable Output Buffering
output_buffering     = On

;; Set mb_output_handler to enable output conversion
output_handler       = mb_output_handler

;; Set HTTP header charset
default_charset      = Shift_JIS

;; Set default language to Japanese
mbstring.language = Japanese

;; Set http input encoding conversion to auto
mbstring.http_input  = auto 

;; Convert to SJIS
mbstring.http_output = SJIS    

;; Set internal encoding to EUC-JP
mbstring.internal_encoding = EUC-JP    

;; Do not print invalid characters
mbstring.substitute_character = none


Erőforrás típusok

Ez a kiterjesztés semmilyen erőforrás típust nem definiál.


Előre definiált állandók

Az itt listázott állandókat ez a kiterjesztés definiálja, és csak akkor elérhetőek, ha az adott kiterjesztés be van fordítva a PHP-be, vagy dinamikusan betöltött.

MB_OVERLOAD_MAIL (integer)

MB_OVERLOAD_STRING (integer)

MB_OVERLOAD_REGEX (integer)


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.

Megjegyzés: For PHP 4.3.2 or earlier, if enctype for HTML form is set to multipart/form-data, mbstring does not convert character encoding in POST data. If it is the case, strings are needed to be converted to internal character encoding.

Megjegyzés: Since PHP 4.3.3, if enctype for HTML form is set to multipart/form-data, and, mbstring.encoding_translation is set to On in php.ini POST variables and uploaded filename will be converted to internal character encoding. But, characters specified in 'name' of HTML form will not be converted.

  • HTTP Input

    There is no way to control HTTP input character conversion from PHP script. To disable HTTP input character conversion, it has to be done in php.ini.

    Példa 4. Disable HTTP input conversion in php.ini

    ;; Disable HTTP Input conversion
    mbstring.http_input = pass
    ;; Disable HTTP Input conversion (PHP 4.3.0 or higher)
    mbstring.encoding_translation = Off

    When using PHP as an Apache module, it is possible to override PHP ini setting per Virtual Host 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 ob_start callback function.

    Megjegyzés: For PHP3-i18n users, mbstring's output conversion differs from PHP3-i18n. Character encoding is converted using output buffer.

Példa 5. 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

Példa 6. 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');

?>


Supported Character Encodings

Currently, the following character encoding is supported by the mbstring module. Character encoding may be specified for mbstring functions' encoding parameter.

The following character encoding is supported in this PHP extension:

UCS-4, UCS-4BE, UCS-4LE, UCS-2, UCS-2BE, UCS-2LE, UTF-32, UTF-32BE, UTF-32LE, UCS-2LE, UTF-16, UTF-16BE, UTF-16LE, UTF-8, UTF-7, ASCII, EUC-JP, SJIS, eucJP-win, SJIS-win, ISO-2022-JP, 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, byte2be, byte2le, byte4be, byte4le, BASE64, 7bit, 8bit and UTF7-IMAP.

As of PHP 4.3.0, the following character encoding support will be added experimentally : EUC-CN, CP936, HZ, EUC-TW, CP950, BIG-5, EUC-KR, UHC (CP949), ISO-2022-KR, Windows-1251 (CP1251), Windows-1252 (CP1252), CP866, KOI8-R.

php.ini entry, which accepts encoding name, accepts "auto" and "pass" also. mbstring functions, which accepts encoding name, and accepts "auto".

If "pass" is set, no character encoding conversion is performed.

If "auto" is set, it is expanded to "ASCII,JIS,UTF-8,EUC-JP,SJIS".

See also mb_detect_order()

Megjegyzés: "Supported character encoding" does not mean that it works as internal character code.


Overloading PHP string functions with multi byte string functions

Because almost PHP application written for language using single-byte character encoding, there are some difficulties for multibyte string handling including Japanese. Almost PHP string functions such as substr() do not support multibyte string.

Multibyte extension (mbstring) has some PHP string functions with multibyte support (ex. substr() supports mb_substr()).

Multibyte extension (mbstring) also supports 'function overloading' to add multibyte string functionality without code modification. Using function overloading, some PHP string functions will be overloaded multibyte string functions. For example, mb_substr() is called instead of substr() if function overloading is enabled. Function overload makes easy to port application supporting only single-byte encoding for multibyte application.

mbstring.func_overload in php.ini should be set some positive value to use function overloading. The value should specify the category of overloading functions, should be set 1 to enable mail function overloading. 2 to enable string functions, 4 to regular expression functions. For example, if is set for 7, mail, strings, regex functions should be overloaded. The list of overloaded functions are shown in below.


Basics of Japanese multi-byte characters

Most Japanese characters need more than 1 byte per character. In addition, several character encoding schemes are used under a Japanese environment. There are EUC-JP, Shift_JIS(SJIS) and ISO-2022-JP(JIS) character encoding. As Unicode becomes popular, UTF-8 is used also. To develop Web applications for a Japanese environment, it is important to use the character set for the task in hand, whether HTTP input/output, RDBMS and E-mail.

  • Storage for a character can be up to six bytes

  • A multi-byte character is usually twice of the width compared to single-byte characters. Wider characters are called "zen-kaku" - meaning full width, narrower characters are called "han-kaku" - meaning half width. "zen-kaku" characters are usually fixed width.

  • Some character encoding defines shift(escape) sequence for entering/exiting multi-byte character strings.

  • ISO-2022-JP must be used for SMTP/NNTP.

  • "i-mode" web site is supposed to use SJIS.


References

Multi-byte character encoding and its related issues are very complex. It is impossible to cover in sufficient detail here. Please refer to the following URLs and other resources for further readings.

  • Unicode/UTF/UCS/etc

    http://www.unicode.org/

  • Japanese/Korean/Chinese character information

    ftp://ftp.ora.com/pub/examples/nutshell/ujip/doc/cjk.inf

Tartalom
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_ereg_match --  Regular expression match for multibyte string
mb_ereg_replace -- Replace regular expression with multibyte support
mb_ereg_search_getpos --  Returns start point for next regular expression match
mb_ereg_search_getregs --  Retrieve the result from the last multibyte regular expression match
mb_ereg_search_init --  Setup string and regular expression for multibyte regular expression match
mb_ereg_search_pos --  Return position and length of matched part of multibyte regular expression for predefined multibyte string
mb_ereg_search_regs --  Returns the matched part of 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_output_handler --  Callback function converts character encoding in output buffer
mb_parse_str --  Parse GET/POST/COOKIE data and set global variable
mb_preferred_mime_name -- Get MIME charset string
mb_regex_encoding --  Returns current encoding for multibyte regex as string
mb_regex_set_options --  Set/Get the default options for mbregex functions
mb_send_mail --  Send encoded mail.
mb_split -- Split multibyte string using regular expression
mb_strcut -- Get part of string
mb_strimwidth -- Get truncated string with specified width
mb_strlen -- Get string length
mb_strpos --  Find position of first occurrence of string in a string
mb_strrpos --  Find position of last occurrence of a string in a string
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

mb_convert_case

(PHP 4 >= 4.3.0)

mb_convert_case -- Perform case folding on a string

Description

string mb_convert_case ( string str, int mode [, string encoding])

mb_convert_case() returns case folded version of string converted in the way specified by mode.

mode can be one of MB_CASE_UPPER, MB_CASE_LOWER or MB_CASE_TITLE.

encoding specifies the encoding of str; if omitted, the internal character encoding value will be used.

The return value is str with the appropriate case folding applied.

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

Példa 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
?>

See also mb_strtolower(), mb_strtoupper(), strtolower() and strtoupper().

mb_convert_encoding

(PHP 4 >= 4.0.6)

mb_convert_encoding -- Convert character encoding

Description

string mb_convert_encoding ( string str, string to-encoding [, mixed from-encoding])

mb_convert_encoding() converts character encoding of string str from from-encoding to to-encoding.

str : String to be converted.

from-encoding is specified by character code name before conversion. it can be array or string - comma separated enumerated list. If it is not specified, the internal encoding will be used.

Példa 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");
?>

See also mb_detect_order().

mb_convert_kana

(PHP 4 >= 4.0.6)

mb_convert_kana --  Convert "kana" one from another ("zen-kaku", "han-kaku" and more)

Description

string mb_convert_kana ( string str, string option [, mixed encoding])

mb_convert_kana() performs "han-kaku" - "zen-kaku" conversion for string str. It returns converted string. This function is only useful for Japanese.

option is conversion option. Default value is "KV".

encoding is character encoding. If it is omitted, internal character encoding is used.

Specify with combination of following options. Default value is KV.

Táblázat 1. Applicable Conversion Options

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

Példa 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_variables

(PHP 4 >= 4.0.6)

mb_convert_variables -- Convert character code in variable(s)

Description

string mb_convert_variables ( string to-encoding, mixed from-encoding, mixed vars)

mb_convert_variables() convert character encoding of variables vars in encoding from-encoding to encoding to-encoding. It returns character encoding before conversion for success, FALSE for failure.

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.

It from-encoding is specified by array or comma separated string, it tries to detect encoding from from-coding. When encoding is omitted, detect_order is used.

vars (3rd and larger) is reference to variable to be converted. String, Array and Object are accepted. mb_convert_variables() assumes all parameters have the same encoding.

Példa 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_decode_mimeheader

(PHP 4 >= 4.0.6)

mb_decode_mimeheader -- Decode string in MIME header field

Description

string mb_decode_mimeheader ( string str)

mb_decode_mimeheader() decodes encoded-word string str in MIME header.

It returns decoded string in internal character encoding.

See also mb_encode_mimeheader().

mb_decode_numericentity

(PHP 4 >= 4.0.6)

mb_decode_numericentity --  Decode HTML numeric string reference to character

Description

string mb_decode_numericentity ( string str, array convmap [, string encoding])

Convert numeric string reference of string str in specified block to character. It returns converted string.

convmap is array to specifies code area to convert.

encoding is character encoding. If it is omitted, internal character encoding is used.

Példa 1. convmap example

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

See also mb_encode_numericentity().

mb_detect_encoding

(PHP 4 >= 4.0.6)

mb_detect_encoding -- Detect character encoding

Description

string mb_detect_encoding ( string str [, mixed encoding-list])

mb_detect_encoding() detects character encoding in string str. It returns detected character encoding.

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.

Példa 1. mb_detect_encoding() example

<?php
/* Detect character encoding with current detect_order */
echo mb_detect_encoding($str);

/* "auto" is expanded to "ASCII,JIS,UTF-8,EUC-JP,SJIS" */
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);
?>

See also mb_detect_order().

mb_detect_order

(PHP 4 >= 4.0.6)

mb_detect_order --  Set/Get character encoding detection order

Description

array mb_detect_order ( [mixed encoding-list])

mb_detect_order() sets automatic character encoding detection order to encoding-list. It returns TRUE for success, FALSE for failure.

encoding-list is array or comma separated list of character encoding. ("auto" is expanded to "ASCII, JIS, UTF-8, EUC-JP, SJIS")

If encoding-list is omitted, it returns current character encoding detection order as array.

This setting affects mb_detect_encoding() and mb_send_mail().

Megjegyzés: mbstring currently implements following encoding detection filters. If there is an invalid byte sequence for following encoding, encoding detection will fail.

Megjegyzés: 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.

Példa 1. Useless detect order example

; Always detect as ISO-8859-1
detect_order = ISO-8859-1, UTF-8

; Always detect as UTF-8, since ASCII/UTF-7 values are 
; valid for UTF-8
detect_order = UTF-8, ASCII, UTF-7

Példa 2. mb_detect_order() examples

<?php
/* Set detection order by enumerated list */
mb_detect_order("eucjp-win,sjis-win,UTF-8");

/* Set detection order by array */
$ary[] = "ASCII";
$ary[] = "JIS";
$ary[] = "EUC-JP";
mb_detect_order($ary);

/* Display current detection order */
echo implode(", ", mb_detect_order());
?>

See also mb_internal_encoding(), mb_http_input(), mb_http_output() and mb_send_mail().

mb_encode_mimeheader

(PHP 4 >= 4.0.6)

mb_encode_mimeheader -- Encode string for MIME header

Description

string mb_encode_mimeheader ( string str [, string charset [, string transfer-encoding [, string linefeed]]])

mb_encode_mimeheader() converts string str to encoded-word for header field. It returns converted string in ASCII encoding.

charset is character encoding name. Default is ISO-2022-JP.

transfer-encoding is transfer encoding. It should be one of "B" (Base64) or "Q" (Quoted-Printable). Default is "B".

linefeed is end of line marker. Default is "\r\n" (CRLF).

Példa 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;
?>

See also mb_decode_mimeheader().

mb_encode_numericentity

(PHP 4 >= 4.0.6)

mb_encode_numericentity --  Encode character to HTML numeric string reference

Description

string mb_encode_numericentity ( string str, array convmap [, string encoding])

mb_encode_numericentity() converts specified character codes in string str from HTML numeric character reference to character code. It returns converted string.

convmap is array specifies code area to convert.

encoding is character encoding.

Példa 1. convmap example

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

Példa 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");
?>

See also mb_decode_numericentity().

mb_ereg_match

(4.2.0 - 4.3.2 only)

mb_ereg_match --  Regular expression match for multibyte string

Description

bool mb_ereg_match ( string pattern, string string [, string option])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

mb_ereg_match() returns TRUE if string matches regular expression pattern, FALSE if not.

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

Megjegyzés: This function is supported in PHP 4.2.0 or higher.

See also: mb_regex_encoding(), mb_ereg().

mb_ereg_replace

(4.2.0 - 4.3.2 only)

mb_ereg_replace -- Replace regular expression with multibyte support

Description

string mb_ereg_replace ( string pattern, string replacement, string string [, array option])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

mb_ereg_replace() scans string for matches to pattern, then replaces the matched text with replacement and returns the result string or FALSE on error. Multibyte character can be used in pattern.

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.

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

Megjegyzés: This function is supported in PHP 4.2.0 or higher.

See also: mb_regex_encoding(), mb_eregi_replace().

mb_ereg_search_getpos

(4.2.0 - 4.3.2 only)

mb_ereg_search_getpos --  Returns start point for next regular expression match

Description

array mb_ereg_search_getpos ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

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.

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

Megjegyzés: This function is supported in PHP 4.2.0 or higher.

See also: mb_regex_encoding(), mb_ereg_search_setpos().

mb_ereg_search_getregs

(4.2.0 - 4.3.2 only)

mb_ereg_search_getregs --  Retrieve the result from the last multibyte regular expression match

Description

array mb_ereg_search_getregs ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

mb_ereg_search_getregs() returns 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 maches, 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;

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

Megjegyzés: This function is supported in PHP 4.2.0 or higher.

See also: mb_regex_encoding(), mb_ereg_search_init().

mb_ereg_search_init

(4.2.0 - 4.3.2 only)

mb_ereg_search_init --  Setup string and regular expression for multibyte regular expression match

Description

array mb_ereg_search_init ( string string [, string pattern [, string option]])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

mb_ereg_search_init() sets string and pattern for multibyte regular expression. These values are used for mb_ereg_search(), mb_ereg_search_pos(), mb_ereg_search_regs(). It returns TRUE for success, FALSE for error.

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

Megjegyzés: This function is supported in PHP 4.2.0 or higher.

See also: mb_regex_encoding(), mb_ereg_search_regs().

mb_ereg_search_pos

(4.2.0 - 4.3.2 only)

mb_ereg_search_pos --  Return position and length of matched part of multibyte regular expression for predefined multibyte string

Description

array mb_ereg_search_pos ( [string pattern [, string option]])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

mb_ereg_search_pos() returns an array including position of matched part for multibyte regular expression. The first element of the array will be the beginning of matched part, the second element will be length (bytes) of matched part. It returns FALSE on error.

The string for match is specified by mb_ereg_search_init(). It it is not specified, the previous one will be used.

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

Megjegyzés: This function is supported in PHP 4.2.0 or higher.

See also: mb_regex_encoding(), mb_ereg_search_init().

mb_ereg_search_regs

(4.2.0 - 4.3.2 only)

mb_ereg_search_regs --  Returns the matched part of multibyte regular expression

Description

array mb_ereg_search_regs ( [string pattern [, string option]])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

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.

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

Megjegyzés: This function is supported in PHP 4.2.0 or higher.

See also: mb_regex_encoding(), mb_ereg_search_init().

mb_ereg_search_setpos

(4.2.0 - 4.3.2 only)

mb_ereg_search_setpos --  Set start point of next regular expression match

Description

array mb_ereg_search_setpos ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

mb_ereg_search_setpos() sets the starting point of match for mb_ereg_search().

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

Megjegyzés: This function is supported in PHP 4.2.0 or higher.

See also: mb_regex_encoding(), mb_ereg_search_init().

mb_ereg_search

(4.2.0 - 4.3.2 only)

mb_ereg_search --  Multibyte regular expression match for predefined multibyte string

Description

bool mb_ereg_search ( [string pattern [, string option]])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

mb_ereg_search() returns TRUE if the multibyte string matches with the regular expression, FALSE for otherwise. The string for matching is set by mb_ereg_search_init(). If pattern is not specified, the previous one is used.

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

Megjegyzés: This function is supported in PHP 4.2.0 or higher.

See also: mb_regex_encoding(), mb_ereg_search_init().

mb_ereg

(4.2.0 - 4.3.2 only)

mb_ereg -- Regular expression match with multibyte support

Description

int mb_ereg ( string pattern, string string [, array regs])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

mb_ereg() executes the regular expression match with multibyte support, and returns 1 if matches are found. If the optional third parameter was specified, the function returns the byte length of matched part, and the array regs will contain the substring of matched string. The functions returns 1 if it matches with the empty string. If no matches found or error happend, FALSE will be returned.

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

Megjegyzés: This function is supported in PHP 4.2.0 or higher.

See also: mb_regex_encoding(), mb_eregi()

mb_eregi_replace

(4.2.0 - 4.3.2 only)

mb_eregi_replace --  Replace regular expression with multibyte support ignoring case

Description

string mb_eregi_replace ( string pattern, string replace, string string)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

mb_ereg_replace() scans string for matches to pattern, then replaces the matched text with replacement and returns the result string or FALSE on error. Multibyte character can be used in pattern. The case will be ignored.

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

Megjegyzés: This function is supported in PHP 4.2.0 or higher.

See also: mb_regex_encoding(), mb_ereg_replace().

mb_eregi

(4.2.0 - 4.3.2 only)

mb_eregi --  Regular expression match ignoring case with multibyte support

Description

int mb_eregi ( string pattern, string string [, array regs])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

mb_eregi() executes the regular expression match with multibyte support, and returns 1 if matches are found. This function ignore case. If the optional third parameter was specified, the function returns the byte length of matched part, and the array regs will contain the substring of matched string. The functions returns 1 if it matches with the empty string. If no matches found or error happend, FALSE will be returned.

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

Megjegyzés: This function is supported in PHP 4.2.0 or higher.

See also: mb_regex_encoding(), mb_ereg().

mb_get_info

(PHP 4 >= 4.2.0)

mb_get_info -- Get internal settings of mbstring

Description

string mb_get_info ( [string type])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

mb_get_info() returns internal setting parameter of mbstring.

If type isn't specified or is specified to "all", an array having the elements "internal_encoding", "http_output", "http_input", "func_overload" will be returned.

If type is specified for "http_output", "http_input", "internal_encoding", "func_overload", the specified setting parameter will be returned.

See also mb_internal_encoding(), mb_http_output().

mb_http_input

(PHP 4 >= 4.0.6)

mb_http_input -- Detect HTTP input character encoding

Description

string mb_http_input ( [string type])

mb_http_input() returns result of HTTP input character encoding detection.

type: Input string specifies input type. "G" for GET, "P" for POST, "C" for COOKIE. If type is omitted, it returns last input type processed.

Return Value: Character encoding name. If mb_http_input() does not process specified HTTP input, it returns FALSE.

See also mb_internal_encoding(), mb_http_output(), mb_detect_order().

mb_http_output

(PHP 4 >= 4.0.6)

mb_http_output -- Set/Get HTTP output character encoding

Description

string mb_http_output ( [string encoding])

If encoding is set, mb_http_output() sets HTTP output character encoding to encoding. Output after this function is converted to encoding. mb_http_output() returns TRUE for success and FALSE for failure.

If encoding is omitted, mb_http_output() returns current HTTP output character encoding.

See also mb_internal_encoding(), mb_http_input(), mb_detect_order().

mb_internal_encoding

(PHP 4 >= 4.0.6)

mb_internal_encoding --  Set/Get internal character encoding

Description

string mb_internal_encoding ( [string encoding])

mb_internal_encoding() sets internal character encoding to encoding If parameter is omitted, it returns current internal encoding.

encoding is used for HTTP input character encoding conversion, HTTP output character encoding conversion and default character encoding for string functions defined by mbstring module.

encoding: Character encoding name

Return Value: If encoding is set,mb_internal_encoding() returns TRUE for success, otherwise returns FALSE. If encoding is omitted, it returns current character encoding name.

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

See also mb_http_input(), mb_http_output() and mb_detect_order().

mb_language

(PHP 4 >= 4.0.6)

mb_language --  Set/Get current language

Description

string mb_language ( [string language])

mb_language() sets language. If language is omitted, it returns current language as string.

language setting is 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.

Return Value: If language is set and language is valid, it returns TRUE. Otherwise, it returns FALSE. When language is omitted, it returns language name as string. If no language is set previously, it returns FALSE.

See also mb_send_mail().

mb_output_handler

(PHP 4 >= 4.0.6)

mb_output_handler --  Callback function converts character encoding in output buffer

Description

string mb_output_handler ( string contents, int status)

mb_output_handler() is ob_start() callback function. mb_output_handler() converts characters in output buffer from internal character encoding to HTTP output character encoding.

4.1.0 or later version, this handler adds charset HTTP header when following conditions are met:

  • Does not set Content-Type by header()

  • Default MIME type begins with text/

  • http_output setting is other than pass

contents : Output buffer contents

status : Output buffer status

Return Value: String converted

Példa 1. mb_output_handler() example

<?php
mb_http_output("UTF-8");
ob_start("mb_output_handler");
?>

Megjegyzés: If you want to output some binary data such as image from PHP script with PHP 4.3.0 or later, Content-Type: header must be send using header() before any binary data was send to client (e.g. header("Content-Type: image/png")). If Content-Type: header was send, output character encoding conversion will not be performed.

Note that if 'Content-Type: text/*' was send using header(), the sending data is regarded as text, encoding conversion will be performed using character encoding settings.

If you want to output some binary data such as image from PHP script with PHP 4.2.x or earlier, you must set output encoding to "pass" using mb_http_output().

See also ob_start().

mb_parse_str

(PHP 4 >= 4.0.6)

mb_parse_str --  Parse GET/POST/COOKIE data and set global variable

Description

bool mb_parse_str ( string encoded_string [, array result])

mb_parse_str() parses GET/POST/COOKIE data and sets global variables. Since PHP does not provide raw POST/COOKIE data, it can only used for GET data for now. It preses URL encoded data, detects encoding, converts coding to internal encoding and set values to result array or global variables.

encoded_string: URL encoded data.

result: Array contains decoded and character encoding converted values.

Return Value: It returns TRUE for success or FALSE for failure.

See also mb_detect_order(), mb_internal_encoding().

mb_preferred_mime_name

(PHP 4 >= 4.0.6)

mb_preferred_mime_name -- Get MIME charset string

Description

string mb_preferred_mime_name ( string encoding)

mb_preferred_mime_name() returns MIME charset string for character encoding encoding. It returns charset string.

Példa 1. mb_preferred_mime_string() 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_regex_encoding

(4.2.0 - 4.3.2 only)

mb_regex_encoding --  Returns current encoding for multibyte regex as string

Description

string mb_regex_encoding ( [string encoding])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

mb_regex_encoding() returns the character encoding used by multibyte regex functions.

If the optional parameter encoding is specified, it is set to the character encoding for multibyte regex. The default value is the internal character encoding.

Megjegyzés: This function is supported in PHP 4.2.0 or higher.

See also: mb_internal_encoding(), mb_ereg()

mb_regex_set_options

(4.3.0 - 4.3.2 only)

mb_regex_set_options --  Set/Get the default options for mbregex functions

Description

string mb_regex_set_options ( [string options])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

mb_regex_set_options() sets the default options described by options for multibyte regex functions.

Returns the previous options. If options is omitted, it returns the string that describes the current options.

Megjegyzés: This function is supported in PHP 4.3.0 or higher.

See also mb_split(), mb_ereg() and mb_eregi()

mb_send_mail

(PHP 4 >= 4.0.6)

mb_send_mail --  Send encoded mail.

Description

bool mb_send_mail ( string to, string subject, string message [, string additional_headers [, string additional_parameter]])

mb_send_mail() sends email. Headers and message are converted and encoded according to mb_language() setting. mb_send_mail() is wrapper function of mail(). See mail() for details.

to is mail addresses send to. Multiple recipients can be specified by putting a comma between each address in to. This parameter is not automatically encoded.

subject is subject of mail.

message is mail message.

additional_headers is inserted at the end of the header. This is typically used to add extra headers. Multiple extra headers are separated with a newline ("\n").

additional_parameter is a MTA command line parameter. It is useful when setting the correct Return-Path header when using sendmail.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

See also mail(), mb_encode_mimeheader(), and mb_language().

mb_split

(4.2.0 - 4.3.2 only)

mb_split -- Split multibyte string using regular expression

Description

array mb_split ( string pattern, string string [, int limit])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

mb_split() split multibyte string using regular expression pattern and returns the result as an array.

If optional parameter limit is specified, it will be split in limit elements as maximum.

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

Megjegyzés: This function is supported in PHP 4.2.0 or higher.

See also: mb_regex_encoding(), mb_ereg().

mb_strcut

(PHP 4 >= 4.0.6)

mb_strcut -- Get part of string

Description

string mb_strcut ( string str, int start [, int length [, string encoding]])

mb_strcut() returns the portion of str specified by the start and length parameters.

mb_strcut() performs equivalent operation as mb_substr() with different method. If start position is multi-byte character's second byte or larger, it starts from first byte of multi-byte character.

It subtracts string from str that is shorter than length AND character that is not part of multi-byte string or not being middle of shift sequence.

encoding is character encoding. If it is not set, internal character encoding is used.

See also mb_substr(), mb_internal_encoding().

mb_strimwidth

(PHP 4 >= 4.0.6)

mb_strimwidth -- Get truncated string with specified width

Description

string mb_strimwidth ( string str, int start, int width, string trimmarker [, string encoding])

mb_strimwidth() truncates string str to specified width. It returns truncated string.

If trimmarker is set, trimmarker is appended to return value.

start is start position offset. Number of characters from the beginning of string. (First character is 0)

trimmarker is string that is added to the end of string when string is truncated.

encoding is character encoding. If it is omitted, internal encoding is used.

Példa 1. mb_strimwidth() example

<?php
$str = mb_strimwidth($str, 0, 40, "..>");
?>

See also mb_strwidth() and mb_internal_encoding().

mb_strlen

(PHP 4 >= 4.0.6)

mb_strlen -- Get string length

Description

string mb_strlen ( string str [, string encoding])

mb_strlen() returns number of characters in string str having character encoding encoding. A multi-byte character is counted as 1.

encoding is character encoding for str. If encoding is omitted, internal character encoding is used.

See also mb_internal_encoding(), strlen().

mb_strpos

(PHP 4 >= 4.0.6)

mb_strpos --  Find position of first occurrence of string in a string

Description

int mb_strpos ( string haystack, string needle [, int offset [, string encoding]])

mb_strpos() returns the numeric position of the first occurrence of needle in the haystack string. If needle is not found, it returns FALSE.

mb_strpos() performs multi-byte safe strpos() operation based on number of characters. needle position is counted from the beginning of the haystack. First character's position is 0. Second character position is 1, and so on.

If encoding is omitted, internal character encoding is used. mb_strrpos() accepts string for needle where strrpos() accepts only character.

offset is search offset. If it is not specified, 0 is used.

encoding is character encoding name. If it is omitted, internal character encoding is used.

See also mb_strpos(), mb_internal_encoding(), strpos()

mb_strrpos

(PHP 4 >= 4.0.6)

mb_strrpos --  Find position of last occurrence of a string in a string

Description

int mb_strrpos ( string haystack, string needle [, string encoding])

mb_strrpos() returns the numeric position of the last occurrence of needle in the haystack string. If needle is not found, it returns FALSE.

mb_strrpos() performs multi-byte safe strrpos() 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.

If encoding is omitted, internal encoding is assumed. mb_strrpos() accepts string for needle where strrpos() accepts only character.

encoding is character encoding. If it is not specified, internal character encoding is used.

See also mb_strpos(), mb_internal_encoding(), strrpos().

mb_strtolower

(PHP 4 >= 4.3.0)

mb_strtolower -- Make a string lowercase

Description

string mb_strtolower ( string str [, string encoding])

mb_strtolower() returns str with all alphabetic characters converted to lowercase.

encoding specifies the encoding of str; if omitted, the internal character encoding value will be used.

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

Példa 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
?>

See also strtolower(), mb_strtoupper() and mb_convert_case().

mb_strtoupper

(PHP 4 >= 4.3.0)

mb_strtoupper -- Make a string uppercase

Description

string mb_strtoupper ( string str [, string encoding])

mb_strtoupper() returns str with all alphabetic characters converted to uppercase.

encoding specifies the encoding of str; if omitted, the internal character encoding value will be used.

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

For more information about the Unicode properties, please see http://www.unicode.org/unicode/reports/tr21/.

Példa 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
?>

See also strtoupper(), mb_strtolower() and mb_convert_case().

mb_strwidth

(PHP 4 >= 4.0.6)

mb_strwidth -- Return width of string

Description

int mb_strwidth ( string str [, string encoding])

mb_strwidth() returns width of string str.

Multi-byte character usually twice of width compare to single byte character.

Táblázat 1. Characters width

CharsWidth
U+0000 - U+00190
U+0020 - U+1FFF1
U+2000 - U+FF602
U+FF61 - U+FF9F1
U+FFA0 - 2

encoding is character encoding. If it is omitted, internal encoding is used.

See also: mb_strimwidth(), mb_internal_encoding().

mb_substitute_character

(PHP 4 >= 4.0.6)

mb_substitute_character -- Set/Get substitution character

Description

mixed mb_substitute_character ( [mixed substrchar])

mb_substitute_character() specifies substitution character when input character encoding is invalid or character code is 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().

substchar : Specify Unicode value as integer or specify as string as follows

  • "none" : no output

  • "long" : Output character code value (Example: U+3000,JIS+7E7E)

Return Value: If substchar is set, it returns TRUE for success, otherwise returns FALSE. If substchar is not set, it returns Unicode value or "none"/"long".

Példa 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_substr_count

(PHP 4 >= 4.3.0)

mb_substr_count -- Count the number of substring occurrences

Description

int mb_substr_count ( string haystack, string needle [, string encoding])

mb_substr_count() returns the number of times the needle substring occurs in the haystack string.

encoding specifies the encoding for needle and haystack. If omitted, internal character encoding is used.

Példa 1. mb_substr_count() example

<?php
echo mb_substr_count("This is a test", "is"); // prints out 2
?>

See also substr_count(), mb_strpos(), mb_substr().

mb_substr

(PHP 4 >= 4.0.6)

mb_substr -- Get part of string

Description

string mb_substr ( string str, int start [, int length [, string encoding]])

mb_substr() returns the portion of str specified by the start and length parameters.

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

If encoding is omitted, internal encoding is assumed.

encoding is character encoding. If it is omitted, internal character encoding is used.

See also mb_strcut(), mb_internal_encoding().

LIV. MCAL functions

Bevezetés

MCAL stands for Modular Calendar Access Library.

Libmcal is a C library for accessing calendars. It's written to be very modular, with pluggable drivers. MCAL is the calendar equivalent of the IMAP module for mailboxes.

With mcal support, a calendar stream can be opened much like the mailbox stream with the IMAP support. Calendars can be local file stores, remote ICAP servers, or other formats that are supported by the mcal library.

Calendar events can be pulled up, queried, and stored. There is also support for calendar triggers (alarms) and recurring events.

With libmcal, central calendar servers can be accessed, removing the need for any specific database or local file programming.

Most of the functions use an internal event structure that is unique for each stream. This alleviates the need to pass around large objects between functions. There are convenience functions for setting, initializing, and retrieving the event structure values.

Megjegyzés: PHP had an ICAP extension previously, but the original library and the PHP extension is not supported anymore. The suggested replacement is MCAL.

Megjegyzés: Ez a kiterjesztés nem működik Windows operációs rendszereken!


Követelmények

This extension requires the mcal library to be installed. Grab the latest version from http://mcal.chek.com/ and compile and install it.


Telepítés

After you installed the mcal library, to get these functions to work, you have to compile PHP -with-mcal[=DIR].


Futásidejű beállítások

Ez a kiterjesztés semmilyen konfigurációs beállításokat nem definiál a php.ini állományban.


Erőforrás típusok

Ez a kiterjesztés semmilyen erőforrás típust nem definiál.


Előre definiált állandók

Az itt listázott állandókat ez a kiterjesztés definiálja, és csak akkor elérhetőek, ha az adott kiterjesztés be van fordítva a PHP-be, vagy dinamikusan betöltött.

MCAL_SUNDAY (integer)

MCAL_MONDAY (integer)

MCAL_TUESDAY (integer)

MCAL_WEDNESDAY (integer)

MCAL_THURSDAY (integer)

MCAL_FRIDAY (integer)

MCAL_SATURDAY (integer)

MCAL_JANUARY (integer)

MCAL_FEBRUARY (integer)

MCAL_MARCH (integer)

MCAL_APRIL (integer)

MCAL_MAY (integer)

MCAL_JUNE (integer)

MCAL_JULY (integer)

MCAL_AUGUST (integer)

MCAL_SEPTEMBER (integer)

MCAL_OCTOBER (integer)

MCAL_NOVEMBER (integer)

MCAL_DECEMBER (integer)

MCAL_RECUR_NONE (integer)

MCAL_RECUR_DAILY (integer)

MCAL_RECUR_WEEKLY (integer)

MCAL_RECUR_MONTHLY_MDAY (integer)

MCAL_RECUR_MONTHLY_WDAY (integer)

MCAL_RECUR_YEARLY (integer)

MCAL_M_SUNDAY (integer)

MCAL_M_MONDAY (integer)

MCAL_M_TUESDAY (integer)

MCAL_M_WEDNESDAY (integer)

MCAL_M_THURSDAY (integer)

MCAL_M_FRIDAY (integer)

MCAL_M_SATURDAY (integer)

MCAL_M_WEEKDAYS (integer)

MCAL_M_WEEKEND (integer)

MCAL_M_ALLDAYS (integer)

Tartalom
mcal_append_event -- Store a new event into an MCAL calendar
mcal_close -- Close an MCAL stream
mcal_create_calendar -- Create a new MCAL calendar
mcal_date_compare -- Compares two dates
mcal_date_valid --  Returns TRUE if the given year, month, day is a valid date
mcal_day_of_week --  Returns the day of the week of the given date
mcal_day_of_year --  Returns the day of the year of the given date
mcal_days_in_month --  Returns the number of days in a month
mcal_delete_calendar -- Delete an MCAL calendar
mcal_delete_event -- Delete an event from an MCAL calendar
mcal_event_add_attribute --  Adds an attribute and a value to the streams global event structure
mcal_event_init --  Initializes a streams global event structure
mcal_event_set_alarm --  Sets the alarm of the streams global event structure
mcal_event_set_category --  Sets the category of the streams global event structure
mcal_event_set_class --  Sets the class of the streams global event structure
mcal_event_set_description --  Sets the description of the streams global event structure
mcal_event_set_end --  Sets the end date and time of the streams global event structure
mcal_event_set_recur_daily --  Sets the recurrence of the streams global event structure
mcal_event_set_recur_monthly_mday --  Sets the recurrence of the streams global event structure
mcal_event_set_recur_monthly_wday --  Sets the recurrence of the streams global event structure
mcal_event_set_recur_none --  Sets the recurrence of the streams global event structure
mcal_event_set_recur_weekly --  Sets the recurrence of the streams global event structure
mcal_event_set_recur_yearly --  Sets the recurrence of the streams global event structure
mcal_event_set_start --  Sets the start date and time of the streams global event structure
mcal_event_set_title --  Sets the title of the streams global event structure
mcal_expunge --  Deletes all events marked for being expunged.
mcal_fetch_current_stream_event --  Returns an object containing the current streams event structure
mcal_fetch_event --  Fetches an event from the calendar stream
mcal_is_leap_year --  Returns if the given year is a leap year or not
mcal_list_alarms --  Return a list of events that has an alarm triggered at the given datetime
mcal_list_events --  Return a list of IDs for a date or a range of dates
mcal_next_recurrence -- Returns the next recurrence of the event
mcal_open -- Opens up an MCAL connection
mcal_popen -- Opens up a persistent MCAL connection
mcal_rename_calendar -- Rename an MCAL calendar
mcal_reopen -- Reopens an MCAL connection
mcal_snooze -- Turn off an alarm for an event
mcal_store_event -- Modify an existing event in an MCAL calendar
mcal_time_valid --  Returns TRUE if the given year, month, day is a valid time
mcal_week_of_year --  Returns the week number of the given date

mcal_append_event

(PHP 4 )

mcal_append_event -- Store a new event into an MCAL calendar

Description

int mcal_append_event ( int mcal_stream)

mcal_append_event() stores the global event into an MCAL calendar for the stream mcal_stream.

Returns the id of the newly inserted event.

mcal_close

(PHP 3>= 3.0.13, PHP 4 )

mcal_close -- Close an MCAL stream

Description

int mcal_close ( int mcal_stream, int flags)

Closes the given mcal stream.

mcal_create_calendar

(PHP 3>= 3.0.13, PHP 4 )

mcal_create_calendar -- Create a new MCAL calendar

Description

bool mcal_create_calendar ( int stream, string calendar)

Creates a new calendar named calendar.

mcal_date_compare

(PHP 3>= 3.0.13, PHP 4 )

mcal_date_compare -- Compares two dates

Description

int mcal_date_compare ( int a_year, int a_month, int a_day, int b_year, int b_month, int b_day)

mcal_date_compare() Compares the two given dates, returns <0, 0, >0 if a<b, a==b, a>b respectively.

mcal_date_valid

(PHP 3>= 3.0.13, PHP 4 )

mcal_date_valid --  Returns TRUE if the given year, month, day is a valid date

Description

int mcal_date_valid ( int year, int month, int day)

mcal_date_valid() Returns TRUE if the given year, month and day is a valid date, FALSE if not.

mcal_day_of_week

(PHP 3>= 3.0.13, PHP 4 )

mcal_day_of_week --  Returns the day of the week of the given date

Description

int mcal_day_of_week ( int year, int month, int day)

mcal_day_of_week() returns the day of the week of the given date. Possible return values range from 0 for Sunday through 6 for Saturday.

mcal_day_of_year

(PHP 3>= 3.0.13, PHP 4 )

mcal_day_of_year --  Returns the day of the year of the given date

Description

int mcal_day_of_year ( int year, int month, int day)

mcal_day_of_year() returns the day of the year of the given date.

mcal_days_in_month

(PHP 3>= 3.0.13, PHP 4 )

mcal_days_in_month --  Returns the number of days in a month

Description

int mcal_days_in_month ( int month, int leap_year)

mcal_days_in_month() returns the number of days in the month month, taking into account if the considered year is a leap year or not.

mcal_delete_calendar

(PHP 3>= 3.0.13, PHP 4 )

mcal_delete_calendar -- Delete an MCAL calendar

Description

string mcal_delete_calendar ( int stream, string calendar)

Deletes the calendar named calendar.

mcal_delete_event

(PHP 3>= 3.0.13, PHP 4 )

mcal_delete_event -- Delete an event from an MCAL calendar

Description

int mcal_delete_event ( int mcal_stream [, int event_id])

mcal_delete_event() deletes the calendar event specified by the event_id.

Returns TRUE.

mcal_event_add_attribute

(PHP 3>= 3.0.15, PHP 4 )

mcal_event_add_attribute --  Adds an attribute and a value to the streams global event structure

Description

void mcal_event_add_attribute ( int stream, string attribute, string value)

mcal_event_add_attribute() adds an attribute to the stream's global event structure with the value given by "value".

mcal_event_init

(PHP 3>= 3.0.13, PHP 4 )

mcal_event_init --  Initializes a streams global event structure

Description

int mcal_event_init ( int stream)

mcal_event_init() initializes a streams global event structure. this effectively sets all elements of the structure to 0, or the default settings.

Returns TRUE.

mcal_event_set_alarm

(PHP 3>= 3.0.13, PHP 4 )

mcal_event_set_alarm --  Sets the alarm of the streams global event structure

Description

int mcal_event_set_alarm ( int stream, int alarm)

mcal_event_set_alarm() sets the streams global event structure's alarm to the given minutes before the event.

Returns TRUE.

mcal_event_set_category

(PHP 3>= 3.0.13, PHP 4 )

mcal_event_set_category --  Sets the category of the streams global event structure

Description

int mcal_event_set_category ( int stream, string category)

mcal_event_set_category() sets the streams global event structure's category to the given string.

Returns TRUE.

mcal_event_set_class

(PHP 3>= 3.0.13, PHP 4 )

mcal_event_set_class --  Sets the class of the streams global event structure

Description

int mcal_event_set_class ( int stream, int class)

mcal_event_set_class() sets the streams global event structure's class to the given value. The class is either 1 for public, or 0 for private.

Returns TRUE.

mcal_event_set_description

(PHP 3>= 3.0.13, PHP 4 )

mcal_event_set_description --  Sets the description of the streams global event structure

Description

int mcal_event_set_description ( int stream, string description)

mcal_event_set_description() sets the streams global event structure's description to the given string.

Returns TRUE.

mcal_event_set_end

(PHP 3>= 3.0.13, PHP 4 )

mcal_event_set_end --  Sets the end date and time of the streams global event structure

Description

int mcal_event_set_end ( int stream, int year, int month [, int day [, int hour [, int min [, int sec]]]])

mcal_event_set_end() sets the streams global event structure's end date and time to the given values.

Returns TRUE.

mcal_event_set_recur_daily

(PHP 3>= 3.0.13, PHP 4 )

mcal_event_set_recur_daily --  Sets the recurrence of the streams global event structure

Description

int mcal_event_set_recur_daily ( int stream, int year, int month, int day, int interval)

mcal_event_set_recur_daily() sets the streams global event structure's recurrence to the given value to be reoccurring on a daily basis, ending at the given date.

mcal_event_set_recur_monthly_mday

(PHP 3>= 3.0.13, PHP 4 )

mcal_event_set_recur_monthly_mday --  Sets the recurrence of the streams global event structure

Description

int mcal_event_set_recur_monthly_mday ( int stream, int year, int month, int day, int interval)

mcal_event_set_recur_monthly_mday() sets the streams global event structure's recurrence to the given value to be reoccurring on a monthly by month day basis, ending at the given date.

mcal_event_set_recur_monthly_wday

(PHP 3>= 3.0.13, PHP 4 )

mcal_event_set_recur_monthly_wday --  Sets the recurrence of the streams global event structure

Description

int mcal_event_set_recur_monthly_wday ( int stream, int year, int month, int day, int interval)

mcal_event_set_recur_monthly_wday() sets the streams global event structure's recurrence to the given value to be reoccurring on a monthly by week basis, ending at the given date.

mcal_event_set_recur_none

(PHP 3>= 3.0.15, PHP 4 )

mcal_event_set_recur_none --  Sets the recurrence of the streams global event structure

Description

int mcal_event_set_recur_none ( int stream)

mcal_event_set_recur_none() sets the streams global event structure to not recur (event->recur_type is set to MCAL_RECUR_NONE).

mcal_event_set_recur_weekly

(PHP 3>= 3.0.13, PHP 4 )

mcal_event_set_recur_weekly --  Sets the recurrence of the streams global event structure

Description

int mcal_event_set_recur_weekly ( int stream, int year, int month, int day, int interval, int weekdays)

mcal_event_set_recur_weekly() sets the streams global event structure's recurrence to the given value to be reoccurring on a weekly basis, ending at the given date.

mcal_event_set_recur_yearly

(PHP 3>= 3.0.13, PHP 4 )

mcal_event_set_recur_yearly --  Sets the recurrence of the streams global event structure

Description

int mcal_event_set_recur_yearly ( int stream, int year, int month, int day, int interval)

mcal_event_set_recur_yearly() sets the streams global event structure's recurrence to the given value to be reoccurring on a yearly basis,ending at the given date.

mcal_event_set_start

(PHP 3>= 3.0.13, PHP 4 )

mcal_event_set_start --  Sets the start date and time of the streams global event structure

Description

int mcal_event_set_start ( int stream, int year, int month [, int day [, int hour [, int min [, int sec]]]])

mcal_event_set_start() sets the streams global event structure's start date and time to the given values.

Returns TRUE.

mcal_event_set_title

(PHP 3>= 3.0.13, PHP 4 )

mcal_event_set_title --  Sets the title of the streams global event structure

Description

int mcal_event_set_title ( int stream, string title)

mcal_event_set_title() sets the streams global event structure's title to the given string.

Returns TRUE.

mcal_expunge

(no version information, might be only in CVS)

mcal_expunge --  Deletes all events marked for being expunged.

Description

int mcal_expunge ( int stream)

mcal_expunge() deletes all events which have been previously marked for deletion.

mcal_fetch_current_stream_event

(PHP 3>= 3.0.13, PHP 4 )

mcal_fetch_current_stream_event --  Returns an object containing the current streams event structure

Description

object mcal_fetch_current_stream_event ( int stream)

mcal_fetch_current_stream_event() returns the current stream's event structure as an object containing:

  • int id - ID of that event.

  • int public - TRUE if the event if public, FALSE if it is private.

  • string category - Category string of the event.

  • string title - Title string of the event.

  • string description - Description string of the event.

  • int alarm - number of minutes before the event to send an alarm/reminder.

  • object start - Object containing a datetime entry.

  • object end - Object containing a datetime entry.

  • int recur_type - recurrence type

  • int recur_interval - recurrence interval

  • datetime recur_enddate - recurrence end date

  • int recur_data - recurrence data

All datetime entries consist of an object that contains:

  • int year - year

  • int month - month

  • int mday - day of month

  • int hour - hour

  • int min - minutes

  • int sec - seconds

  • int alarm - minutes before event to send an alarm

mcal_fetch_event

(PHP 3>= 3.0.13, PHP 4 )

mcal_fetch_event --  Fetches an event from the calendar stream

Description

object mcal_fetch_event ( int mcal_stream, int event_id [, int options])

mcal_fetch_event() fetches an event from the calendar stream specified by id.

Returns an event object consisting of:

  • int id - ID of that event.

  • int public - TRUE if the event if public, FALSE if it is private.

  • string category - Category string of the event.

  • string title - Title string of the event.

  • string description - Description string of the event.

  • int alarm - number of minutes before the event to send an alarm/reminder.

  • object start - Object containing a datetime entry.

  • object end - Object containing a datetime entry.

  • int recur_type - recurrence type

  • int recur_interval - recurrence interval

  • datetime recur_enddate - recurrence end date

  • int recur_data - recurrence data

All datetime entries consist of an object that contains:

  • int year - year

  • int month - month

  • int mday - day of month

  • int hour - hour

  • int min - minutes

  • int sec - seconds

  • int alarm - minutes before event to send an alarm

The possible values for recur_type are:

  • 0 - Indicates that this event does not recur

  • 1 - This event recurs daily

  • 2 - This event recurs on a weekly basis

  • 3 - This event recurs monthly on a specific day of the month (e.g. the 10th of the month)

  • 4 - This event recurs monthly on a sequenced day of the week (e.g. the 3rd Saturday)

  • 5 - This event recurs on an annual basis

mcal_is_leap_year

(PHP 3>= 3.0.13, PHP 4 )

mcal_is_leap_year --  Returns if the given year is a leap year or not

Description

int mcal_is_leap_year ( int year)

mcal_is_leap_year() returns 1 if the given year is a leap year, 0 if not.

mcal_list_alarms

(PHP 3>= 3.0.13, PHP 4 )

mcal_list_alarms --  Return a list of events that has an alarm triggered at the given datetime

Description

array mcal_list_alarms ( int mcal_stream [, int begin_year [, int begin_month [, int begin_day [, int end_year [, int end_month [, int end_day]]]]]])

Returns an array of event ID's that has an alarm going off between the start and end dates, or if just a stream is given, uses the start and end dates in the global event structure.

mcal_list_events() function takes in an optional beginning date and an end date for a calendar stream. An array of event id's that are between the given dates or the internal event dates are returned.

mcal_list_events

(PHP 3>= 3.0.13, PHP 4 )

mcal_list_events --  Return a list of IDs for a date or a range of dates

Description

array mcal_list_events ( int mcal_stream, object begin_date [, object end_date])

Returns an array of ID's that are between the start and end dates, or if just a stream is given, uses the start and end dates in the global event structure.

mcal_list_events() takes in an beginning date and an optional end date for a calendar stream. An array of event id's that are between the given dates or the internal event dates are returned.

mcal_next_recurrence

(PHP 3>= 3.0.13, PHP 4 )

mcal_next_recurrence -- Returns the next recurrence of the event

Description

int mcal_next_recurrence ( int stream, int weekstart, array next)

mcal_next_recurrence() returns an object filled with the next date the event occurs, on or after the supplied date. Returns empty date field if event does not occur or something is invalid. Uses weekstart to determine what day is considered the beginning of the week.

mcal_open

(PHP 3>= 3.0.13, PHP 4 )

mcal_open -- Opens up an MCAL connection

Description

int mcal_open ( string calendar, string username, string password [, int options])

Returns an MCAL stream on success, FALSE on error.

mcal_open() opens up an MCAL connection to the specified calendar store. If the optional options is specified, passes the options to that mailbox also. The streams internal event structure is also initialized upon connection.

mcal_popen

(PHP 3>= 3.0.13, PHP 4 )

mcal_popen -- Opens up a persistent MCAL connection

Description

int mcal_popen ( string calendar, string username, string password [, int options])

Returns an MCAL stream on success, FALSE on error.

mcal_popen() opens up an MCAL connection to the specified calendar store. If the optional options is specified, passes the options to that mailbox also. The streams internal event structure is also initialized upon connection.

mcal_rename_calendar

(PHP 3>= 3.0.13, PHP 4 )

mcal_rename_calendar -- Rename an MCAL calendar

Description

string mcal_rename_calendar ( int stream, string old_name, string new_name)

Renames the calendar old_name to new_name.

mcal_reopen

(PHP 3>= 3.0.13, PHP 4 )

mcal_reopen -- Reopens an MCAL connection

Description

int mcal_reopen ( string calendar [, int options])

Reopens an MCAL stream to a new calendar.

mcal_reopen() reopens an MCAL connection to the specified calendar store. If the optional options is specified, passes the options to that mailbox also.

mcal_snooze

(PHP 3>= 3.0.13, PHP 4 )

mcal_snooze -- Turn off an alarm for an event

Description

bool mcal_snooze ( int stream_id, int event_id)

mcal_snooze() turns off an alarm for a calendar event specified by the stream_id and event_id.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

mcal_store_event

(PHP 3>= 3.0.13, PHP 4 )

mcal_store_event -- Modify an existing event in an MCAL calendar

Description

int mcal_store_event ( int mcal_stream)

mcal_store_event() stores the modifications to the current global event for the given stream.

Returns the event id of the modified event on success and FALSE on error.

mcal_time_valid

(PHP 3>= 3.0.13, PHP 4 )

mcal_time_valid --  Returns TRUE if the given year, month, day is a valid time

Description

int mcal_time_valid ( int hour, int minutes, int seconds)

mcal_time_valid() Returns TRUE if the given hour, minutes and seconds is a valid time, FALSE if not.

mcal_week_of_year

(PHP 4 )

mcal_week_of_year --  Returns the week number of the given date

Description

int mcal_week_of_year ( int day, int month, int year)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

LV. Mcrypt Encryption Functions

Bevezetés

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


Követelmények

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. Windows users will find all the needed compiled mcrypt binaries at http://ftp.emini.dk/pub/php/win32/mcrypt/.

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.


Telepítés

You need to compile PHP with the --with-mcrypt[=DIR] parameter to enable this extension. DIR is the mcrypt install directory. Make sure you compile libmcrypt with the option --disable-posix-threads.


Futásidejű beállítások

Az alábbi függvények viselkedése befolyásolható a php.ini segítségével.

Táblázat 1. Mcrypt configuration options

NameDefaultChangeable
mcrypt.algorithms_dirNULLPHP_INI_ALL
mcrypt.modes_dirNULLPHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().


Erőforrás típusok

Ez a kiterjesztés semmilyen erőforrás típust nem definiál.


Előre definiált állandók

Az itt listázott állandókat ez a kiterjesztés definiálja, és csak akkor elérhetőek, ha az adott kiterjesztés be van fordítva a PHP-be, vagy dinamikusan betöltött.

Mcrypt can operate in four block cipher modes (CBC, OFB, CFB, and ECB). If linked against libmcrypt-2.4.x or higher the functions can also operate in the block cipher mode nOFB and in STREAM mode. Below you find a list with all supported encryption modes together with the constants that are defines for the encryption mode. For a more complete reference and discussion see Applied Cryptography by Schneier (ISBN 0-471-11709-9).

  • MCRYPT_MODE_ECB (electronic codebook) is suitable for random data, such as encrypting other keys. Since data there is short and random, the disadvantages of ECB have a favorable negative effect.

  • MCRYPT_MODE_CBC (cipher block chaining) is especially suitable for encrypting files where the security is increased over ECB significantly.

  • MCRYPT_MODE_CFB (cipher feedback) is the best mode for encrypting byte streams where single bytes must be encrypted.

  • MCRYPT_MODE_OFB (output feedback, in 8bit) is comparable to CFB, but can be used in applications where error propagation cannot be tolerated. It's insecure (because it operates in 8bit mode) so it is not recommended to use it.

  • MCRYPT_MODE_NOFB (output feedback, in nbit) is comparable to OFB, but more secure because it operates on the block size of the algorithm.

  • MCRYPT_MODE_STREAM is an extra mode to include some stream algorithms like WAKE or RC4.

Some other mode and random device constants:

MCRYPT_ENCRYPT (integer)

MCRYPT_DECRYPT (integer)

MCRYPT_DEV_RANDOM (integer)

MCRYPT_DEV_URANDOM (integer)

MCRYPT_RAND (integer)


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


Példák

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.

Példa 1. Encrypt an input value with TripleDES under 2.2.x in ECB mode

<?php
$key = "this is a secret key";
$input = "Let us meet at 9 o'clock at the secret place.";

$encrypted_data = mcrypt_ecb (MCRYPT_3DES, $key, $input, MCRYPT_ENCRYPT);
?>
This example will give you the encrypted data as a string in $encrypted_data.

If you linked against libmcrypt 2.4.x or 2.5.x, these functions are still available, but it is recommended that you use the advanced functions.

Példa 2. Encrypt an input value with TripleDES under 2.4.x and higher in ECB mode

<?php
    $key = "this is a secret key";
    $input = "Let us meet at 9 o'clock at the secret place.";

    $td = mcrypt_module_open('tripledes', '', 'ecb', '');
    $iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
    mcrypt_generic_init($td, $key, $iv);
    $encrypted_data = mcrypt_generic($td, $input);
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);
?>
This example will give you the encrypted data as a string in $encrypted_data. For a full example see mcrypt_module_open().

Tartalom
mcrypt_cbc -- Encrypt/decrypt data in CBC mode
mcrypt_cfb -- Encrypt/decrypt data in CFB mode
mcrypt_create_iv --  Create an initialization vector (IV) from a random source
mcrypt_decrypt -- Decrypts crypttext with given parameters
mcrypt_ecb -- Encrypt/decrypt 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 -- This function 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 -- Get the block size of the specified cipher
mcrypt_get_cipher_name -- Get 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 -- Get the key size of the specified cipher
mcrypt_list_algorithms -- Get an array of all supported ciphers
mcrypt_list_modes -- Get an array of all supported modes
mcrypt_module_close --  Close 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 -- Encrypt/decrypt data in OFB mode
mdecrypt_generic -- Decrypt data

mcrypt_cbc

(PHP 3>= 3.0.8, PHP 4 )

mcrypt_cbc -- Encrypt/decrypt data in CBC mode

Description

string mcrypt_cbc ( int cipher, string key, string data, int mode [, string iv])

string mcrypt_cbc ( string cipher, string key, string data, int mode [, string iv])

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or higher. The mode should be either MCRYPT_ENCRYPT or MCRYPT_DECRYPT.

This function should not be used anymore, see mcrypt_generic() and mdecrypt_generic() for replacements.

mcrypt_cfb

(PHP 3>= 3.0.8, PHP 4 )

mcrypt_cfb -- Encrypt/decrypt data in CFB mode

Description

string mcrypt_cfb ( int cipher, string key, string data, int mode, string iv)

string mcrypt_cfb ( string cipher, string key, string data, int mode [, string iv])

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or higher. The mode should be either MCRYPT_ENCRYPT or MCRYPT_DECRYPT.

This function should not be used anymore, see mcrypt_generic() and mdecrypt_generic() for replacements.

mcrypt_create_iv

(PHP 3>= 3.0.8, PHP 4 )

mcrypt_create_iv --  Create an initialization vector (IV) from a random source

Description

string mcrypt_create_iv ( int size, int source)

mcrypt_create_iv() is used to create an IV.

mcrypt_create_iv() takes two arguments, size determines the size of the IV, source specifies 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). If you use MCRYPT_RAND, make sure to call srand() before to initialize the random number generator. MCRYPT_RAND is the only one supported on Windows because Windows (of course) doesn't have /dev/random or /dev/urandom.

Példa 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);
?>

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

More information can be found at http://www.ciphersbyritter.com/GLOSSARY.HTM#IV, http://fn2.freenet.edmonton.ab.ca/~jsavard/crypto/co0409.htm and in chapter 9.3 of Applied Cryptography by Schneier (ISBN 0-471-11709-9) for a discussion of this topic.

mcrypt_decrypt

(PHP 4 >= 4.0.2)

mcrypt_decrypt -- Decrypts crypttext with given parameters

Description

string mcrypt_decrypt ( string cipher, string key, string data, string mode [, string iv])

mcrypt_decrypt() decrypts the data and returns the unencrypted data.

Cipher is one of the MCRYPT_ciphername constants of the name of the algorithm as string.

Key is the key with which the data is encrypted. If it's smaller that the required keysize, it is padded with '\0'.

Data is 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 is one of the MCRYPT_MODE_modename constants of one of "ecb", "cbc", "cfb", "ofb", "nofb" or "stream".

The IV parameter is used for the initialisation in CBC, CFB, OFB modes, and in some algorithms in STREAM mode. If you do not supply an IV, while it is needed for an algorithm, the function issues a warning and uses an IV with all bytes set to '\0'.

mcrypt_ecb

(PHP 3>= 3.0.8, PHP 4 )

mcrypt_ecb -- Encrypt/decrypt data in ECB mode

Description

string mcrypt_ecb ( int cipher, string key, string data, int mode)

string mcrypt_ecb ( string cipher, string key, string data, int mode [, string iv])

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or higher. The mode should be either MCRYPT_ENCRYPT or MCRYPT_DECRYPT.

This function should not be used anymore, see mcrypt_generic() and mdecrypt_generic() for replacements.

mcrypt_enc_get_algorithms_name

(PHP 4 >= 4.0.2)

mcrypt_enc_get_algorithms_name -- Returns the name of the opened algorithm

Description

string mcrypt_enc_get_algorithms_name ( resource td)

This function returns the name of the algorithm.

Példa 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";
?>

Prints:
CAST-256
CAST-256

mcrypt_enc_get_block_size

(PHP 4 >= 4.0.2)

mcrypt_enc_get_block_size -- Returns the blocksize of the opened algorithm

Description

int mcrypt_enc_get_block_size ( resource td)

This function returns the block size of the algorithm specified by the encryption descriptor td in bytes.

mcrypt_enc_get_iv_size

(PHP 4 >= 4.0.2)

mcrypt_enc_get_iv_size -- Returns the size of the IV of the opened algorithm

Description

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. If it returns '0' then the IV is ignored in the algorithm. An IV is used in cbc, cfb and ofb modes, and in some algorithms in stream mode.

mcrypt_enc_get_key_size

(PHP 4 >= 4.0.2)

mcrypt_enc_get_key_size -- Returns the maximum supported keysize of the opened mode

Description

int mcrypt_enc_get_key_size ( resource td)

This function returns the maximum supported key size of the algorithm specified by the encryption descriptor td in bytes.

mcrypt_enc_get_modes_name

(PHP 4 >= 4.0.2)

mcrypt_enc_get_modes_name -- Returns the name of the opened mode

Description

string mcrypt_enc_get_modes_name ( resource td)

This function returns the name of the mode.

Példa 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";
?>

Prints:

CFB
ECB

mcrypt_enc_get_supported_key_sizes

(PHP 4 >= 4.0.2)

mcrypt_enc_get_supported_key_sizes -- Returns an array with the supported keysizes of the opened algorithm

Description

array mcrypt_enc_get_supported_key_sizes ( resource td)

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.

Példa 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));
?>

This will print:

array(3) {
  [0]=>
  int(16)
  [1]=>
  int(24)
  [2]=>
  int(32)
}

mcrypt_enc_is_block_algorithm_mode

(PHP 4 >= 4.0.2)

mcrypt_enc_is_block_algorithm_mode -- Checks whether the encryption of the opened mode works on blocks

Description

bool mcrypt_enc_is_block_algorithm_mode ( resource td)

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_enc_is_block_algorithm

(PHP 4 >= 4.0.2)

mcrypt_enc_is_block_algorithm -- Checks whether the algorithm of the opened mode is a block algorithm

Description

bool mcrypt_enc_is_block_algorithm ( resource td)

This function returns TRUE if the algorithm is a block algorithm, or FALSE if it is a stream algorithm.

mcrypt_enc_is_block_mode

(PHP 4 >= 4.0.2)

mcrypt_enc_is_block_mode -- Checks whether the opened mode outputs blocks

Description

bool mcrypt_enc_is_block_mode ( resource td)

This function returns TRUE if the mode outputs blocks of bytes or FALSE if it outputs bytes. (e.g. TRUE for cbc and ecb, and FALSE for cfb and stream).

mcrypt_enc_self_test

(PHP 4 >= 4.0.2)

mcrypt_enc_self_test -- This function runs a self test on the opened module

Description

bool mcrypt_enc_self_test ( resource td)

This function runs the self test on the algorithm specified by the descriptor td. If the self test succeeds it returns FALSE. In case of an error, it returns TRUE.

mcrypt_encrypt

(PHP 4 >= 4.0.2)

mcrypt_encrypt -- Encrypts plaintext with given parameters

Description

string mcrypt_encrypt ( string cipher, string key, string data, string mode [, string iv])

mcrypt_encrypt() encrypts the data and returns the encrypted data.

Cipher is one of the MCRYPT_ciphername constants of the name of the algorithm as string.

Key is the key with which the data will be encrypted. If it's smaller that the required keysize, it is padded with '\0'. It is better not to use ASCII strings for keys. It is recommended to use the mhash functions to create a key from a string.

Data is 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 that the size of the data that is given by data.

Mode is one of the MCRYPT_MODE_modename constants of one of "ecb", "cbc", "cfb", "ofb", "nofb" or "stream".

The IV parameter is used for the initialisation in CBC, CFB, OFB modes, and in some algorithms in STREAM mode. If you do not supply an IV, while it is needed for an algorithm, the function issues a warning and uses an IV with all bytes set to '\0'.

Példa 1. mcrypt_encrypt() Example

<?php
    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    $key = "This is a very secret key";
    $text = "Meet me at 11 o'clock behind the monument.";
    echo strlen($text) . "\n";

    $crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_ECB, $iv);
    echo strlen($crypttext) . "\n";
?>

The above example will print out:
42
64

See also mcrypt_module_open() for a more advanced API and an example.

mcrypt_generic_deinit

(PHP 4 >= 4.1.1)

mcrypt_generic_deinit --  This function deinitializes an encryption module

Description

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.) Returns FALSE on error, or TRUE on success.

See for an example mcrypt_module_open() and the entry on mcrypt_generic_init().

mcrypt_generic_end

(PHP 4 >= 4.0.2)

mcrypt_generic_end -- This function terminates encryption

Description

bool mcrypt_generic_end ( resource td)

Figyelem

This function is deprecated, use mcrypt_generic_deinit() instead. It can cause crashes when used with mcrypt_module_close() due to multiple buffer frees.

This function terminates encryption specified by the encryption descriptor (td). Actually it clears all buffers, and closes all the modules used. Returns FALSE on error, or TRUE on success.

mcrypt_generic_init

(PHP 4 >= 4.0.2)

mcrypt_generic_init -- This function initializes all buffers needed for encryption

Description

int mcrypt_generic_init ( resource td, string key, string iv)

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

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.

You need to call this function before every call to mcrypt_generic() or mdecrypt_generic().

See for an example mcrypt_module_open().

mcrypt_generic

(PHP 4 >= 4.0.2)

mcrypt_generic -- This function encrypts data

Description

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

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.

See also mdecrypt_generic(), mcrypt_generic_init(), and mcrypt_generic_deinit().

mcrypt_get_block_size

(PHP 3>= 3.0.8, PHP 4 )

mcrypt_get_block_size -- Get the block size of the specified cipher

Description

int mcrypt_get_block_size ( int cipher)

int mcrypt_get_block_size ( string cipher, string module)

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or 2.5.x.

mcrypt_get_block_size() is used to get the size of a block of the specified cipher (in combination with an encryption mode).

It is more useful to use the mcrypt_enc_get_block_size() function as this uses the resource returned by mcrypt_module_open().

This example shows how to use this function when linked against libmcrypt 2.4.x and 2.5.x.

Példa 1. mcrypt_get_block_size() example

<?php
    echo mcrypt_get_block_size('tripledes', 'ecb');
?>

Prints:
8

See also: mcrypt_get_key_size(), mcrypt_enc_get_block_size() and mcrypt_encrypt().

mcrypt_get_cipher_name

(PHP 3>= 3.0.8, PHP 4 )

mcrypt_get_cipher_name -- Get the name of the specified cipher

Description

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.

Példa 1. mcrypt_get_cipher_name() Example

<?php
   $cipher = MCRYPT_TripleDES;

   echo mcrypt_get_cipher_name($cipher);
?>

The above example will produce:
3DES

mcrypt_get_iv_size

(PHP 4 >= 4.0.2)

mcrypt_get_iv_size --  Returns the size of the IV belonging to a specific cipher/mode combination

Description

int mcrypt_get_iv_size ( string cipher, string mode)

mcrypt_get_iv_size() returns the size of the Initialisation Vector (IV) in bytes. On error the function returns FALSE. If the IV is ignored in the specified cipher/mode combination zero is returned.

cipher is one of the MCRYPT_ciphername constants of the name of the algorithm as string.

mode is one of the MCRYPT_MODE_modename constants or one of "ecb", "cbc", "cfb", "ofb", "nofb" or "stream". The IV is ignored in ECB mode as this mode does not require it. You will need to have the same IV (think: starting point) both at encryption and decryption stages, otherwise your encryption will fail.

It is more useful to use the mcrypt_enc_get_iv_size() function as this uses the resource returned by mcrypt_module_open().

Példa 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";
?>

See also mcrypt_get_block_size(), mcrypt_enc_get_iv_size() and mcrypt_create_iv().

mcrypt_get_key_size

(PHP 3>= 3.0.8, PHP 4 )

mcrypt_get_key_size -- Get the key size of the specified cipher

Description

int mcrypt_get_key_size ( int cipher)

int mcrypt_get_key_size ( string cipher, string module)

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or 2.5.x.

mcrypt_get_key_size() is used to get the size of a key of the specified cipher (in combination with an encryption mode).

This example shows how to use this function when linked against libmcrypt 2.4.x and 2.5.x. It is more useful to use the mcrypt_enc_get_key_size() function as this uses the resource returned by mcrypt_module_open().

Példa 1. mcrypt_get_block_size() example

<?php
    echo mcrypt_get_key_size('tripledes', 'ecb');
?>

Prints:
24

See also: mcrypt_get_block_size(), mcrypt_end_get_key_size() and mcrypt_encrypt().

mcrypt_list_algorithms

(PHP 4 >= 4.0.2)

mcrypt_list_algorithms -- Get an array of all supported ciphers

Description

array mcrypt_list_algorithms ( [string lib_dir])

mcrypt_list_algorithms() is used to get an array of all supported algorithms in the lib_dir parameter.

mcrypt_list_algorithms() takes an optional lib_dir parameter which specifies the directory where all algorithms are located. If not specifies, the value of the mcrypt.algorithms_dir php.ini directive is used.

Példa 1. mcrypt_list_algorithms() Example

<?php
    $algorithms = mcrypt_list_algorithms("/usr/local/lib/libmcrypt");

    foreach ($algorithms as $cipher) {
        echo "$cipher<br />\n";
    }
?>

The above example will produce a list with all supported algorithms in the "/usr/local/lib/libmcrypt" directory.

mcrypt_list_modes

(PHP 4 >= 4.0.2)

mcrypt_list_modes -- Get an array of all supported modes

Description

array mcrypt_list_modes ( [string lib_dir])

mcrypt_list_modes() is used to get an array of all supported modes in the lib_dir.

mcrypt_list_modes() takes as optional parameter a directory which specifies the directory where all modes are located. If not specifies, the value of the mcrypt.modes_dir php.ini directive is used.

Példa 1. mcrypt_list_modes() Example

<?php
    $modes = mcrypt_list_modes();

    foreach ($modes as $mode) {
        echo "$mode <br />\n";
    }
?>

The above example will produce a list with all supported algorithms in the default mode directory. If it is not set with the ini directive mcrypt.modes_dir, the default directory of mcrypt is used (which is /usr/local/lib/libmcrypt).

mcrypt_module_close

(PHP 4 >= 4.0.2)

mcrypt_module_close --  Close the mcrypt module

Description

bool mcrypt_module_close ( resource td)

This function closes the specified encryption handle.

See mcrypt_module_open() for an example.

mcrypt_module_get_algo_block_size

(PHP 4 >= 4.0.2)

mcrypt_module_get_algo_block_size -- Returns the blocksize of the specified algorithm

Description

int mcrypt_module_get_algo_block_size ( string algorithm [, string lib_dir])

This function returns the block size of the algorithm specified in bytes. The optional lib_dir parameter can contain the location where the mode module is on the system.

mcrypt_module_get_algo_key_size

(PHP 4 >= 4.0.2)

mcrypt_module_get_algo_key_size -- Returns the maximum supported keysize of the opened mode

Description

int mcrypt_module_get_algo_key_size ( string algorithm [, string lib_dir])

This function returns the maximum supported key size of the algorithm specified in bytes. The optional lib_dir parameter can contain the location where the mode module is on the system.

mcrypt_module_get_supported_key_sizes

(PHP 4 >= 4.0.2)

mcrypt_module_get_supported_key_sizes -- Returns an array with the supported keysizes of the opened algorithm

Description

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. The optional lib_dir parameter can contain the location where the mode module is on the system.

See also mcrypt_enc_get_supported_key_sizes() which is used on open encryption modules.

mcrypt_module_is_block_algorithm_mode

(PHP 4 >= 4.0.2)

mcrypt_module_is_block_algorithm_mode -- returns if the specified module is a block algorithm or not

Description

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). The optional lib_dir parameter can contain the location where the mode module is on the system.

mcrypt_module_is_block_algorithm

(PHP 4 >= 4.0.2)

mcrypt_module_is_block_algorithm -- This function checks whether the specified algorithm is a block algorithm

Description

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 is it is a stream algorithm. The optional lib_dir parameter can contain the location where the algorithm module is on the system.

mcrypt_module_is_block_mode

(PHP 4 >= 4.0.2)

mcrypt_module_is_block_mode -- Returns if the specified mode outputs blocks or not

Description

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). The optional lib_dir parameter can contain the location where the mode module is on the system.

mcrypt_module_open

(PHP 4 >= 4.0.2)

mcrypt_module_open -- Opens the module of the algorithm and the mode to be used

Description

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(). Normally it returns an encryption descriptor, or FALSE on error.

The algorithm_directory and mode_directory are used to locate the encryption modules. When you supply a directory name, it is used. When you set one of these to the empty string (""), the value set by the mcrypt.algorithms_dir or mcrypt.modes_dir ini-directive is used. When these are not set, the default directories that are used are the ones that were compiled in into libmcrypt (usually /usr/local/lib/libmcrypt).

Példa 1. mcrypt_module_open() examples

<?php
    $td = mcrypt_module_open(MCRYPT_DES, '',
        MCRYPT_MODE_ECB, '/usr/lib/mcrypt-modes');

    $td = mcrypt_module_open('rijndael-256', '', 'ofb', '');
?>

The first line in the example above will try to open the DES cipher from the default directory and the EBC mode from the directory /usr/lib/mcrypt-modes. The second example uses strings as name for the cipher and mode, this only works when the extension is linked against libmcrypt 2.4.x or 2.5.x.

Példa 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, used 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";
?>

The first line in the example above will try to open the DES cipher from the default directory and the EBC mode from the directory /usr/lib/mcrypt-modes. The second example uses strings as name for the cipher and mode, this only works when the extension is linked against libmcrypt 2.4.x or 2.5.x.

See also mcrypt_module_close(), mcrypt_generic(), mdecrypt_generic(), mcrypt_generic_init(), and mcrypt_generic_deinit().

mcrypt_module_self_test

(PHP 4 >= 4.0.2)

mcrypt_module_self_test -- This function runs a self test on the specified module

Description

bool mcrypt_module_self_test ( string algorithm [, string lib_dir])

This function runs the self test on the algorithm specified. The optional lib_dir parameter can contain the location of where the algorithm module is on the system.

The function returns TRUE if the self test succeeds, or FALSE when if fails.

Példa 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));
?>

The above example will output:

bool(true)
bool(false)

mcrypt_ofb

(PHP 3>= 3.0.8, PHP 4 )

mcrypt_ofb -- Encrypt/decrypt data in OFB mode

Description

string mcrypt_ofb ( int cipher, string key, string data, int mode, string iv)

string mcrypt_ofb ( string cipher, string key, string data, int mode [, string iv])

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or higher. The mode should be either MCRYPT_ENCRYPT or MCRYPT_DECRYPT.

This function should not be used anymore, see mcrypt_generic() and mdecrypt_generic() for replacements.

mdecrypt_generic

(PHP 4 >= 4.0.2)

mdecrypt_generic -- Decrypt data

Description

string mdecrypt_generic ( resource td, string data)

This function decrypts data. Note that the length of the returned string can in fact be longer then the unencrypted string, due to the padding of the data.

Példa 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 above example 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.

See also mcrypt_generic(), mcrypt_generic_init(), and mcrypt_generic_deinit().

LVI. MCVE Payment Functions

Bevezetés

These functions interface the MCVE API (libmcve), allowing you to work directly with MCVE from your PHP scripts. MCVE is Main Street Softworks' solution to direct credit card processing for Linux / Unix ( 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 module for PHP, you can process credit cards directly through MCVE via your PHP scripts. The following references will outline the process.

Megjegyzés: MCVE is the replacement for RedHat's CCVS. They contracted with RedHat in late 2001 to migrate all existing clientele to the MCVE platform.

Megjegyzés: Ez a kiterjesztés nem működik Windows operációs rendszereken!


Telepítés

To enable MCVE Support in PHP, first verify your LibMCVE installation directory. You will then need to configure PHP with the --with-mcve option. If you use this option without specifying the path to your MCVE installation, PHP will attempt to look in the default LibMCVE Install location (/usr/local). If MCVE is in a non-standard location, run configure with: --with-mcve=$mcve_path, where $mcve_path is the path to your MCVE installation. Please note that MCVE support requires that $mcve_path/lib and $mcve_path/include exist, and include mcve.h under the include directory and libmcve.so and/or libmcve.a under the lib directory.

Since MCVE has true server/client separation, there are no additional requirements for running PHP with MCVE support. To test your MCVE extension in PHP, you may connect to testbox.mcve.com on port 8333 for IP, or port 8444 for SSL using the MCVE PHP API. Use 'vitale' for your username, and 'test' for your password. Additional information about test facilities are available at http://www.mainstreetsoftworks.com/.


Lásd még

Additional documentation about MCVE's PHP API can be found at http://www.mainstreetsoftworks.com/docs/phpapi.pdf. Main Street's documentation is complete and should be the primary reference for functions.


Előre definiált állandók

Az itt listázott állandókat ez a kiterjesztés definiálja, és csak akkor elérhetőek, ha az adott kiterjesztés be van fordítva a PHP-be, vagy dinamikusan betöltött.

MC_TRANTYPE (integer)

MC_USERNAME (integer)

MC_PASSWORD (integer)

MC_ACCOUNT (integer)

MC_TRACKDATA (integer)

MC_EXPDATE (integer)

MC_STREET (integer)

MC_ZIP (integer)

MC_CV (integer)

MC_COMMENTS (integer)

MC_CLERKID (integer)

MC_STATIONID (integer)

MC_APPRCODE (integer)

MC_AMOUNT (integer)

MC_PTRANNUM (integer)

MC_TTID (integer)

MC_USER (integer)

MC_PWD (integer)

MC_ACCT (integer)

MC_BDATE (integer)

MC_EDATE (integer)

MC_BATCH (integer)

MC_FILE (integer)

MC_ADMIN (integer)

MC_AUDITTYPE (integer)

MC_CUSTOM (integer)

MC_EXAMOUNT (integer)

MC_EXCHARGES (integer)

MC_RATE (integer)

MC_RENTERNAME (integer)

MC_RETURNCITY (integer)

MC_RETURNSTATE (integer)

MC_RETURNLOCATION (integer)

MC_PRIORITY (integer)

MC_INQUIRY (integer)

MC_CARDTYPES (integer)

MC_SUB (integer)

MC_MARKER (integer)

MC_DEVICETYPE (integer)

MC_ERRORCODE (integer)

MC_NEWBATCH (integer)

MC_CURR (integer)

MC_DESCMERCH (integer)

MC_DESCLOC (integer)

MC_ORIGTYPE (integer)

MC_PIN (integer)

MC_VOIDORIGTYPE (integer)

MC_TIMESTAMP (integer)

MC_PRIO_HIGH (integer)

MC_PRIO_NORMAL (integer)

MC_PRIO_LOW (integer)

MC_USER_PROC (integer)

MC_USER_USER (integer)

MC_USER_PWD (integer)

MC_USER_INDCODE (integer)

MC_USER_MERCHID (integer)

MC_USER_BANKID (integer)

MC_USER_TERMID (integer)

MC_USER_CLIENTNUM (integer)

MC_USER_STOREID (integer)

MC_USER_AGENTID (integer)

MC_USER_CHAINID (integer)

MC_USER_ZIPCODE (integer)

MC_USER_TIMEZONE (integer)

MC_USER_MERCHCAT (integer)

MC_USER_MERNAME (integer)

MC_USER_MERCHLOC (integer)

MC_USER_STATECODE (integer)

MC_USER_PHONE (integer)

MC_USER_SUB (integer)

MC_USER_CARDTYPES (integer)

MC_USER_MODE (integer)

MC_USER_VNUMBER (integer)

MC_USER_ROUTINGID (integer)

MC_USER_PPROPERTY (integer)

MC_USER_PID (integer)

MC_USER_PIDPWD (integer)

MC_USER_SMID (integer)

MC_USER_SMIDPWD (integer)

MC_USER_USDDIV (integer)

MC_USER_AUDDIV (integer)

MC_USER_DKKDIV (integer)

MC_USER_GBPDIV (integer)

MC_USER_HKDDIV (integer)

MC_USER_JPYDIV (integer)

MC_USER_NZDDIV (integer)

MC_USER_NOKDIV (integer)

MC_USER_SGDDIV (integer)

MC_USER_ZARDIV (integer)

MC_USER_SEKDIV (integer)

MC_USER_CHFDIV (integer)

MC_USER_CADDIV (integer)

MC_USER_DIVNUM (integer)

MC_CARD_VISA (integer)

MC_CARD_MC (integer)

MC_CARD_AMEX (integer)

MC_CARD_DISC (integer)

MC_CARD_JCB (integer)

MC_CARD_CB (integer)

MC_CARD_DC (integer)

MC_CARD_GIFT (integer)

MC_CARD_OTHER (integer)

MC_CARD_ALL (integer)

MC_MODE_AUTH (integer)

MC_MODE_SETTLE (integer)

MC_MODE_BOTH (integer)

MC_MODE_ALL (integer)

MC_EXCHARGES_REST (integer)

MC_EXCHARGES_GIFT (integer)

MC_EXCHARGES_MINI (integer)

MC_EXCHARGES_TELE (integer)

MC_EXCHARGES_OTHER (integer)

MC_EXCHARGES_LAUND (integer)

MC_EXCHARGES_NONE (integer)

MC_EXCHARGES_GAS (integer)

MC_EXCHARGES_MILE (integer)

MC_EXCHARGES_LATE (integer)

MC_EXCHARGES_1WAY (integer)

MC_EXCHARGES_VIOL (integer)

MC_TRAN_SALE (integer)

MC_TRAN_REDEMPTION (integer)

MC_TRAN_PREAUTH (integer)

MC_TRAN_VOID (integer)

MC_TRAN_PREAUTHCOMPLETE (integer)

MC_TRAN_FORCE (integer)

MC_TRAN_OVERRIDE (integer)

MC_TRAN_RETURN (integer)

MC_TRAN_RELOAD (integer)

MC_TRAN_CREDIT (integer)

MC_TRAN_SETTLE (integer)

MC_TRAN_INCREMENTAL (integer)

MC_TRAN_REVERSAL (integer)

MC_TRAN_ACTIVATE (integer)

MC_TRAN_BALANCEINQ (integer)

MC_TRAN_CASHOUT (integer)

MC_TRAN_TOREVERSAL (integer)

MC_TRAN_SETTLERFR (integer)

MC_TRAN_ISSUE (integer)

MC_TRAN_TIP (integer)

MC_TRAN_MERCHRETURN (integer)

MC_TRAN_IVRREQ (integer)

MC_TRAN_IVRRESP (integer)

MC_TRAN_ADMIN (integer)

MC_TRAN_PING (integer)

MC_TRAN_CHKPWD (integer)

MC_TRAN_CHNGPWD (integer)

MC_TRAN_LISTSTATS (integer)

MC_TRAN_LISTUSERS (integer)

MC_TRAN_GETUSERINFO (integer)

MC_TRAN_ADDUSER (integer)

MC_TRAN_EDITUSER (integer)

MC_TRAN_DELUSER (integer)

MC_TRAN_ENABLEUSER (integer)

MC_TRAN_DISABLEUSER (integer)

MC_TRAN_IMPORT (integer)

MC_TRAN_EXPORT (integer)

MC_TRAN_ERRORLOG (integer)

MC_TRAN_CLEARERRORLOG (integer)

MC_TRAN_GETSUBACCTS (integer)

MC_ADMIN_GUT (integer)

MC_ADMIN_GL (integer)

MC_ADMIN_GFT (integer)

MC_ADMIN_BT (integer)

MC_ADMIN_UB (integer)

MC_ADMIN_QC (integer)

MC_ADMIN_RS (integer)

MC_ADMIN_CTH (integer)

MC_ADMIN_CFH (integer)

MC_ADMIN_FORCESETTLE (integer)

MC_ADMIN_SETBATCHNUM (integer)

MC_ADMIN_RENUMBERBATCH (integer)

MC_ADMIN_FIELDEDIT (integer)

MC_ADMIN_CLOSEBATCH (integer)

MCVE_UNUSED (integer)

MCVE_NEW (integer)

MCVE_PENDING (integer)

MCVE_DONE (integer)

MCVE_GOOD (integer)

MCVE_BAD (integer)

MCVE_STREET (integer)

MCVE_ZIP (integer)

MCVE_UNKNOWN (integer)

MCVE_ERROR (integer)

MCVE_FAIL (integer)

MCVE_SUCCESS (integer)

MCVE_AUTH (integer)

MCVE_DENY (integer)

MCVE_CALL (integer)

MCVE_DUPL (integer)

MCVE_PKUP (integer)

MCVE_RETRY (integer)

MCVE_SETUP (integer)

MCVE_TIMEOUT (integer)

MCVE_SALE (integer)

MCVE_PREAUTH (integer)

MCVE_FORCE (integer)

MCVE_OVERRIDE (integer)

MCVE_RETURN (integer)

MCVE_SETTLE (integer)

MCVE_PROC (integer)

MCVE_USER (integer)

MCVE_PWD (integer)

MCVE_INDCODE (integer)

MCVE_MERCHID (integer)

MCVE_BANKID (integer)

MCVE_TERMID (integer)

MCVE_CLIENTNUM (integer)

MCVE_STOREID (integer)

MCVE_AGENTID (integer)

MCVE_CHAINID (integer)

MCVE_ZIPCODE (integer)

MCVE_TIMEZONE (integer)

MCVE_MERCHCAT (integer)

MCVE_MERNAME (integer)

MCVE_MERCHLOC (integer)

MCVE_STATECODE (integer)

MCVE_SERVICEPHONE (integer)

Tartalom
mcve_adduser --  Add an MCVE user using usersetup structure
mcve_adduserarg --  Add a value to user configuration structure
mcve_bt --  Get unsettled batch totals
mcve_checkstatus --  Check to see if a transaction has completed
mcve_chkpwd --  Verify Password
mcve_chngpwd --  Change the system administrator's password
mcve_completeauthorizations --  Number of complete authorizations in queue, returning an array of their identifiers
mcve_connect --  Establish the connection to MCVE
mcve_connectionerror --  Get a textual representation of why a connection failed
mcve_deleteresponse --  Delete specified transaction from MCVE_CONN structure
mcve_deletetrans --  Delete specified transaction from MCVE_CONN structure
mcve_deleteusersetup --  Deallocate data associated with usersetup structure
mcve_deluser --  Delete an MCVE user account
mcve_destroyconn --  Destroy the connection and MCVE_CONN structure
mcve_destroyengine --  Free memory associated with IP/SSL connectivity
mcve_disableuser --  Disable an active MCVE user account
mcve_edituser --  Edit MCVE user using usersetup structure
mcve_enableuser --  Enable an inactive MCVE user account
mcve_force --  Send a FORCE to MCVE. (typically, a phone-authorization)
mcve_getcell --  Get a specific cell from a comma delimited response by column name
mcve_getcellbynum --  Get a specific cell from a comma delimited response by column number
mcve_getcommadelimited --  Get the RAW comma delimited data returned from MCVE
mcve_getheader --  Get the name of the column in a comma-delimited response
mcve_getuserarg --  Grab a value from usersetup structure
mcve_getuserparam --  Get a user response parameter
mcve_gft --  Audit MCVE for Failed transactions
mcve_gl --  Audit MCVE for settled transactions
mcve_gut --  Audit MCVE for Unsettled Transactions
mcve_initconn --  Create and initialize an MCVE_CONN structure
mcve_initengine --  Ready the client for IP/SSL Communication
mcve_initusersetup --  Initialize structure to store user data
mcve_iscommadelimited --  Checks to see if response is comma delimited
mcve_liststats --  List statistics for all users on MCVE system
mcve_listusers --  List all users on MCVE system
mcve_maxconntimeout --  The maximum amount of time the API will attempt a connection to MCVE
mcve_monitor --  Perform communication with MCVE (send/receive data) Non-blocking
mcve_numcolumns --  Number of columns returned in a comma delimited response
mcve_numrows --  Number of rows returned in a comma delimited response
mcve_override --  Send an OVERRIDE to MCVE
mcve_parsecommadelimited --  Parse the comma delimited response so mcve_getcell, etc will work
mcve_ping --  Send a ping request to MCVE
mcve_preauth --  Send a PREAUTHORIZATION to MCVE
mcve_preauthcompletion --  Complete a PREAUTHORIZATION... Ready it for settlement
mcve_qc --  Audit MCVE for a list of transactions in the outgoing queue
mcve_responseparam --  Get a custom response parameter
mcve_return --  Issue a RETURN or CREDIT to MCVE
mcve_returncode --  Grab the exact return code from the transaction
mcve_returnstatus --  Check to see if the transaction was successful
mcve_sale --  Send a SALE to MCVE
mcve_setblocking --  Set blocking/non-blocking mode for connection
mcve_setdropfile --  Set the connection method to Drop-File
mcve_setip --  Set the connection method to IP
mcve_setssl_files --  Set certificate key files and certificates if server requires client certificate verification
mcve_setssl --  Set the connection method to SSL
mcve_settimeout --  Set maximum transaction time (per trans)
mcve_settle --  Issue a settlement command to do a batch deposit
mcve_text_avs --  Get a textual representation of the return_avs
mcve_text_code --  Get a textual representation of the return_code
mcve_text_cv --  Get a textual representation of the return_cv
mcve_transactionauth --  Get the authorization number returned for the transaction (alpha-numeric)
mcve_transactionavs --  Get the Address Verification return status
mcve_transactionbatch --  Get the batch number associated with the transaction
mcve_transactioncv --  Get the CVC2/CVV2/CID return status
mcve_transactionid --  Get the unique system id for the transaction
mcve_transactionitem --  Get the ITEM number in the associated batch for this transaction
mcve_transactionssent --  Check to see if outgoing buffer is clear
mcve_transactiontext --  Get verbiage (text) return from MCVE or processing institution
mcve_transinqueue --  Number of transactions in client-queue
mcve_transnew --  Start a new transaction
mcve_transparam --  Add a parameter to a transaction
mcve_transsend --  Finalize and send the transaction
mcve_ub --  Get a list of all Unsettled batches
mcve_uwait --  Wait x microsecs
mcve_verifyconnection --  Set whether or not to PING upon connect to verify connection
mcve_verifysslcert --  Set whether or not to verify the server ssl certificate
mcve_void --  VOID a transaction in the settlement queue

mcve_adduser

(PHP 4 >= 4.2.0)

mcve_adduser --  Add an MCVE user using usersetup structure

Description

int mcve_adduser ( resource conn, string admin_password, int usersetup)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_adduserarg

(PHP 4 >= 4.2.0)

mcve_adduserarg --  Add a value to user configuration structure

Description

int mcve_adduserarg ( resource usersetup, int argtype, string argval)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_bt

(PHP 4 >= 4.2.0)

mcve_bt --  Get unsettled batch totals

Description

int mcve_bt ( resource conn, string username, string password)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_checkstatus

(PHP 4 >= 4.2.0)

mcve_checkstatus --  Check to see if a transaction has completed

Description

int mcve_checkstatus ( resource conn, int identifier)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_chkpwd

(PHP 4 >= 4.2.0)

mcve_chkpwd --  Verify Password

Description

int mcve_chkpwd ( resource conn, string username, string password)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_chngpwd

(PHP 4 >= 4.2.0)

mcve_chngpwd --  Change the system administrator's password

Description

int mcve_chngpwd ( resource conn, string admin_password, string new_password)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_completeauthorizations

(PHP 4 >= 4.2.0)

mcve_completeauthorizations --  Number of complete authorizations in queue, returning an array of their identifiers

Description

int mcve_completeauthorizations ( resource conn, int &array)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_connect

(PHP 4 >= 4.2.0)

mcve_connect --  Establish the connection to MCVE

Description

int mcve_connect ( resource conn)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_connectionerror

(PHP 4 >= 4.3.0)

mcve_connectionerror --  Get a textual representation of why a connection failed

Description

string mcve_connectionerror ( resource conn)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_deleteresponse

(PHP 4 >= 4.2.0)

mcve_deleteresponse --  Delete specified transaction from MCVE_CONN structure

Description

bool mcve_deleteresponse ( resource conn, int identifier)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_deletetrans

(PHP 4 >= 4.3.0)

mcve_deletetrans --  Delete specified transaction from MCVE_CONN structure

Description

bool mcve_deletetrans ( resource conn, int identifier)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_deleteusersetup

(PHP 4 >= 4.2.0)

mcve_deleteusersetup --  Deallocate data associated with usersetup structure

Description

void mcve_deleteusersetup ( resource usersetup)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_deluser

(PHP 4 >= 4.2.0)

mcve_deluser --  Delete an MCVE user account

Description

int mcve_deluser ( resource conn, string admin_password, string username)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_destroyconn

(PHP 4 >= 4.2.0)

mcve_destroyconn --  Destroy the connection and MCVE_CONN structure

Description

void mcve_destroyconn ( resource conn)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_destroyengine

(PHP 4 >= 4.2.0)

mcve_destroyengine --  Free memory associated with IP/SSL connectivity

Description

void mcve_destroyengine ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_disableuser

(PHP 4 >= 4.2.0)

mcve_disableuser --  Disable an active MCVE user account

Description

int mcve_disableuser ( resource conn, string admin_password, string username)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_edituser

(PHP 4 >= 4.2.0)

mcve_edituser --  Edit MCVE user using usersetup structure

Description

int mcve_edituser ( resource conn, string admin_password, int usersetup)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_enableuser

(PHP 4 >= 4.2.0)

mcve_enableuser --  Enable an inactive MCVE user account

Description

int mcve_enableuser ( resource conn, string admin_password, string username)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_force

(PHP 4 >= 4.2.0)

mcve_force --  Send a FORCE to MCVE. (typically, a phone-authorization)

Description

int mcve_force ( resource conn, string username, string password, string trackdata, string account, string expdate, float amount, string authcode, string comments, string clerkid, string stationid, int ptrannum)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_getcell

(PHP 4 >= 4.2.0)

mcve_getcell --  Get a specific cell from a comma delimited response by column name

Description

string mcve_getcell ( resource conn, int identifier, string column, int row)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_getcellbynum

(PHP 4 >= 4.2.0)

mcve_getcellbynum --  Get a specific cell from a comma delimited response by column number

Description

string mcve_getcellbynum ( resource conn, int identifier, int column, int row)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_getcommadelimited

(PHP 4 >= 4.2.0)

mcve_getcommadelimited --  Get the RAW comma delimited data returned from MCVE

Description

string mcve_getcommadelimited ( resource conn, int identifier)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_getheader

(PHP 4 >= 4.2.0)

mcve_getheader --  Get the name of the column in a comma-delimited response

Description

string mcve_getheader ( resource conn, int identifier, int column_num)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_getuserarg

(PHP 4 >= 4.2.0)

mcve_getuserarg --  Grab a value from usersetup structure

Description

string mcve_getuserarg ( resource usersetup, int argtype)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_getuserparam

(PHP 4 >= 4.3.0)

mcve_getuserparam --  Get a user response parameter

Description

string mcve_getuserparam ( resource conn, long identifier, int key)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_gft

(PHP 4 >= 4.2.0)

mcve_gft --  Audit MCVE for Failed transactions

Description

int mcve_gft ( resource conn, string username, string password, int type, string account, string clerkid, string stationid, string comments, int ptrannum, string startdate, string enddate)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_gl

(PHP 4 >= 4.2.0)

mcve_gl --  Audit MCVE for settled transactions

Description

int mcve_gl ( int conn, string username, string password, int type, string account, string batch, string clerkid, string stationid, string comments, int ptrannum, string startdate, string enddate)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_gut

(PHP 4 >= 4.2.0)

mcve_gut --  Audit MCVE for Unsettled Transactions

Description

int mcve_gut ( resource conn, string username, string password, int type, string account, string clerkid, string stationid, string comments, int ptrannum, string startdate, string enddate)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_initconn

(PHP 4 >= 4.2.0)

mcve_initconn --  Create and initialize an MCVE_CONN structure

Description

resource mcve_initconn ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_initengine

(PHP 4 >= 4.2.0)

mcve_initengine --  Ready the client for IP/SSL Communication

Description

int mcve_initengine ( string location)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_initusersetup

(PHP 4 >= 4.2.0)

mcve_initusersetup --  Initialize structure to store user data

Description

resource mcve_initusersetup ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_iscommadelimited

(PHP 4 >= 4.2.0)

mcve_iscommadelimited --  Checks to see if response is comma delimited

Description

int mcve_iscommadelimited ( resource conn, int identifier)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_liststats

(PHP 4 >= 4.2.0)

mcve_liststats --  List statistics for all users on MCVE system

Description

int mcve_liststats ( resource conn, string admin_password)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_listusers

(PHP 4 >= 4.2.0)

mcve_listusers --  List all users on MCVE system

Description

int mcve_listusers ( resource conn, string admin_password)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_maxconntimeout

(PHP 4 >= 4.3.0)

mcve_maxconntimeout --  The maximum amount of time the API will attempt a connection to MCVE

Description

bool mcve_maxconntimeout ( resource conn, int secs)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_monitor

(PHP 4 >= 4.2.0)

mcve_monitor --  Perform communication with MCVE (send/receive data) Non-blocking

Description

int mcve_monitor ( resource conn)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_numcolumns

(PHP 4 >= 4.2.0)

mcve_numcolumns --  Number of columns returned in a comma delimited response

Description

int mcve_numcolumns ( resource conn, int identifier)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_numrows

(PHP 4 >= 4.2.0)

mcve_numrows --  Number of rows returned in a comma delimited response

Description

int mcve_numrows ( resource conn, int identifier)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_override

(PHP 4 >= 4.2.0)

mcve_override --  Send an OVERRIDE to MCVE

Description

int mcve_override ( resource conn, string username, string password, string trackdata, string account, string expdate, float amount, string street, string zip, string cv, string comments, string clerkid, string stationid, int ptrannum)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_parsecommadelimited

(PHP 4 >= 4.2.0)

mcve_parsecommadelimited --  Parse the comma delimited response so mcve_getcell, etc will work

Description

int mcve_parsecommadelimited ( resource conn, int identifier)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_ping

(PHP 4 >= 4.3.0)

mcve_ping --  Send a ping request to MCVE

Description

int mcve_ping ( resource conn)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_preauth

(PHP 4 >= 4.2.0)

mcve_preauth --  Send a PREAUTHORIZATION to MCVE

Description

int mcve_preauth ( resource conn, string username, string password, string trackdata, string account, string expdate, float amount, string street, string zip, string cv, string comments, string clerkid, string stationid, int ptrannum)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_preauthcompletion

(PHP 4 >= 4.2.0)

mcve_preauthcompletion --  Complete a PREAUTHORIZATION... Ready it for settlement

Description

int mcve_preauthcompletion ( resource conn, string username, string password, float finalamount, int sid, int ptrannum)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_qc

(PHP 4 >= 4.2.0)

mcve_qc --  Audit MCVE for a list of transactions in the outgoing queue

Description

int mcve_qc ( resource conn, string username, string password, string clerkid, string stationid, string comments, int ptrannum)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_responseparam

(PHP 4 >= 4.3.0)

mcve_responseparam --  Get a custom response parameter

Description

string mcve_responseparam ( resource conn, long identifier, string key)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_return

(PHP 4 >= 4.2.0)

mcve_return --  Issue a RETURN or CREDIT to MCVE

Description

int mcve_return ( int conn, string username, string password, string trackdata, string account, string expdate, float amount, string comments, string clerkid, string stationid, int ptrannum)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_returncode

(PHP 4 >= 4.2.0)

mcve_returncode --  Grab the exact return code from the transaction

Description

int mcve_returncode ( resource conn, int identifier)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_returnstatus

(PHP 4 >= 4.2.0)

mcve_returnstatus --  Check to see if the transaction was successful

Description

int mcve_returnstatus ( resource conn, int identifier)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_sale

(PHP 4 >= 4.2.0)

mcve_sale --  Send a SALE to MCVE

Description

int mcve_sale ( resource conn, string username, string password, string trackdata, string account, string expdate, float amount, string street, string zip, string cv, string comments, string clerkid, string stationid, int ptrannum)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_setblocking

(PHP 4 >= 4.3.0)

mcve_setblocking --  Set blocking/non-blocking mode for connection

Description

int mcve_setblocking ( resource conn, int tf)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_setdropfile

(PHP 4 >= 4.2.0)

mcve_setdropfile --  Set the connection method to Drop-File

Description

int mcve_setdropfile ( resource conn, string directory)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_setip

(PHP 4 >= 4.2.0)

mcve_setip --  Set the connection method to IP

Description

int mcve_setip ( resource conn, string host, int port)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_setssl_files

(no version information, might be only in CVS)

mcve_setssl_files --  Set certificate key files and certificates if server requires client certificate verification

Description

int mcve_setssl_files ( string sslkeyfile, string sslcertfile)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_setssl

(PHP 4 >= 4.2.0)

mcve_setssl --  Set the connection method to SSL

Description

int mcve_setssl ( resource conn, string host, int port)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_settimeout

(PHP 4 >= 4.2.0)

mcve_settimeout --  Set maximum transaction time (per trans)

Description

int mcve_settimeout ( resource conn, int seconds)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_settle

(PHP 4 >= 4.2.0)

mcve_settle --  Issue a settlement command to do a batch deposit

Description

int mcve_settle ( resource conn, string username, string password, string batch)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_text_avs

(PHP 4 >= 4.3.0)

mcve_text_avs --  Get a textual representation of the return_avs

Description

string mcve_text_avs ( string code)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_text_code

(PHP 4 >= 4.3.0)

mcve_text_code --  Get a textual representation of the return_code

Description

string mcve_text_code ( string code)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_text_cv

(PHP 4 >= 4.3.0)

mcve_text_cv --  Get a textual representation of the return_cv

Description

string mcve_text_cv ( int code)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_transactionauth

(PHP 4 >= 4.2.0)

mcve_transactionauth --  Get the authorization number returned for the transaction (alpha-numeric)

Description

string mcve_transactionauth ( resource conn, int identifier)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_transactionavs

(PHP 4 >= 4.2.0)

mcve_transactionavs --  Get the Address Verification return status

Description

int mcve_transactionavs ( resource conn, int identifier)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_transactionbatch

(PHP 4 >= 4.2.0)

mcve_transactionbatch --  Get the batch number associated with the transaction

Description

int mcve_transactionbatch ( resource conn, int identifier)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_transactioncv

(PHP 4 >= 4.2.0)

mcve_transactioncv --  Get the CVC2/CVV2/CID return status

Description

int mcve_transactioncv ( resource conn, int identifier)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_transactionid

(PHP 4 >= 4.2.0)

mcve_transactionid --  Get the unique system id for the transaction

Description

int mcve_transactionid ( resource conn, int identifier)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_transactionitem

(PHP 4 >= 4.2.0)

mcve_transactionitem --  Get the ITEM number in the associated batch for this transaction

Description

int mcve_transactionitem ( resource conn, int identifier)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_transactionssent

(PHP 4 >= 4.2.0)

mcve_transactionssent --  Check to see if outgoing buffer is clear

Description

int mcve_transactionssent ( resource conn)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_transactiontext

(PHP 4 >= 4.2.0)

mcve_transactiontext --  Get verbiage (text) return from MCVE or processing institution

Description

string mcve_transactiontext ( resource conn, int identifier)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_transinqueue

(PHP 4 >= 4.2.0)

mcve_transinqueue --  Number of transactions in client-queue

Description

int mcve_transinqueue ( resource conn)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_transnew

(PHP 4 >= 4.3.0)

mcve_transnew --  Start a new transaction

Description

int mcve_transnew ( resource conn)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_transparam

(PHP 4 >= 4.3.0)

mcve_transparam --  Add a parameter to a transaction

Description

int mcve_transparam ( resource conn, long identifier, int key)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_transsend

(PHP 4 >= 4.3.0)

mcve_transsend --  Finalize and send the transaction

Description

int mcve_transsend ( resource conn, long identifier)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_ub

(PHP 4 >= 4.2.0)

mcve_ub --  Get a list of all Unsettled batches

Description

int mcve_ub ( resource conn, string username, string password)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_uwait

(PHP 4 >= 4.3.0)

mcve_uwait --  Wait x microsecs

Description

int mcve_uwait ( long microsecs)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_verifyconnection

(PHP 4 >= 4.3.0)

mcve_verifyconnection --  Set whether or not to PING upon connect to verify connection

Description

bool mcve_verifyconnection ( resource conn, int tf)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_verifysslcert

(PHP 4 >= 4.3.0)

mcve_verifysslcert --  Set whether or not to verify the server ssl certificate

Description

bool mcve_verifysslcert ( resource conn, int tf)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mcve_void

(PHP 4 >= 4.2.0)

mcve_void --  VOID a transaction in the settlement queue

Description

int mcve_void ( resource conn, string username, string password, int sid, int ptrannum)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

LVII. Mhash függvények

Ezek a függvények az mhash eljáráskönyvtárral működnek együtt.

Ezek egy felületet biztosítanak az mhash könyvtárhoz. Az mhash széles skáláját támogatja a hash algoritmusoknak, mint például az MD5, SHA1, GOST és még számos más. Az mhash például ellenőrzőösszegek, kivonatok, azonosítási kódok előállítására is használható.

A használatukhoz le kell tölteni az mhash csomagot az mhash webhelyről és a csomagban található a telepítési utasítások szerint installálni kell. A PHP-t a --with-mhash paraméterrel kell fordítani, amivel engedélyezzük ezt a kiterjesztést.

Példa 1. Az MD5 kivonat és a hmac előállítása és kiírása hexa formában

<?php
$input = "mit kérsz a semmiért?";
$hash = mhash (MHASH_MD5, $input);
print "A 'hash' értéke: ".bin2hex ($hash)."\n<br />";
$hash = mhash (MHASH_MD5, $input, "Jefe");
print "A 'hmac' értéke: ".bin2hex ($hash)."\n<br />";
?>
Ez a következő kimenetet eredményezi:
A 'hash' értéke: 08dd459b941ee225cc6b33717f87d9a4  
A 'hash' értéke: d6044d59c420fecb5e5e2910d2134129
A támogatott hash algoritmusok teljes listája az mhash dokumentációban található. Az általános szabály, hogy a hash algoritmust az MHASH_HASHNEVE formában lehet elérni PHP-ből, például a TIGER eléréséhez az MHASH_TIGER PHP konstans használható.

Itt következnek az mhash által jelenleg támogatott hash-ek. Az mhash dokumentációban szereplő, de itt fel nem soroltak is nyugodtan használhatók, ebben az esetben ez a dokumentáció már nem tekinthető aktuálisnak.

  • MHASH_MD5

  • MHASH_SHA1

  • MHASH_HAVAL256

  • MHASH_HAVAL192

  • MHASH_HAVAL160

  • MHASH_HAVAL128

  • MHASH_RIPEMD160

  • MHASH_GOST

  • MHASH_TIGER

  • MHASH_CRC32

  • MHASH_CRC32B

Tartalom
mhash_count -- Visszaadja a legnagyobb elérhető hash azonosítót
mhash_get_block_size -- A megadott hash blokkméretével tér vissza
mhash_get_hash_name -- A megadott hash nevét adja vissza
mhash_keygen_s2k -- Kulcsot generál
mhash -- Hash számítás

mhash_count

(PHP 3>= 3.0.9, PHP 4 )

mhash_count -- Visszaadja a legnagyobb elérhető hash azonosítót

Leírás

int mhash_count ( void )

Az mhash_count() visszaadja a legnagyobb elérhető hash azonosítót. A használható hash-ek azonosító számai nullától eddig a számig terjednek.

Példa 1. Az összes hash használata

<?php

$nr = mhash_count();

for ($i = 0; $i &lt;= $nr; $i++) {
    echo sprintf ("The blocksize of %s is %d\n", 
        mhash_get_hash_name ($i),
        mhash_get_block_size ($i));
}
?>

mhash_get_block_size

(PHP 3>= 3.0.9, PHP 4 )

mhash_get_block_size -- A megadott hash blokkméretével tér vissza

Leírás

int mhash_get_block_size ( int hash)

Az mhash_get_block_size() a megadott hash blokkméretét adja vissza byte-okban mérve.

Ha az mhash_get_block_size() függvénynek érvénytelen hash paramétert adsz, FALSE értékkel tér vissza.

mhash_get_hash_name

(PHP 3>= 3.0.9, PHP 4 )

mhash_get_hash_name -- A megadott hash nevét adja vissza

Leírás

string mhash_get_hash_name ( int hash)

Az mhash_get_hash_name() a megadott hash nevével tér vissza.

Ha az mhash_get_hash_name() függvénynek átadott hash azonosító egy nemlétező hash-re hivatkozik, FALSE értékkel tér vissza.

Példa 1. mhash_get_hash_name() példa

<?php
$hash = MHASH_MD5;

print mhash_get_hash_name ($hash);
?>
Ez a következő kimenetet eredményezi:
MD5

mhash_keygen_s2k

(PHP 4 >= 4.0.4)

mhash_keygen_s2k -- Kulcsot generál

Leírás

string mhash_keygen_s2k ( int hash, string password, string salt, int bytes)

Az mhash_keygen_s2k() bytes méretű kulcsot generál a megadott password alapján. Az S2K algoritmust használja, amely az OpenPGP leírásban (RFC 2440) van definiálva. A megadott hash algoritmust használja a kulcs előállítására. A salt minden generált kulcsra más-más kell legyen, kellőképpen véletlenszerű értékekkel, hogy különböző kulcsok álljanak elő. A salt-nak ismertnek kell lennie a kulcsok ellenőrzésekor, ezért jó ötlet a kulcsokat hozzáfűzni ehhez. A salt mindig nyolc bájt hosszú legyen, ha ennél kevesebb, automatikusan nullákkal töltődik fel.

Figyelembe veendő mindenek előtt, hogy a felhasználók által beadott jelszavak nem túlságosan alkalmasak arra, hogy titkosítási rendszerek kulcsai legyenek, mivel a felhasználók általában jól begépelhető kulcsot választanak. Ezek a jelszavak csak 6-7 bitet (vagy még kevesebbet) használnak ki karakterenként. Nagyon ajánlott a beadott jelszóra olyan átalakítás használata, mint ez a függvény.

mhash

(PHP 3>= 3.0.9, PHP 4 )

mhash -- Hash számítás

Leírás

string mhash ( int hash, string data [, string key])

Az mhash() alkalmazza a hash által megadott algoritmust a data paraméterre, és visszatér az eredmény hash-el (amit kivonatnak [digest-nek] is hívnak). A key paraméter megadásával visszaadja az keletkező HMAC-ot. A HMAC egy kulcsos hash-elés üzenet azonosításra, vagy csak egyszerűen egy üzenet kivonat, amely a megadott kulcstól függ. Nem minden mhash algoritmus használható HMAC módban. Hiba esetén a függvény FALSE értéket ad.

LVIII. Mimetype Functions

Bevezetés

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.


Követelmények

Az itt leírt függvények használatához semmilyen külső függvénykönyvtár megléte nem szükségeltetik.


Telepítés

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.

Megjegyzés: The configure option has been changed from --enable-mime-magic to --with-mime-magic since PHP 4.3.2

Megjegyzés: 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.

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.

Példa 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


Futásidejű beállítások

Az alábbi függvények viselkedése befolyásolható a php.ini segítségével.

Táblázat 1. Mimetype configuration options

NameDefaultChangeable
mime_magic.magicfile"/usr/share/misc/magic.mime"PHP_INI_SYSTEM
For further details and definition of the PHP_INI_* constants see ini_set().


Erőforrás típusok

Ez a kiterjesztés semmilyen erőforrás típust nem definiál.


Előre definiált állandók

Ez a kiterjesztés semmilyen konstans értéket nem definiál.

Tartalom
mime_content_type -- Detect MIME Content-type for a file

mime_content_type

(PHP 4 >= 4.3.0)

mime_content_type -- Detect MIME Content-type for a file

Description

string mime_content_type ( string filename)

Returns the MIME content type for a file as determined by using information from the magic.mime file. Content types are returned in MIME format, like text/plain or application/octet-stream.

Példa 1. mime_content_type() example

<?php
echo mime_content_type('php.gif') . "\n";
echo mime_content_type('test.php');
?>

The above example will output:

image/gif
text/plain

LIX. Microsoft SQL Server functions

Bevezetés

These functions allow you to access MS SQL Server database.


Követelmények

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. Configuration of the client will require installation of all the tools.

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/

Megjegyzés: In 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.


Telepítés

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.


Futásidejű beállítások

Az alábbi függvények viselkedése befolyásolható a php.ini segítségével.

Táblázat 1. MS SQL Server configuration options

NameDefaultChangeable
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
mssql.textsize"-1"PHP_INI_ALL
mssql.textlimit"-1"PHP_INI_ALL
mssql.batchsize"0"PHP_INI_ALL
mssql.datetimeconvert"1"PHP_INI_ALL
mssql.secure_connection"0"PHP_INI_SYSTEM
mssql.max_procs"25"PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().


Erőforrás típusok


Előre definiált állandók

Az itt listázott állandókat ez a kiterjesztés definiálja, és csak akkor elérhetőek, ha az adott kiterjesztés be van fordítva a PHP-be, vagy dinamikusan betöltött.

MSSQL_ASSOC (integer)

MSSQL_NUM (integer)

MSSQL_BOTH (integer)

SQLTEXT (integer)

SQLVARCHAR (integer)

SQLCHAR (integer)

SQLINT1 (integer)

SQLINT2 (integer)

SQLINT4 (integer)

SQLBIT (integer)

SQLFLT8 (integer)

Tartalom
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 set specified by result_id
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 lower error severity
mssql_min_message_severity -- Sets the lower 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

mssql_bind

(PHP 4 >= 4.1.0)

mssql_bind --  Adds a parameter to a stored procedure or a remote stored procedure

Description

bool mssql_bind ( resource stmt, string param_name, mixed var, int type [, int is_output [, int is_null [, int maxlen]]])

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

See also mssql_execute(), mssql_free_statement(), and mssql_init().

mssql_close

(PHP 3, PHP 4 )

mssql_close -- Close MS SQL Server connection

Description

bool mssql_close ( [resource link_identifier])

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

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Note that this isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.

mssql_close() will not close persistent links generated by mssql_pconnect().

See also mssql_connect(), and mssql_pconnect().

mssql_connect

(PHP 3, PHP 4 )

mssql_connect -- Open MS SQL server connection

Description

int mssql_connect ( [string servername [, string username [, string password]]])

Returns: A positive MS SQL link identifier on success, or FALSE on error.

mssql_connect() establishes a connection to a MS SQL server. The servername argument has to be a valid servername that is defined in the 'interfaces' file.

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

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

See also mssql_pconnect(), mssql_close().

mssql_data_seek

(PHP 3, PHP 4 )

mssql_data_seek -- Moves internal row pointer

Description

bool mssql_data_seek ( resource result_identifier, int row_number)

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

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.

See also mssql_data_seek().

mssql_execute

(PHP 4 >= 4.1.0)

mssql_execute --  Executes a stored procedure on a MS SQL server database

Description

mixed mssql_execute ( resource stmt [, bool skip_results])

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

Megjegyzés: 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.

See also mssql_bind(), mssql_free_statement(), and mssql_init().

mssql_fetch_array

(PHP 3, PHP 4 )

mssql_fetch_array --  Fetch a result row as an associative array, a numeric array, or both

Description

array mssql_fetch_array ( resource result [, int result_type])

Returns: An array that corresponds to the fetched row, or FALSE if there are no more rows.

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.

Megjegyzés: Field names returned by this function are case-sensitive.

For further details, also see mssql_fetch_row().

mssql_fetch_assoc

(PHP 4 >= 4.2.0)

mssql_fetch_assoc --  Returns an associative array of the current row in the result set specified by result_id

Description

array mssql_fetch_assoc ( resource result_id)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mssql_fetch_batch

(PHP 4 >= 4.0.4)

mssql_fetch_batch --  Returns the next batch of records

Description

int mssql_fetch_batch ( resource result_index)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mssql_fetch_field

(PHP 3, PHP 4 )

mssql_fetch_field -- Get field information

Description

object mssql_fetch_field ( resource result [, int field_offset])

Returns an object containing field information.

mssql_fetch_field() can be used in order to obtain information about fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by mssql_fetch_field() is retrieved.

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.

See also mssql_field_seek().

mssql_fetch_object

(PHP 3)

mssql_fetch_object -- Fetch row as object

Description

object mssql_fetch_object ( resource result)

Returns: An object with properties that correspond to the fetched row, or FALSE if there are no more rows.

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

Megjegyzés: Field names returned by this function are case-sensitive.

Speed-wise, the function is identical to mssql_fetch_array(), and almost as quick as mssql_fetch_row() (the difference is insignificant).

See also mssql_fetch_array(), and mssql_fetch_row().

mssql_fetch_row

(PHP 3, PHP 4 )

mssql_fetch_row -- Get row as enumerated array

Description

array mssql_fetch_row ( resource result)

Returns: An array that corresponds to the fetched row, or FALSE if there are no more rows.

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.

See also mssql_fetch_array(), mssql_fetch_object(), mssql_data_seek(), mssql_fetch_lengths(), and mssql_result().

mssql_field_length

(PHP 3>= 3.0.3, PHP 4 )

mssql_field_length -- Get the length of a field

Description

int mssql_field_length ( resource result [, int offset])

This function returns the length of field no. offset in result result. If offset is omitted, the current field is used.

Note to Win32 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.

mssql_field_name

(PHP 3>= 3.0.3, PHP 4 )

mssql_field_name -- Get the name of a field

Description

string mssql_field_name ( resource result [, int offset])

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mssql_field_seek

(PHP 3, PHP 4 )

mssql_field_seek -- Seeks to the specified field offset

Description

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.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

See also mssql_fetch_field().

mssql_field_type

(PHP 3>= 3.0.3, PHP 4 )

mssql_field_type -- Gets the type of a field

Description

string mssql_field_type ( resource result [, int offset])

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mssql_free_result

(PHP 3, PHP 4 )

mssql_free_result -- Free result memory

Description

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.

mssql_free_statement

(PHP 4 >= 4.3.2)

mssql_free_statement -- Free statement memory

Description

bool mssql_free_statement ( resource statement)

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.

See also mssql_bind(), mssql_execute(), and mssql_init()

mssql_get_last_message

(PHP 3, PHP 4 )

mssql_get_last_message --  Returns the last message from the server

Description

string mssql_get_last_message ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mssql_guid_string

(PHP 4 >= 4.1.0)

mssql_guid_string --  Converts a 16 byte binary GUID to a string

Description

string mssql_guid_string ( string binary [, int short_format])

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mssql_init

(PHP 4 >= 4.1.0)

mssql_init --  Initializes a stored procedure or a remote stored procedure

Description

int mssql_init ( string sp_name [, resource conn_id])

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

See also mssql_bind(), mssql_execute(), and mssql_free_statement()

mssql_min_error_severity

(PHP 3, PHP 4 )

mssql_min_error_severity -- Sets the lower error severity

Description

void mssql_min_error_severity ( int severity)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mssql_min_message_severity

(PHP 3, PHP 4 )

mssql_min_message_severity -- Sets the lower message severity

Description

void mssql_min_message_severity ( int severity)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mssql_next_result

(PHP 4 >= 4.0.5)

mssql_next_result -- Move the internal result pointer to the next result

Description

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. The function will return TRUE if an additional result set was available or FALSE otherwise.

Példa 1. mssql_next_result() example

<?php
    $link = mssql_connect("localhost", "userid", "secret");
    mssql_select_db("MyDB", $link);
    $SQL = "Select * from table1 select * from table2";
    $rs = mssql_query($SQL, $link);
    do {
        while ($row = mssql_fetch_row($rs)) {
        }
    } while (mssql_next_result($rs));
    mssql_free_result($rs);
    mssql_close($link);
?>

mssql_num_fields

(PHP 3, PHP 4 )

mssql_num_fields -- Gets the number of fields in result

Description

int mssql_num_fields ( resource result)

mssql_num_fields() returns the number of fields in a result set.

See also mssql_query(), mssql_fetch_field(), and mssql_num_rows().

mssql_num_rows

(PHP 3, PHP 4 )

mssql_num_rows -- Gets the number of rows in result

Description

int mssql_num_rows ( resource result)

mssql_num_rows() returns the number of rows in a result set.

See also mssql_query() and mssql_fetch_row().

mssql_pconnect

(PHP 3, PHP 4 )

mssql_pconnect -- Open persistent MS SQL connection

Description

int mssql_pconnect ( [string servername [, string username [, string password]]])

Returns: A positive MS SQL persistent link identifier on success, or FALSE on error.

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

mssql_query

(PHP 3, PHP 4 )

mssql_query -- Send MS SQL query

Description

resource mssql_query ( string query [, resource link_identifier [, int batch_size]])

Returns: A positive MS SQL result identifier on success, or FALSE on error.

mssql_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 mssql_connect() was called, and use it.

See also mssql_select_db() and mssql_connect().

mssql_result

(PHP 3, PHP 4 )

mssql_result -- Get result data

Description

string mssql_result ( resource result, int row, mixed field)

mssql_result() returns the contents of one cell from a MS SQL result set. The field argument 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.

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(). 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: mssql_fetch_row(), mssql_fetch_array(), and mssql_fetch_object().

mssql_rows_affected

(PHP 4 >= 4.0.4)

mssql_rows_affected --  Returns the number of records affected by the query

Description

int mssql_rows_affected ( resource conn_id)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mssql_select_db

(PHP 3, PHP 4 )

mssql_select_db -- Select MS SQL database

Description

bool mssql_select_db ( string database_name [, resource link_identifier])

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

mssql_select_db() sets the current active database on the server that's associated with the specified 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 mssql_connect() was called, and use it.

Every subsequent call to mssql_query() will be made on the active database.

In order to select a database containing a space or a hyphen ("-") you need to enclose the database name in brackets, like is shown in the example below:

Példa 1. mssql_select_db() example

<?php
    $conn = mssql_connect('MYSQLSERVER', 'sa', 'password');
    mssql_select_db('[my data-base]', $conn);
?>

See also: mssql_connect(), mssql_pconnect(), and mssql_query()

LX. Ming függvénykönyvtár Flash mozik előállításához

Figyelem

Ez a kiterjesztés KÍSÉRLETI JELLEGGEL MŰKÖDIK. Ez azt jelenti, hogy minden itt dokumentált működés, beleértve a függvények nevét, működését vagy bármi más, amit a kiterjesztés kapcsán leírtunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a kiterjesztést csak a saját felelősségedre használd!


Bevezetés

Mindenekelőtt: A "Ming" nem mozaikszó. A Ming egy nyílt forráskódú (LGPL) függvénykönyvtár, amely segítségével SWF formátumú (Flash) mozikat tudsz létrehozni. A Ming függvényeivel nagyjából lefedi a Flash 4 összes képeségét, mint: alakzatok, színátmenetek, bitmap képek (png és jpeg formátum), alakváltozások, szövegek, gombok, akciók, moziklipek, mp3 aláfestőzenék (stream típus), és színtranszformációk. Az egyedüli hiányosság, hogy eseményekhez rendelt hangkeltést nem tudunk vele létrehozni.

Érdemes még most, mindenek előtt tisztázni: a különféle hosszokat, távolságokat, méreteket mind "twip" (twenty units per pixel) mértékegységben kell megadni. Ez annyit jelent, hogy egy eredeti méreteiben megjelenített Flash moziban egy képpont húsz twinpek felel meg. Így lehet csak pontos, jól nagyítható mozikat létrehozni.

A már korábban létező PHP/libswf modulhoz képest a Ming több előrelépést is jelent. Egyrészt a Ming nyílt forráskódú, így lehetőség van bárhol, bármilyen rendszeren annak használatára, ahol a forrásból fordítást végre tudod hajtani. A libswf ezzel szemben nem publikus forrással rendelkezik, és csak a jelentősebb platformokra fordítottak belőle bináris függvénykönyvtárt. Ezen platformok közt a Windows nincs jelen. A Ming ráadásul jóval emberközelibb módon kínálja fel a Flash generáláshoz szükséges eljárásokat, ezeket különféle objektumokon keresztül tudjuk hívni. A Ming jelenleg is fejlesztés és karbantartás alatt áll. Ha van olyan, amit a Ming nem tud, de szükségesnek érzed, nosza tudasd velünk ezt a következő címen: ming@opaque.net.

A Ming modul a 4.0.5-ös php verziótól szerepel a hivatalos kiadásban.


Követelmények

A Ming használatbavételéhez először is le kell fordítanod, és telepítened azt. Letölthető forráskódot, és telepítési útmutatót találsz a Ming saját honlapján: http://ming.sourceforge.net/. Ugyanitt találhasz példákat, egy kissebb gyorstalpalót, és a legfrissebb Ming-kapcsolatos híreket.

Töltsd le a Ming forráskódjának tömörített állományát, csomagold ki. Lépj bele a Ming könyvtárba, majd a következp parancsokat add ki: make, majd ha ez végzett: make isntall.

Ezen műveletek során létrejön a libming.so bináris állomány és a megfelelő helyre is telepedik: /usr/lib/. Emellett egy ming.h állomány is helyet kap az /usr/include/ könyvtárban. Ha máshová szeretnéd telepíteni, akkor fordítás előtt módosítsd a Makefile állomány PREFIX= bejegyzését, hogy a telepítés helyét megjelöld magad.


Telepítés

Példa 1. built into PHP (Unix)



    mkdir <phpdir>/ext/ming
    cp php_ext/* <phpdir>/ext/ming
    cd <phpdir>
    ./buildconf 
    ./configure --with-ming <other config options>

    

Build and install PHP as usual, restart web server if necessary.

Now either just add extension=php_ming.so to your php.ini file, or put dl('php_ming.so'); at the head of all of your Ming scripts.


Futásidejű beállítások

Ez a kiterjesztés semmilyen konfigurációs beállításokat nem definiál a php.ini állományban.


Erőforrás típusok


Előre definiált állandók

Az itt listázott állandókat ez a kiterjesztés definiálja, és csak akkor elérhetőek, ha az adott kiterjesztés be van fordítva a PHP-be, vagy dinamikusan betöltött.

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)


Előre definiált osztályok

A következő osztályokat ez a kiterjesztés definiálja azaz csak akkor érhetőek el, ha ez a kiterjesztés a PHP-be fordítva vagy betöltve rendelkezésre áll.

A Ming 13 új osztályt hoz be a PHP rendszerbe, ezek mind saját tulajdonságokkal és eljárásokkal rendelkeznek. A használatba vételükhöz érdemes tehát ismerni, hogy kezeli a PHP az objektum alapú programozást.

swfshape

swffill

swfgradient

swfbitmap

swftext

swftextfield

swffont

swfdisplayitem

swfmovie

swfbutton

swfaction

swfmorph

swfsprite

Tartalom
ming_setcubicthreshold --  Set cubic threshold (?)
ming_setscale --  Set scale (?)
ming_useswfversion --  Use SWF version (?)
SWFAction -- Creates a new Action.
SWFBitmap->getHeight -- A kép magasságának meghatározása.
SWFBitmap->getWidth -- A kép szélességének meghatározása.
SWFBitmap -- Loads Bitmap object
swfbutton_keypress --  Returns the action flag for keyPress(char)
SWFbutton->addAction -- Adds an action
SWFbutton->addShape -- Alakzat gombhoz rendelése
SWFbutton->setAction -- Sets the action
SWFbutton->setdown -- Alias for addShape(shape, SWFBUTTON_DOWN))
SWFbutton->setHit -- Alias for addShape(shape, SWFBUTTON_HIT)
SWFbutton->setOver -- Alias for addShape(shape, SWFBUTTON_OVER)
SWFbutton->setUp -- Alias for addShape(shape, SWFBUTTON_UP)
SWFbutton -- Creates a new Button.
SWFDisplayItem->addColor -- Adds the given color to this item's color transform.
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->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.
SWFDisplayItem -- Creates a new displayitem object.
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
SWFFill -- Loads SWFFill object
swffont->getwidth -- Returns the string's width
SWFFont -- Loads a font definition
SWFGradient->addEntry -- Adds an entry to the gradient list.
SWFGradient -- Creates a gradient object
SWFMorph->getshape1 -- Gets a handle to the starting shape
SWFMorph->getshape2 -- Gets a handle to the ending shape
SWFMorph -- Creates a new SWFMorph object.
SWFMovie->add -- Bármiféle elem moziba helyezése.
SWFMovie->nextframe -- Az animáció következő kockájára ugrik.
SWFMovie->output -- A kész mozi kiemetre küldése.
SWFMovie->remove -- Egy objektumegyed eltávolítása a mozi megjelenített elemeinek listájából.
SWFMovie->save -- Az SWFMovie objektum SWF fájlba mentése
SWFMovie->setbackground -- A mozi alap háttárszínének beállítása.
SWFMovie->setdimension -- Beállítja a mozi szélességét, magasságát.
SWFMovie->setframes -- Beállítja a mozi képkockákban mért hosszát.
SWFMovie->setrate -- A mozi lejátszási sebességének beállítása
SWFMovie->streammp3 -- MP3 formátumú hangfolyam hozzáadása.
SWFMovie -- Egy új, 4-es SWF változatnak megfelelő Flash mozi objektumot hoz létre.
SWFShape->addFill -- Adds a solid fill to the shape.
SWFShape->drawCurve -- Draws a curve (relative).
SWFShape->drawCurveTo -- Draws a curve.
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 -- Creates a new shape object.
SWFSprite->add -- Adds an object to a sprite
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 -- Creates a movie clip (a sprite)
SWFText->addString -- Draws a string
SWFText->getWidth -- Computes string's width
SWFText->moveTo -- Moves the pen
SWFText->setColor -- Sets the current font color
SWFText->setFont -- Sets the current font
SWFText->setHeight -- Sets the current font height
SWFText->setSpacing -- Sets the current font spacing
SWFText -- Creates a new SWFText object.
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->setrightMargin -- Sets the right margin width of the text field.
SWFTextField -- Szövegmező objektum létrehozása

ming_setcubicthreshold

(PHP 4 >= 4.0.5)

ming_setcubicthreshold --  Set cubic threshold (?)

Description

void ming_setcubicthreshold ( int threshold)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ming_setscale

(PHP 4 >= 4.0.5)

ming_setscale --  Set scale (?)

Description

void ming_setscale ( int scale)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ming_useswfversion

(PHP 4 >= 4.2.0)

ming_useswfversion --  Use SWF version (?)

Description

void ming_useswfversion ( int version)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

SWFAction

(PHP 4 >= 4.0.5)

SWFAction -- Creates a new Action.

Description

new swfaction ( string script)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

swfaction() creates a new Action, and compiles the given script into an SWFAction object.

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.

This simple example will move the red square across the window.

Példa 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.

Példa 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...

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

This simple example will handles keyboard actions. (You'll probably have to click in the window to give it focus. And you'll probably have to leave your mouse in the frame, too. If you know how to give buttons focus programatically, feel free to share, won't you?)

Példa 4. swfaction() example

<?php

  /* sprite has one letter per frame */

  $p = new SWFSprite();
  $p->add(new SWFAction("stop();"));

  $chars = "abcdefghijklmnopqrstuvwxyz".
       "ABCDEFGHIJKLMNOPQRSTUVWXYZ".
           "1234567890!@#$%^&/*()_+-=/[]{}|;:,.<>?`~";

  $f = new SWFFont("_sans");

  for($n=0; $nremove($i);
    $t = new SWFTextField();
    $t->setFont($f);
    $t->setHeight(240);
    $t->setBounds(600,240);
    $t->align(SWFTEXTFIELD_ALIGN_CENTER);
    $t->addString($c);
    $i = $p->add($t);
    $p->labelFrame($c);
    $p->nextFrame();
  }

  /* hit region for button - the entire frame */

  $s = new SWFShape();
  $s->setFillStyle0($s->addSolidFill(0, 0, 0, 0));
  $s->drawLine(600, 0);
  $s->drawLine(0, 400);
  $s->drawLine(-600, 0);
  $s->drawLine(0, -400);

  /* button checks for pressed key, sends sprite to the right frame */

  $b = new SWFButton();
  $b->addShape($s, SWFBUTTON_HIT);

  for($n=0; $naddAction(new SWFAction("

setTarget('/char');
gotoFrame('$c');

    "), SWFBUTTON_KEYPRESS($c));
  }

  $m = new SWFMovie();
  $m->setDimension(600,400);
  $i = $m->add($p);
  $i->setName('char');
  $i->moveTo(0,80);

  $m->add($b);

  header('Content-type: application/x-shockwave-flash');
  $m->output();

?>

SWFBitmap->getHeight

(no version information, might be only in CVS)

SWFBitmap->getHeight -- A kép magasságának meghatározása.

Leírás

int swfbitmap->getheight ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Az swfbitmap->getheight() visszaadja a pixelgrafikus kép magasságát.

Lásd még swfbitmap->getwidth().

SWFBitmap->getWidth

(no version information, might be only in CVS)

SWFBitmap->getWidth -- A kép szélességének meghatározása.

Leírás

int swfbitmap->getwidth ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Az swfbitmap->getwidth() visszaadja a pixelgrafikus kép szélességét.

Lásd még swfbitmap->getheight().

SWFBitmap

(PHP 4 >= 4.0.5)

SWFBitmap -- Loads Bitmap object

Description

new swfbitmap ( string filename [, int alphafilename])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

swfbitmap() creates a new SWFBitmap object from the Jpeg or DBL file named filename. alphafilename indicates a MSK file to be used as an alpha mask for a Jpeg image.

Megjegyzés: We can only deal with baseline (frame 0) jpegs, no baseline optimized or progressive scan jpegs!

SWFBitmap has the following methods : swfbitmap->getwidth() and swfbitmap->getheight().

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.

Példa 1. Import PNG files

<?php
  $s = new SWFShape();
  $f = $s->addFill(new SWFBitmap("png.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();
?>

And you can put an alpha mask on a jpeg fill.

Példa 2. swfbitmap() example

<?php

  $s = new SWFShape();

  // .msk file generated with "gif2mask" utility
  $f = $s->addFill(new SWFBitmap("alphafill.jpg", "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();
?>

swfbutton_keypress

(PHP 4 >= 4.0.5)

swfbutton_keypress --  Returns the action flag for keyPress(char)

Description

int swfbutton_keypress ( string str)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

SWFbutton->addAction

(no version information, might be only in CVS)

SWFbutton->addAction -- Adds an action

Description

void swfbutton->addaction ( ressource action, int flags)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

swfbutton->addaction() adds the action action to this button for the given conditions. The following flags are valid: SWFBUTTON_MOUSEOVER, SWFBUTTON_MOUSEOUT, SWFBUTTON_MOUSEUP, SWFBUTTON_MOUSEUPOUTSIDE, SWFBUTTON_MOUSEDOWN, SWFBUTTON_DRAGOUT and SWFBUTTON_DRAGOVER.

See also swfbutton->addshape() and SWFAction().

SWFbutton->addShape

(no version information, might be only in CVS)

SWFbutton->addShape -- Alakzat gombhoz rendelése

Leírás

void swfbutton->addshape ( resource shape, int flags)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Az swfbutton->addshape() függvény segítségével adhatóak alakzatok (shwShape objektumok) a gombhoz. Az alakzatot a shape paraméterben adhatjuk át. A következő flags értékek használhatóak: SWFBUTTON_UP, SWFBUTTON_OVER, SWFBUTTON_DOWN vagy SWFBUTTON_HIT. Az SWFBUTTON_HIT sosem fog megjelenni, ez határozza meg a gomb klikkelhető területét. Tehát ez a forma fogja meghatározni, mely területei "érinthetőek" az adott gombnak.

SWFbutton->setAction

(no version information, might be only in CVS)

SWFbutton->setAction -- Sets the action

Description

void swfbutton->setaction ( ressource action)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

swfbutton->setaction() sets the action to be performed when the button is clicked. Alias for addAction(shape, SWFBUTTON_MOUSEUP). action is a swfaction().

See also swfbutton->addshape() and SWFAction().

SWFbutton->setdown

(no version information, might be only in CVS)

SWFbutton->setdown -- Alias for addShape(shape, SWFBUTTON_DOWN))

Description

void swfbutton->setdown ( ressource shape)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

swfbutton->setdown() alias for addShape(shape, SWFBUTTON_DOWN).

See also swfbutton->addshape() and SWFAction().

SWFbutton->setHit

(no version information, might be only in CVS)

SWFbutton->setHit -- Alias for addShape(shape, SWFBUTTON_HIT)

Description

void swfbutton->sethit ( ressource shape)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

swfbutton->sethit() alias for addShape(shape, SWFBUTTON_HIT).

See also swfbutton->addshape() and SWFAction().

SWFbutton->setOver

(no version information, might be only in CVS)

SWFbutton->setOver -- Alias for addShape(shape, SWFBUTTON_OVER)

Description

void swfbutton->setover ( ressource shape)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

swfbutton->setover() alias for addShape(shape, SWFBUTTON_OVER).

See also swfbutton->addshape() and SWFAction().

SWFbutton->setUp

(no version information, might be only in CVS)

SWFbutton->setUp -- Alias for addShape(shape, SWFBUTTON_UP)

Description

void swfbutton->setup ( ressource shape)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

swfbutton->setup() alias for addShape(shape, SWFBUTTON_UP).

See also swfbutton->addshape() and SWFAction().

SWFbutton

(PHP 4 >= 4.0.5)

SWFbutton -- Creates a new Button.

Description

new swfbutton ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

swfbutton() creates a new Button. Roll over it, click it, see it call action code. Swank.

SWFButton has the following methods : swfbutton->addshape(), swfbutton->setup(), swfbutton->setover() swfbutton->setdown(), swfbutton->sethit() swfbutton->setaction() and swfbutton->addaction().

This simple example will show your usual interactions with buttons : rollover, rollon, mouseup, mousedown, noaction.

Példa 1. swfbutton() example

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

Példa 2. swfbutton->addaction() 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();
?>

SWFDisplayItem->addColor

(no version information, might be only in CVS)

SWFDisplayItem->addColor -- Adds the given color to this item's color transform.

Description

void swfdisplayitem->addcolor ( [int red [, int green [, int blue [, int a]]]])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

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

SWFDisplayItem->move

(no version information, might be only in CVS)

SWFDisplayItem->move -- Moves object in relative coordinates.

Description

void swfdisplayitem->move ( int dx, int dy)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

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

See also swfdisplayitem->moveto().

SWFDisplayItem->moveTo

(no version information, might be only in CVS)

SWFDisplayItem->moveTo -- Moves object in global coordinates.

Description

void swfdisplayitem->moveto ( int x, int y)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

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

See also swfdisplayitem->move().

SWFDisplayItem->multColor

(no version information, might be only in CVS)

SWFDisplayItem->multColor -- Multiplies the item's color transform.

Description

void swfdisplayitem->multcolor ( [int red [, int green [, int blue [, int a]]]])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

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

This simple example will modify your picture's atmospher to Halloween (use a landscape or bright picture).

Példa 1. swfdisplayitem->multcolor() example

<?php

  $b = new SWFBitmap("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->remove

(no version information, might be only in CVS)

SWFDisplayItem->remove -- Removes the object from the movie

Description

void swfdisplayitem->remove ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

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

See also swfmovie->add().

SWFDisplayItem->Rotate

(no version information, might be only in CVS)

SWFDisplayItem->Rotate -- Rotates in relative coordinates.

Description

void swfdisplayitem->rotate ( float ddegrees)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

swfdisplayitem->rotate() rotates the current object by ddegrees 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().

See also swfdisplayitem->rotateto().

SWFDisplayItem->rotateTo

(no version information, might be only in CVS)

SWFDisplayItem->rotateTo -- Rotates the object in global coordinates.

Description

void swfdisplayitem->rotateto ( float degrees)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

swfdisplayitem->rotateto() set the current object rotation to degrees 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().

This example bring three rotating string from the background to the foreground. Pretty nice.

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

See also swfdisplayitem->rotate().

SWFDisplayItem->scale

(no version information, might be only in CVS)

SWFDisplayItem->scale -- Scales the object in relative coordinates.

Description

void swfdisplayitem->scale ( int dx, int dy)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

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

See also swfdisplayitem->scaleto().

SWFDisplayItem->scaleTo

(no version information, might be only in CVS)

SWFDisplayItem->scaleTo -- Scales the object in global coordinates.

Description

void swfdisplayitem->scaleto ( int x, int y)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

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

See also swfdisplayitem->scale().

SWFDisplayItem->setDepth

(no version information, might be only in CVS)

SWFDisplayItem->setDepth -- Sets z-order

Description

void swfdisplayitem->setdepth ( float depth)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

swfdisplayitem->rotate() sets the object's z-order to depth. Depth defaults to the order in which instances are created (by add'ing 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().

SWFDisplayItem->setName

(no version information, might be only in CVS)

SWFDisplayItem->setName -- Sets the object's name

Description

void swfdisplayitem->setname ( string name)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

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

SWFDisplayItem->setRatio

(no version information, might be only in CVS)

SWFDisplayItem->setRatio -- Sets the object's ratio.

Description

void swfdisplayitem->setratio ( float ratio)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

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

This simple example will morph nicely three concentric circles.

Példa 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->skewX

(no version information, might be only in CVS)

SWFDisplayItem->skewX -- Sets the X-skew.

Description

void swfdisplayitem->skewx ( float ddegrees)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

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

See also swfdisplayitem->skewx(), swfdisplayitem->skewy() and swfdisplayitem->skewyto().

SWFDisplayItem->skewXTo

(no version information, might be only in CVS)

SWFDisplayItem->skewXTo -- Sets the X-skew.

Description

void swfdisplayitem->skewxto ( float degrees)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

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

See also swfdisplayitem->skewx(), swfdisplayitem->skewy() and swfdisplayitem->skewyto().

SWFDisplayItem->skewY

(no version information, might be only in CVS)

SWFDisplayItem->skewY -- Sets the Y-skew.

Description

void swfdisplayitem->skewy ( float ddegrees)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

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

See also swfdisplayitem->skewyto(), swfdisplayitem->skewx() and swfdisplayitem->skewxto().

SWFDisplayItem->skewYTo

(no version information, might be only in CVS)

SWFDisplayItem->skewYTo -- Sets the Y-skew.

Description

void swfdisplayitem->skewyto ( float degrees)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

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

See also swfdisplayitem->skewy(), swfdisplayitem->skewx() and swfdisplayitem->skewxto().

SWFDisplayItem

(no version information, might be only in CVS)

SWFDisplayItem -- Creates a new displayitem object.

Description

new swfdisplayitem ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

swfdisplayitem() creates a new swfdisplayitem object.

Here's where all the animation takes place. After you define a shape, a text object, a sprite, or a button, you add it to the movie, then use the returned handle to move, rotate, scale, or skew the thing.

SWFDisplayItem has the following methods : swfdisplayitem->move(), swfdisplayitem->moveto(), swfdisplayitem->scaleto(), swfdisplayitem->scale(), swfdisplayitem->rotate(), swfdisplayitem->rotateto(), swfdisplayitem->skewxto(), swfdisplayitem->skewx(), swfdisplayitem->skewyto() swfdisplayitem->skewyto(), swfdisplayitem->setdepth() swfdisplayitem->remove(), swfdisplayitem->setname() swfdisplayitem->setratio(), swfdisplayitem->addcolor() and swfdisplayitem->multcolor().

SWFFill->moveTo

(no version information, might be only in CVS)

SWFFill->moveTo -- Moves fill origin

Description

void swffill->moveto ( int x, int y)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

swffill->moveto() moves fill's origin to (x,y) in global coordinates.

SWFFill->rotateTo

(no version information, might be only in CVS)

SWFFill->rotateTo -- Sets fill's rotation

Description

void swffill->rotateto ( float degrees)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

swffill->rotateto() sets fill's rotation to degrees degrees.

SWFFill->scaleTo

(no version information, might be only in CVS)

SWFFill->scaleTo -- Sets fill's scale

Description

void swffill->scaleto ( int x, int y)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

swffill->scaleto() sets fill's scale to x in the x-direction, y in the y-direction.

SWFFill->skewXTo

(no version information, might be only in CVS)

SWFFill->skewXTo -- Sets fill x-skew

Description

void swffill->skewxto ( float x)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

swffill->skewxto() sets fill x-skew to x. For x is 1.0, it is a is a 45-degree forward slant. More is more forward, less is more backward.

SWFFill->skewYTo

(no version information, might be only in CVS)

SWFFill->skewYTo -- Sets fill y-skew

Description

void swffill->skewyto ( float y)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

swffill->skewyto() sets fill y-skew to y. For y is 1.0, it is a is a 45-degree upward slant. More is more upward, less is more downward.

SWFFill

SWFFill -- Loads SWFFill object

Description

The swffill() object allows you to transform (scale, skew, rotate) bitmap and gradient fills. swffill() objects are created by the swfshape->addfill() methods.

SWFFill has the following methods : swffill->moveto() and swffill->scaleto(), swffill->rotateto(), swffill->skewxto() and swffill->skewyto().

swffont->getwidth

(no version information, might be only in CVS)

swffont->getwidth -- Returns the string's width

Description

int swffont->getwidth ( string string)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

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.

SWFFont

(PHP 4 >= 4.0.5)

SWFFont -- Loads a font definition

Description

new swffont ( string filename)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

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() returns a reference to the font definition, for use in the SWFText->setFont() and the SWFTextField->setFont() methods.

SWFFont has the following methods : swffont->getwidth().

SWFGradient->addEntry

(no version information, might be only in CVS)

SWFGradient->addEntry -- Adds an entry to the gradient list.

Description

void swfgradient->addentry ( float ratio, int red, int green, int blue [, int a])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

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). Last parameter a is optional.

SWFGradient

(PHP 4 >= 4.0.5)

SWFGradient -- Creates a gradient object

Description

new swfgradient ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

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 redish disc in its center.

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

SWFMorph->getshape1

(no version information, might be only in CVS)

SWFMorph->getshape1 -- Gets a handle to the starting shape

Description

mixed swfmorph->getshape1 ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

swfmorph->getshape1() gets a handle to the morph's starting shape. swfmorph->getshape1() returns an swfshape() object.

SWFMorph->getshape2

(no version information, might be only in CVS)

SWFMorph->getshape2 -- Gets a handle to the ending shape

Description

mixed swfmorph->getshape2 ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

swfmorph->getshape2() gets a handle to the morph's ending shape. swfmorph->getshape2() returns an swfshape() object.

SWFMorph

(PHP 4 >= 4.0.5)

SWFMorph -- Creates a new SWFMorph object.

Description

new swfmorph ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

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

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

SWFMorph has the following methods : swfmorph->getshape1() and swfmorph->getshape1().

This simple example will morph a big red square into a smaller blue black-bordered square.

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

SWFMovie->add

(no version information, might be only in CVS)

SWFMovie->add -- Bármiféle elem moziba helyezése.

Leírás

void swfmovie->add ( ressource egyed)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Az swfmovie->add() függvénnyel tehető be új elem a mozi objektumba. Az behelyezendő elem az egyed paraméterben adandó meg. Az egyed paraméterben mindenféle adattípus behelyetesíthető : Formák (shape), szöveges elemek, betűkészletek, stb. - ezeket először minden esetben a moziba kell helyezni, hogy dolgozni lehesen ott velük.

A megjeleníthető elemek esetében visszaad egy SWFDisplayItem() objektum azonosítót, ami segítségével az a továbbiakban kezelhető. Egy elem többízben is a moziba helyezhető, ezáltal külön kezelhető egyedeket hozhatunk létre.

Lásd még az összes többi objektumot (a későbbiekben), valamint swfmovie->remove() függvényt.

Példákat lásd itt : swfdisplayitem->rotateto() és swfshape->addfill().

SWFMovie->nextframe

(no version information, might be only in CVS)

SWFMovie->nextframe -- Az animáció következő kockájára ugrik.

Leírás

void swfmovie->nextframe ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Az swfmovie->nextframe() függvény segítségével léphetünk egy kockát előre az animációnkban.

SWFMovie->output

(no version information, might be only in CVS)

SWFMovie->output -- A kész mozi kiemetre küldése.

Leírás

void swfmovie->output ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Az swfmovie->output() függvény kinyomja a kimenetre a szépre csiszolt mozinkat. Ahhoz, hogy a kimenetet a böngésző megfelelően kezelje, az SWF adathalmaz kiemetre nyomása előtt szükség lesz a következő fejléc kiküldésére :
<?php
header('Content-type: application/x-shockwave-flash'); 
?>

Lásd még swfmovie->save().

Példákat lásd itt : swfmovie->streammp3(), swfdisplayitem->rotateto(), swfaction()... Bármelyik példában látható ennek az eljárásnak a használata.

SWFMovie->remove

(no version information, might be only in CVS)

SWFMovie->remove -- Egy objektumegyed eltávolítása a mozi megjelenített elemeinek listájából.

Leírás

void swfmovie->remove ( resource egyed)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Az swfmovie->remove() függvény kiszedi az egyed paraméterben megadott objektumegyedet a mozi megjelenített elemeinek listájából.

Lásd még swfmovie->add().

SWFMovie->save

(no version information, might be only in CVS)

SWFMovie->save -- Az SWFMovie objektum SWF fájlba mentése

Leírás

void swfmovie->save ( string fájlnév)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Az swfmovie->save() segítségével mentheted a mozidat a fájlnév paraméterben megadott fájlba.

Lásd még output().

SWFMovie->setbackground

(no version information, might be only in CVS)

SWFMovie->setbackground -- A mozi alap háttárszínének beállítása.

Leírás

void swfmovie->setbackground ( int vörös_összetevő, int zöld_összetevő, int kék_összetevő)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Az swfmovie->setbackground() szolgál a háttérszín beállítására. Hogy miért is nem lehet alfa értéket is adni neki? Nem lenne hülye ötlet, hisz így az alápakolt html átlátszhatna, de ennek támogatottsága csak az Internet Explorerben létezik, annak 4.0-ás verziójától felfele. A dolog részleteiről a http://www.macromedia.com/ webhelyen olvashatsz.

SWFMovie->setdimension

(no version information, might be only in CVS)

SWFMovie->setdimension -- Beállítja a mozi szélességét, magasságát.

Leírás

void swfmovie->setdimension ( int szélesség, int magasság)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Az swfmovie->setdimension() beállítja a mozi méreteit a szélesség és magasság paramétereknek megfelelően.

SWFMovie->setframes

(no version information, might be only in CVS)

SWFMovie->setframes -- Beállítja a mozi képkockákban mért hosszát.

Leírás

void swfmovie->setframes ( string kockák_száma)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Az swfmovie->setframes() beállítja a mozi képkockákban márt hosszát a kockák_száma paraméter szerinti értékre.

SWFMovie->setrate

(no version information, might be only in CVS)

SWFMovie->setrate -- A mozi lejátszási sebességének beállítása

Leírás

void swfmovie->setrate ( int sebesség)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Az swfmovie->setrate() beállítja a mozi lejátászási sebességét a sebesség paraméterben megadott értékre. Ez a sebesség a másodpercenként lejátszott képkockák számát jelenti. Az animáció belassulhat, ha a gép képtelen valós időben előállítani a képkockékat, hacsak nincs a mozinak aláfestő zenéje, ekkor ugyanis a lejátszó kockakihagyással előzi meg, hogy a zenelejátszás szaggatot legyen.

SWFMovie->streammp3

(no version information, might be only in CVS)

SWFMovie->streammp3 -- MP3 formátumú hangfolyam hozzáadása.

Leírás

void swfmovie->streammp3 ( string mp3_fájl_neve)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Az swfmovie->streammp3() egy aláfestőzene, vagy egyéb hangfolyam beillesztésére alkalmas. Az MP3 fájl megadását az egyetlen, mp3_fájl_neve paraméterben intézhetjük el. A nagyon speciális mp3-akkal nem feltétlen birkózik meg, de azért az ID3 adatokat képes átugrani. Hasonlóan, mint az SWFShape->addJpegFill() eljárás, ez sem túlságosan stabil. A jövőbeni tervek közt szerepel egy teljesen különálló SWFSound osztály létrehozása, az összes hangokkal kapcsolatos dolgok kezelésére.

Megjegyzendő, hogy önmagától nem lesz olyan hosszú a mozi, hogy beleférjen teljes hosszában a zene. Ha vége szakad a mozinak, a zenének is annyi, ezért szükség van megfelelő számú képkocka beillesztésére. Ezek száma a zene hosszából és az fps értékből egy egyzerű szorzás segítségével meghatározható.

Igen! Ezzel a lehetősséggel élve bármiféle szörnyűséges zeneművel fel lehet dobni az SWF fájljainkat. A jogdíj az már egy más kérdéskör.

Példa 1. swfmovie->streammp3() példa

<?php
  $m = new SWFMovie();
  $m->setRate(12.0);
  $m->streamMp3("distortobass.mp3");
  // saját MP3 felhasználása

  // 11.85 másodperc 12 fps-el számolva: 142 képkocka
  $m->setFrames(142);

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

SWFMovie

(PHP 4 >= 4.0.5)

SWFMovie -- Egy új, 4-es SWF változatnak megfelelő Flash mozi objektumot hoz létre.

Leírás

new swfmovie ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Az swfmovie() egy új mozi objektumot hoz létre, amely egy 4-es verziójú SWF mozinak felel meg.

Az SWFMovie a következő eljárásokat adja : swfmovie->output(),swfmovie->save(), swfmovie->add(), swfmovie->remove(), swfmovie->nextframe(), swfmovie->setbackground(), swfmovie->setrate(), swfmovie->setdimension(), swfmovie->setframes() és swfmovie->streammp3().

Példákat lásd itt : swfdisplayitem->rotateto(), swfshape->setline(), swfshape->addfill()... Egy kis példa ennek az objektumnak a használatára.

SWFShape->addFill

(no version information, might be only in CVS)

SWFShape->addFill -- Adds a solid fill to the shape.

Description

void swfshape->addfill ( int red, int green, int blue [, int a])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

void swfshape->addfill ( SWFbitmap bitmap [, int flags])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

void swfshape->addfill ( SWFGradient gradient [, int flags])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

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). Last parameter a is optional.

The bitmap argument is an swfbitmap() object. The flags argument can be one of the following values : SWFFILL_CLIPPED_BITMAP or SWFFILL_TILED_BITMAP. Default is SWFFILL_TILED_BITMAP. I think.

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.

See also swfshape->setleftfill() and swfshape->setrightfill().

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

Példa 1. swfshape->addfill() example

<?php

  $p = new SWFMorph();

  $b = new SWFBitmap("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();
?>

SWFShape->drawCurve

(no version information, might be only in CVS)

SWFShape->drawCurve -- Draws a curve (relative).

Description

void swfshape->drawcurve ( int controldx, int controldy, int anchordx, int anchordy)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

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.

See also swfshape->drawlineto(), swfshape->drawline(), swfshape->movepento() and swfshape->movepen().

SWFShape->drawCurveTo

(no version information, might be only in CVS)

SWFShape->drawCurveTo -- Draws a curve.

Description

void swfshape->drawcurveto ( int controlx, int controly, int anchorx, int anchory)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

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.

See also swfshape->drawlineto(), swfshape->drawline(), swfshape->movepento() and swfshape->movepen().

SWFShape->drawLine

(no version information, might be only in CVS)

SWFShape->drawLine -- Draws a line (relative).

Description

void swfshape->drawline ( int dx, int dy)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

swfshape->drawline() draws a line (using the current line style set by swfshape->setline()) from the current pen position to displacement (dx,dy).

See also swfshape->movepento(), swfshape->drawcurveto(), swfshape->movepen() and swfshape->drawlineto().

SWFShape->drawLineTo

(no version information, might be only in CVS)

SWFShape->drawLineTo -- Draws a line.

Description

void swfshape->drawlineto ( int x, int y)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

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.

See also swfshape->movepento(), swfshape->drawcurveto(), swfshape->movepen() and swfshape->drawline().

SWFShape->movePen

(no version information, might be only in CVS)

SWFShape->movePen -- Moves the shape's pen (relative).

Description

void swfshape->movepen ( int dx, int dy)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

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.

See also swfshape->movepento(), swfshape->drawcurveto(), swfshape->drawlineto() and swfshape->drawline().

SWFShape->movePenTo

(no version information, might be only in CVS)

SWFShape->movePenTo -- Moves the shape's pen.

Description

void swfshape->movepento ( int x, int y)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

swfshape->setrightfill() move the shape's pen to (x,y) in the shape's coordinate space.

See also swfshape->movepen(), swfshape->drawcurveto(), swfshape->drawlineto() and swfshape->drawline().

SWFShape->setLeftFill

(no version information, might be only in CVS)

SWFShape->setLeftFill -- Sets left rasterizing color.

Description

void swfshape->setleftfill ( swfgradient fill)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

void swfshape->setleftfill ( int red, int green, int blue [, int a])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

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

See also swfshape->setrightfill().

SWFShape->setLine

(no version information, might be only in CVS)

SWFShape->setLine -- Sets the shape's line style.

Description

void swfshape->setline ( int width [, int red [, int green [, int blue [, int a]]]])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

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.

swfshape->setline() accepts 1, 4 or 5 arguments (not 3 or 2).

You must declare all line styles before you use them (see example).

This simple example will draw a big "!#%*@", in funny colors and gracious style.

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

SWFShape->setRightFill

(no version information, might be only in CVS)

SWFShape->setRightFill -- Sets right rasterizing color.

Description

void swfshape->setrightfill ( swfgradient fill)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

void swfshape->setrightfill ( int red, int green, int blue [, int a])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

See also swfshape->setleftfill().

Shortcut for swfshape->setrightfill($s->addfill($r, $g, $b [, $a]));.

SWFShape

(PHP 4 >= 4.0.5)

SWFShape -- Creates a new shape object.

Description

new swfshape ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

swfshape() creates a new shape object.

SWFShape has the following methods : swfshape->setline(), swfshape->addfill(), swfshape->setleftfill(), swfshape->setrightfill(), swfshape->movepento(), swfshape->movepen(), swfshape->drawlineto(), swfshape->drawline(), swfshape->drawcurveto() and swfshape->drawcurve().

This simple example will draw a big red elliptic quadrant.

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

SWFSprite->add

(no version information, might be only in CVS)

SWFSprite->add -- Adds an object to a sprite

Description

void swfsprite->add ( resource object)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

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.

SWFSprite->nextframe

(no version information, might be only in CVS)

SWFSprite->nextframe -- Moves to the next frame of the animation.

Description

void swfsprite->nextframe ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

swfsprite->setframes() moves to the next frame of the animation.

SWFSprite->remove

(no version information, might be only in CVS)

SWFSprite->remove -- Removes an object to a sprite

Description

void swfsprite->remove ( ressource object)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

swfsprite->remove() remove a swfshape(), a swfbutton(), a swftext(), a swfaction() or a swfsprite() object from the sprite.

SWFSprite->setframes

(no version information, might be only in CVS)

SWFSprite->setframes -- Sets the total number of frames in the animation.

Description

void swfsprite->setframes ( int numberofframes)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

swfsprite->setframes() sets the total number of frames in the animation to numberofframes.

SWFSprite

(PHP 4 >= 4.0.5)

SWFSprite -- Creates a movie clip (a sprite)

Description

new swfsprite ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

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

swfsprite() has the following methods : swfsprite->add(), swfsprite->remove(), swfsprite->nextframe() and swfsprite->setframes().

This simple example will spin gracefully a big red square.

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

SWFText->addString

(no version information, might be only in CVS)

SWFText->addString -- Draws a string

Description

void swftext->addstring ( string string)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

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.

SWFText->getWidth

(no version information, might be only in CVS)

SWFText->getWidth -- Computes string's width

Description

void swftext->addstring ( string string)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

swftext->addstring() returns the rendered width of the string string at the text object's current font, scale, and spacing settings.

SWFText->moveTo

(no version information, might be only in CVS)

SWFText->moveTo -- Moves the pen

Description

void swftext->moveto ( int x, int y)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

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.

SWFText->setColor

(no version information, might be only in CVS)

SWFText->setColor -- Sets the current font color

Description

void swftext->setcolor ( int red, int green, int blue [, int a])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

swftext->setspacing() changes the current text color. Default is black. I think. Color is represented using the RGB system.

SWFText->setFont

(no version information, might be only in CVS)

SWFText->setFont -- Sets the current font

Description

void swftext->setfont ( string font)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

swftext->setfont() sets the current font to font.

SWFText->setHeight

(no version information, might be only in CVS)

SWFText->setHeight -- Sets the current font height

Description

void swftext->setheight ( int height)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

swftext->setheight() sets the current font height to height. Default is 240.

SWFText->setSpacing

(no version information, might be only in CVS)

SWFText->setSpacing -- Sets the current font spacing

Description

void swftext->setspacing ( float spacing)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

swftext->setspacing() sets the current font spacing to spacingspacing. 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.

SWFText

(PHP 4 >= 4.0.5)

SWFText -- Creates a new SWFText object.

Description

new swftext ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

swftext() creates a new SWFText object, fresh for manipulating.

SWFText has the following methods : swftext->setfont(), swftext->setheight(), swftext->setspacing(), swftext->setcolor(), swftext->moveto(), swftext->addstring() and swftext->getwidth().

This simple example will draw a big yellow "PHP generates Flash with Ming" text, on white background.

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

SWFTextField->addstring

(no version information, might be only in CVS)

SWFTextField->addstring -- Concatenates the given string to the text field

Description

void swftextfield->addstring ( string string)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

swftextfield->setname() concatenates the string string to the text field.

SWFTextField->align

(no version information, might be only in CVS)

SWFTextField->align -- Sets the text field alignment

Description

void swftextfield->align ( int alignement)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

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.

SWFTextField->setbounds

(no version information, might be only in CVS)

SWFTextField->setbounds -- Sets the text field width and height

Description

void swftextfield->setbounds ( int width, int height)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

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.

SWFTextField->setcolor

(no version information, might be only in CVS)

SWFTextField->setcolor -- Sets the color of the text field.

Description

void swftextfield->setcolor ( int red, int green, int blue [, int a])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

swftextfield->setcolor() sets the color of the text field. Default is fully opaque black. Color is represented using RGB system.

SWFTextField->setFont

(no version information, might be only in CVS)

SWFTextField->setFont -- Sets the text field font

Description

void swftextfield->setfont ( string font)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

swftextfield->setfont() sets the text field font to the [browser-defined?] font font.

SWFTextField->setHeight

(no version information, might be only in CVS)

SWFTextField->setHeight -- Sets the font height of this text field font.

Description

void swftextfield->setheight ( int height)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

swftextfield->setheight() sets the font height of this text field font to the given height height. Default is 240.

SWFTextField->setindentation

(no version information, might be only in CVS)

SWFTextField->setindentation -- Sets the indentation of the first line.

Description

void swftextfield->setindentation ( int width)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

swftextfield->setindentation() sets the indentation of the first line in the text field, to width.

SWFTextField->setLeftMargin

(no version information, might be only in CVS)

SWFTextField->setLeftMargin -- Sets the left margin width of the text field.

Description

void swftextfield->setleftmargin ( int width)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

swftextfield->setleftmargin() sets the left margin width of the text field to width. Default is 0.

SWFTextField->setLineSpacing

(no version information, might be only in CVS)

SWFTextField->setLineSpacing -- Sets the line spacing of the text field.

Description

void swftextfield->setlinespacing ( int height)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

swftextfield->setlinespacing() sets the line spacing of the text field to the height of height. Default is 40.

SWFTextField->setMargins

(no version information, might be only in CVS)

SWFTextField->setMargins -- Sets the margins width of the text field.

Description

void swftextfield->setmargins ( int left, int right)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

swftextfield->setmargins() set both margins at once, for the man on the go.

SWFTextField->setname

(no version information, might be only in CVS)

SWFTextField->setname -- Sets the variable name

Description

void swftextfield->setname ( string name)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

swftextfield->setname() sets the variable name of this text field to name, for form posting and action scripting purposes.

SWFTextField->setrightMargin

(no version information, might be only in CVS)

SWFTextField->setrightMargin -- Sets the right margin width of the text field.

Description

void swftextfield->setrightmargin ( int width)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

swftextfield->setrightmargin() sets the right margin width of the text field to width. Default is 0.

SWFTextField

(PHP 4 >= 4.0.5)

SWFTextField -- Szövegmező objektum létrehozása

Leírás

new swftextfield ( [int flags])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Az swftextfield() által hozhatók létre új szövegmező objektumok. Ezek a szövegmezők kevésbé rugalmasak, mint az swftext() objektumok. Forgatni, nem arányosan nyújtani, vagy másképp átgyúrmázni. Ezzel szemben felhasználhatóak űrlapok létrehozására, és képesek a böngésző karakterkészletének felhasználására.

A flag opionálisan megadható paraméterben lehetséges megváltoztatni a szövegmező tulajdonságait. A következő értékek rendelhetők hozzá:

  • SWFTEXTFIELD_DRAWBOX a szövegmező köré keretet tesz

  • SWFTEXTFIELD_HASLENGTH

  • SWFTEXTFIELD_HTML html formázás engedélyezése

  • 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

Ezen kapcsolók összekombinálhatóak ehhez a bináris OR operátort kell alkalmazni. Egy példa:
<?php
$t = newSWFTextField(SWFTEXTFIELD_PASSWORD | SWFTEXTFIELD_NOEDIT); 
?>
A fenti példa egy nem szerkeszthető, jelszübekérőt hoz létre. Teljességgel haszontalan összeállítás természetesen. :)

Az SWFTextField a következő eljárásokat tartalmazza: 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().

LXI. Miscellaneous functions

Bevezetés

These functions were placed here because none of the other categories seemed to fit.


Követelmények

Az itt leírt függvények használatához semmilyen külső függvénykönyvtár megléte nem szükségeltetik.


Telepítés

Semmilyen telepítés nem szükséges ezen függvények használatához, a PHP alapelemei.


Futásidejű beállítások

Az alábbi függvények viselkedése befolyásolható a php.ini segítségével.

Táblázat 1. Misc. Configuration Options

NameDefaultChangeable
ignore_user_abort"0"PHP_INI_ALL
highlight.string#DD0000PHP_INI_ALL
highlight.comment#FF9900PHP_INI_ALL
highlight.keyword#007700PHP_INI_ALL
highlight.bg#FFFFFFPHP_INI_ALL
highlight.default#0000BBPHP_INI_ALL
highlight.html#000000PHP_INI_ALL
browscapNULLPHP_INI_SYSTEM
For further details and definition of the PHP_INI_* constants see ini_set().

Here's a short explanation of the configuration directives.

ignore_user_abort boolean

TRUE by default. If changed to FALSE scripts will be terminated as soon as they try to output something after a client has aborted their connection.

See also ignore_user_abort().

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


Erőforrás típusok

Ez a kiterjesztés semmilyen erőforrás típust nem definiál.


Előre definiált állandók

Az itt listázott állandókat ez a kiterjesztés definiálja, és csak akkor elérhetőek, ha az adott kiterjesztés be van fordítva a PHP-be, vagy dinamikusan betöltött.

CONNECTION_ABORTED (integer)

CONNECTION_NORMAL (integer)

CONNECTION_TIMEOUT (integer)

Tartalom
connection_aborted -- Returns TRUE if client disconnected
connection_status -- Returns connection status bitfield
connection_timeout -- Return TRUE if script timed out
constant -- Returns the value of a constant
define -- Defines a named constant.
defined --  Checks whether a given named constant exists
die -- Equivalent to exit()
eval -- Evaluate a string as PHP code
exit -- Output a message and terminate the current script
get_browser --  Tells what the user's browser is capable of
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.
show_source -- Alias of highlight_file()
sleep -- Delay execution
uniqid -- Generate a unique ID
unpack -- Unpack data from binary string
usleep -- Delay execution in microseconds

connection_aborted

(PHP 3>= 3.0.7, PHP 4 )

connection_aborted -- Returns TRUE if client disconnected

Description

int connection_aborted ( void )

Returns TRUE if client disconnected. See the Connection Handling description in the Features chapter for a complete explanation.

See also connection_status(), and ignore_user_abort().

connection_status

(PHP 3>= 3.0.7, PHP 4 )

connection_status -- Returns connection status bitfield

Description

int connection_status ( void )

Returns the connection status bitfield. See the Connection Handling description in the Features chapter for a complete explanation.

See also connection_aborted(), and ignore_user_abort().

connection_timeout

(PHP 3>= 3.0.7, PHP 4 <= 4.0.4)

connection_timeout -- Return TRUE if script timed out

Description

bool connection_timeout ( void )

Returns TRUE if script timed out.

Deprecated

This function is deprecated, and doesn't even exist anymore as of 4.0.5.

See the Connection Handling description in the Features chapter for a complete explanation.

constant

(PHP 4 >= 4.0.4)

constant -- Returns the value of a constant

Description

mixed constant ( string name)

constant() will 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 it's name. i.e. It is stored in a variable or returned by a function.

Példa 1. constant() example

<?php

define("MAXSIZE", 100);

echo MAXSIZE;
echo constant("MAXSIZE"); // same thing as the previous line

?>

See also define(), defined() and the section on Constants.

define

(PHP 3, PHP 4 )

define -- Defines a named constant.

Description

bool define ( string name, mixed value [, bool case_insensitive])

Defines a named constant. See the section on constants for more details.

The name of the constant is given by name; the value is given by value.

The optional third parameter case_insensitive is also available. If the value TRUE is given, then the constant will be defined case-insensitive. The default behaviour is case-sensitive; i.e. CONSTANT and Constant represent different values.

Példa 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."

?>

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

See also defined(), constant() and the section on Constants.

defined

(PHP 3, PHP 4 )

defined --  Checks whether a given named constant exists

Description

bool defined ( string name)

Returns TRUE if the named constant given by name has been defined, FALSE otherwise.

Példa 1. Checking Constants

<?php
/* Note the use of quotes, this is important.  This example is checking 
 * if the string 'CONSTANT' is the name of a constant named CONSTANT */
if (defined('CONSTANT')) {
    echo CONSTANT;
}
?>

Megjegyzés: 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().

See also define(), constant(), get_defined_constants(), function_exists(), and the section on Constants.

die

die -- Equivalent to exit()

Description

This language construct is equivalent to exit().

eval

(PHP 3, PHP 4 )

eval -- Evaluate a string as PHP code

Description

mixed eval ( string code_str)

eval() evaluates the string given in code_str as PHP code. Among other things, this can be useful for storing code in a database text field for later execution.

There are some factors to keep in mind when using eval(). Remember that the string passed must be valid PHP code, including things like terminating statements with a semicolon so the parser doesn't die on the line after the eval(), and properly escaping things in code_str.

Also remember that variables given values under eval() will retain these values in the main script afterwards.

A return statement will terminate the evaluation of the string immediately. In PHP 4, eval() returns NULL unless return is called in the evaluated code, in which case the value passed to return is returned. In PHP 3, eval() does not return a value.

Példa 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";
?>

The above example will show:

This is a $string with my $name in it.
This is a cup with my coffee in it.

Tipp: Mint bármilyen más esetben, amikor a kimenet közvetlenül a böngészőhöz kerül, használhatod az kimenet szabályozó függvényeket, hogy a függvény kimenetét "elkapd", és elmentsd például egy string-ben.

exit

(PHP 3, PHP 4 )

exit -- Output a message and terminate the current script

Description

void exit ( [string status])

void exit ( int status)

Megjegyzés: This is not a real function, but a language construct.

Megjegyzés: PHP version >= 4.2.0 does NOT print the status if it is an integer.

The exit() function terminates execution of the script. It prints status just before exiting.

If status is an integer, that value will also be used as the exit status. Exit statuses should be in the range 1 to 254, the exit status 255 is reserved by PHP and shall not be used.

Példa 1. exit() example

<?php

$filename = '/path/to/data-file';
$file = fopen($filename, 'r')
    or exit("unable to open file ($filename)");

?>

Megjegyzés: The die() function is an alias for exit().

See also: register_shutdown_function().

get_browser

(PHP 3, PHP 4 )

get_browser --  Tells what the user's browser is capable of

Description

object get_browser ( [string user_agent])

get_browser() attempts to determine the capabilities of the user's browser. This is done by looking up the browser's information in the browscap.ini file. By default, the value of HTTP_USER_AGENT is used; however, you can alter this (i.e., look up another browser's info) by passing the optional user_agent parameter to get_browser().

The information is returned in an object, 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.

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.

The following example shows how one might list all available information retrieved about the user's browser.

Példa 1. get_browser() example

<?php
echo $_SERVER['HTTP_USER_AGENT'] . "<hr />\n";

$browser = get_browser();

foreach ($browser as $name => $value) {
    echo "<b>$name</b> $value <br />\n";
}

?>

The output of the above script would look something like this:

Mozilla/4.5 [en] (X11; U; Linux 2.2.9 i586)<hr />
<b>browser_name_pattern:</b> Mozilla/4\.5.*<br />
<b>parent:</b> Netscape 4.0<br />
<b>platform:</b> Linux<br />
<b>majorver:</b> 4<br />
<b>minorver:</b> 5<br />
<b>browser:</b> Netscape<br />
<b>version:</b> 4<br />
<b>frames:</b> 1<br />
<b>tables:</b> 1<br />
<b>cookies:</b> 1<br />
<b>backgroundsounds:</b> <br />
<b>vbscript:</b> <br />
<b>javascript:</b> 1<br />
<b>javaapplets:</b> 1<br />
<b>activexcontrols:</b> <br />
<b>beta:</b> <br />
<b>crawler:</b> <br />
<b>authenticodeupdate:</b> <br />
<b>msn:</b> <br />

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 browscap.ini file here. By default, the browscap directive is commented out.

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.

Megjegyzés: On versions older than PHP 4.0.6, you will have to pass the user agent in via the optional user_agent parameter if the PHP directive register_globals is off. In this case, you will pass in $HTTP_SERVER_VARS['HTTP_USER_AGENT'].

highlight_file

(PHP 4 )

highlight_file -- Syntax highlighting of a file

Description

mixed highlight_file ( string filename [, bool return])

The highlight_file() function prints out a syntax highlighted version of the code contained in filename using the colors defined in the built-in syntax highlighter for PHP.

If the second parameter return is set to TRUE then highlight_file() will return the highlighted code as a string instead of printing it out. If the second parameter is not set to TRUE then highlight_file() will return TRUE on success, FALSE on failure.

Megjegyzés: The return parameter became available in PHP 4.2.0. Before this time it behaved like the default, which is FALSE

Figyelem

Care should be taken when using the show_source() and highlight_file() functions 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.

Megjegyzés: Since PHP 4.2.1 this function is also affected by safe_mode and open_basedir.

To setup a URL that can code hightlight any script that you pass to it, we will make use of the "ForceType" directive in Apache to generate a nice URL pattern, and use the function highlight_file() to show a nice looking code list.

In your httpd.conf you can add the following:

Példa 1. Creating a source highlighting URL

<Location /source>
    ForceType application/x-httpd-php
</Location>

And then make a file named "source" and put it in your web root directory.

<html>
<head>
<title>Source Display</title>
</head>
<body bgcolor="white">
<?php
    $script = getenv("PATH_TRANSLATED");
    if (!$script) {
        echo "<br /><b>ERROR: Script Name needed</b><br />";
    } else {
        if (ereg("(\\.php|\\.inc)$", $script)) {
            echo "<h1>Source of: " . getenv("PATH_INFO") . "</h1>\n<hr />\n";
            highlight_file($script);
        } else {
            echo "<h1>ERROR: Only PHP or include script names are allowed</h1>"; 
        }
    }
    echo "<hr />Processed: " . date("Y/M/d H:i:s", time());
?>
</BODY>
</HTML>

Then you can use a URL like the one below to display a colorized version of a script located in "/path/to/script.php" in your web site.

http://www.example.com/source/path/to/script.php

See also highlight_string().

highlight_string

(PHP 4 )

highlight_string -- Syntax highlighting of a string

Description

mixed highlight_string ( string str [, bool return])

The highlight_string() function outputs a syntax highlighted version of str using the colors defined in the built-in syntax highlighter for PHP.

If the second parameter return is set to TRUE then highlight_string() will return the highlighted code as a string instead of printing it out. If the second parameter is not set to TRUE then highlight_string() will return TRUE on success, FALSE on failure.

Megjegyzés: The return parameter became available in PHP 4.2.0. Before this time it behaved like the default, which is FALSE

See also highlight_file().

ignore_user_abort

(PHP 3>= 3.0.7, PHP 4 )

ignore_user_abort --  Set whether a client disconnect should abort script execution

Description

int ignore_user_abort ( [bool setting])

This function sets whether a client disconnect should cause a script to be aborted. It will return the previous setting and can be called without an argument to not change the current setting and only return the current setting. See the Connection Handling section in the Features chapter for a complete description of connection handling in PHP.

See also connection_aborted(), and connection_status().

pack

(PHP 3, PHP 4 )

pack -- Pack data into binary string.

Description

string pack ( string format [, mixed args])

Pack given arguments into binary string according to format. Returns binary string containing data.

The idea to this function was taken from Perl and all formatting codes work the same as there, however, there are some formatting codes that are missing such as Perl's "u" format code. 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 are

Táblázat 1. pack() format characters

CodeDescription
aNUL-padded string
ASPACE-padded string
hHex string, low nibble first
HHex string, high nibble first
csigned char
Cunsigned char
ssigned short (always 16 bit, machine byte order)
Sunsigned short (always 16 bit, machine byte order)
nunsigned short (always 16 bit, big endian byte order)
vunsigned short (always 16 bit, little endian byte order)
isigned integer (machine dependent size and byte order)
Iunsigned integer (machine dependent size and byte order)
lsigned long (always 32 bit, machine byte order)
Lunsigned long (always 32 bit, machine byte order)
Nunsigned long (always 32 bit, big endian byte order)
Vunsigned long (always 32 bit, little endian byte order)
ffloat (machine dependent size and representation)
ddouble (machine dependent size and representation)
xNUL byte
XBack up one byte
@NUL-fill to absolute position

Példa 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 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.

Also note that PHP internally stores integer values as signed values of a machine dependent size. If you give it an unsigned integer value too large to be stored that way it is converted to a float which often yields an undesired result.

show_source

show_source -- Alias of highlight_file()

Description

This function is an alias of highlight_file().

sleep

(PHP 3, PHP 4 )

sleep -- Delay execution

Description

void sleep ( int seconds)

The sleep() function delays program execution for the given number of seconds.

Példa 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

See also usleep() and set_time_limit()

uniqid

(PHP 3, PHP 4 )

uniqid -- Generate a unique ID

Description

string uniqid ( string prefix [, bool lcg])

uniqid() returns a prefixed unique identifier based on the current time in microseconds. The 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. Prefix can be up to 114 characters long.

If the optional lcg parameter is TRUE, uniqid() will add additional "combined LCG" entropy at the end of the return value, which should make the results more unique.

With an empty prefix, the returned string will be 13 characters long. If lcg is TRUE, it will be 23 characters.

Megjegyzés: The lcg parameter is only available in PHP 4 and PHP 3.0.13 and later.

If you need a unique identifier or token and you intend to give out that token to the user via the network (i.e. session cookies), it is recommended that you use something along these lines:

<?php
// no prefix
$token = md5(uniqid(""));

// better, difficult to guess
$better_token = md5(uniqid(rand(), true));
?>

This will create a 32 character identifier (a 128 bit hex number) that is extremely difficult to predict.

unpack

(PHP 3, PHP 4 )

unpack -- Unpack data from binary string

Description

array unpack ( string format, string data)

unpack() from binary string into array according to format. Returns array containing unpacked elements of binary string.

unpack() works slightly different from Perl as 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 /.

Példa 1. unpack() example

<?php
$array = unpack("c2chars/nint", $binarydata);
?>

The resulting array will contain the entries "chars1", "chars2" and "int".

Figyelem

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.

See also pack() for an explanation of the format codes.

usleep

(PHP 3, PHP 4 )

usleep -- Delay execution in microseconds

Description

void usleep ( int micro_seconds)

The usleep() function delays program execution for the given number of micro_seconds. A microsecond is one millionth of a second.

Megjegyzés: This function does not work on Windows systems.

See also sleep() and set_time_limit().

LXII. mnoGoSearch Functions

Bevezetés

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

Megjegyzés: Ez a kiterjesztés nem működik Windows operációs rendszereken!


Követelmények

Download mnoGosearch from http://www.mnogosearch.ru/ and install it on your system. You need at least version 3.1.10 of mnoGoSearch installed to use these functions.


Telepítés

In order to have these functions available, you must compile PHP with mnoGosearch support by using the --with-mnogosearchoption. If you use this option without specifying the path to mnoGosearch, PHP will look for mnoGosearch under /usr/local/mnogosearch path by default. If you installed mnoGosearch at a different location you should specify it: --with-mnogosearch=DIR.

Megjegyzés: 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.


Futásidejű beállítások

Ez a kiterjesztés semmilyen konfigurációs beállításokat nem definiál a php.ini állományban.


Erőforrás típusok


Előre definiált állandók

Az itt listázott állandókat ez a kiterjesztés definiálja, és csak akkor elérhetőek, ha az adott kiterjesztés be van fordítva a PHP-be, vagy dinamikusan betöltött.

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)

Tartalom
udm_add_search_limit -- Add various search limits
udm_alloc_agent_array -- Allocate mnoGoSearch session
udm_alloc_agent -- Allocate mnoGoSearch session
udm_api_version -- Get mnoGoSearch API version.
udm_cat_list -- Get all the categories on the same level with the current one.
udm_cat_path -- Get the path to the current category.
udm_check_charset --  Check if the given charset is known to mnogosearch
udm_check_stored --  Check connection to stored
udm_clear_search_limits -- Clear all mnoGoSearch search restrictions
udm_close_stored --  Close connection to stored
udm_crc32 --  Return CRC32 checksum of given string
udm_errno -- Get mnoGoSearch error number
udm_error -- Get mnoGoSearch error message
udm_find -- Perform search
udm_free_agent -- Free mnoGoSearch session
udm_free_ispell_data -- Free memory allocated for ispell data
udm_free_res -- Free mnoGoSearch result
udm_get_doc_count -- Get total number of documents in database.
udm_get_res_field -- Fetch mnoGoSearch result field
udm_get_res_param -- Get mnoGoSearch result parameters
udm_hash32 -- Return Hash32 checksum of gived string
udm_load_ispell_data -- Load ispell data
udm_open_stored --  Open connection to stored
udm_set_agent_param -- Set mnoGoSearch agent session parameters

udm_add_search_limit

(PHP 4 >= 4.0.5)

udm_add_search_limit -- Add various search limits

Description

bool udm_add_search_limit ( resource agent, int var, string val)

udm_add_search_limit() adds search restrictions. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

agent - a link to Agent, received after call to udm_alloc_agent().

var - defines parameter, indicating limit.

val - defines the value of the current parameter.

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:

    Példa 1.

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

udm_alloc_agent_array

(PHP 5 CVS only)

udm_alloc_agent_array -- Allocate mnoGoSearch session

Description

resource udm_alloc_agent_array ( array databases)

udm_alloc_agent_array() will create an agent with multiple database connections. The array databases must contain one database URL per element, analog to the first parameter of udm_alloc_agent().

See also: udm_alloc_agent().

udm_alloc_agent

(PHP 4 >= 4.0.5)

udm_alloc_agent -- Allocate mnoGoSearch session

Description

resource udm_alloc_agent ( string dbaddr [, string dbmode])

Returns a mnogosearch agent identifier on success, FALSE on failure. This function creates a session with database parameters.

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

Megjegyzés: dbaddr and dbmode must match those used during indexing.

Megjegyzés: 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_api_version

(PHP 4 >= 4.0.5)

udm_api_version -- Get mnoGoSearch API version.

Description

int udm_api_version ( void )

udm_api_version() returns the mnoGoSearch API version number. E.g. if mnoGoSearch 3.1.10 API is used, this function will return 30110.

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.

Példa 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_cat_list

(PHP 4 >= 4.0.6)

udm_cat_list -- Get all the categories on the same level with the current one.

Description

array udm_cat_list ( resource agent, string category)

Returns an array listing all categories of the same level as the current category in the categories tree. agent is the agent identifier returned by a previous call to >udm_alloc_agent().

The function can be useful for developing categories tree browser.

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.

Following is an example of displaying links of the current level in format:
Audi
  BMW
  Opel
  ...

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

See also udm_cat_path().

udm_cat_path

(PHP 4 >= 4.0.6)

udm_cat_path -- Get the path to the current category.

Description

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. agent is the agent identifier returned by a previous call to >udm_alloc_agent().

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'

Példa 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> ";
  }
?>

See also udm_cat_list().

udm_check_charset

(PHP 4 >= 4.2.0)

udm_check_charset --  Check if the given charset is known to mnogosearch

Description

bool udm_check_charset ( resource agent, string charset)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

udm_check_stored

(PHP 4 >= 4.2.0)

udm_check_stored --  Check connection to stored

Description

int udm_check_stored ( resource agent, int link, string doc_id)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

udm_clear_search_limits

(PHP 4 >= 4.0.5)

udm_clear_search_limits -- Clear all mnoGoSearch search restrictions

Description

bool udm_clear_search_limits ( resource agent)

udm_clear_search_limits() resets defined search limitations and returns TRUE.

See also udm_add_search_limit().

udm_close_stored

(PHP 4 >= 4.2.0)

udm_close_stored --  Close connection to stored

Description

int udm_close_stored ( resource agent, int link)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

udm_crc32

(PHP 4 >= 4.2.0)

udm_crc32 --  Return CRC32 checksum of given string

Description

int udm_crc32 ( resource agent, string str)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

udm_errno

(PHP 4 >= 4.0.5)

udm_errno -- Get mnoGoSearch error number

Description

int udm_errno ( resource agent)

udm_errno() returns mnoGoSearch error number, zero if no error.

agent - link to agent identifier, received after call to udm_alloc_agent().

Receiving numeric agent error code.

udm_error

(PHP 4 >= 4.0.5)

udm_error -- Get mnoGoSearch error message

Description

string udm_error ( resource agent)

udm_error() returns mnoGoSearch error message, empty string if no error.

agent - link to agent identifier, received after call to udm_alloc_agent().

Receiving agent error message.

udm_find

(PHP 4 >= 4.0.5)

udm_find -- Perform search

Description

resource udm_find ( resource agent, string query)

Returns a result link identifier on success, or FALSE on failure.

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.

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.

udm_free_agent

(PHP 4 >= 4.0.5)

udm_free_agent -- Free mnoGoSearch session

Description

int udm_free_agent ( resource agent)

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

agent - link to agent identifier, received ` after call to udm_alloc_agent().

Freeing up memory allocated for agent session.

udm_free_ispell_data

(PHP 4 >= 4.0.5)

udm_free_ispell_data -- Free memory allocated for ispell data

Description

bool udm_free_ispell_data ( int agent)

udm_free_ispell_data() always returns TRUE.

agent - agent link identifier, received after call to udm_alloc_agent().

Megjegyzés: This function is supported beginning from version 3.1.12 of mnoGoSearch and it does not do anything in previous versions.

udm_free_res

(PHP 4 >= 4.0.5)

udm_free_res -- Free mnoGoSearch result

Description

bool udm_free_res ( resource res)

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

res - a link to result identifier, received after call to udm_find().

Freeing up memory allocated for results.

udm_get_doc_count

(PHP 4 >= 4.0.5)

udm_get_doc_count -- Get total number of documents in database.

Description

int udm_get_doc_count ( resource agent)

udm_get_doc_count() returns the number of documents in the database.

agent - link to agent identifier, received after call to udm_alloc_agent().

Megjegyzés: This function is supported only in mnoGoSearch 3.1.11 or later.

udm_get_res_field

(PHP 4 >= 4.0.5)

udm_get_res_field -- Fetch mnoGoSearch result field

Description

string udm_get_res_field ( resource res, int row, int field)

udm_get_res_field() returns result field value on success, FALSE on error.

res - a link to result identifier, received after call to udm_find().

row - the number of the link on the current page. May have values from 0 to UDM_PARAM_NUM_ROWS-1.

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.

udm_get_res_param

(PHP 4 >= 4.0.5)

udm_get_res_param -- Get mnoGoSearch result parameters

Description

string udm_get_res_param ( resource res, int param)

udm_get_res_param() returns result parameter value on success, FALSE on error.

res - a link to result identifier, received after call to udm_find().

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.

udm_hash32

(PHP 5 CVS only)

udm_hash32 -- Return Hash32 checksum of gived string

Description

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. Requires an allocated agent.

See also: udm_alloc_agent().

udm_load_ispell_data

(PHP 4 >= 4.0.5)

udm_load_ispell_data -- Load ispell data

Description

bool udm_load_ispell_data ( resource agent, int var, string val1, string val2, int flag)

udm_load_ispell_data() loads ispell data. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

agent - agent link identifier, received after call to udm_alloc_agent().

var - parameter, indicating the source for ispell data. May have the following values:

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.

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.

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

    Megjegyzés: 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().

    Példa 1. 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_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.

    Példa 2. 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;
    }
    ?>

    Megjegyzés: 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;
          }
    ?>

    Megjegyzés: 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.

    Megjegyzés: 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;
    }
    ?>

udm_open_stored

(PHP 4 >= 4.2.0)

udm_open_stored --  Open connection to stored

Description

int udm_open_stored ( resource agent, string storedaddr)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

udm_set_agent_param

(PHP 4 >= 4.0.5)

udm_set_agent_param -- Set mnoGoSearch agent session parameters

Description

bool udm_set_agent_param ( resource agent, int var, string val)

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad. Defines mnoGoSearch session parameters.

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.

    Megjegyzés: Crosswords are supported only in mnoGoSearch 3.1.11 or later.

  • 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. The parameter is available in PHP 4.1.0 or later.

LXIII. mSQL functions

Bevezetés

These functions allow you to access mSQL database servers. More information about mSQL can be found at http://www.hughes.com.au/.


Követelmények


Telepítés

In order to have these functions available, you must compile PHP with msql support by using the --with-msql[=DIR] option. DIR is the mSQL base install directory, defaults to /usr/local/Hughes.

Note to Win32 Users: In order to enable this module on a Windows environment, you must copy msql.dll from the DLL folder of the PHP/Win32 binary package to the SYSTEM32 folder of your windows machine. (Ex: C:\WINNT\SYSTEM32 or C:\WINDOWS\SYSTEM32)


Futásidejű beállítások

Az alábbi függvények viselkedése befolyásolható a php.ini segítségével.

Táblázat 1. mSQL configuration options

NameDefaultChangeable
msql.allow_persistent"On"PHP_INI_SYSTEM
msql.max_persistent"-1"PHP_INI_SYSTEM
msql.max_links"-1"PHP_INI_SYSTEM
For further details and definition of the PHP_INI_* constants see ini_set().

Here's a short explanation of the configuration directives.

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.


Erőforrás típusok


Előre definiált állandók

Az itt listázott állandókat ez a kiterjesztés definiálja, és csak akkor elérhetőek, ha az adott kiterjesztés be van fordítva a PHP-be, vagy dinamikusan betöltött.

MSQL_ASSOC (integer)

MSQL_NUM (integer)

MSQL_BOTH (integer)

Tartalom
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 -- Create mSQL database
msql_data_seek -- Move internal row pointer
msql_dbname -- Get current mSQL database name
msql_drop_db -- Drop (delete) mSQL database
msql_dropdb -- 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_seek -- Set field offset
msql_fieldflags -- Get field flags
msql_fieldlen -- Get field length
msql_fieldname -- Get field name
msql_fieldtable -- Get table name for field
msql_fieldtype -- Get field type
msql_free_result -- Free result memory
msql_freeresult -- 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_listdbs -- List mSQL databases on server
msql_listfields -- List result fields
msql_listtables -- 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 -- Get number of fields in result
msql_numrows -- Get number of rows in result
msql_pconnect -- Open persistent mSQL connection
msql_query -- Send mSQL query
msql_regcase --  Make regular expression for case insensitive match
msql_result -- Get result data
msql_select_db -- Select mSQL database
msql_selectdb -- Select mSQL database
msql_tablename -- Get table name of field
msql -- Send mSQL query

msql_affected_rows

(PHP 3>= 3.0.6, PHP 4 )

msql_affected_rows -- Returns number of affected rows

Description

int msql_affected_rows ( int query_identifier)

Returns number of affected ("touched") rows by a specific query (i.e. the number of rows returned by a SELECT, the number of rows modified by an update, or the number of rows removed by a delete).

See also: msql_query().

msql_close

(PHP 3, PHP 4 )

msql_close -- Close mSQL connection

Description

int msql_close ( int link_identifier)

Returns TRUE on success, FALSE on error.

msql_close() closes the link to a mSQL 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.

msql_close() will not close persistent links generated by msql_pconnect().

See also: msql_connect() and msql_pconnect().

msql_connect

(PHP 3, PHP 4 )

msql_connect -- Open mSQL connection

Description

int msql_connect ( [string hostname [, string server [, string username [, string password]]]])

msql_connect() establishes a connection to a mSQL server. The server parameter can also include a port number. e.g. "hostname:port". It defaults to 'localhost'.

Returns a positive mSQL link identifier on success, or FALSE on error.

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

See also msql_pconnect() and msql_close().

msql_create_db

(PHP 3, PHP 4 )

msql_create_db -- Create mSQL database

Description

int msql_create_db ( string database_name [, int link_identifier])

msql_create_db() attempts to create a new database on the server associated with the specified link identifier.

See also msql_drop_db().

msql_createdb

(PHP 3, PHP 4 )

msql_createdb -- Create mSQL database

Description

int msql_createdb ( string database_name [, int link_identifier])

Identical to msql_create_db().

msql_data_seek

(PHP 3, PHP 4 )

msql_data_seek -- Move internal row pointer

Description

int msql_data_seek ( int query_identifier, 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.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

See also msql_fetch_row().

msql_dbname

(PHP 3, PHP 4 )

msql_dbname -- Get current mSQL database name

Description

string msql_dbname ( int query_identifier, int i)

msql_dbname() returns the database name stored in position i of the result pointer returned from the msql_listdbs() function. The msql_numrows() function can be used to determine how many database names are available.

msql_drop_db

(PHP 3, PHP 4 )

msql_drop_db -- Drop (delete) mSQL database

Description

int msql_drop_db ( string database_name, int link_identifier)

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

msql_drop_db() attempts to drop (remove) an entire database from the server associated with the specified link identifier.

See also: msql_create_db().

msql_dropdb

msql_dropdb -- Drop (delete) mSQL database

Description

See msql_drop_db().

msql_error

(PHP 3, PHP 4 )

msql_error -- Returns error message of last msql call

Description

string msql_error ( [int link_identifier])

Errors coming back from the mSQL database backend no longer issue warnings. Instead, use these functions to retrieve the error string.

msql_fetch_array

(PHP 3, PHP 4 )

msql_fetch_array -- Fetch row as array

Description

int msql_fetch_array ( int query_identifier [, int result_type])

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

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.

The second optional argument result_type in msql_fetch_array() is a constant and can take the following values: MSQL_ASSOC, MSQL_NUM, and MSQL_BOTH.

Be careful if you are retrieving results from a query that may return a record that contains only one field that has a value of 0 (or an empty string, or NULL).

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.

See also msql_fetch_row().

msql_fetch_field

(PHP 3, PHP 4 )

msql_fetch_field -- Get field information

Description

object msql_fetch_field ( int query_identifier, int field_offset)

Returns an object containing field information

msql_fetch_field() can be used in order to obtain information about fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by msql_fetch_field() is retrieved.

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

  • primary_key - 1 if the column is a primary key

  • unique - 1 if the column is a unique key

  • type - the type of the column

See also msql_field_seek().

msql_fetch_object

(PHP 3, PHP 4 )

msql_fetch_object -- Fetch row as object

Description

int msql_fetch_object ( int query_identifier [, int result_type])

Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows.

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

The optional second argument result_type in msql_fetch_array() is a constant and can take the following values: MSQL_ASSOC, MSQL_NUM, and MSQL_BOTH.

Speed-wise, the function is identical to msql_fetch_array(), and almost as quick as msql_fetch_row() (the difference is insignificant).

See also: msql_fetch_array() and msql_fetch_row().

msql_fetch_row

(PHP 3, PHP 4 )

msql_fetch_row -- Get row as enumerated array

Description

array msql_fetch_row ( int query_identifier)

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

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.

See also: msql_fetch_array(), msql_fetch_object(), msql_data_seek(), and msql_result().

msql_field_seek

(PHP 3, PHP 4 )

msql_field_seek -- Set field offset

Description

int msql_field_seek ( int query_identifier, 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.

See also: msql_fetch_field().

msql_fieldflags

(PHP 3, PHP 4 )

msql_fieldflags -- Get field flags

Description

string msql_fieldflags ( int query_identifier, int i)

msql_fieldflags() returns the field flags of the specified field. Currently this is either, "not NULL", "primary key", a combination of the two or "" (an empty string).

msql_fieldlen

(PHP 3, PHP 4 )

msql_fieldlen -- Get field length

Description

int msql_fieldlen ( int query_identifier, int i)

msql_fieldlen() returns the length of the specified field.

msql_fieldname

(PHP 3, PHP 4 )

msql_fieldname -- Get field name

Description

string msql_fieldname ( int query_identifier, int field)

msql_fieldname() returns the name of the specified field. query_identifier is the query identifier, and field is the field index. msql_fieldname($result, 2); will return the name of the second field in the result associated with the result identifier.

msql_fieldtable

(PHP 3, PHP 4 )

msql_fieldtable -- Get table name for field

Description

int msql_fieldtable ( int query_identifier, int field)

Returns the name of the table field was fetched from.

msql_fieldtype

(PHP 3, PHP 4 )

msql_fieldtype -- Get field type

Description

string msql_fieldtype ( int query_identifier, int i)

msql_fieldtype() is similar to the msql_fieldname() function. The arguments are identical, but the field type is returned. This will be one of "int", "char" or "real".

msql_free_result

(PHP 3, PHP 4 )

msql_free_result -- Free result memory

Description

int msql_free_result ( int query_identifier)

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.

msql_freeresult

msql_freeresult -- Free result memory

Description

See msql_free_result()

msql_list_dbs

(PHP 3, PHP 4 )

msql_list_dbs -- List mSQL databases on server

Description

int msql_list_dbs ( void )

msql_list_dbs() will return a result pointer containing the databases available from the current msql daemon. Use the msql_dbname() function to traverse this result pointer.

msql_list_fields

(PHP 3, PHP 4 )

msql_list_fields -- List result fields

Description

int msql_list_fields ( string database, string tablename)

msql_list_fields() retrieves information about the given tablename. Arguments are the database name and the table name. A result pointer is returned which can be used with msql_fieldflags(), msql_fieldlen(), msql_fieldname(), and msql_fieldtype(). A query identifier is a positive integer. The function returns -1 if a error occurs. A string describing the error will be placed in $phperrmsg, and unless the function was called as @msql_list_fields() then this error string will also be printed out.

See also msql_error().

msql_list_tables

(PHP 3, PHP 4 )

msql_list_tables -- List tables in an mSQL database

Description

int msql_list_tables ( string database)

msql_list_tables() takes a database name and result pointer much like the msql() function. The msql_tablename() function should be used to extract the actual table names from the result pointer.

msql_listdbs

msql_listdbs -- List mSQL databases on server

Description

See msql_list_dbs().

msql_listfields

msql_listfields -- List result fields

Description

See msql_list_fields().

msql_listtables

msql_listtables -- List tables in an mSQL database

Description

See msql_list_tables().

msql_num_fields

(PHP 3, PHP 4 )

msql_num_fields -- Get number of fields in result

Description

int msql_num_fields ( int query_identifier)

msql_num_fields() returns the number of fields in a result set.

See also: msql(), msql_query(), msql_fetch_field(), and msql_num_rows().

msql_num_rows

(PHP 3, PHP 4 )

msql_num_rows -- Get number of rows in result

Description

int msql_num_rows ( resource query_identifier)

msql_num_rows() returns the number of rows in a result set.

See also: msql(), msql_query(), and msql_fetch_row().

msql_numfields

(PHP 3, PHP 4 )

msql_numfields -- Get number of fields in result

Description

int msql_numfields ( int query_identifier)

Identical to msql_num_fields().

msql_numrows

(PHP 3, PHP 4 )

msql_numrows -- Get number of rows in result

Description

int msql_numrows ( void )

Identical to msql_num_rows().

msql_pconnect

(PHP 3, PHP 4 )

msql_pconnect -- Open persistent mSQL connection

Description

int msql_pconnect ( [string server [, string username [, string password]]])

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

Returns a positive mSQL persistent link identifier on success, or FALSE on error.

This type of links is therefore called 'persistent'.

msql_query

(PHP 3, PHP 4 )

msql_query -- Send mSQL query

Description

int msql_query ( string query, int link_identifier)

msql_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 msql_connect() was called, and use it.

Returns a positive mSQL query identifier on success, or FALSE on error.

Példa 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"];
}
?>

See also msql(), msql_select_db(), and msql_connect().

msql_regcase

msql_regcase --  Make regular expression for case insensitive match

Description

See sql_regcase().

msql_result

(PHP 3, PHP 4 )

msql_result -- Get result data

Description

int msql_result ( int query_identifier, int i, mixed field)

Returns the contents of the cell at the row and offset in the specified mSQL result set.

msql_result() returns the contents of one cell from a mSQL result set. The field argument can be the field's offset, or the field's name, or the field's table dot field's name (fieldname.tablename). If the column name has been aliased ('select foo as bar from ...'), use the alias instead of the column name.

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 msql_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: msql_fetch_row(), msql_fetch_array(), and msql_fetch_object().

msql_select_db

(PHP 3, PHP 4 )

msql_select_db -- Select mSQL database

Description

int msql_select_db ( string database_name, int link_identifier)

Returns TRUE on success, FALSE on error.

msql_select_db() sets the current active database on the server that's associated with the specified 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 msql_connect() was called, and use it.

Every subsequent call to msql_query() will be made on the active database.

See also msql_connect(), msql_pconnect(), and msql_query().

msql_selectdb

msql_selectdb -- Select mSQL database

Description

See msql_select_db().

msql_tablename

(PHP 3, PHP 4 )

msql_tablename -- Get table name of field

Description

string msql_tablename ( int query_identifier, int field)

msql_tablename() takes a result pointer returned by the msql_list_tables() function as well as an integer index and returns the name of a table. The msql_numrows() function may be used to determine the number of tables in the result pointer.

Példa 1. msql_tablename() example

<?php 
msql_connect("localhost");
$result = msql_list_tables("wisconsin");
$i = 0;
while ($i < msql_numrows($result)) {
    $tb_names[$i] = msql_tablename($result, $i);
    echo $tb_names[$i] . "<br />";
    $i++; 
}
?>

msql

(PHP 3, PHP 4 )

msql -- Send mSQL query

Description

int msql ( string database, string query, int link_identifier)

Returns a positive mSQL query identifier to the query result, or FALSE on error.

msql() selects a database and executes a query on it. If the optional link identifier isn't specified, the function will try to find an open link to the mSQL server and if no such link is found it'll try to create one as if msql_connect() was called with no arguments (see msql_connect()).

LXIV. MySQL függvények

Bevezetés

E függvények segítségével érheted el a MySQL adatbázisokat. A MySQL-ről további információt a http://www.mysql.com/ címen találsz. A MySQL dokumentációját pedig a http://www.mysql.com/documentation/ címen találod.


Követelmények

Ahhoz, hogy ezeket a függvényeket használhasd, a PHP-t MySQL támogatással kell lefordítanod.


Telepítés

Ha a PHP-t a --with-mysql opcióval fordítod, a PHP hozzá tud férni MySQL adatbázisokhoz. Ha nem adsz meg elérési utat, akkor a PHP a beépített MySQL könyvtárat fogja használni. Ha nem adod meg az opció után a mysql elérési útvonalát, akkor a php a beépített mysql kliens könyvtárat fogja használni. Ha a felhasználók más alkalmazásokat is használnak, amelyek mysql-t használnak (például a php 3-as és 4-es verzióját, vagy az auth-mysql-t), akkor mindig meg kell adni a mysql elérési útvonalát a --with-mysql=/path/to/mysql formában. Ez ki fogja kényszeríteni, hogy a meglévő mysql kliens könyvtárat használja a php, elkerülve az ebből adódó ütközéseket.

Figyelem

A PHP rendszer-összeomlás és indítási problémák fordulhatnak elő, ha a recode kiterjesztéssel együtt használod a MySQL modult. Lásd a recode kiterjesztést további információért.


Futásidejű beállítások

A MySQL függvények viselkedését a globális php.ini nevű konfigurációs fájlban tudod beállítani.

Táblázat 1. MySQL konfigurációs beállítások

NévAlapértelmezésHol állítható
mysql.allow_persistent"On"PHP_INI_SYSTEM
mysql.max_persistent"-1"PHP_INI_SYSTEM
mysql.max_links"-1"PHP_INI_SYSTEM
mysql.default_portNULLPHP_INI_ALL
mysql.default_socketNULLPHP_INI_ALL
mysql.default_hostNULLPHP_INI_ALL
mysql.default_userNULLPHP_INI_ALL
mysql.default_passwordNULLPHP_INI_ALL
mysql.connect_timeout"-1"PHP_INI_SYSTEM
A PHP_INI_* állandók meghatározást és további részleteket találsz az ini_set() függvény leírásánál.

A beállítási lehetőségek rövid leírása.

mysql.allow_persistent boolean

Állandó kapcsolatok engedélyezése.

mysql.max_persistent integer

Az állandó MySQL kapcsolatok maximális száma folyamatonként.

mysql.max_links integer

A MySQL kapcsolatok maximális száma folyamatonként. (Ebbe az állandó kapcsolatok is beszámítanak

mysql.default_port string

Az alapértelmezett TCP port, amelyet a PHP akkor használ, ha nincs portszám megadva. Ha nincs más alapértelmezés megadva, akkor a MYSQL_TCP_PORT környezeti változóból, majd a /etc/services fájl mysql-tcp bejegyzéséből, végül a fordításkor megadott MYSQL_PORT állandóból próbálja meg kideríteni a PHP. A windows alatt csak a MYSQL_PORT állandóval próbálkozik.

mysql.default_socket string

Az alapértelmezett socketnév helyi adatbázishoz való csatlakozáskor, ha nincs más socketnév megadva.

mysql.default_host string

Az alapértelmezett adatbáziskiszolgáló, ha másképp nincs meghatározva. Nem alkalmazható safe mode-ban.

mysql.default_user string

Az alapértelmezett felhasználónév, ha más módon nincs meghatározva. Nem alkalmazható safe mode-ban.

mysql.default_password string

Az alapértelmezett jelszó, ha más módon nincs meghatározva. Nem alkalmazható safe mode-ban.

mysql.connect_timeout integer

Kapcsolat elévülési ideje másodpercben. Linux alatt ennyi időt vár a PHP a szerver első válaszára.


Erőforrás típusok

Kétféle erőforrástípus van a MySQL modulban. Az első egy adatbáziskapcsolatot azonosít, a második pedig egy kérésre adott választ.


Előre definiált állandók

Az itt listázott állandókat ez a kiterjesztés definiálja, és csak akkor elérhetőek, ha az adott kiterjesztés be van fordítva a PHP-be, vagy dinamikusan betöltött.

A PHP 4.3.0-es változata óta lehetőség van a mysql_connect() és a mysql_pconnect() függvények számára kliens jelzőket átadni. A következő konstansok léteznek:

Táblázat 2. MySQL kliens állandók

konstansleírás
MYSQL_CLIENT_COMPRESStömörített protokoll használata
MYSQL_CLIENT_IGNORE_SPACEFüggvénynevek után szóközök engedélyezése
MYSQL_CLIENT_INTERACTIVEInteractive_timeout másodpercnyi (wait_timeout helyett) tétlenség engedélyezése a kapcsolat bezárása előtt.

A mysql_fetch_array() függvénynél az eredménytömb fajtáját konstans segítségével adhatod meg. Az alábbi állandókat használhatod:

Táblázat 3. MySQL fetch állandók

állandóleírás
MYSQL_ASSOC A tömb kulcsai az eredményben szereplő mezőnevek.
MYSQL_BOTH Az eredményt mezőnevek valamint az eredmény oszlopszáma alapján érheted el.
MYSQL_NUM Az eredmény oszlopai egy számmal indexelt tömb formájában állnak rendelkezésre. Az első oszlop indexe 0.


Példák

Az alábbi példa bemutatja, hogyan kell csatlakozni, kéréseket végrehajtani, eredményt kinyomtatni és lecsatlakozni a MySQL szerverről.

Példa 1. MySQL modul áttekintő példa

<?php
// Csatlakozás, adatbázis kiválasztása
$kapcsolat = mysql_connect("mysql_hoszt", "mysql_azonosito", "mysql_jelszo")
    or die("Nem tudok csatlakozni");
print "A kapcsolódás sikerül";
mysql_select_db("az_en_adatbazisom") or die("Nem sikerült kiválasztanom az adatbázist");

// SQL kérés végrehajtása
$keres = "SELECT * FROM az_en_tablam";
$eredmeny = mysql_query($keres) or die("Hiba a kérésben");

// Az eredmény kiírása HTML-ben
print "<table>\n";
while ($line = mysql_fetch_array($eredmeny, MYSQL_ASSOC)) {
    print "\t<tr>\n";
    foreach ($sor as $egy_oszlop) {
        print "\t\t<td>$egy_oszlop</td>\n";
    }
    print "\t</tr>\n";
}
print "</table>\n";

/* Eredményhalmaz felszabadítása */
mysql_free_result($result);

// Kapcsolat lezárása
mysql_close($kapcsolat);
?>

Tartalom
mysql_affected_rows -- Az előző MySQL műveletben érintett sorok számát adja meg
mysql_change_user --  Aktív kapcsolat felhasználójának módosítása
mysql_client_encoding -- A karaktertábla nevét adja
mysql_close -- Lezár egy MySQL kapcsolatot
mysql_connect -- Kapcsolatot nyit meg egy MySQL szerverhez
mysql_create_db -- Létrehoz egy MySQL adatbázist
mysql_data_seek -- Belső eredménymutató mozgatása
mysql_db_name -- Get result data
mysql_db_query -- MySQL kérést küld az adatbázisnak
mysql_drop_db -- Töröl egy MySQL adatbázist
mysql_errno --  Az előző MySQL művelet hibakódját tartalmazza
mysql_error --  Az előző MySQL művelet hibaszövegét adja
mysql_escape_string --  Egy karakerláncban szereplő speciális karakterek értelmezését szünteti meg.
mysql_fetch_array --  Kérés egy sorát adja vissza (tetszőleges) tömb formájában.
mysql_fetch_assoc --  Az eredmény egy sorát asszociatív tömbként adja vissza.
mysql_fetch_field --  Eredményhalmaz egy oszlopáról ad információt objektum formájában
mysql_fetch_lengths --  Az eredmény oszlopainak hosszáról nyújt információt
mysql_fetch_object --  Az eredmény következő sorát objektum formájában adja vissza
mysql_fetch_row -- Az eredmény következő sorát adja vissza számmal indexelt tömb formájában
mysql_field_flags --  Adott eredmény adott mezejének flagjeit adja vissza.
mysql_field_len --  A kérdezett mező hosszát adja vissza
mysql_field_name --  Adott mező nevét adja vissza
mysql_field_seek --  Az eredménymutatót a kívánt pozícióba mozgatja
mysql_field_table --  Visszaadja annak a táblának a nevét, melyben a megadott mező található
mysql_field_type --  Az eredmény adott mezejének típusát adja vissza
mysql_free_result -- Felszabadítja az eredmény által lefoglalt memóriát
mysql_get_client_info -- MySQL kliens információ
mysql_get_host_info -- MySQL kiszolgáló információ
mysql_get_proto_info -- MySQL protokoll információ
mysql_get_server_info -- MySQL szerver információ
mysql_info --  Get information about the most recent query
mysql_insert_id --  Visszaadja az előző INSERT művelet által előállított id-t
mysql_list_dbs --  Kilistázza a MySQL szerveren elérhető adatbázisokat
mysql_list_fields -- Kilistázza a MySQL eredmény mezőit
mysql_list_processes -- List MySQL processes
mysql_list_tables -- Adott adatbázisbeli táblaneveket listázza
mysql_num_fields -- Az eredményben szereplő mezők számát adja
mysql_num_rows -- Az eredményben szereplő sorok számát adja vissza.
mysql_pconnect --  Perzisztens kapcsolatot nyit meg a MySQL szerverhez
mysql_ping -- Ping a server connection or reconnect if there is no connection
mysql_query -- MySQL kérést küld a szervernek
mysql_real_escape_string --  Escapes special characters in a string for use in a SQL statement, taking into account the current charset of the connection.
mysql_result -- Eredmény egy sorának lekérdezése
mysql_select_db -- Kiválaszt egy MySQL adatbázist
mysql_stat -- Get current system status
mysql_tablename -- Egy tábla nevével tér vissza
mysql_thread_id -- Return the current thread ID
mysql_unbuffered_query --  SQL kérést küld küld a MySQL-nek anélkül, hogy az eredményt előfeldolgozná.

mysql_affected_rows

(PHP 3, PHP 4 )

mysql_affected_rows -- Az előző MySQL műveletben érintett sorok számát adja meg

Leírás

int mysql_affected_rows ( [resource link_identifier])

A mysql_affected_rows() függvény az előző link_identifier-rel azonosított kapcsolatban kiadott INSERT, UPDATE vagy DELETE kérésben érintett sorok számát adja vissza. Ha nem adsz meg kapcsolat-azonosítót, akkor az utolsó mysql_connect()-tel megnyitott kapcsolatról kapsz információt.

Megjegyzés: Ha transzakciókezelést használsz, akkor a mysql_affected_rows() függvényt az INSERT, UPDATE, vagy DELETE kérés után közvetlenül, nem a kommit után kell meghívni.

Ha az utolsó lekérdezés egy WHERE feltétel nélküli DELETE volt, akkor bár a táblából minden sor törlődik, a függvény nullát fog visszaadni.

Megjegyzés: Ha UPDATE-tel használod, a MySQL nem fogja azokat a sorokat frissíteni, ahol a sor régi és új értéke megegyezik. Így nem kizárt, hogy a mysql_affected_rows() függvény nem pont az egyező sorok számát adja vissza, hanem csak a ténylegesen megváltoztatott sorok számát.

A függvény nem működik a lekérdező SELECT kéréssel együtt használva, csak azokkal a lekérdezésekkel, melyek rekordokat módosítanak. Ha egy SELECT lekérdezésben kapott sorok számát szeretnéd megkapni, akkor használd a mysql_num_rows() függvényt.

Ha az utolsó kérés meghiusult, akkor a függvény -1-gyel tér vissza.

Példa 1. Delete kérés

<?php
    /* Csatlakozás az adatbázishoz */
    mysql_pconnect("localhost", "mysql_felhasználó", "titok") or
        die ("Nem tudok csatlakozni");

    /* Ez visszaadja a törölt rekordszámot */
    mysql_query("DELETE FROM mytable WHERE id < 10");
    printf ("%d rekordot töröltem\n", mysql_affected_rows());

    /* Ha where feltétel nélkül használjuk a delete-ben, 0-át ad */
    mysql_query("DELETE FROM mytable");
    printf ("%d rekordot töröltem\n", mysql_affected_rows());
?>

A fenti példa kimenete:
10 rekordot töröltem
0 rekordot töröltem

Példa 2. Update kérés

<?php
    /* Csatlakozás az adatbázishoz */
    mysql_pconnect("localhost", "mysql_felhasználó", "titok") or
        die ("Nem tudok csatlakozni");

    /* Update */
    mysql_query("UPDATE mytable SET used=1 WHERE id < 10");
    printf ("%d rekordot frissítettem\n", mysql_affected_rows());
mysql_query("COMMIT");
?>

A fenti példa kimenete:
10 rekordot frissítettem

Lásd még amysql_num_rows() és a mysql_info() függvényt!

mysql_change_user

(PHP 3>= 3.0.13)

mysql_change_user --  Aktív kapcsolat felhasználójának módosítása

Leírás

int mysql_change_user ( string user, string password [, string database [, resource link_identifier]])

A mysql_change_user() függvény megváltoztatja az aktuális, vagy az opcionális link_identifier paraméterben megadott azonosítójú kapcsolat felhasználóját. Ha egy adatbázis nevét megadod, akkor ez lesz az alapértelmezett, illetve az aktuális adatbázis, miután a mysql felhasználó megváltozott. Ha az új név-jelszó páros helytelen, akkor a függvényhívás előtti kapcsolat él tovább.

Megjegyzés: A függvény a PHP 3.0.13 változatával került a nyelvbe és MySQL 3.23.3, vagy későbbi változata szükséges a használatához. PHP 4 alatt nem elérhető!

mysql_client_encoding

(PHP 4 >= 4.3.0)

mysql_client_encoding -- A karaktertábla nevét adja

Leírás

int mysql_client_encoding ( [resource link_identifier])

A mysql_client_encoding() függvény az aktuális kapcsolat alapértelmezett karakterkészletének nevét adja.

Példa 1. mysql_client_encoding() example

<?php
$link = mysql_connect('localhost', 'mysql_felhasználó', 'titok');
$charset = mysql_client_encoding($link);
printf ("Az aktuális karakterkészlet: %s\n", $charset);
?>

A fenti példa kimenete:
Az aktuális karakterkészlet: latin2

Lásd még a mysql_real_escape_string() függvényt!

mysql_close

(PHP 3, PHP 4 )

mysql_close -- Lezár egy MySQL kapcsolatot

Leírás

bool mysql_close ( [resource link_identifier])

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

A mysql_close() függvény bezárja az adott azonosítójú MySQL kapcsolatot. Ha nem adsz meg link_identifier paramétert, akkor az utoljára megnyitott kapcsolatot zárja le.

A mysql_close() függvény használata általában szükségtelen, mert a nem perzisztens kapcsolatok a szkript végén bezáródnak. Lásd még: erőforrások felszabadítása

Megjegyzés: A mysql_close() függvény nem zárja be a mysql_pconnect() függvénnyel megnyitott kapcsolatokat.

Példa 1. MySQL close példa

<?php
    $link = mysql_connect ("kraemer", "marliesle", "titok")
        or die ("Nem lehet csatlakozni");
    print ("A csatlakozás sikerült");
    mysql_close ($link);
?>

Lásd még a mysql_connect() és a mysql_pconnect() függvényeket!

mysql_connect

(PHP 3, PHP 4 )

mysql_connect -- Kapcsolatot nyit meg egy MySQL szerverhez

Leírás

resource mysql_connect ( [string server [, string username [, string password [, bool new_link [, int client_flags]]]]])

Pozitív MySQL azonosítóval tér vissza, ha a csatlakozás sikerült, FALSE-sal ha nem.

A mysql_connect() függvény kapcsolatot nyit meg egy MySQL szerverhez. A paramétereket elhagyhatod. Az alapértelmezett értékek: server = 'localhost:3306', username = a folyamat tulajdonosának belépési neve password = üres karakterlánc.

A server paraméter tartalmazhat egy portszámot is, például: "hostname:port" vagy tartalmazhatja a MySQL socket elérési útvonalát, például: ":/path/to/socket".

Megjegyzés: A ":port" formátumú kiegészítés a PHP 3.0B4-es változatában került a nyelvbe.

A ":/path/to/socket" formát pedig a PHP 3.0.10-es verziójától kezdve használhatjuk.

A sikertelen kapcsolatkor kiírt hibaüzenetet elnyomhatod, ha @ jelet írsz a függvény elé.

Ha a mysql_connect() függvényt kétszer ugyanazokkal a paraméterekkel hívod meg, akkor nem jön létre újabb kapcsolat; a függvény a már meglévő kapcsolat azonosítóját fogja visszaadni. A new_link paraméter módosítja ezt a viselkedésmódot, és a mysql_connect() függvényt új link megnyitására kényszeríti, még akkor is, ha előzőleg a mysql_connect() függvényt ugyanazokkal a paraméterekkel hívtad meg. A client_flags paraméter lehetséges értékei a MYSQL_CLIENT_SSL, MYSQL_CLIENT_COMPRESS, MYSQL_CLIENT_IGNORE_SPACE vagy MYSQL_CLIENT_INTERACTIVE konstansok tetszőleges kombinációja lehet.

Megjegyzés: A new_link paraméter a PHP 4.2.0-s változatától használható.

A client_flags paraméter a PHP 4.3.0-s változata óta létezik.

A kapcsolat a PHP program végén bezárul, ha előbb nem zártuk volna le a mysql_close() függvénnyel.

Példa 1. MySQL connect példa

<?php
    $link = mysql_connect ("localhost", "felhasználónév", "titok")
        or die ("Nem lehet csatlakozni");
    print ("A csatlakozás sikerült");
    mysql_close ($link);
?>

Lásd még a mysql_pconnect() és a mysql_close() függvényeket.

mysql_create_db

(PHP 3, PHP 4 )

mysql_create_db -- Létrehoz egy MySQL adatbázist

Leírás

bool mysql_create_db ( string database name [, resource link_identifier])

A mysql_create_db() függvény megkísérel létrehozni egy új adatbázist a megadott kapcsolatazonosítón keresztül.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Példa 1. MySQL 'create database' példa

<?php
    $link = mysql_pconnect ("kron", "jutta", "geheim")
        or die ("Nem lehet csatlakozni")
    if (mysql_create_db ("my_db")) {
        print ("Az adatbázist létrehoztam\n");
    } else {
        printf ("Hiba az adatbázis létrehozásakor: %s\n", mysql_error ());
    }
?>

Kompatíbilitási okokból a mysql_createdb() függvény is használható, de nem javasolt.

Megjegyzés: A mysql_create_db() függvény használata nem javasolt. Inkább használd a mysql_query() függvénnyel, amiben egy SQL CREATE DATABASE parancsot küldesz.

Lásd még a: mysql_drop_db() és a mysql_query() függvényeket!

mysql_data_seek

(PHP 3, PHP 4 )

mysql_data_seek -- Belső eredménymutató mozgatása

Leírás

bool mysql_data_seek ( resource result_identifier, int row_number)

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

A mysql_data_seek() függvény az adott azonosítójú ereményhalmazban ugrik a megadott pozícióra. A mysql_fetch_row() függvény következő hívásakor ezt a sorszámú sort kapod meg.

Ha az első sorra akarsz pozicionálni, akkor Row_number 0 legyen! A row_number paraméternek 0 és mysql_num_rows - 1 közötti számnak kell lennie.

Megjegyzés: A mysql_data_seek() függvényt csak a mysql_query() függvénnyel használhatód együtt, a mysql_unbuffered_query() függvénnyel nem!

Példa 1. MySQL data seek példa

<?php
    $link = mysql_pconnect ("weblabor", "kgergely", "titok")
        or die ("Nem tudok csatlakozni");

    mysql_select_db ("samp_db")
        or die ("Nem tudok belépni az adatbázisba");

    $query = "SELECT last_name, first_name FROM friends";
    $eredmeny = mysql_query ($query)
        or die ("Rossz kérés");

    // sorok betöltése fordított sorrendben
    for ($i = mysql_num_rows ($eredmeny) - 1; $i &gt;=0; $i--) {
        if (!mysql_data_seek ($eredmeny, $i)) {
            echo ("Nem tudok a $i. sorra ugorni\n");
            continue;
        }

        if(!($sor = mysql_fetch_object ($eredmeny)))
            continue;

            echo "$sor->vezeteknev $sor->keresztnev<br />\n");
    }

    mysql_free_result ($eredmeny);
?>

Lásd még a mysql_query() és a mysql_num_rows() függvényeket!

mysql_db_name

(PHP 3>= 3.0.6, PHP 4 )

mysql_db_name -- Get result data

Leírás

string mysql_db_name ( resource result, int row [, mixed field])

A mysql_db_name() függvény első paramétere egy mysql_list_dbs() által visszaadott érték. A row paraméter az eredményhalmaz indexe.

Ha hiba történt, a függvény FALSE-sal tér vissza. Használd a mysql_errno() és a mysql_error() függvényeket a hiba eredetének megállapítására!

Példa 1. Mysql_db_name() példa

<?php
error_reporting(E_ALL);

mysql_connect('dbhost', 'név', 'jelszó');
$db_list = mysql_list_dbs();

$i = 0;
$cnt = mysql_num_rows($db_list);
while ($i < $cnt) {
    echo mysql_db_name($db_list, $i) . "\n";
    $i++;
}
?>

Kompatíbilitási okokból a mysql_dbname() függvény is használható, de használata nem javasolt.

mysql_db_query

(PHP 3, PHP 4 )

mysql_db_query -- MySQL kérést küld az adatbázisnak

Leírás

resource mysql_db_query ( string database, string query [, resource link_identifier])

Visszatérési értéke egy pozitív MySQL eredmény-azonosító, ha a kérés sikeres volt; FALSE, ha a kérés hibás volt.

A mysql_db_query() függvény kiválaszt egy adatbázist, majd azon végrehajt egy kérést. Ha a kapcsolat azonosító nincs megadva, akkor a függvény keres egyet. Ha nem talál ilyet, akkor megpróbál létrehozni egyet oly módon, mintha meghívta volna a mysql_connect() függvényt paraméterek nélkül.

Lásd még a mysql_connect() és a mysql_query() függvényeket.

Megjegyzés: A függvény használata a PHP 4.0.6-os változata óta nem javasolt, ezért NE használd ezt a függvényt. Inkább használd a mysql_select_db() és a mysql_query() függvényeket.

mysql_drop_db

(PHP 3, PHP 4 )

mysql_drop_db -- Töröl egy MySQL adatbázist

Leírás

bool mysql_drop_db ( string database_name [, resource link_identifier])

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

A mysql_drop_db() függvény megpróbálja az egész adatbázist kitörölni, melyet az adott kapcsolat-azonosító határoz meg.

Kompatíbilitási okokból mysql_dropdb() néven is hívható a függvény, de használata nem javasolt.

Megjegyzés: A mysql_drop_db() függvény használata nem javasolt. Ehelyett inkább a mysql_query() függvényt használd az SQL-es DROP DATABASE utasítással.

Lásd még a mysql_create_db() és a mysql_query() függvényeket!

mysql_errno

(PHP 3, PHP 4 )

mysql_errno --  Az előző MySQL művelet hibakódját tartalmazza

Leírás

int mysql_errno ( [resource link_identifier])

Az utoljára végrehajtott MySQL hiba kódjával tér vissza, vagy ha az sikeres volt, akkor 0-t (nullát) ad vissza.

A MySQL hibái már nem jelennek meg figyelmeztetésként. Ha szeretnéd megkapni a hiba kódját, használd a mysql_errno() függvényt! Ez a függvény csak az utolsó MySQL művelet hibakódját adja vissza (nem számítva a mysql_error() és a mysql_errno() függvényeket), ha használni szeretnéd, ügyelj rá, hogy még azelőtt hívd meg a függvényt, mielőtt egy másik MySQL függvényt meghívsz.

Példa 1. mysql_errno példa

<?php
mysql_connect("helyi vendéglátó","mysql_használó","jelszó"); // :-)

mysql_select_db("dehátNincsIsIlyenAdatbázis");
echo mysql_errno() . ": " . mysql_error() . "<BR>";

mysql_select_db("ilyenAzértCsakLesz");
$conn = mysql_query("SELECT * FROM deAbbanNincsIlyenTábla");
echo mysql_errno().": ".mysql_error()."<BR>";
?>

The above example would produce the following output:

1049: Unknown database 'dehátNincsIsIlyenAdatbázis'
1146: Table 'ilyenAzértCsakLesz.deAbbanNincsIlyenTábla' doesn't exist

Megjegyzés: Ha megadod a kapcsolatazonosítót, arról kapsz infomációt, egyébként az utoljára használt nyitottról.

Lásd még a mysql_error() függvényt!

mysql_error

(PHP 3, PHP 4 )

mysql_error --  Az előző MySQL művelet hibaszövegét adja

Leírás

string mysql_error ( [resource link_identifier])

Az utolsó MySQL művelet hibaszövegével tér vissza, vagy '' (üres karakterlánccal) ha nem volt hiba.

A MySQL hibái már nem jelennek meg figyelmeztetésként. Ha szeretnéd megkapni a hiba kódját, használd a mysql_errno() függvényt! Ez a függvény csak az utolsó MySQL művelet hibakódját adja vissza (nem számítva a mysql_error() és a mysql_errno() függvényeket), ha használni szeretnéd, ügyelj rá, hogy még azelőtt hívd meg a függvényt, mielőtt egy másik MySQL függvényt meghívsz.

Példa 1. mysql_errno példa

<?php
mysql_connect("helyi vendéglátó","mysql_használó","jelszó"); // :-)

mysql_select_db("dehátNincsIsIlyenAdatbázis");
echo mysql_errno() . ": " . mysql_error() . "<BR>";

mysql_select_db("ilyenAzértCsakLesz");
$conn = mysql_query("SELECT * FROM deAbbanNincsIlyenTábla");
echo mysql_errno().": ".mysql_error()."<BR>";
?>

The above example would produce the following output:

1049: Unknown database 'dehátNincsIsIlyenAdatbázis'
1146: Table 'ilyenAzértCsakLesz.deAbbanNincsIlyenTábla' doesn't exist

Megjegyzés: Ha megadod a kapcsolatazonosítót, arról kapsz infomációt, egyébként az utoljára használt nyitottról.

Lásd még a mysql_errno() függvényt!

mysql_escape_string

(PHP 4 >= 4.0.3)

mysql_escape_string --  Egy karakerláncban szereplő speciális karakterek értelmezését szünteti meg.

Leírás

string mysql_escape_string ( string unescaped_string)

A függvény az unescaped_string karakterláncot átalakítja úgy, hogy az biztonságosan elhelyezhető legyen egy mysql_query() függvényben.

Megjegyzés: A mysql_escape_string() függvény nem nyúl a % és a _ jelekhez.

A függvény azt csinálja, mint a mysql_real_escape_string() függvény azzal a kivétellel, hogy a mysql_real_escape_string() függvény egy kapcsolatazonosítót is kér, és a kapcsolathoz tartozó karakterkészletet is figyelembe veszi. Mivel a mysql_escape_string() függvény nem vár kapcsolatazonosítót, így nem is tudja figyelembe venni az aktuális karakterkészletre vonatkozó beállításokat

Példa 1. mysql_escape_string() example

<?php
    $item = "'Az én számítógépem'";
    $escaped_item = mysql_escape_string($item);
    printf ("Az átalakított szöveg: %s\n", $escaped_item);
?>

A fenti példa az alábbi kimenetet eredményezi:
Az átalakított szöveg: \'Az én számítógépem\'

Lásd még a mysql_real_escape_string(), addslashes() és a magic_quotes_gpc direktívákat.

mysql_fetch_array

(PHP 3, PHP 4 )

mysql_fetch_array --  Kérés egy sorát adja vissza (tetszőleges) tömb formájában.

Leírás

array mysql_fetch_array ( resource result [, int result_type])

Az eredmény következő sorával tér vissza tömb formájában, vagy FALSE-sal, ha már nincs több sor.

A mysql_fetch_array() függvény a mysql_fetch_row() függvény kiterjesztett változata. Ráadásul az eredményt nem csak számokkal indexelt tömbbe írja, hanem asszociatív tömbbe is, ahol a mező nevei a kulcsok.

Ha az eredmény több sorának ugyanaz a neve, akkor a később szereplő oszlop marad meg. Ha szeretnéd az összes mezőt elérni ilyenkor is, akkor számmal indexeld a tömböt, vagy az SQL parancsban kérj aliast az oszlopra. Az alias-olt [ez mi magyarul?] oszlopok tartalmát nem tudod az oszlopok eredeti nevével elérni (pl. itt a 'field' használatával).

select tik.f1 as ize tak.f1 as bigyo from tik, tak

Jó tudni, hogy a mysql_fetch_array() függvény használata nem jelentősen lassabb a mysql_fetch_row() használatánál, de a kapott eredmény feldolgozása jóval kényelmesebb.

A mysql_fetch_array() függvény elhagyható result_type paramétere a következő lehet: MYSQL_ASSOC, MYSQL_NUM, vagy MYSQL_BOTH. Ez a lehetőség a PHP 3.0.7-es változatában került a nyelvbe. A paraméter alapértelmezett értéke a MYSQL_BOTH.

A MYSQL_BOTH használatával egy olyan tömböt kapsz, amelyben az elemek számmal és karakterlánccal is indexelve vannak. MYSQL_ASSOC értékkel használva csak asszociatív tömböt kapsz (mint a mysql_fetch_assoc() függvénnyel), MYSQL_NUM értékkel meghívva a fügvényt számozott indexű tömböt kapsz (mint a mysql_fetch_row() függvénnyel).

További részletekért olvasd még a mysql_fetch_row() és a mysql_fetch_assoc() függvényeket!

Példa 1. Mysql_fetch_array() példa

<?php
mysql_connect ($host, $felhasznalo, $jelszo);
$eredmeny = mysql_db_query ("adatbázis","select user_id, teljesnev from table");
while ($sor = mysql_fetch_array ($eredmeny)) {
    echo "felhasznalonev: ".$sor["felhasznalonev"]."<br>\n";
    echo "felhasznalonev: ".$sor[0]."<br>\n";
    echo "nev: ".$sor["nev"]."<br>\n";
    echo "nev: ".$sor[1]."<br>\n";
}
mysql_free_result ($eredmeny);
?>

mysql_fetch_assoc

(PHP 4 >= 4.0.3)

mysql_fetch_assoc --  Az eredmény egy sorát asszociatív tömbként adja vissza.

Leírás

array mysql_fetch_assoc ( resource result)

Az eredmény következő sorával, mint asszociatív tömbbel tér vissza, vagy FALSE-sal, ha nincs több sor.

A mysql_fetch_assoc() függvény hívásával ugyanazt érjük el, mintha a mysql_fetch_array() függvényt hívtuk volna meg MYSQL_ASSOC második paraméterrel. Ez a függvény egy tisztán asszociatív tömböt ad vissza. Eredetileg a mysql_fetch_array() függvény így működött. Ha a számokkal indexelt elemekre is szükséged van, akkor használd a mysql_fetch_array() függvényt.

Ha az eredmény több oszlopának ugyanaz a neve, akkor a később szereplő oszlop marad meg. Ha szeretnéd az összes mezőt elérni, akkor vagy számokkal indexszel érd el az eredményt a mysql_fetch_array() függvény használatával, vagy az SQL parancsban kérj aliast az oszlopra. Lásd még a mysql_fetch_array() függvénynél szereplő példát az aliasok leírásáért.

Jó tudni, hogy a mysql_fetch_assoc() függvény használata NEM jelentősen lassabb a mysql_fetch_row() használatánál, de a kapott eredmény feldolgozása jóval kényelmesebb.

További részletekért lásd még a mysql_fetch_row() és a mysql_fetch_array() függvényeket.

Példa 1. mysql_fetch_assoc()

<?php
mysql_connect ($host, $felhasznalo, $jelszo);
$eredmeny = mysql_db_query ("adatbázis","select * from table");
while ($sor = mysql_fetch_assoc ($eredmeny)) {
    echo $sor["felhasznalonev"];
    echo $sor["nev"];
}
mysql_free_result ($eredmeny);
?>

mysql_fetch_field

(PHP 3, PHP 4 )

mysql_fetch_field --  Eredményhalmaz egy oszlopáról ad információt objektum formájában

Leírás

object mysql_fetch_field ( resource result [, int field_offset])

Egy mezőinformációt tartalmazó objektummal tér vissza.

A mysql_fetch_field() függvényt arra használhatod, hogy az eredmény egy oszlopáról információt kaphass. Ha a mező sorszámát nem adod meg, akkor a következő olyan oszlopról kapsz információt, amelyre még nem hívtad meg a mysql_fetch_field() függvényt.

Az objektum tulajdonságai:

  • name - az oszlop neve

  • table - a tábla neve, amelyhez az oszlop tartozik

  • max_length - az oszlop maximális hossza

  • not_null - értéke 1, ha az oszlop nem veheti fel a NULL értéket

  • primary_key - értéke 1, ha az oszlop elsődleges kulcs

  • unique_key - értéke 1, ha az oszlop egyszerű kulcs

  • multiple_key - értéke 1, ha az oszlop összetett kulcs része

  • numeric - értéke 1, ha az oszlop szám

  • blob - értéke 1, ha az oszlop BLOB típusú

  • type - az oszlop típusa

  • unsigned - értéke 1, ha az oszlop nem előjeles

  • zerofill - értéke 1, ha az oszlop nullával feltöltött

Példa 1. mysql_fetch_field()

<?php
mysql_connect ($host, $felhasznalo, $jelszo)
    or die ("Nem lehet csatlakozni az adatbázishoz");
$eredmeny = mysql_db_query ("adatbázis", "select * from table")
    or die ("Hibás kérés");
# oszlopinformáció lekérése
$i = 0;
while ($i < mysql_num_fields ($eredmeny)) {
    echo "Információ a $i. oszlopról:<BR>\n";
    $meta = mysql_fetch_field ($eredmeny);
    if (!$meta) {
        echo "Nem tudok információt lekérni<BR>gt;\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 ($eredmeny);
?>

Lásd még a mysql_field_seek() függvényt!

mysql_fetch_lengths

(PHP 3, PHP 4 )

mysql_fetch_lengths --  Az eredmény oszlopainak hosszáról nyújt információt

Leírás

array mysql_fetch_lengths ( resource result)

Egy tömbbel tér vissza. A tömb elemei az utolsó mysql_fetch_row() függvény által betöltött oszlopok hosszait tartalmazza. Hiba esetén FALSE értékkel tér vissza.

A mysql_fetch_lengths() függvény a mysql_fetch_row(), mysql_fetch_array() vagy a mysql_fetch_object() által visszaadott eredmény-oszlopok hosszát tárolja, illetve megmondja számmal indexelt tömb formájában.

Lásd még a mysql_fetch_row() függvényt!

mysql_fetch_object

(PHP 3, PHP 4 )

mysql_fetch_object --  Az eredmény következő sorát objektum formájában adja vissza

Leírás

object mysql_fetch_object ( resource result [, int result_type])

Egy objektummal tér vissza, amelynek tulajdonságai a betöltött sor oszlopait tartalmazzák. Ha nincs több sor, a függvény FALSE-at ad eredményül.

A mysql_fetch_object() függvény hasonló a mysql_fetch_array() függvényhez, egy különbséggel: nem tömböt, hanem objektumot ad vissza a függvény. Ez azt jelenti, hogy a mezőket csak a nevük alapján tudod elérni, mivel a számok nem érvényes tulajdonságnevek.

Az elhagyható result_type parméter egy konstans, ami MYSQL_ASSOC, MYSQL_NUM vagy MYSQL_BOTH lehet. Lásd még a mysql_fetch_array() függvényt, ha kíváncsi vagy az állandók leírására.

Sebesség szempontjából a mysql_fetch_array() függvénnyel azonos sebességű és majdnem olyan gyors, mint a mysql_fetch_row() függvény (a különbség elhanyagolható)

Példa 1. mysql_fetch_object() példa

<?php
mysql_connect ($host, $felhasznalo, $jelszo);
$eredmeny = mysql_db_query ("adatbázis", "select * from table");
while ($sor = mysql_fetch_object ($eredmeny)) {
    echo $sor-&gt;user_id;
    echo $sor-&gt;fullname;
}
mysql_free_result ($eredmeny);
?>

Lásd még a mysql_fetch_array() és a mysql_fetch_row() függvényt!

mysql_fetch_row

(PHP 3, PHP 4 )

mysql_fetch_row -- Az eredmény következő sorát adja vissza számmal indexelt tömb formájában

Leírás

array mysql_fetch_row ( resource result)

Egy számmal indexelt tömbbel tér vissza, ami a betöltött sorokat tartalmazza, vagy hamissal, ha nincs több sor.

A mysql_fetch_row() függvény betölt egy sort a megadott eredmény-azonosítójú eredményhalmazból. A sort (számmal indexelt) tömb formájában adja vissza. Az oszlopok számozása 0-tól indul.

A mysql_fetch_row() többszöri alkamazásával végig tudjuk járni az eredményhalmazt, mivel az mindig a következő sort tölti be, majd ha elfogytak a sorok, FALSE-at ad vissza.

Lásd még a mysql_fetch_array(), mysql_fetch_object(), mysql_data_seek(), mysql_fetch_lengths() és a mysql_result() függvényeket!

mysql_field_flags

(PHP 3, PHP 4 )

mysql_field_flags --  Adott eredmény adott mezejének flagjeit adja vissza.

Leírás

string mysql_field_flags ( resource result, int field_offset)

A mysql_field_flags() függvény az adott mező flagjeit adja vissza. A flagek egyszerű szavak, melyeket egyetlen szóköz választ el, így a kapott értéket feldolgozhatod a explode() függvény segítségével.

A MySQL a következő flageket támogatja (feltéve, hogy elég friss a használt MySQL, amit használsz): "not_null", "primary_key", "unique_key", "multiple_key", "blob", "unsigned", "zerofill", "binary", "enum", "auto_increment", "timestamp".

Kompatíbilitási okokból a mysql_fieldflags() függvény is használható, de nem javasolt.

mysql_field_len

(PHP 3, PHP 4 )

mysql_field_len --  A kérdezett mező hosszát adja vissza

Leírás

int mysql_field_len ( resource result, int field_offset)

A mysql_field_len() függvény a kérdezett mező hosszával tér vissza.

Kompatíbilitási okokból a mysql_fieldlen() függvény is használható, de nem ajánlott.

mysql_field_name

(PHP 3, PHP 4 )

mysql_field_name --  Adott mező nevét adja vissza

Leírás

string mysql_field_name ( resource result, int field_index)

A mysql_field_name() függvény az eredményben szereplő megadott indexű mező nevét adja vissza. A result paraméternek érvényes eredményazonosítónak kell lennie, a field_index paraméter pedig a mező indexe.

Megjegyzés: A field_index paraméter számozása 0-tól kezdődik.

Például a harmadik mező indexe 2, a negyedik mezőé pedig 3.

Példa 1. mysql_field_name() példa

// A felhasznalok tábla három mezőből áll:
//   azonosito
//   felhasznalonev
//   jelszo.

$eredmeny = mysql_db_query("felhasznalok", "select * from felhasznalok", $link);

echo mysql_field_name($eredmeny, 0) . "\n";
echo mysql_field_name($eredmeny, 2);

A fenti példa ay alábbi kimenetet eredményezi:
azonosito
jelszo

Kompatíbilitási okokból a mysql_fieldname() függvény is használható, de nem ajánlott.

mysql_field_seek

(PHP 3, PHP 4 )

mysql_field_seek --  Az eredménymutatót a kívánt pozícióba mozgatja

Leírás

int mysql_field_seek ( resource result, int field_offset)

A megadott helyre mozgatja az eredmény-mutatót. Ha a következő mysql_fetch_field() függvényhívás nem tartalmaz mező pozíciót, akkor a mysql_field_seek() függvény által visszaadott mezőpozíciót fogja visszaadni.

Lásd még a mysql_fetch_field() függvényt!

mysql_field_table

(PHP 3, PHP 4 )

mysql_field_table --  Visszaadja annak a táblának a nevét, melyben a megadott mező található

Leírás

string mysql_field_table ( resource result, int field_offset)

A függvény annak a táblának a nevével tér vissza, melyben a megadott mező szerepel.

Kompatíbilitási okokból a mysql_fieldtable() függvény is használható, de nem ajánlott.

mysql_field_type

(PHP 3, PHP 4 )

mysql_field_type --  Az eredmény adott mezejének típusát adja vissza

Leírás

string mysql_field_type ( resource result, int field_offset)

A mysql_field_type() függvény hasonló a mysql_field_name() függvényhez. A paraméterek megegyeznek, de a függvény a mező típusával tér vissza. A mezőtípus az "int", "real", "string", "blob" vagy hasonló, a MySQL dokumentációban található típusok közül való.

Példa 1. mysql mezőtípusok

<?php

mysql_connect ("localhost:3306");
mysql_select_db ("wisconsin");
$eredmeny = mysql_query ("SELECT * FROM onek");
$mezo = mysql_num_fields ($eredmeny);
$sor   = mysql_num_rows ($eredmeny);
$i = 0;
$table = mysql_field_table ($eredmeny, $i);
echo "A '$table' nevű táblának $mezo mezője és $sor sora van <BR>";
echo "A táblának az alábbi mezői vannak<BR>";
while ($i < $mezo) {
    $tipus = mysql_field_type  ($eredmeny, $i);
    $nev   = mysql_field_name  ($eredmeny, $i);
    $hossz = mysql_field_hossz ($eredmeny, $i);
    $flags = mysql_field_flags ($eredmeny, $i);
    echo "$tipus $nev $hossz $flags."<BR>";
    $i++;
}
mysql_close();

?>

Kompatíbilitási okokból a mysql_fieldtype() függvény is használható, de nem ajánlott.

mysql_free_result

(PHP 3, PHP 4 )

mysql_free_result -- Felszabadítja az eredmény által lefoglalt memóriát

Leírás

bool mysql_free_result ( resource result)

A mysql_free_result() függvény az összes result eredményazonosító által használt memóriát felszabadítja.

A mysql_free_result() függvényt csak akkor kell meghívnod, ha nagyon aggódsz a használt memória mennyisége miatt. A memória a php program végén úgyis felszabadul.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Kompatíbilitási okokból a mysql_freeresult() függvény is használható, de nem ajánlott.

mysql_get_client_info

(PHP 4 >= 4.0.5)

mysql_get_client_info -- MySQL kliens információ

Leírás

string mysql_get_client_info ( void )

A mysql_get_client_info() függvény a kliensprogram által használt könyvtár verziójáról ad információt.

A mysql_get_client_info() függvény a PHP 4.0.5-ös verziójában került a nyelvbe.

mysql_get_host_info

(PHP 4 >= 4.0.5)

mysql_get_host_info -- MySQL kiszolgáló információ

Leírás

string mysql_get_host_info ( [resource link_identifier])

A mysql_get_host_info() függvény egy karakterlánccal tér vissza, ami a link_identifier által használt kapcsolatról ad információt, például a kiszolgáló gép nevét. Ha a link_identifier paramétert elhagyjuk, akkor a legutóbb megnyitott kapcsolatról kapunk információt.

A mysql_get_host_info() függvény a PHP 4.0.5-ös változatával került a nyelvbe.

mysql_get_proto_info

(PHP 4 >= 4.0.5)

mysql_get_proto_info -- MySQL protokoll információ

Leírás

int mysql_get_proto_info ( [resource link_identifier])

A mysql_get_proto_info() függvény a link_identifier által használt protokoll verzióját adja vissza. Ha a link_identifier paramétert nem adod meg, akkor az utoljára használt kapcsolatról kapsz információt.

mysql_get_proto_info() függvény a PHP 4.0.5-ös változatával került a nyelvbe.

mysql_get_server_info

(PHP 4 >= 4.0.5)

mysql_get_server_info -- MySQL szerver információ

Leírás

int mysql_get_server_info ( [resource link_identifier])

A mysql_get_server_info() függvény a link_identifier-ban megadott kapcsolat által használt szerver verzióját adja. Ha nincs megadva link_identifier, akkor az utoljára használt kapcsolatról kapsz információt.

A mysql_get_server_info() függvény a PHP 4.0.5-ös változatával került a nyelvbe.

mysql_info

(PHP 4 >= 4.3.0)

mysql_info --  Get information about the most recent query

Description

string mysql_info ( [resource link_identifier])

mysql_info() returns detailed information about the last query using the given link_identifier. If link_identifier isn't specified, the last opened link is assumed.

mysql_info() returns a string for all statements listed below. For everything else, it returns FALSE. The string format depends on the given statement.

Példa 1. Relevant MySQL Statements

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
The numbers are only for illustrating purpose; their values will correspond to the query.

Megjegyzés: mysql_info() returns a non-FALSE value for the INSERT ... VALUES statement only if multiple value lists are specified in the statement.

See also mysql_affected_rows().

mysql_insert_id

(PHP 3, PHP 4 )

mysql_insert_id --  Visszaadja az előző INSERT művelet által előállított id-t

Leírás

int mysql_insert_id ( [resource link_identifier])

A mysql_insert_id() függvény az előző INSERT műveletben szereplő AUTO_INCREMENT tulajdonságú mező értékét adja vissza. Ha megadjuk link_identifier-t az adott linkkel rendelekező, ha nem adunk meg paramétert, az utolsó megnyitott linkhez tartozó eredményt szolgáltatja.

A mysql_insert_id() függvény 0-val tér vissza, ha az előző kérésben nem jött létre AUTO_INCREMENT érték. Ha szükséged van később az értékre, hívd meg a mysql_insert_id() függvényt rögtön az értéket generáló lekérdezés után!

Megjegyzés: A LAST_INSERT_ID() függvény értéke mindig az utoljára előállított AUTO_INCREMENT értéket tartalmazza, nem törlődik az értéke lekérdezések között.

Figyelem

A mysql_insert_id() függvény a MySQL C API függvény mysql_insert_id() visszatérési értékét long-gá (PHP-ban ez az int) konvertálja. Ha az AUTO_INCREMENT meződ mondjuk BIGINT típusú, akkor a mysql_insert_id() függvény rossz eredményt adhat vissza. Ezért inkább az SQL-be beépített LAST_INSERT_ID() MySQL függvényt használd!

mysql_list_dbs

(PHP 3, PHP 4 )

mysql_list_dbs --  Kilistázza a MySQL szerveren elérhető adatbázisokat

Leírás

resource mysql_list_dbs ( [resource link_identifier])

A mysql_list_dbs() függvény egy eredménymutatót ad vissza, ami a mysql démontól elérhető adatbázisokat tartalmazza. Használd a mysql_tablename() függvényt az eredménymutatón történő végigjárásra, vagy bármely függvényt az eredménytáblákra!

Példa 1. mysql_list_dbs() példa

<?php
$link = mysql_connect('localhost', 'nevem', 'titok');
$db_list = mysql_list_dbs($link);

while ($sor = mysql_fetch_object($db_list)) {
  echo $sor->Database . "\n";
}
?>

A fenti példa az alábbi kimenetet eredményezi.
adatbázis1
adatbázis2
adatbázis3
...

Megjegyzés: A fenti program egyszerűen bővíthető a mysql_fetch_row() függvénnyel vagy más hasonló függvénnyel.

Kompatíbilitási okokból a mysql_listdbs() függvény is használható, de nem javasolt.

Lásd még a mysql_db_name() függvényt!

mysql_list_fields

(PHP 3, PHP 4 )

mysql_list_fields -- Kilistázza a MySQL eredmény mezőit

Leírás

resource mysql_list_fields ( string database_name, string table_name [, resource link_identifier])

A mysql_list_fields() függvény az adott tábláról szolgáltat információt. A paraméterek az adatbázis és a tábla neve. A függvény egy eredmény-azonosító tér vissza, amit a mysql_field_flags(), mysql_field_len(), mysql_field_name(), és a mysql_field_type() függvényekkel hámozhatsz meg.

Példa 1. mysql_list_fields() példa

<?php
$link = mysql_connect('localhost', 'nevem', 'titok');

$mezo = mysql_list_fields("adatbázis1", "tabla1", $link);
$oszlop = mysql_num_fields($mezo);

for ($i = 0; $i < $oszlop; $i++) {
  echo mysql_field_name($mezo, $i) . "\n";;
}

A fenti példa az alábbi kimenetet eredményezi:
mezo1
mezo2
mezo3
...

Kompatíbilitási okokból a mysql_listfields() függvény is használható, de nem ajánlott.

mysql_list_processes

(PHP 4 >= 4.3.0)

mysql_list_processes -- List MySQL processes

Description

resource mysql_list_processes ( [resource link_identifier])

mysql_list_processes() returns a result pointer describing the current server threads.

Példa 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);
?>

The above example would produce the following output:

1 localhost test Processlist 0
4 localhost mysql sleep 5

See also mysql_thread_id().

mysql_list_tables

(PHP 3, PHP 4 )

mysql_list_tables -- Adott adatbázisbeli táblaneveket listázza

Leírás

resource mysql_list_tables ( string database [, resource link_identifier])

A mysql_list_tables() függvény veszi az adatbázisnevet, és egy eredmény-mutatót ad vissza, a mysql_db_query() függvényhez hasonlóan. A mysql_tablename() függvényt használhatod arra, hogy az eredmény-mutatóból, vagy más tábla eredményéből a tényleges táblaneveket megállapítsd.

Kompatíbilitási okokból a mysql_listtables() függvény is használható, de nem ajánlott.

mysql_num_fields

(PHP 3, PHP 4 )

mysql_num_fields -- Az eredményben szereplő mezők számát adja

Leírás

int mysql_num_fields ( resource result)

A mysql_num_fields() függvény az eredményhalmazban levő mezők számát adja vissza.

Lásd még a mysql_db_query(), mysql_query(), mysql_fetch_field() és a mysql_num_rows() függvényeket!

Kompatíbilitási okokból a mysql_numfields() függvény is használható, de nem ajánlott.

mysql_num_rows

(PHP 3, PHP 4 )

mysql_num_rows -- Az eredményben szereplő sorok számát adja vissza.

Leírás

int mysql_num_rows ( resource result)

A mysql_num_rows() függvény az eredményhalmazban szereplő sorok számát adja vissza. A függvény csak SELECT kérésre használható. Ha egy INSERT, UPDATE vagy DELETE kérésben érintett sorok számát szeretnéd megtudni, használd a DELETE, use mysql_affected_rows() függvényt!

Példa 1. mysql_num_rows() példa

<?php
$conn = mysql_connect("mlabdial", "juzer", "jelszo");
mysql_select_db("adatbázis",$conn);

$eredmeny = mysql_query("SELECT * FROM tabla1", $conn);
$sorok_szama = mysql_num_rows($eredmeny);

echo "$sorok_szama sor van";
?>

Lásd még a mysql_affected_rows(), mysql_connect(), mysql_select_db() és a mysql_query() függvényeket!

Kompatíbilitási okokból a mysql_numrows() függvény is használható, de nem javasolt.

mysql_pconnect

(PHP 3, PHP 4 )

mysql_pconnect --  Perzisztens kapcsolatot nyit meg a MySQL szerverhez

Leírás

resource mysql_pconnect ( [string server [, string username [, string password]]])

Visszatérési értéke: Egy pozitív MySQL perzisztens kapcsolatazonosító siker esetén, vagy FALSE, ha hiba történt.

A mysql_pconnect() függvény létrehoz egy kapcsolatot a MySQL szerverhez. Az elhagyott paraméterek az alábbi értékeket veszik fel: server = 'localhost:3306', username = annak a felhasználónak a neve, akié a szerver folyamat és végül: password = üres jelszó.

A server karakterlánc a port számát is tartalmazhatja; pl.: "hostname:port" vagy a socket teljes elérési útvonalát pl.: ":/path/to/socket". Ez persze csak a helyi gépen működik.

Megjegyzés: A ":port" használata a 3.0B4-es verzió óta lehetséges.

A ":/path/to/socket" forma használata a 3.0.10-es verzió óta támogatott.

A mysql_pconnect() függvény a mysql_connect() függvényhez hasonlóan működik, csupán két nagyobb különbség van:

Először is, a kapcsolat felvételekor a függvény először megpróbál egy (perzisztens) kapcsolatot találni, amely már nyitva van arra a hostra ugyanazzal a név/jelszó párossal. Ha talál ilyet, akkor ennek a kapocsnak az azonosítóját adja vissza és nem nyit újat.

Másodszor pedig a kapcsolat az SQL szerverhez nem kerül bezárásra, amikor a php program véget ér, hanem megmarad későbbi felhasználásra. (A mysql_close() függvény nem fogja neked lezárni a mysql_pconnect() függvénnyel megnyitott kapcsolatokat).

Az ilyen típusú kapcsolatot ezért hívják 'perzisztensnek'.

Megjegyzés: Ügyelj rá, hogy ezek a fajta kapcsolatok csak a PHP betölthető modulos változatában működnek. Lást a Perzisztens Adatbázis Kapcsolatok fejezetet további információkért!

mysql_ping

(PHP 4 >= 4.3.0)

mysql_ping -- Ping a server connection or reconnect if there is no connection

Description

bool mysql_ping ( [resource link_identifier])

mysql_ping() 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. mysql_ping() returns TRUE if the connection to the server is working, otherwise FALSE.

See also mysql_thread_id() and mysql_list_processes().

mysql_query

(PHP 3, PHP 4 )

mysql_query -- MySQL kérést küld a szervernek

Leírás

resource mysql_query ( string query [, resource link_identifier])

A mysql_query() függvény kérést küld a megadott kapcsolat-azonosítójú szerver aktív adatbázisához. Ha nem adsz meg link_identifier-t, akkor a legutóbb megnyitott kapcsolatot használja a függvény. Ha nincs nyitva ilyen kapcsolat, akkor a függvény megpróbál nyitni egyet, mintha a mysql_connect() függvényt hívtuk volna paraméterek nélkül.

Megjegyzés: A kérésnek nem szabad pontosvesszővel végződnie.

A SELECT utasításra alkalmazott mysql_query() függvény eredményazonosítóval vagy FALSE-sal tér vissza a kérés végrehajtásától függően. Egyéb esetekben mysql_query() függvény TRUE-val (nemnulla) vagy FALSE-szal tér vissza, attól függően, hogy a kérés teljesítése sikeres volt-e. A TRUE visszatérési érték azt jelenti, hogy a kérés szintaktikailag helyes volt, és lefuttatta a szerver. Az érintett sorok számáról azonban nem mond semmit. Előfordulhat ugyanis, hogy a kérés sikeresen lefutott, de nem érintett egyetlen sort sem, vagy az eredményben egyetlen sor sincs.

A következő kérés szintaktikailag rossz, igy a mysql_query() függvény meghiúsul és FALSE eredményt ad:

Példa 1. mysql_query()

<?php
$eredmeny = mysql_query ("SELECT * WHERE 1=1")
  or die ("Érvénytelen lekérdezés");
?>

Az alábbi kérés szemantikailag helytelen, ha nincs my_col nevű oszlop a my_tbl nevű táblában, így a mysql_query() meghiúsul és FALSE értékkel tér vissza.

Példa 2. mysql_query()

<?php
$eredmeny = mysql_query ("SELECT my_col FROM my_tbl")
    or die ("Érvénytelen kérés");
?>

A mysql_query() függvény akkor is meghiúsul és FALSE értékkel tér vissza, ha nincs megfelelő engedélyed a kérés által hivatkozott táblá(k)hoz.

Feltéve, hogy a kérés sikeres, meghívhatod a mysql_num_rows() függvényt, hogy kiderítsd, hány sort kaptál vissza a SELECT kérésedre, vagy a mysql_affected_rows() függvényt, hogy megtudd hány sort érintett a DELETE, NSERT, REPLACE vagy UPDATE kérésed.

SELECT kérés esetében a mysql_query() függvény egy új eredmény-azonosítót ad vissza, amit később a mysql_fetch_array() vagy más eredménytáblákkal foglalkozó függvénnyel használhatsz. Ha az eredményre már nincs szükség és memóriafóbiád van, akkor a mysql_free_result() függvénnyel a foglalt memóriát felszabadíthatod, normál esetben megvárod a program végét és a memória felszabadul.

Lásd még a mysql_num_rows(), mysql_affected_rows(), mysql_db_query(), mysql_unbuffered_query(), mysql_free_result(), mysql_fetch_array(), mysql_fetch_row(), mysql_fetch_assoc(), mysql_result(), mysql_select_db() és a mysql_connect() függvényeket!

mysql_real_escape_string

(PHP 4 >= 4.3.0)

mysql_real_escape_string --  Escapes special characters in a string for use in a SQL statement, taking into account the current charset of the connection.

Description

string mysql_real_escape_string ( string unescaped_string [, resource link_identifier])

This function will escape special characters in the unescaped_string, taking into account the current charset of the connection so that it is safe to place it in a mysql_query().

Megjegyzés: mysql_real_escape_string() does not escape % and _.

Példa 1. mysql_real_escape_string() example

<?php
$link = mysql_connect("localhost", "mysql_user", "mysql_password")
    or die("Could not connect: " . mysql_error());
$item = "Zak's and Derick's Laptop";
$escaped_item = mysql_real_escape_string($item, $link);
printf("Escaped string: %s\n", $escaped_item);
?>

The above example would produce the following output:

Escaped string: Zak\'s and Derick\'s Laptop

See also mysql_escape_string() and mysql_client_encoding().

mysql_result

(PHP 3, PHP 4 )

mysql_result -- Eredmény egy sorának lekérdezése

Leírás

mixed mysql_result ( resource result, int row [, mixed field])

A mysql_result() függvény egy MySQL eredményhalmaz egy elemét adja vissza. A mező paraméter a mező sorszáma vagy neve lehet vagy táblanév pont mezőnév (táblanév.mezőnév). Ha az oszlop más néven lett lekérve, mint ami az oszlop eredeti neve volt ('select izé as bigyó from...'), akkor használd azt a bizonyos 'más nevet'!

Amikor nagy eredményhalmazokkal dolgozol, akkor mérlegelned kell az olyan függvyének használatát, amelyek az egész eredménysort betöltik. Mivel ezek több cella tartalmát olvassák be egy függvényhívással, így ezek SOKKAL gyorsabbak, mint a mysql_result() függvény hívogatása. Említést érdemel még, hogy a numerikus index használata jóval gyorsabb, mint a mezőnév vagy a táblanév.mezőnév forma használata.

A mysql_result() függvényhívásokat más, ugyanazon eredményhalmazzal foglalkozó függvényhívásokkal nem illik (gyk. TILOS) együtt használni!

Ajánlott az alábbi, gyors [és programozóbarát] függvények használata: mysql_fetch_row(), mysql_fetch_array() és mysql_fetch_object().

mysql_select_db

(PHP 3, PHP 4 )

mysql_select_db -- Kiválaszt egy MySQL adatbázist

Leírás

bool mysql_select_db ( string database_name [, resource link_identifier])

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

A mysql_select_db() függvény az adott kapcsolat-azonosítójú szerverkapcsolat adatbázisát módosítja. Ha nincs kapcsolat-azonosító megadva, akkor az utoljára megnyitott kapcsolatban választ adatbázist. Ha ilyen sincs, akkor megpróbál a MySQL szerverhez kapcsolódni úgy, mintha a mysql_connect() függvény lett volna meghívva paraméterek nélkül.

Az összes további mysql_query() függvény az aktív adatbázison fog történni.

Lásd még a mysql_connect(), mysql_pconnect() és a mysql_query() függvényeket!

Kompatíbilitási okokból a mysql_selectdb() függvény is használható, de használata nem ajánlott.

mysql_stat

(PHP 4 >= 4.3.0)

mysql_stat -- Get current system status

Description

string mysql_stat ( [resource link_identifier])

mysql_stat() returns the current server status.

Megjegyzés: mysql_stat() currently only returns 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.

Példa 1. mysql_stat() example

<?php
$link = mysql_connect('localhost', "mysql_user", "mysql_password");
$status = explode('  ', mysql_stat($link));
print_r($status);
?>

The above example would produce the following output:

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
)

mysql_tablename

(PHP 3, PHP 4 )

mysql_tablename -- Egy tábla nevével tér vissza

Leírás

string mysql_tablename ( resource result, int i)

A mysql_tablename() függvény veszi a mysql_list_tables() függvény által visszaadott eredmény-mutatót és egy indexet, majd megmondja az oszlophoz tartozó tábla nevét. A mysql_num_rows() függvény használható arra, hogy megmondja hány tábla van az eredményhalmazban.

Példa 1. Mysql_tablename() példa

<?php
mysql_connect ("localhost:3306");
$eredmeny = mysql_list_tables ("wisconsin");
$i = 0;
while ($i < mysql_num_rows ($eredmeny)) {
    $tb_nevek[$i] = mysql_tablename ($eredmeny, $i);
    echo $tb_nevek[$i] . "<BR>";
    $i++;
}
?>

mysql_thread_id

(PHP 4 >= 4.3.0)

mysql_thread_id -- Return the current thread ID

Description

int mysql_thread_id ( [resource link_identifier])

mysql_thread_id() returns the current thread ID. If the connection is lost and you reconnect with mysql_ping(), the thread ID will change. This means you should not get the thread ID and store it for later. You should get it when you need it.

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

The above example would produce the following output:

current thread id is 73

See also mysql_ping() and mysql_list_processes().

mysql_unbuffered_query

(PHP 4 >= 4.0.6)

mysql_unbuffered_query --  SQL kérést küld küld a MySQL-nek anélkül, hogy az eredményt előfeldolgozná.

Leírás

resource mysql_unbuffered_query ( string query [, resource link_identifier])

A mysql_unbuffered_query() függvény a query SQL kérést küldi a MySQL-nek anélkül, hogy bármi módon betöltené, vagy pufferelni, mint azt a mysql_query() függvény teszi. Egyfelől, ez elég jelentős memória-megtakarítást tesz lehetővé az olyan SQL kérések számára, amelyek nagy eredményhalmazt állítanak elő. Másfelől, az eredményhalmazzal rögtön dolgozni kezdhetsz, amint az első sor megérkezik: nem kell megvárnod a teljes SQL kérés lefutását. Ha több adatbáziskapcsolatot használsz, meg kell mondanod a link_identifier paraméterben, hogy melyik kapcsolatra vonatkozik a kérés.

Megjegyzés: A mysql_unbuffered_query() függvénynek az a hátránya, hogy nem használhatod a mysql_num_rows() függvényt a visszakapott eredményhalmazra. A bufferelés nélküli SQL kérés minden sorát be kell töltened, mielőtt egy új SQL kérést küldesz a MySQL-nek.

Lásd még a mysql_query()függvényt!

LXV. Improved MySQL Extension

Bevezetés

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/

Documentation for MySQL can be found at http://www.mysql.com/documentation/.

Parts of this documentation included from MySQL manual with permissions of MySQL AB.


Követelmények

In order to have these functions available, you must compile PHP with support for the mysqli extension.

Megjegyzés: The mysqli extension is designed to work with the version 4.1.2 or above of MySQL. For previous versions, please see the MySQL extension documentation.


Telepítés

To install the mysqli extension for PHP, use the --with-mysqli=mysql_config_path configuration option where mysql_config_path represents the location of the mysql_config program that comes with MySQL versions greater than 4.1. Also, disable the standard MySQL extension (which is enabled by default) by also using the --without-mysql configuration option. If you would like to install the standard mysql extension along with the mysqli extension, the bundled libmysql library that comes with PHP cannot be used. Instead, use the client libraries installed by MySQL with versions below 4.1. This will force PHP to use the client libraries installed by MySQL thus avoiding any conflicts.


Futásidejű beállítások

Az alábbi függvények viselkedése befolyásolható a php.ini segítségével.

Táblázat 1. MySQLi Configuration Options

NameDefaultChangeable
mysqli.max_links"-1"PHP_INI_SYSTEM
mysqli.default_portNULLPHP_INI_ALL
mysqli.default_socketNULLPHP_INI_ALL
mysqli.default_hostNULLPHP_INI_ALL
mysqli.default_userNULLPHP_INI_ALL
mysqli.default_pwNULLPHP_INI_ALL

For further details and definitions of the above PHP_INI_* constants, see the chapter on configuration changes.

Here's a short explanation of the configuration directives.

mysqli.max_links integer

The maximum number of MySQL connections per process, including persistent connections.

mysqli.default_port string

The default TCP port number to use when connecting to the database server if no other port is specified. If no default is specified, the port will be obtained from the MYSQL_TCP_PORT environment variable, the mysql-tcp entry in /etc/services or the compile-time MYSQL_PORT constant, in that order. Win32 will only use the MYSQL_PORT constant.

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

The default password to use when connecting to the database server if no other password is specified. Doesn't apply in safe mode.


Előre definiált osztályok

mysqli

Represents a connection between PHP and a MySQL database.


Constructor

  • mysqli() - construct a new mysqli object


Methods

  • 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 MySQL 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 MySQL server

  • init - initializes mysqli object

  • info - retrieves information about the most recently executed query

  • kill - asks the server to kill a mysql thread

  • multi_query - performs multiple queries

  • more_results - checks if more results exists 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 a SQL query

  • query - performs a query

  • real_connect - attempts to open a connection to MySQL database server

  • escape_string - Escapes special characters in a string for use in a SQL statement, taking into account the current charset of the connection

  • rollback - rolls back the current transaction

  • select_db - selects the default database

  • set_opt - sets options

  • ssl_set - sets ssl parameters

  • stat - gets the current system status

  • 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


Properties

  • affected_rows - gets the number of affected rows in a previous MySQL operation

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


stmt

Represents a prepared statement.


Methods

  • 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

  • get_metadata - Retrieves a resultset from a prepared statement for metadata information

  • send_long_data - Sends data in chunks

  • store_result - Buffers complete resultset from a prepared statement


Properties

  • affected_rows - Returns affected rows from last statement execution

  • field_count - Returns number of fields for a given prepared statement

  • 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


result

Represents the result set obtained from a query against the database.


Methods

  • 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


Properties


Előre definiált állandók

Táblázat 2. MySQLi Constants

NameDescription
MYSQLI_READ_DEFAULT_GROUP (integer) Read options from the named group from `my.cnf' or the file specified with MYSQLI_READ_DEFAULT_FILE
MYSQLI_READ_DEFAULT_FILE (integer) Read options from the named option file instead of from my.cnf
MYSQLI_OPT_CONNECT_TIMEOUT (integer) Connect timeout in seconds
MYSQLI_OPT_LOCAL_INFILE (integer) Enables command LOAD LOCAL INFILE
MYSQLI_INIT_COMMAND (integer) Command to execute when connecting to MySQL server. Will automatically be re-executed when reconnecting.
MYSQLI_CLIENT_SSL (integer) 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 (integer) Use compression protocol
MYSQLI_CLIENT_INTERACTIVE (integer) 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 (integer) Allow spaces after function names. Makes all functions names reserved words.
MYSQLI_CLIENT_NO_SCHEMA (integer) Don't allow the db_name.tbl_name.col_name syntax.
MYSQLI_CLIENT_MULTI_QUERIES (integer)  
MYSQLI_STORE_RESULT (integer) For using buffered resultsets
MYSQLI_USE_RESULT (integer) For using unbuffered resultsets
MYSQLI_ASSOC (integer) Columns are returned into the array having the fieldname as the array index.
MYSQLI_NUM (integer) Columns are returned into the array having an enumerated index.
MYSQLI_BOTH (integer) Columns are returned into the array having both a numerical index and the fieldname as the associative index.
MYSQLI_NOT_NULL_FLAG (integer) Indicates that a field is defined as NOT NULL
MYSQLI_PRI_KEY_FLAG (integer) Field is part of a primary index
MYSQLI_UNIQUE_KEY_FLAG (integer) Field is part of an unique index.
MYSQLI_MULTIPLE_KEY_FLAG (integer) Field is part of an index.
MYSQLI_BLOB_FLAG (integer) Field is defined as BLOB
MYSQLI_UNSIGNED_FLAG (integer) Field is defined as UNSIGNED
MYSQLI_ZEROFILL_FLAG (integer) Field is defined as ZEROFILL
MYSQLI_AUTO_INCREMENT_FLAG (integer) Field is defined as AUTO_INCREMENT
MYSQLI_TIMESTAMP_FLAG (integer) Field is defined as TIMESTAMP
MYSQLI_SET_FLAG (integer) Field is defined as SET
MYSQLI_NUM_FLAG (integer) Field is defined as NUMERIC
MYSQLI_PART_KEY_FLAG (integer) Field is part of an multi-index
MYSQLI_GROUP_FLAG (integer) Field is part of GROUP BY
MYSQLI_TYPE_DECIMAL (integer) Field is defined as DECIMAL
MYSQLI_TYPE_TINY (integer) Field is defined as TINYINT
MYSQLI_TYPE_SHORT (integer) Field is defined as INT
MYSQLI_TYPE_LONG (integer) Field is defined as MEDIUMINT
MYSQLI_TYPE_FLOAT (integer) Field is defined as FLOAT
MYSQLI_TYPE_DOUBLE (integer) Field is defined as double
MYSQLI_TYPE_NULL (integer) Field is defined as DEFAULT NULL
MYSQLI_TYPE_TIMESTAMP (integer) Field is defined as TIMESTAMP
MYSQLI_TYPE_LONGLONG (integer) Field is defined as BIGINT
MYSQLI_TYPE_INT24 (integer)  
MYSQLI_TYPE_DATE (integer) Field is defined as DATE
MYSQLI_TYPE_TIME (integer) Field is defined as TIME
MYSQLI_TYPE_DATETIME (integer) Field is defined as DATETIME
MYSQLI_TYPE_YEAR (integer) Field is defined as YEAR
MYSQLI_TYPE_NEWDATE (integer) Field is defined as DATE
MYSQLI_TYPE_ENUM (integer) Field is defined as ENUM
MYSQLI_TYPE_SET (integer) Field is defined as SET
MYSQLI_TYPE_TINY_BLOB (integer) Field is defined as TINYBLOB
MYSQLI_TYPE_MEDIUM_BLOB (integer) Field is defined as MEDIUMBLOB
MYSQLI_TYPE_LONG_BLOB (integer) Field is defined as LONGBLOB
MYSQLI_TYPE_BLOB (integer) Field is defined as BLOB
MYSQLI_TYPE_STRING (integer) Field is defined as VARCHAR
MYSQLI_TYPE_CHAR (integer) Field is defined as CHAR
MYSQLI_TYPE_GEOMETRY (integer) Field is defined as GEOMETRY
MYSQLI_BIND_STRING (integer) Bind variable has type STRING
MYSQLI_BIND_INT (integer) Bind variable has type INT
MYSQLI_BIND_DOUBLE (integer) Bind variable has type DOUBLE
MYSQLI_BIND_SEND_DATA (integer) Sending bind variable in chunks
MYSQLI_NEED_DATA (integer) More data available for bind variable
MYSQLI_NO_DATA (integer) No more data available for bind variable
Tartalom
mysqli_affected_rows -- Gets the number of affected rows in a previous MySQL operation
mysqli_autocommit -- Turns on or off auto-commiting database modifications
mysqli_bind_param -- Binds variables to a prepared statement as parameters
mysqli_bind_result -- Binds variables to a prepared statement for result storage
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_connect -- Open a new connection to the MySQL server
mysqli_data_seek -- Adjusts the result pointer to an arbitary row in the result
mysqli_debug -- Performs debugging operations
mysqli_disable_reads_from_master -- 
mysqli_dump_debug_info -- Dump debugging information into the log
mysqli_errno -- Returns the error code for the most recent function call
mysqli_error -- Returns a string description of the last error
mysqli_execute -- Executes a prepared Query
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_field_direct --  Fetch meta-data for a single field
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_fetch_lengths -- Returns the lengths of the columns of the current row in the result set
mysqli_fetch_object -- Returns the current row of a result set as an object
mysqli_fetch_row -- Get a result row as an enumerated array
mysqli_fetch --  Fetch results from a prepared statement into the bound variables
mysqli_field_count -- Returns the number of columns for the most recent query
mysqli_field_seek --  Set result pointer to a specified field offset
mysqli_field_tell --  Get current field offset of a result pointer
mysqli_free_result -- Frees the memory associated with a result
mysqli_get_client_info -- Returns the MySQL client version as a string
mysqli_get_host_info -- Returns a string representing the type of connection used
mysqli_get_proto_info -- Returns the version of the MySQL protocol used
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_info -- Retrieves information about the most recently executed query
mysqli_init --  Initializes MySQLi and returns an object for use with mysqli_real_connect
mysqli_insert_id -- Returns the auto generated id used in the last query
mysqli_kill -- Asks the server to kill a MySQL thread
mysqli_num_fields --  Get the number of fields in a result
mysqli_num_rows --  Gets the number of rows in a result
mysqli_options -- set options
mysqli_param_count -- Returns the number of parameter for the given statement
mysqli_ping --  Pings a server connection, or tries to reconnect if the connection has gone down.
mysqli_prepare --  Prepare a SQL statement for execution
mysqli_profiler -- 
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 a SQL statement, taking into account the current charset of the connection
mysqli_real_query -- Execute an SQL query
mysqli_rollback -- Rolls back current transaction
mysqli_select_db -- Selects the default database for database queries
mysqli_send_long_data -- Send data in blocks
mysqli_send_query -- 
mysqli_ssl_set -- Used for establishing secure connections using SSL.
mysqli_stat -- Gets the current system status
mysqli_stmt_affected_rows -- Returns the total number of rows changed, deleted, or inserted by the last executed statement
mysqli_stmt_close -- Closes a prepared 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_store_result -- Transfers a result set from a prepared statement
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_affected_rows

(PHP 5 CVS only)

mysqli_affected_rows

(no version information, might be only in CVS)

mysqli->affected_rows -- Gets the number of affected rows in a previous MySQL operation

Description

Procedural style:

mixed mysqli_affected_rows ( object link)

Object oriented style (property):

class mysqli {

mixed affected_rows

}

mysqli_affected_rows() returns the number of rows affected by the last INSERT, UPDATE, or DELETE query associated with the provided link parameter. If the last query was invalid, this function will return -1.

Megjegyzés: For SELECT statements mysqli_affected_rows() works like mysqli_num_rows().

The mysqli_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 mysqli_num_rows() function instead.

Return Values

An integer greater than zero indicates the number of rows affected or retrieved. Zero indicates that no records where updated for an UPDATE statement, no rows matched the WHERE clause in the query or that no query has yet been executed. -1 indicates that the query returned an error.

Megjegyzés: If the number of affected rows is greater than maximal int value, the number of affected rows will be returned as a string.

Example

Példa 1. Example for affected rows

<?php
     /*
     +-----------------------------------------------------------+
     | file: mysqli_affected_rows.php                            |
     +-----------------------------------------------------------+
     | modifies some datasets and returns number of affected     |
     | rows                                                      |
     +-----------------------------------------------------------+
     */
     
     /* ---- Procedural style ---- */
     $link = mysqli_connect("localhost", "my_user", "my_password", "test")
     or die("Can't connect to MySQL server on localhost");

     /* create table and insert some data */
     mysqli_query($link, "DROP TABLE IF EXISTS affected_rows");
     mysqli_query($link, "CREATE TABLE affected_rows (a int)");
     mysqli_query($link, "INSERT INTO affected_rows VALUES (1),(2),(3),(4)");

     /* update values and retrieve number of affected rows */
     mysqli_query($link, "UPDATE affected_rows SET a=5 WHERE a=1");
     printf("Affected rows (update): %d\n", mysqli_affected_rows($link));

     /* delete rows and retrieve number of affected_rows */
     mysqli_query($link, "DELETE FROM affected_rows WHERE a < 4");
     printf("Affected rows (delete): %d\n", mysqli_affected_rows($link));

     /* select all rows and retrieve number of affected_rows */
     mysqli_query($link, "SELECT a FROM affected_rows");
     printf("Affected rows (select): %d\n", mysqli_affected_rows($link));

     mysqli_close($link);

     /* ---- Object oriented style ----*/
     $mysqli = new mysqli("localhost", "my_user", "my_password", "test");

     if (mysqli_connect_errno()) {
     printf("Connect failed: %s\n", mysqli_connect_error());
     exit();
     }

     /* create table and insert some data */
     $mysqli->query("DROP TABLE IF EXISTS affected_rows");
     $mysqli->query("CREATE TABLE affected_rows (a int)");
     $mysqli->query("INSERT INTO affected_rows VALUES (1),(2),(3),(4)");

     /* update values and retrieve number of affected rows */
     $mysqli->query("UPDATE affected_rows SET a=5 WHERE a=1");
     printf("Affected rows (update): %d\n", $mysqli->affected_rows);

     /* delete rows and retrieve number of affected_rows */
     $mysqli->query("DELETE FROM affected_rows WHERE a < 4");
     printf("Affected rows (delete): %d\n", $mysqli->affected_rows);

     /* select all rows and retrieve number of affected_rows */
     $mysqli->query("SELECT a FROM affected_rows");
     printf("Affected rows (select): %d\n", $mysqli->affected_rows);

     $mysqli->close();
     ?>

mysqli_autocommit

(PHP 5 CVS only)

mysqli_autocommit

(no version information, might be only in CVS)

mysqli->auto_commit -- Turns on or off auto-commiting database modifications

Description

Procedural style:

bool mysqli_autocommit ( object link, bool mode)

Object oriented style (method)

class mysqli {

bool auto_commit ( bool mode)

}

mysqli_autocommit() is used to turn on or off auto-commit mode on queries for the database connection represented by the link object.

Megjegyzés: mysqli_autocommit() doesn't work with non transactional table types (like MyISAM or ISAM).

To determine the current state of autocommit use the SQL command 'SELECT @@autocommit'.

Return values

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Example

Példa 1. Using the mysqli_autocommit function

<?php
/*
  +-----------------------------------------------------------+
  | file: mysqli_autocommit.php                               |
  +-----------------------------------------------------------+
  | connects to MySQL server on localhost, turns autocommit   |
  | on and retrieves autocommit variable                      |
  +-----------------------------------------------------------+
*/
   
   /* ---- Procedural style ---- */
   $link = mysqli_connect("localhost", "my_user", "my_password", "test")
      or die("Can't connect to MySQL server on localhost");

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

   mysqli_close($link);

   /* ---- Object oriented style ----*/
   $mysqli = new mysqli("localhost", "my_user", "my_password", "test");

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

   $mysqli->close();
?>

?>

mysqli_bind_param

(PHP 5 CVS only)

mysqli_bind_param

(no version information, might be only in CVS)

stmt->bind_param -- Binds variables to a prepared statement as parameters

Description

Procedural style:

bool mysqli_bind_param ( object stmt, array types, mixed var1 [, mixed var2, ...])

Object oriented style (method):

class stmt {

bool bind_param ( array types, mixed var1 [, mixed var2, ...])

}

mysql_bind_param() is used to bind variables for the parameter markers in the SQL statement that was passed to mysql_prepare(). The array types specifies the types for the diffrent bind variables. Valid array values are MYSQLI_BIND_INT, MYSQLI_BIND_DOUBLE, MYSQLI_BIND_STRING and MYSQLI_SEND_DATA.

Megjegyzés: If data size of a variable exceeds max. allowed package size (max_allowed_package), you have to specify MYSQLI_SEND_DATA and use mysqli_send_long_data() to send the data in packages.

The number of variables and array values must match the number of parameters in the statement.

Return values

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Example

Példa 1. Prepared statements

<?php

    /* --- procedural style --- */
    $link = mysqli_connect("localhost", "mysql_user", "mysql_password", "mydb") or
        die("Could not connect: " . mysqli_connect_error());

    /* create mytable */
    mysqli_query($link, "CREATE TABLE mytable (a int, b int, c varchar(30))");
    
    /* prepare statement and bind variables for insert statements */
    $stmt = mysqli_prepare($link, "INSERT INTO mytable VALUES (?, ?, ?)");
    mysqli_bind_param($stmt, array(MYSQLI_BIND_INT, MYSQLI_BIND_INT,
                      MYSQLI_BIND_STRING), $a, $b, $c);

    $a = 1;
    $b = 2;
    $c = "I prefer OpenSource software";

    /* execute prepared statement */
    mysqli_execute($stmt);

    /* close statement and connection */
    mysqli_close_stmt(stmt);
    mysqli_close(link);

    /* --- object oriented style --- */
    $mysql = new mysqli("localhost", "mysql_user", "mysql_password", "mydb");

    /* create mytable */
    $mysql->query("CREATE TABLE mytable (a int, b int, c varchar(30))");
    
    /* prepare statement and bind parameters */
    $stmt = $mysql->prepare("INSERT INTO mytable VALUES (?, ?, ?)");
    $stmt->bind_param(array(MYSQLI_BIND_INT, MYSQLI_BIND_INT,
                      MYSQLI_BIND_STRING), $a, $b, $c);

    $a = 1;
    $b = 2;
    $c = "I prefer opensource software";

    /* execute prepared statement */
    $stmt->execute();

    /* close statement and connection */
    $stmt->close();
    $mysql->close();
?>

mysqli_bind_result

(PHP 5 CVS only)

mysqli_bind_result

(no version information, might be only in CVS)

stmt->bind_result -- Binds variables to a prepared statement for result storage

Description

Procedural style:

bool mysqli_bind_result ( object stmt, mixed var1 [, mixed var2, ...])

Object oriented style (method):

class stmt {

bool bind_result ( mixed var1 [, mixed var2, ...])

}

mysqli_bind_result() is used to associate (bind) columns in the result set to variables. When mysqli_fetch() is called to fetch data, the MySQL client/server protocol places the data for the bound columns into the specified variables var1, ....

Megjegyzés: Note that all columns must be bound prior to calling mysqli_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_fetch() is called.

Return values

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

mysqli_change_user

(PHP 5 CVS only)

mysqli_change_user

(no version information, might be only in CVS)

mysqli->change_user -- Changes the user of the specified database connection

Description

Procedural style:

bool mysqli_change_user ( object link, string user, string password, string database)

Object oriented style (method):

class mysqli {

bool change_user ( string user, string password, string database)

}

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

If desired, the NULL value may be passed in place of the database parameter resulting in only changing the user and not selecting a database. To select a database in this case use the mysqli_select_db() function.

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.

Megjegyzés: 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.

Return Values

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Example

Példa 1. Using the mysqli_change_user function

<?php
                            
    /* Open a connection as foo@localhost and select foo_db */
    $link = mysqli_connect("localhost", "foo", "pass");
    mysqli_select_db("foo_db");
                                         
    /* Change user to bar@localhost and default database to bar_db */
    mysqli_change_user($link, "bar", "otherpass", "bar_db");

?>

mysqli_character_set_name

(PHP 5 CVS only)

mysqli_character_set_name

(no version information, might be only in CVS)

mysqli->character_set_name -- Returns the default character set for the database connection

Description

Procedural style:

string mysqli_character_set_name ( object link)

Object oriented style (method):

class mysqli {

string character_set_name ( void )

}

Returns the current character set for the database connection specified by the link parameter.

Return values

The default character set for the current connection

Example

Példa 1. Using the mysqli_character_set_name function

<?php
                                                     
    /* Open a connection */
    $link = mysqli_connect("localhost", "username", "password");
                                                                              
    /* Print current character set */
    $charset = mysqli_character_set_name($link);
    printf ("Current character set is %s\n",$charset);

?>

mysqli_close

(PHP 5 CVS only)

mysqli_close

(no version information, might be only in CVS)

mysqli->close -- Closes a previously opened database connection

Description

Procedural style:

bool mysqli_close ( object link)

Object oriented style (method):

class mysqli {

bool close ( void )

}

The mysqli_close() function closes a previously opened database connection specified by the link parameter.

Return values

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

mysqli_commit

(PHP 5 CVS only)

mysqli_commit

(no version information, might be only in CVS)

mysqli->commit -- Commits the current transaction

Description

Procedural style:

bool mysqli_commit ( object link)

Object oriented style (method)

class mysqli {

bool commit ( void )

}

Commits the current transaction for the database specified by the link parameter.

Return values

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

mysqli_connect

(PHP 5 CVS only)

mysqli_connect

(no version information, might be only in CVS)

mysqli() -- Open a new connection to the MySQL server

Description

Procedural style

object mysqli_connect ( [string hostname [, string username [, string passwd [, string dbname [, int port [, string socket]]]]]])

Object oriented style (constructor):

class mysqli {

( string hostnamestring usernamestring passwdstring dbnameint portstring socket]]]]]])

}

The mysqli_connect() function attempts to open a connection to the MySQL Server running on host which can be either a hostname 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. If successful, the mysqli_connect() will return an object representing the connection to the database, or FALSE on failure.

The username and password parameters specify the username and password under which to connect to the MySQL server. If the password is not provided (the NULL value is passed), 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).

The dbname parameter if provided will specify the default database to be used when performing queries.

The port and socket parameters are used in conjunction with the hostname parameter to further control how to connect to the database server. The port parameter specifies the port number to attempt to connect to the MySQL server on, while the socket parameter specifies the socket or named pipe that should be used.

Megjegyzés: 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.

Return values

Returns a object which represents the connection to a MySQL Server or FALSE if the connection failed.

Example

Példa 1. Using the mysqli_connect function

<?php
/*
  +-----------------------------------------------------------+
  | file: mysqli_connect.php                                  |
  +-----------------------------------------------------------+
  | connects to MySQL server on localhost and prints host     |
  | information                                               |
  +-----------------------------------------------------------+
*/
   
   /* ---- Procedural style ---- */
   $link = mysqli_connect("localhost", "my_user", "my_password", "test")
      or die("Can't connect to MySQL server on localhost");

   printf("Host information: %s\n", mysqli_get_host_info($link));

   mysqli_close($link);

   /* ---- Object oriented style ----*/
   $mysqli = new mysqli("localhost", "my_user", "my_password", "test");

   if (mysqli_connect_errno()) {
      printf("Connect failed: %s\n", mysqli_connect_error());
      exit();
   }

   printf("Host information: %s\n", $mysqli->host_info);

   $mysqli->close();
?>

mysqli_data_seek

(PHP 5 CVS only)

mysqli_data_seek

(no version information, might be only in CVS)

result->data_seek -- Adjusts the result pointer to an arbitary row in the result

Description

Procedural style:

bool mysqli_data_seek ( object result, int offset)

Object oriented style (method):

class result {

bool data_seek ( int offset)

}

The mysqli_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..mysqli_num_rows() - 1).

Megjegyzés: This function can only be used with unbuffered results attained from the use of the mysqli_store_result() or mysqli_query() functions.

Return values

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Example

Példa 1. Using the mysqli_data_seek function

<?php
                                                                              
    /* Open a connection */
    $link = mysqli_connect("localhost", "username", "password");
    mysqli_select_db("mydb");
                                                                                                               
    /* Get some rows and store them */
    $query = "SELECT DINSTINCT name FROM employee ORDER BY name";
    $result = mysqli_query($query) or die(mysqli_error());

    $rows = mysqli_store_result($result);

    $total = mysqli_num_fields($rows);

    if ($total > 0) { // there is at least one row
        /* Get the last employee */
        mysqli_data_seek($rows, mysqli_num_rows($result) -1);
        $employee = mysqli_fetch_row($rows);
        printf ("Employee name : %s\n", $employee[0]);
    }
        
    mysqli_free_result($rows);
    mysqli_close($link);

?>

mysqli_debug

(PHP 5 CVS only)

mysqli_debug -- Performs debugging operations

Description

void mysqli_debug ( string debug)

The mysqli_debug() function is used to perform debugging operations using the Fred Fish debugging library. The debug parameter is a string representing the debugging operation to perform.

Return values

mysqli_debug() doesn't return any value.

Example

Példa 1. Generating a Trace File

<?php
    
    /* Create a trace file in '/tmp/client.trace' on the local (client) machine: */
    mysqli_debug("d:t:0,/tmp/client.trace");
    
?>

mysqli_disable_reads_from_master

(PHP 5 CVS only)

mysqli_disable_reads_from_master -- 

Description

void mysqli_disable_reads_from_master ( resource link)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mysqli_dump_debug_info

(PHP 5 CVS only)

mysqli_dump_debug_info -- Dump debugging information into the log

Description

bool mysqli_dump_debug_info ( object link)

This function is designed to be executed by an user with the SUPER privlege and is used to dump debugging information into the log for the MySQL Server relating to the connection specified by the link parameter.

Return values

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

See also

mysqli_debug().

mysqli_errno

(PHP 5 CVS only)

mysqli_errno

(no version information, might be only in CVS)

mysql->errno -- Returns the error code for the most recent function call

Description

Procedural style:

int mysqli_errno ( object link)

Object oriented style (property):

class mysqli {

int errno

}

The mysqli_errno() function will return the last error code for the most recent MySQLi function call that can succeed or fail with respect to the database link defined by the link parameter. If no errors have occured, this function will return zero.

Megjegyzés: 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.

Return values

An error code value for the last call, if it failed. zero means no error occurred.

mysqli_error

(PHP 5 CVS only)

mysqli_error -- Returns a string description of the last error

Description

Procedural style:

string mysqli_error ( object link)

Object oriented style (property)

class mysqli {

string error

}

The mysqli_error() function is identical to the corresponding mysqli_errno() function in every way, except instead of returning an integer error code the mysqli_error() function will return a string representation of the last error to occur for the database connection represented by the link parameter. If no error has occured, this function will return an empty string.

Return values

A string that describes the error. An empty string if no error occurred.

Example

Példa 1. Using the mysqli_error function

<?php
                                                                         
    /* Fail to open a connection */
    $host = "no_such_host";
    $link = mysqli_connect($host, "username", "password") or 
            die("Couldn't connect : " . mysqli_error());
                                                                                                          
?>

mysqli_execute

(PHP 5 CVS only)

mysqli_execute

(no version information, might be only in CVS)

stmt->execute -- Executes a prepared Query

Description

Procedural style:

bool mysqli_execute ( object stmt)

Object oriented style (method):

class mysql {

bool execute ( void )

}

The mysqli_execute() function executes a query that has been previously prepared using the mysqli_prepare() function represented by the stmt object. 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 mysqli_stmt_affected_rows() function. Likewise, if the query yields a result set the mysqli_fetch() function is used.

Megjegyzés: When using mysqli_execute(), the mysqli_fetch() function must be used to fetch the data prior to preforming any additional queries.

Return values

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Example

Példa 1. Using the mysqli_execute function

<?php
    
    /* Open a connection */
    $link = mysqli_connect("localhost", "user", "pass");
    mysqli_select_db("mydb");
    
    /* Turn on autocommit */
    mysqli_autocommit($link, true);
    
    /* Prepare an insert statement */
    $query = "INSERT INTO mytable VALUES(?, ?)";
    $stmt = mysqli_prepare($link, $query);
    
    $value_one = "hello";
    $value_two = "world";
    
    mysqli_bind_param($link, $value_one, $value_two);
    
    /* Execute the statement */
    mysqli_execute($stmt);
    
    /* Return the affected rows for the statement */
    $affected_rows = mysqli_stmt_affected_rows($stmt);
    
    /* Close the statement */
    
    mysqli_stmt_close($stmt);
    
    echo "The total affected rows was $affected_rows";
    
?>

mysqli_fetch_array

(PHP 5 CVS only)

mysqli_fetch_array

(no version information, might be only in CVS)

result->fetch_array -- Fetch a result row as an associative, a numeric array, or both.

Description

Procedural style:

mixed mysqli_fetch_array ( object result [, int resulttype])

Object oriend style (method):

class result {

mixed fetch_array ( [int resulttype])

}

Returns an array that corresponds to the fetched row or FALSE if there are no more rows for the database connection represented by the link 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.

Megjegyzés: Field names returned by this function are case-sensitive.

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 result_type 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 default the mysqli_fetch_array() function will assume MYSQLI_BOTH for this parameter.

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.

Return values

Returns an array that corresponds to the fetched row or FALSE if there are no more rows in resultset.

Example

Példa 1. mysqli_fetch_array with MYSQLI_NUM

<?php
    mysqli_connect("localhost", "mysql_user", "mysql_password") or
        die("Could not connect: " . mysqli_error());
    mysqli_select_db("mydb");

    $result = mysqli_query("SELECT id, name FROM mytable");

    while ($row = mysqli_fetch_array($result, MYSQLI_NUM)) {
        printf ("ID: %s  Name: %s", $row[0], $row[1]);  
    }

    mysqli_free_result($result);
?>

Példa 2. mysqli_fetch_array with MYSQLI_ASSOC

<?php
    mysqli_connect("localhost", "mysql_user", "mysql_password") or
        die("Could not connect: " . mysqli_error());
    mysqli_select_db("mydb");

    $result = mysqli_query("SELECT id, name FROM mytable");

    while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
        printf ("ID: %s  Name: %s", $row["id"], $row["name"]);
    }

    mysqli_free_result($result);
?>

Példa 3. mysqli_fetch_array with MYSQLI_BOTH

<?php
    mysqli_connect("localhost", "mysql_user", "mysql_password") or
        die("Could not connect: " . mysqli_error());
    mysqli_select_db("mydb");

    $result = mysqli_query("SELECT id, name FROM mytable");

    while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
        printf ("ID: %s  Name: %s", $row[0], $row["name"]);
    }

    mysqli_free_result($result);
?>

mysqli_fetch_assoc

(PHP 5 CVS only)

mysqli_fetch_assoc

(no version information, might be only in CVS)

mysqli->fetch_assoc -- Fetch a result row as an associative array

Description

Procedural style:

array mysqli_fetch_assoc ( object result)

Object oriend style (method):

class result {

array fetch_assoc ( void )

}

Returns an associative array that corresponds to the fetched row or FALSE if there are no more rows.

The mysqli_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 in the result set have the same column name, the associative array returned by the mysqli_fetch_assoc() function will contain the value of the last column of that name. If you must work with result sets with this properity, the mysqli_fetch_row() should be used which returns an numerically-indexed array instead.

Megjegyzés: Field names returned by this function are case-sensitive.

Return values

Returns an array that corresponds to the fetched row or FALSE if there are no more rows in resultset.

Example

Példa 1. An expanded mysqli_fetch_assoc() example

<?php

    $conn = mysqli_connect("localhost", "mysql_user", "mysql_password");
    
    if (!$conn) {
        echo "Unable to connect to DB: " . mysqli_error();
        exit;
    }
    
    if (!mysqli_select_db("mydbname")) {
        echo "Unable to select mydbname: " . mysqli_error();
        exit;
    }
    
    $sql = "SELECT id as userid, fullname, userstatus 
            FROM   sometable
            WHERE  userstatus = 1";

    $result = mysqli_query($sql);

    if (!$result) {
        echo "Could not successfully run query ($sql) from DB: " . mysqli_error();
        exit;
    }
    
    if (mysqli_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 = mysqli_fetch_assoc($result)) {
        echo $row["userid"];
        echo $row["fullname"];
        echo $row["userstatus"];
    }
	    
    mysqli_free_result($result);

?>

mysqli_fetch_field_direct

(PHP 5 CVS only)

mysqli_fetch_field_direct

(no version information, might be only in CVS)

result->fetch_field_direct --  Fetch meta-data for a single field

Description

Procedural style:

mixed mysqli_fetch_field_direct ( object result, int fieldnr)

Object oriented style (method):

class result {

mixed fetch_field_direct ( int fieldnr)

}

mysqli_fetch_field_direct() returns an associative array which contains field definition informations from specified resultset. The value of fieldnr must be in the range from 0 to number of fields - 1.

Return values

Returns an associative array which contains field definition informations or FALSE if no field information for specified fieldnr is available.

mysqli_fetch_field

(PHP 5 CVS only)

mysqli_fetch_field

(no version information, might be only in CVS)

result->fetch_field -- Returns the next field in the result set

Description

Procedural style:

mixed mysqli_fetch_field ( object result)

Object oriented style (method):

class result {

mixed fetch_field ( void )

}

The mysqli_fetch_field() function is used to return the attributes of the next column in the result set represented by the result parameter as an object. When executed this function will return an object containing the attributes of the current column or FALSE if there are no more columns in the result set.

Táblázat 1. Object attributes

AttributeDescription
nameThe name of the column
orgnameOriginal column name if an alias was specified
tableThe name of the table this field belongs to (if not calculated)
orgtableOriginal table name if an alias was specified
defThe default value for this field, represented as a string
max_lengthThe maximum width of the field for the result set.
flagsAn integer representing the bit-flags for the field.
typeThe data type used for this field
decimalsThe number of decimals used (for integer fields)

Return values

Returns an object which contains field definition informations or FALSE if no field information is available.

mysqli_fetch_fields

(PHP 5 CVS only)

mysqli_fetch_fields

(no version information, might be only in CVS)

result->fetch_fields -- Returns an array of objects representing the fields in a result set

Description

Procedural Style:

mixed mysqli_fetch_fields ( object result)

Object oriented style (method):

class result {

mixed fetch_fields ( int fieldnr)

}

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. For a description of the attributes of each object and their meaning, see the mysqli_fetch_field() function.

Return values

Returns an array of objects which contains field definition informations or FALSE if no field information is available.

mysqli_fetch_lengths

(PHP 5 CVS only)

mysqli_fetch_lengths

(no version information, might be only in CVS)

result->fetch_lengths -- Returns the lengths of the columns of the current row in the result set

Description

Procedural style:

mixed mysqli_fetch_lengths ( object result)

Object oriented style (property):

class result {

mixed fetch_lengths

}

The mysqli_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 or FALSE on failure.

Return values

An array of integers representing the size of each column (not including any terminating null characters). FALSE if an error occurred.

mysql_fetch_lengths() is valid only for the current row of the result set. It returns FALSE if you call it before calling mysql_fetch_row/array/object or after retrieving all rows in the result.

mysqli_fetch_object

(PHP 5 CVS only)

mysqli_fetch_object

(no version information, might be only in CVS)

result->fetch_object -- Returns the current row of a result set as an object

Description

Procedural style:

mixed mysqli_fetch_object ( object result)

Object oriented style (method):

class result {

mixed fetch_object ( void )

}

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. If no more rows exist in the current result set, FALSE is returned.

Return values

Returns an object or FALSE if an error occured.

Megjegyzés: Field names returned by this function are case-sensitive.

mysqli_fetch_row

(PHP 5 CVS only)

mysqli_fetch_row

(no version information, might be only in CVS)

result->fetch_row -- Get a result row as an enumerated array

Description

Procedural style:

mixed mysqli_fetch_row ( object result)

Object oriented style (method):

class result {

mixed fetch_row ( void )

}

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

mysqli_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 mysqli_fetch_row() function will return the next row within the result set, or FALSE if there are no more rows.

Return values

mysqli_fetch_row() returns an array that corresponds to the fetched row or FALSE if there are no more rows in result set.

mysqli_fetch

(PHP 5 CVS only)

mysqli_fetch

(no version information, might be only in CVS)

stmt->fetch --  Fetch results from a prepared statement into the bound variables

Description

Procedural style:

mixed mysqli_fetch ( object stmt)

Object oriented style (method):

class stmt {

mixed fetch ( void )

}

mysqli_fetch() returns row data using the variables bound by mysqli_bind_result().

Megjegyzés: Note that all columns must be bound by the application before calling mysqli_fetch().

Return values

Táblázat 1. Return values

ValueDescription
TRUESuccess. Data has been fetched
FALSEError occured
MYSQLI_NO_DATANo more rows/data exists

mysqli_field_count

(PHP 5 CVS only)

mysqli_field_count

(no version information, might be only in CVS)

mysql->field_cont -- Returns the number of columns for the most recent query

Description

Procedural style:

int mysqli_field_count ( object link)

Object oriented style (method):

class mysql {

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

Return values

An integer representing the number of fields in a result set

mysqli_field_seek

(PHP 5 CVS only)

mysqli_field_seek

(no version information, might be only in CVS)

result->field_seek --  Set result pointer to a specified field offset

Description

Procedural style:

int mysqli_field_seek ( object result, int fieldnr)

Object oriented style (method):

class result {

int field_seek ( 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.

Megjegyzés: To seek to the beginning of a row, pass an offset value of zero.

Return values

mysqli_field_seek() returns previuos value of field cursor.

mysqli_field_tell

(PHP 5 CVS only)

mysqli_field_tell

(no version information, might be only in CVS)

result->current_field --  Get current field offset of a result pointer

Description

Procedural style:

int mysqli_field_tell ( object result)

Object oriented style (property):

class result {

int current_field

}

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

Return values

Returns current offset of field cursor.

mysqli_free_result

(PHP 5 CVS only)

mysqli_free_result

(no version information, might be only in CVS)

result->free -- Frees the memory associated with a result

Description

Procedural style:

void mysqli_free_result ( object result)

Object oriented style (method):

class result {

void free ( void )

}

The mysqli_free_result() function frees the memory associated with the result represented by the result parameter, which was allocated by mysqli_query(), mysqli_store_result() or mysqli_use_result().

Megjegyzés: You should always free your result with mysqli_free_result(), when your result object is not needed anymore.

Return values

This function doesn't return any value.

mysqli_get_client_info

(PHP 5 CVS only)

mysqli_get_client_info -- Returns the MySQL client version as a string

Description

string mysqli_get_client_info ( void )

The mysqli_get_client_info() function is used to return a string representing the client version being used in the MySQLi extension.

Return values

A string that represents the MySQL client library version

Lásd még

mysqli_get_client_version()

mysqli_get_host_info

(PHP 5 CVS only)

mysqli_get_host_info

(no version information, might be only in CVS)

mysqli->get_host_info -- Returns a string representing the type of connection used

Description

Procdural style:

string mysqli_get_host_info ( object link)

Object oriented style (property):

class mysqli {

string host_info

}

The mysqli_get_host_info() function returns a string describing the connection represented by the link parameter is using (including the server host name).

Return values

A character string representing the server hostname and the connection type.

mysqli_get_proto_info

(PHP 5 CVS only)

mysqli_get_proto_info

(no version information, might be only in CVS)

mysqli->protocol_version -- Returns the version of the MySQL protocol used

Description

Procedural style:

int mysqli_get_proto_info ( object link)

Object oriented style (property):

class mysqli {

string protocol_version

}

Returns an integer representing the MySQL protocol version used by the connection represented by the link parameter.

Return values

Returns an integer representing the protcol version.

mysqli_get_server_info

(PHP 5 CVS only)

mysqli_get_server_info

(no version information, might be only in CVS)

mysqli->server_info -- Returns the version of the MySQL server

Description

Procedural style:

string mysqli_get_server_info ( object link)

Object oriented style (property):

class mysqli {

string server_info

}

Returns a string representing the version of the MySQL server that the MySQLi extension is connected to (represented by the link parameter).

Return values

A character string representing the server version.

mysqli_get_server_version

(PHP 5 CVS only)

mysqli_get_server_version -- Returns the version of the MySQL server as an integer

Description

Procedural style:

int mysqli_get_server_version ( object link)

Object oriented style (property):

class mysqli {

int server_version

}

The mysqli_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 4.1.0 is 40100).

Return values

An integer representing the server version.

mysqli_info

(PHP 5 CVS only)

mysqli_info

(no version information, might be only in CVS)

mysqli->info -- Retrieves information about the most recently executed query

Description

Procedural style:

string mysqli_info ( object link)

Object oriented style (property)

class mysqli {

string info

}

The mysqli_info() function returns a string providing information about the last query executed. The nature of this string is provided below:

Táblázat 1. Possible mysqli_info return values

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

Megjegyzés: Queries which do not fall into one of the above formats are not supported. In these situations, mysqli_info() will return an empty string.

Return values

A character string representing additional information about the most recently executed query.

mysqli_init

(PHP 5 CVS only)

mysqli_init --  Initializes MySQLi and returns an object for use with mysqli_real_connect

Description

object mysqli_init ( void )

Allocates or initializes a MYSQL object suitable for mysqli_options() and mysqli_real_connect().

Megjegyzés: Any subsequent calls to any mysqli function (except mysqli_options()) will fail until mysqli_real_connect() was called.

Return values

Returns an object.

mysqli_insert_id

(PHP 5 CVS only)

mysqli_insert_id

(no version information, might be only in CVS)

mysqli->insert_id -- Returns the auto generated id used in the last query

Description

Procedural style:

mixed mysqli_insert_id ( object link)

Object oriented style (property):

class mysqli {

mixed insert_id

}

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.

Megjegyzés: Performing an INSERT or UPDATE statement using the LAST_INSERT_ID() function will also modify the value returned by the mysqli_insert_id() function.

Return values

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.

Megjegyzés: If the number is greater than maximal int value, mysqli_insert_id() will return a string.

mysqli_kill

(PHP 5 CVS only)

mysqli_kill

(no version information, might be only in CVS)

mysqli->kill -- Asks the server to kill a MySQL thread

Description

Procedural style:

bool mysqli_kill ( object link, int processid)

Object oriented style (method)

class mysqli {

bool kill ( 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.

Megjegyzés: To stop a running query you should use the SQL command KILL QUERY processid.

Return values

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Lásd még

mysqli_thread_id()

mysqli_num_fields

(PHP 5 CVS only)

mysqli_num_fields

(no version information, might be only in CVS)

result->num_fields --  Get the number of fields in a result

Description

Procedural style:

int mysqli_num_fields ( object result)

Object oriented style (property):

class mysqli {

int field_count

}

mysqli_num_fields() returns the number of fields from specified result set.

Return values

The number of fields from a result set

mysqli_num_rows

(PHP 5 CVS only)

mysqli_num_rows --  Gets the number of rows in a result

Description

Procedural style:

mixed mysqli_num_rows ( object result)

Object oriented style (property):

class mysqli {

mixed num_rows

}

Returns the number of rows in the result set.

The use of mysqli_num_rows() depends on whether you use buffered or unbuffered result sets. In case you use unbuffered resultsets mysqli_num_rows() will not correct the correct number of rows until all the rows in the result have been retrieved.

Return values

Returns number of rows in the result set.

Megjegyzés: If the number of rows is greater than maximal int value, the number will be returned as a string.

mysqli_options

(PHP 5 CVS only)

mysqli_options

(no version information, might be only in CVS)

mysqli->options -- set options

Description

Procedural style:

bool mysqli_options ( object link, int option, mixed value)

Object oriented style (method)

class mysqli {

bool options ( int option, mixed value)

}

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

mysqli_options() should be called after mysqli_init() and before mysqli_real_connect().

The parameter option is the option that you want to set, the value is the value for the option. The parameter option can be one of the following values:

Táblázat 1. Valid options

NameDescription
MYSQLI_OPT_CONNECT_TIMEOUTconnection timeout in seconds
MYSQLI_OPT_COMPRESSuse compression protocol
MYSQLI_OPT_LOCAL_INFILEenable/disable use of LOAD LOCAL INFILE
MYSQLI_INIT_CMDcommand 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.

Return values

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

mysqli_param_count

(PHP 5 CVS only)

mysqli_param_count

(no version information, might be only in CVS)

stmt->param_count -- Returns the number of parameter for the given statement

Description

Procedural style:

int mysqli_param_count ( object stmt)

Object oriented style (property):

class stmt {

int param_count

}

mysqli_param_count() returns the number of parameter markers present in the prepared statement.

Return values

returns an integer representing the number of parameters.

Lásd még

mysqli_prepare()

mysqli_ping

(PHP 5 CVS only)

mysqli_ping

(no version information, might be only in CVS)

mysqli->ping --  Pings a server connection, or tries to reconnect if the connection has gone down.

Description

Procedural style:

int mysqli_ping ( object link)

Object oriented style (method):

class mysqli {

int ping ( void )

}

Checks whether the connection to the server is working. If it has gone down, 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.

mysqli_ping() returns 0 if the connection is alive and non-zero value if an error has occured.

mysqli_prepare

(PHP 5 CVS only)

mysqli_prepare

(no version information, might be only in CVS)

stmt->prepare --  Prepare a SQL statement for execution

Description

Procedure style:

mixed mysqli_prepare ( object link, string query)

Object oriented style (method)

class stmt {

mixed prepare ( string query)

}

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

Megjegyzés: 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.

Megjegyzés: 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 mysqli_bind_param() and/or mysqli_bind_result() before executing the statement or fetching rows.

Return values

mysqli_prepare() returns a statement object or FALSE if an error occured.

mysqli_profiler

(PHP 5 CVS only)

mysqli_profiler -- 

Description

bool mysqli_profiler ( int flags, string info, int port)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mysqli_query

(PHP 5 CVS only)

mysqli_query

(no version information, might be only in CVS)

mysqli->query -- Performs a query on the database

Description

Procedural style:

mixed mysqli_query ( object link, string query [, int resultmode])

Object oriented style (method):

class mysqli {

mixed query ( string query)

}

The mysqli_query() function is used to simplify the act of performing a query against the database represented by the link parameter.

Functionally, using this function is identical to calling mysqli_real_query() followed either by mysqli_use_result() or mysqli_store_result() where query is the query string itself and resultmode is either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, if the resultmode is not provided MYSQLI_STORE_RESULT is used.

If you execute mysqli_query() with resultmode MYSQLI_USE_RESULT all subsequent calls will return error Commands out of sync unless you call mysqli_free_result().

Return values

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad. For SELECT, SHOW, DESCRIBE or EXPLAIN mysqli_query() will return a result object.

mysqli_real_connect

(PHP 5 CVS only)

mysqli_real_connect

(no version information, might be only in CVS)

mysqli->real_connect -- Opens a connection to a mysql server

Description

Procedural style

bool mysqli_real_connect ( object link [, string hostname [, string username [, string passwd [, string dbname [, int port [, string socket [, int flags]]]]]]])

Object oriented style (method)

class mysqli {

bool real_connect ( [string hostname [, string username [, string passwd [, string dbname [, int port [, string socket [, int flags]]]]]]])

}

mysql_real_connect() attempts to establish a connection to a MySQL database engine running on host.

This function differs from mysqli_connect():

  • mysqli_real_connect() needs a valid object which has to be created by function mysqli_init()

  • With function mysqli_options() you can set various options for connection.

  • With the parameter flags you can set diffrent connection options:

    Táblázat 1. Supported flags

    NameDescription
    MYSQLI_CLIENT_COMPRESSUse compression protocol
    MYSQLI_CLIENT_FOUND_ROWSreturn number of matched rows, not the number of affected rows
    MYSQLI_CLIENT_IGNORE_SPACEAllow 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_SSLUse SSL (encryption)

    Megjegyzés: 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.

Return values

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

mysqli_real_escape_string

(PHP 5 CVS only)

mysqli_real_escape_string

(no version information, might be only in CVS)

mysqli->real_escape_string --  Escapes special characters in a string for use in a SQL statement, taking into account the current charset of the connection

Description

Procedural style:

string mysqli_real_escape_string ( object link, string escapestr)

Object oriented style (method):

class mysqli {

string real_escape_sring ( string query)

}

This function is used to create a legal SQL string that you can use in a 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 NUL (ASCII 0), \n, \r, \, ', ", and Control-Z.

Return values

Returns an escaped string.

mysqli_real_query

(PHP 5 CVS only)

mysqli_real_query

(no version information, might be only in CVS)

mysqli->real_query -- Execute an SQL query

Description

Procedural style

bool mysqli_real_query ( object link, string query)

Object oriented style (method):

class mysqli {

bool real_query ( string query)

}

The mysqli_real_query() function is used to execute only a query against the database represented by the link whose result can then be retrieved or stored using the mysqli_store_result() or mysqli_use_result() functions.

Megjegyzés: In order to determine if a given query should return a result set or not, see mysqli_field_count().

Return values

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

mysqli_rollback

(PHP 5 CVS only)

mysqli_rollback

(no version information, might be only in CVS)

mysqli->rollback -- Rolls back current transaction

Description

bool mysqli_rollback ( object link)

class mysqli {

bool rollback ( void )

}

Rollbacks the current transaction for the database specified by the link parameter.

Return values

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

mysqli_select_db

(PHP 5 CVS only)

mysqli_select_db

(no version information, might be only in CVS)

mysqli->select_db -- Selects the default database for database queries

Description

bool mysqli_select_db ( object link, string dbname)

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

Megjegyzés: 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().

Return values

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

mysqli_send_long_data

(PHP 5 CVS only)

mysqli_send_long_data

(no version information, might be only in CVS)

stmt->send_long_data -- Send data in blocks

Description

Procedural style:

bool mysqli_send_long_data ( object stmt, int param_nr, string data)

Object oriented style (method)

class stmt {

bool send_long_data ( 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.

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.

Return values

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

mysqli_send_query

(PHP 5 CVS only)

mysqli_send_query -- 

Description

bool mysqli_send_query ( resource link, string query)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

mysqli_ssl_set

(PHP 5 CVS only)

mysqli_ssl_set

(no version information, might be only in CVS)

mysqli->ssl_set -- Used for establishing secure connections using SSL.

Description

Procedural style:

bool mysqli_ssl_set ( object link [, string key [, string cert [, string ca [, string capath [, string cipher]]]]])

Object oriented style (method):

class mysqli {

bool ssl_set ( [string key [, string cert [, string ca [, string capath [, string cipher]]]]])

}

The function mysqli_ssl_set() is used for establishing secure connections using SSL. It must be called before mysqli_real_connect(). This function does nothing unless OpenSSL support is enabled.

key is the pathname to the key file. cert is the pathname to the certificate file. ca is the pathname to the certificate authority file. capath is the pathname to a directory that contains trusted SSL CA certificates in pem format. cipher is a list of allowable ciphers to use for SSL encryption. Any unused SSL parameters may be given as NULL

Return values

This function always returns TRUE value. If SSL setup is incorrect mysqli_real_connect() will return an error when you attempt to connect.

mysqli_stat

(PHP 5 CVS only)

mysqli_stat

(no version information, might be only in CVS)

mysqli->stat -- Gets the current system status

Description

Procedural style:

string mysqli_stat ( object link)

Object oriented style (method):

class mysqli {

string mysqli->stat ( void )

}

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.

Return values

A string describing the server status. FALSE if an error occurred.

mysqli_stmt_affected_rows

(PHP 5 CVS only)

mysqli_stmt_affected_rows

(no version information, might be only in CVS)

mysqli_stmt->affected_rows -- Returns the total number of rows changed, deleted, or inserted by the last executed statement

Description

Procedural style :

mixed mysqli_stmt_affected_rows ( object stmt)

Object oriented style (property):

class stmt {

mixed affected_rows

}

mysqli_stmt_affected_rows() returns the number of rows affected by INSERT, UPDATE, or DELETE query. If the last query was invalid, this function will return -1.

Megjegyzés: For SELECT statements mysqli_affected_rows() works like mysqli_num_rows().

The mysqli_stmt_affected_rows() function only works with queries which update a table. In order to return the number of rows from a SELECT query, use the mysqli_stmt_num_rows() function instead.

Return Values

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.

Megjegyzés: 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.

See also

mysqli_stmt_num_rows(), mysqli_prepare()

mysqli_stmt_close

(PHP 5 CVS only)

mysqli_stmt_close

(no version information, might be only in CVS)

mysqli_stmt->close -- Closes a prepared statement

Description

Procedural style:

bool mysqli_stmt_close ( object stmt)

Object oriented style (method):

class mysqli_stmt {

bool mysqli_stmt->close ( void )

}

Closes a prepared statement. mysql_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.

Return values

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

See also

mysqli_stmt_num_rows(), mysqli_prepare(), mysqli_execute()

mysqli_stmt_errno

(PHP 5 CVS only)

mysqli_stmt_errno

(no version information, might be only in CVS)

mysqli_stmt->errno -- Returns the error code for the most recent statement call

Description

Procedural style :

int mysqli_stmt_errno ( object stmt)

Object oriented style (property):

class stmt {

int errno

}

For the statement specified by stmt, mysqli_stmt_errno()() returns the error code for the most recently invoked statement function that can succeed or fail.

Megjegyzés: 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.

Return values

An error code value. Zero means no error occurred.

mysqli_stmt_error

(PHP 5 CVS only)

mysqli_stmt_error

(no version information, might be only in CVS)

mysqli_stmt->error -- Returns a string description for last statement error

Description

Procedural style:

string mysqli_stmt_error ( object stmt)

Object oriented style (property):

class stmt {

string error

}

For the statement specified by stmt, mysql_stmt_error() returns a containing the error message for the most recently invoked statement function that can succeed or fail.

Return values

A string that describes the error. An empty string if no error occurred.

mysqli_stmt_store_result

(PHP 5 CVS only)

mysqli_stmt_store_result

(no version information, might be only in CVS)

mysqli_stmt->store_result -- Transfers a result set from a prepared statement

Description

Procedural style:

bool mysqli_stmt_store_result ( object stmt)

Object oriented style (method):

class mysqli_stmt {

bool store_result ( void )

}

You must call mysql_stmt_store_result() for every query that successfully produces a result set (SELECT, SHOW, DESCRIBE, EXPLAIN), and only if you want to buffer the complete result set by the client, so that the subsequent mysql_fetch() call returns buffered data.

Megjegyzés: It is unnecessary to call mysql_stmt_store_result()() for other queries, but if you do, it will not harm or cause any notable performance in all cases. You can detect whether the query produced a result set by checking if mysql_get_metadata() returns NULL.

Return values

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

mysqli_store_result

(PHP 5 CVS only)

mysqli_store_result

(no version information, might be only in CVS)

mysqli->store_result -- Transfers a result set from the last query

Description

Procedural style:

object mysqli_store_result ( object link)

Object oriented style (method):

class mysqli {

object store_result ( void )

}

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.

Megjegyzés: Although it is always good practice to free the memory used by the result of a query using the mysqli_free_result() function, when transfering large result sets using the mysqli_store_result() this becomes particularly important.

Megjegyzés: 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 successfull 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.

Return values

Returns a buffered result object or FALSE if an error occured.

mysqli_thread_id

(PHP 5 CVS only)

mysqli_thread_id

(no version information, might be only in CVS)

mysqli->thread_id -- Returns the thread ID for the current connection

Description

Procedural style:

int mysqli_thread_id ( object link)

Object oriented style (property):

class mysqli {

int thread_id

}

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.

Megjegyzés: 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].

Return values

mysqli_thread_id() returns the Thread ID for the current connection.

See also

mysqli_kill()

mysqli_thread_safe

(PHP 5 CVS only)

mysqli_thread_safe -- Returns whether thread safety is given or not

Description

Procedural style:

bool mysqli_thread_safe ( void )

mysqli_thread_safe() indicates whether the client library is compiled as thread-safe.

Return values

TRUE if the client library is thread-safe, otherwise FALSE.

mysqli_use_result

(PHP 5 CVS only)

mysqli_use_result

(no version information, might be only in CVS)

mysqli->use_result -- Initiate a result set retrieval

Description

Procedural style:

mixed mysqli_use_result ( object link)

Object oriented style (method):

class mysqli {

mixed use_result ( void )

}

mysqli_use_result() is used to initiate the retrieval of a result set from the last query executed using the mysqli_real_query() function on the database connection specified by the link parameter. 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.

Megjegyzés: 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.

Return values

Returns an unbuffered result object or FALSE if an error occured.

mysqli_warning_count

(PHP 5 CVS only)

mysqli_warning_count

(no version information, might be only in CVS)

mysqli->warning_count -- Returns the number of warnings from the last query for the given link

Description

Procedural style:

int mysqli_warning_count ( object link)

Object oriented style (property):

class mysqli {

int warning_count

}

mysqli_warning_count() returns the number of warnings from the last query in the connection represented by the link parameter.

Megjegyzés: For retrieving warning messages you can use the SQL command SHOW WARNINGS [limit row_count].

Return values

Number of warnings or zero if there are no warnings.

LXVI. Mohawk Software session handler functions

Bevezetés

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://devel.mohawksoft.com/msession.html.

Megjegyzés: Ez a kiterjesztés nem működik Windows operációs rendszereken!


Követelmények


Telepítés

To enable Msession support configure PHP --with-msession[=DIR], where DIR is the Msession install directory.


Futásidejű beállítások


Erőforrás típusok


Előre definiált állandók

Tartalom
msession_connect -- Connect to msession server
msession_count -- Get session count
msession_create -- Create a session
msession_destroy -- Destroy a session
msession_disconnect -- Close connection to msession server
msession_find -- Find value
msession_get_array -- Get array of ... ?
msession_get -- Get value from session
msession_getdata -- Get data ... ?
msession_inc -- Increment value in session
msession_list -- List ... ?
msession_listvar -- List sessions with variable
msession_lock -- Lock a session
msession_plugin -- Call an escape function within the msession personality plugin
msession_randstr -- Get random string
msession_set_array -- Set array of ...
msession_set -- Set value in session
msession_setdata -- Set data ... ?
msession_timeout -- Set/get session timeout
msession_uniq -- Get uniq id
msession_unlock -- Unlock a session

msession_connect

(PHP 4 >= 4.2.0)

msession_connect -- Connect to msession server

Description

bool msession_connect ( string host, string port)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

msession_count

(PHP 4 >= 4.2.0)

msession_count -- Get session count

Description

int msession_count ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

msession_create

(PHP 4 >= 4.2.0)

msession_create -- Create a session

Description

bool msession_create ( string session)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

msession_destroy

(PHP 4 >= 4.2.0)

msession_destroy -- Destroy a session

Description

bool msession_destroy ( string name)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

msession_disconnect

(PHP 4 >= 4.2.0)

msession_disconnect -- Close connection to msession server

Description

void msession_disconnect ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

msession_find

(PHP 4 >= 4.2.0)

msession_find -- Find value

Description

array msession_find ( string name, string value)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

msession_get_array

(PHP 4 >= 4.2.0)

msession_get_array -- Get array of ... ?

Description

array msession_get_array ( string session)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

msession_get

(PHP 4 >= 4.2.0)

msession_get -- Get value from session

Description

string msession_get ( string session, string name, string value)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

msession_getdata

(no version information, might be only in CVS)

msession_getdata -- Get data ... ?

Description

string msession_getdata ( string session)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

msession_inc

(PHP 4 >= 4.2.0)

msession_inc -- Increment value in session

Description

string msession_inc ( string session, string name)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

msession_list

(PHP 4 >= 4.2.0)

msession_list -- List ... ?

Description

array msession_list ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

msession_listvar

(PHP 4 >= 4.2.0)

msession_listvar -- List sessions with variable

Description

array msession_listvar ( string name)

Returns an associative array of value/session for all sessions with a variable named name.

Used for searching sessions with common attributes.

msession_lock

(PHP 4 >= 4.2.0)

msession_lock -- Lock a session

Description

int msession_lock ( string name)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

msession_plugin

(PHP 4 >= 4.2.0)

msession_plugin -- Call an escape function within the msession personality plugin

Description

string msession_plugin ( string session, string val [, string param])

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

msession_randstr

(PHP 4 >= 4.2.0)

msession_randstr -- Get random string

Description

string msession_randstr ( int param)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

msession_set_array

(PHP 4 >= 4.2.0)

msession_set_array -- Set array of ...

Description

bool msession_set_array ( string session, array tuples)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

msession_set

(PHP 4 >= 4.2.0)

msession_set -- Set value in session

Description

bool msession_set ( string session, string name, string value)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

msession_setdata

(no version information, might be only in CVS)

msession_setdata -- Set data ... ?

Description

bool msession_setdata ( string session, string value)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

msession_timeout

(PHP 4 >= 4.2.0)

msession_timeout -- Set/get session timeout

Description

int msession_timeout ( string session [, int param])

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

msession_uniq

(PHP 4 >= 4.2.0)

msession_uniq -- Get uniq id

Description

string msession_uniq ( int param)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

msession_unlock

(PHP 4 >= 4.2.0)

msession_unlock -- Unlock a session

Description

int msession_unlock ( string session, int key)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

LXVII. muscat functions

Bevezetés

Figyelem

Ez a kiterjesztés KÍSÉRLETI JELLEGGEL MŰKÖDIK. Ez azt jelenti, hogy minden itt dokumentált működés, beleértve a függvények nevét, működését vagy bármi más, amit a kiterjesztés kapcsán leírtunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a kiterjesztést csak a saját felelősségedre használd!


Telepítés

These functions are only available if PHP was configured with --with-muscat[=DIR].

Tartalom
muscat_close -- Shuts down the muscat session and releases any memory back to PHP.
muscat_get -- Gets a line back from the core muscat API.
muscat_give -- Sends string to the core muscat API
muscat_setup_net -- Creates a new muscat session and returns the handle.
muscat_setup -- Creates a new muscat session and returns the handle.

muscat_close

(4.0.5 - 4.2.3 only)

muscat_close -- Shuts down the muscat session and releases any memory back to PHP.

Description

int muscat_close ( resource muscat_handle)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

[Not back to the system, note!]

muscat_get

(4.0.5 - 4.2.3 only)

muscat_get -- Gets a line back from the core muscat API.

Description

string muscat_get ( resource muscat_handle)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

Returns a literal FALSE when there is no more to get (as opposed to ""). Use === FALSE or !== FALSE to check for this.

muscat_give

(4.0.5 - 4.2.3 only)

muscat_give -- Sends string to the core muscat API

Description

int muscat_give ( resource muscat_handle, string string)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

muscat_setup_net

(4.0.5 - 4.2.3 only)

muscat_setup_net -- Creates a new muscat session and returns the handle.

Description

resource muscat_setup_net ( string muscat_host, int port)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

muscat_host is the hostname to connect to port is the port number to connect to - actually takes exactly the same args as fsockopen

muscat_setup

(4.0.5 - 4.2.3 only)

muscat_setup -- Creates a new muscat session and returns the handle.

Description

resource muscat_setup ( int size [, string muscat_dir])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

Size is the amount of memory in bytes to allocate for muscat muscat_dir is the muscat installation dir e.g. "/usr/local/empower", it defaults to the compile time muscat directory

LXVIII. Hálózatkezelési Függvények

Bevezetés


Követelmények

Az itt leírt függvények használatához semmilyen külső függvénykönyvtár megléte nem szükségeltetik.


Telepítés

Semmilyen telepítés nem szükséges ezen függvények használatához, a PHP alapelemei.


Futásidejű beállítások

Az alábbi függvények viselkedése befolyásolható a php.ini segítségével.

Táblázat 1. Network Configuration Options

NameDefaultChangeable
define_syslog_variables"0"PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().

Here's a short explanation of the configuration directives.

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


Erőforrás típusok

Ez a kiterjesztés semmilyen erőforrás típust nem definiál.


Előre definiált állandók

Az itt felsorolt konstansok mindig elérthetőek, mivel részei a PHP alaptelepítésének.

Táblázat 2. openlog() Options

ConstantDescription
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_PERRORprint log message also to standard error
LOG_PIDinclude PID with each message

Táblázat 3. openlog() Facilities

ConstantDescription
LOG_AUTH security/authorization messages (use LOG_AUTHPRIV instead in systems where that constant is defined)
LOG_AUTHPRIVsecurity/authorization messages (private)
LOG_CRONclock daemon (cron and at)
LOG_DAEMONother system daemons
LOG_KERNkernel messages
LOG_LOCAL0 ... LOG_LOCAL7reserved for local use, these are not available in Windows
LOG_LPRline printer subsystem
LOG_MAILmail subsystem
LOG_NEWSUSENET news subsystem
LOG_SYSLOGmessages generated internally by syslogd
LOG_USERgeneric user-level messages
LOG_UUCPUUCP subsystem

Táblázat 4. syslog() Priorities (in descending order)

ConstantDescription
LOG_EMERGsystem is unusable
LOG_ALERTaction must be taken immediately
LOG_CRITcritical conditions
LOG_ERRerror conditions
LOG_WARNINGwarning conditions
LOG_NOTICEnormal, but significant, condition
LOG_INFOinformational message
LOG_DEBUGdebug-level message

Táblázat 5. dns_get_record() Options

ConstantDescription
DNS_AIPv4 Address Resource
DNS_MXMail Exchanger Resource
DNS_CNAMEAlias (Canonical Name) Resource
DNS_NSAuthoritative Name Server Resource
DNS_PTRPointer Resource
DNS_HINFOHost Info Resource (See IANA's Operating System Names for the meaning of these values)
DNS_SOAStart of Authority Resource
DNS_TXTText Resource
DNS_ANYAny 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_AAAAIPv6 Address Resource
DNS_ALLIteratively query the name server for each available record type.
Tartalom
checkdnsrr --  Adott Internet domainnév vagy IP címnek megfelelő bejegyzés létének vizsgálata a DNS rekordokban
closelog -- Syslog (rendszer napló) kapcsolat zárása
debugger_off -- A beépített PHP debugger letiltása (PHP 3)
debugger_on -- A beépített PHP debugger engedélyezése (PHP 3)
define_syslog_variables -- A rendszer naplózóval kapcsolatos konstansok inicializálása
dns_check_record -- Synonym for checkdnsrr()
dns_get_mx -- Synonym for getmxrr()
dns_get_record --  Fetch DNS Resource Records associated with a hostname
fsockopen --  Internet vagy Unix domain socket megnyitása
gethostbyaddr --  Adott IP címnek megfelelő hostnév kinyerése
gethostbyname --  Kinyeri a megadott Internet hostnak megfelelő IP címet
gethostbynamel --  Adott hostnévnek megfelelő összes IP cím listájának kinyerése
getmxrr --  Adott Internet hostnévhez tartozó MX rekordok kigyűjtése
getprotobyname --  Névvel megadott protokol számát adja vissza
getprotobynumber --  Számmal megadott protokol nevét adja vissza
getservbyname --  Adott szolgáltatástípus portszámának megallapítása név alapján
getservbyport --  Adott porton levő szolgáltatás nevének megállapítása
ip2long --  Pontozott IP címet tartalmazó karakterláncot valódi IP cimmé alakít
long2ip --  Négy byteon tárolt (IPv4) hálózatcímet alakít az Internet szabványnak megfelelő pontozott formára
openlog -- A rendszer naplózóval való kapcsolat nyitása
pfsockopen --  Tartós Internet vagy Unix domain socket-kapcsolat megnyitása
socket_get_status --  A stream_get_meta_data() függvény egy álneve
socket_set_blocking -- A stream_set_blocking() függvény egy álneve
socket_set_timeout -- A socket_set_timeout() függvény egy álneve
syslog -- Syslog üzenet létrehozása

checkdnsrr

(PHP 3, PHP 4 )

checkdnsrr --  Adott Internet domainnév vagy IP címnek megfelelő bejegyzés létének vizsgálata a DNS rekordokban

Leírás

int checkdnsrr ( string host [, string típus])

Keresést kér a névszervertől, a típus paraméterben megadott típusú rekordokban, a host paraméternek megfelelő bejegyzésekre. A visszatérési érték TRUE lesz, amennyiben volt találat. Ha nem volt találat, avagy hiba merült fel a művelet során, a visszatérési érték FALSE lesz.

A típus paraméter a következők közül választható: A, MX, NS, SOA, PTR, CNAME, AAAA vagy ANY. Az alapértelmezés az MX.

A keresett host lehet IP cím és domainnév is.

Megjegyzés: Az AAAA típus a PHP 4.3.0 változattal lett bevezetve.

Megjegyzés: Ez a függvény a Windows változatokban nem elérhető. Helyette a PEAR Net-DNS környékén érdemes szétnézni.

Lásd még: getmxrr(), gethostbyaddr(), gethostbyname(), gethostbynamel(), valamint a man named(8) oldalát!

closelog

(PHP 3, PHP 4 )

closelog -- Syslog (rendszer napló) kapcsolat zárása

Leírás

int closelog ( void )

A closelog() függvény zárja a rendszer naplózóval való kapcsolatot. A függvény használata opcionális.

Lásd még: define_syslog_variables(), syslog() és openlog()!

debugger_off

(PHP 3)

debugger_off -- A beépített PHP debugger letiltása (PHP 3)

Leírás

int debugger_off ( void )

Letiltja beépített PHP debuggert (hibakeresőt). E függvény csak a PHP 3 változatban található meg.

További információkért a PHP hibakeresés oldalra érdemes ellátogatni.

debugger_on

(PHP 3)

debugger_on -- A beépített PHP debugger engedélyezése (PHP 3)

Leírás

int debugger_on ( string address)

Engedélyezi a beépített PHP debugger működését, az a address paraméterben megadott címhez kapcsolódva. E függvény csak a PHP 3 változatban található meg.

További információkért a PHP hibakeresés oldalra érdemes ellátogatni.

define_syslog_variables

(PHP 3, PHP 4 )

define_syslog_variables -- A rendszer naplózóval kapcsolatos konstansok inicializálása

Leírás

void define_syslog_variables ( void )

Minden állandót, amelyeknek csak köze van a syslog függvényekhez, újrainicializál.

Lásd még: openlog(), syslog() és closelog()!

dns_check_record

(PHP 5 CVS only)

dns_check_record -- Synonym for checkdnsrr()

Description

int dns_check_record ( string host [, string type])

Check DNS records corresponding to a given Internet host name or IP address

dns_get_mx

(PHP 5 CVS only)

dns_get_mx -- Synonym for getmxrr()

Description

int dns_get_mx ( string hostname, array mxhosts [, array &weight])

Get MX records corresponding to a given Internet host name.

dns_get_record

(PHP 5 CVS only)

dns_get_record --  Fetch DNS Resource Records associated with a hostname

Description

array dns_get_record ( string hostname [, int type [, array &authns, array &addtl]])

Megjegyzés: This function is not implemented on Windows platforms. Try the PEAR class Net_DNS.

This function returns an array of associative arrays. Each associative array contains at minimum the following keys:

Táblázat 1. Basic DNS attributes

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

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.

By default, dns_get_record() will search for any resource records associated with hostname. To limit the query, specify the optional type parameter. type may be any one of the following: DNS_A, DNS_CNAME, DNS_HINFO, DNS_MX, DNS_NS, DNS_PTR, DNS_SOA, DNS_TXT, DNS_AAAA, DNS_SRV, DNS_NAPTR, DNS_ALL or DNS_ANY. The default is DNS_ANY.

Megjegyzés: 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.

The optional third and fourth arguments to this function, authns and addtl are passed by reference and, if given, will be populated with Resource Records for the Authoritative Name Servers, and any Additional Records respectively. See the example below.

Táblázat 2. Other keys in associative arrays dependant on 'type'

TypeExtra Columns
A ip: An IPv4 addresses in dotted decimal notation.
MX pri: Priority of mail exchanger. Lower numbers indicate greater priority. target: FQDN of the mail exchanger. See also dns_get_mx().
CNAME target: FQDN of location in DNS namespace to which the record is aliased.
NS target: FQDN of the name server which is authoritative for this hostname.
PTR target: Location within the DNS namespace to which this record points.
TXT txt: Arbitrary string data associated with this record.
HINFO cpu: IANA number designating the CPU of the machine referenced by this record. os: IANA number designating the Operating System on the machine referenced by this record. See IANA's Operating System Names for the meaning of these values.
SOA mname: FQDN of the machine from which the resource records originated. rname: Email address of the administrative contain for this domain. serial: Serial # of this revision of the requested domain. refresh: Refresh interval (seconds) secondary name servers should use when updating remote copies of this domain. retry: Length of time (seconds) to wait after a failed refresh before making a second attempt. expire: Maximum length of time (seconds) a secondary DNS server should retain remote copies of the zone data without a successful refresh before discarding. minimum-ttl: Minimum length of time (seconds) a client can continue to use a DNS resolution before it should request a new resolution from the server. Can be overridden by individual resource records.
AAAA ipv6: IPv6 address
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.

Megjegyzés: 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().

Példa 1. Using dns_get_record()

<?php
$result = dns_get_record("php.net");
print_r($result);
?>

Produces output similar to the following:

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
        )

)

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.

Példa 2. Using dns_get_record() and DNS_ANY

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

Produces output similar to the following:

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
        )

)

See also dns_get_mx(), and dns_check_record()

fsockopen

(PHP 3, PHP 4 )

fsockopen --  Internet vagy Unix domain socket megnyitása

Leírás

int fsockopen ( string hostname, int port [, int errno [, string errstr [, float timeout]]])

Stream típusú kapcsolatot kezdeményez egy Internet (AF_INET, TCP vagy UDP protokollal) vagy Unix (AF_UNIX) tartomány felé. Internet tartomány megadása esetén TCP kapcsolatot nyit a hostname paraméterben megadott géppel, a port paraméterben megadott porton. Ez esetben a hostname lehet tartománynév vagy IP cím is. UDP kapcsolat esetén explicit meg kell adni a protokollt a hostname paraméterben, a következő módon: udp://hostname. Unix domain esetén a hostname paraméternek kell tartalmaznia a socket elérési útját, ekkor a port értékének nullának kell lennie. A timeout paraméter elhagyható, értéke másodpercekben megadandó. Ez a kapcsolatfelvételkori időtúllépés mértékét szabályozza.

Megjegyzés: Amennyiben az socketen keresztüli írás-olvasás időtúllépési idejét szeretnéd beállítani, a socket_set_timeout() függvény segítségével teheted meg azt. A fsockopen() függvény timeout paraméterével csak a kapcsolatfelvétel időtúllépését tudod szabályozni.

A PHP 4.3.0 verziótól kezdve, ha az OpenSSL támogatást befordítottad a PHP-be, a hostname elé írhatsz 'ssl://' vagy 'tls://' karaktersorozatot is, ha SSL vagy TLS kliens kapcsolatot szeretnél létesíteni a TCP/IP felett a távoli hoszttal.

A fsockopen() függvény egy fájl-azonosítót ad vissza, ami a rendes fájlkezelő parancsokkal együtt használható átlátszó módon. Ezek a következőek: fgets(), fgetss(), fputs(), fclose(), és feof()).

Ha a kapcsolatfelvétel meghiúsul, a visszatérési érték FALSE lesz, és amennyiben az errno és errstr opcionális paraméterek meg lettek adva, ezekben visszakapjuk a connect() rendszerhívás hibaértékét és hibaüzenetét. Amennyiben az errno nulla értékkel jön vissza, miközben a függvény értéke is FALSE, akkor a hiba még valahol a connect() rendszerhívás előtt következett be. Ez általában annak köszönhető, hogy valami probléma merül fel már az inicializáció közben. Az errno és errstr argumentumok referenciaként adják vissza a visszatérési értéket.

Bizonyos rendszereken előfordulhat, hogy a Unix domain illetve a timeout nem használható.

Alapesetben a socket blokkolt módban nyílik meg. Amennyiben ez nem megfelelő, ez átkapcsolható a socket_set_blocking() segítségével.

Példa 1. fsockopen() Példa

$fp = fsockopen ("www.php.net", 80, $errno, $errstr, 30);
if (!$fp) {
    echo "$errstr ($errno)<br>\n";
} else {
    fputs ($fp, "GET / HTTP/1.0\r\nHost: www.php.net\r\n\r\n");
    while (!feof($fp)) {
        echo fgets ($fp,128);
    }
    fclose ($fp);
}
?>
A következő példa bemutatja, hogy gyűjthető be a saját gépünkön levő "daytime" nevű, 13-as porton figyelő szolgáltatástól információ.

Példa 2. UDP kapcsolat használata

<?php
$fp = fsockopen("udp://127.0.0.1", 13, $errno, $errstr);
if (!$fp) {
    echo "Hiba: $errno - $errstr<br>\n";
} else {
    fwrite($fp,"\n");
    echo fread($fp, 26);
    fclose($fp);
}
?>

Figyelem

UDP socketek megnyitásakor bizonyos esetekben nem jön létre hiba, ha a célgép nem elérhető. A hiba ekkor csak az írás/olvasás szakaszában bukkan elő. Ennek az oka az, hogy maga az UDP kapcsolat nem egy hagyományos kapcsolat, ezért az operációs rendszer nem próbál hivatkozást létrehozni egészen addíg, amíg konkrét adattovábbításra nincs szükség.

Megjegyzés: A timeout paraméter a 3.0.9-es verziótól felfele, míg az UDP támogatás csak a 4-es verziókban elérhető.

Lásd még: pfsockopen(), socket_set_blocking(), socket_set_timeout(), fgets(), fgetss(), fputs(), fclose() és feof()!

gethostbyaddr

(PHP 3, PHP 4 )

gethostbyaddr --  Adott IP címnek megfelelő hostnév kinyerése

Leírás

string gethostbyaddr ( string ip_cím)

Az ip_cím-nek megfelelő hostnevet, sikertelenség esetén pedig a kapott ip_cím-et adja vissza.

Példa 1. Egy egyszerű gethostbyaddr() példa

<?php
$gep_neve = gethostbyaddr($_SERVER['REMOTE_ADDR']);

print $gep_neve;
?>

Lásd még: gethostbyname()!

gethostbyname

(PHP 3, PHP 4 )

gethostbyname --  Kinyeri a megadott Internet hostnak megfelelő IP címet

Leírás

string gethostbyname ( string hostnév)

A hostname paraméter által megadott Internet host IP címét, vagy sikertelenség esetén a kapott hostname paraméter értékét adja vissza.

Példa 1. Egy egyszerű gethostbyname() példa

<?php
$ip = gethostbyname('www.example.com');

print $ip;
?>

Lásd még: gethostbyaddr().

gethostbynamel

(PHP 3, PHP 4 )

gethostbynamel --  Adott hostnévnek megfelelő összes IP cím listájának kinyerése

Leírás

array gethostbynamel ( string hostnév)

Tömbben adja vissza a megadott hostnév-re illő IP címek listáját.

Példa 1. gethostbynamel() példa

<?php
  $hosts = gethostbynamel('www.example.com');
  print_r($hosts);
?>

A fenti program a következőket mondja:
Array
(
    [0] => 192.0.34.166
)

Lásd még: gethostbyname(), gethostbyaddr(), checkdnsrr(), getmxrr(), valamint a man named(8) oldala!

getmxrr

(PHP 3, PHP 4 )

getmxrr --  Adott Internet hostnévhez tartozó MX rekordok kigyűjtése

Leírás

int getmxrr ( string hosztnév, tömb mxhosts [, array weight])

Névszerver keresést kezdeményez a megadott hostnév-re, MX (Mail Exchanger - levélszerver) rekordok után kutatva. Találat esetén TRUE értékkel tér vissza, míg hiba estén vagy találat hiányában FALSE értékkel.

A talált MX rekordokat az mxhosts argumentumban megadott tömbben kapjuk vissza. A weight opcionális paramétert megadva, az ott megjelölt tömbben visszakapjuk az egyes MX rekordok súlyozottságát.

Megjegyzés: E-mail címek valódiságának ellenőrzésére ez a függvény nem ajánlatos. Igaz, helyesen visszadja a DNS keresés eredményét, de hivatkozva az RFC 2821 dokumentumra, ha nem található ilyen DNS bejegyzés, maga a kérdéses hosztnév mögött álló gép lehet annak egyetlen levélkiszolgáló szervere, 0-ás prioritási szinttel.

Megjegyzés: A Windows változatokban ez a függvény nincs implementálva. Hasonló funkcionalitás elérhető a PEAR Net_DNS osztályának használatával

Lásd még: checkdnsrr(), gethostbyname(), gethostbynamel(), gethostbyaddr(), valamint a man named(8) oldala!

getprotobyname

(PHP 4 )

getprotobyname --  Névvel megadott protokol számát adja vissza

Leírás

int getprotobyname ( string név)

A getprotobyname() függvény a név paraméterben megadott protokol számát adja vissza. A név paraméternek az /etc/protocols-ban megadott névnek kell, hogy megfeleljen.

Lásd még: getprotobynumber()!

getprotobynumber

(PHP 4 )

getprotobynumber --  Számmal megadott protokol nevét adja vissza

Leírás

string getprotobynumber ( int protokolszám)

A getprotobynumber() visszaadja a protokolszám paraméternek megfelelő protokol /etc/protocols szerinti nevét.

Lásd még: getprotobyname()!

getservbyname

(PHP 4 )

getservbyname --  Adott szolgáltatástípus portszámának megallapítása név alapján

Leírás

int getservbyname ( string szolgáltatás, string protokol)

A getservbyname() a szolgáltatás és a protokol paraméterekre illő portszámot adja vissza. A szolgáltatás neve az /etc/services-nek megfelelő kell, hogy legyen. A protokol paraméter értéke "tcp" avagy "ucp" lehet (csupa kisbetűvel!).

Lásd még: getservbyport()!

getservbyport

(PHP 4 )

getservbyport --  Adott porton levő szolgáltatás nevének megállapítása

Leírás

string getservbyport ( int port, string protokol)

A getservbyport() /etc/services szerű nevét adja vissza az adott port-on levő, adott protokol-ú szolgáltatásnak. A protokol paraméter "tcp" vagy "udp" értéket vehet fel (csupa kisbetűvel).

Lásd még: getservbyname()!

ip2long

(PHP 4 )

ip2long --  Pontozott IP címet tartalmazó karakterláncot valódi IP cimmé alakít

Leírás

int ip2long ( string ip_cím)

Az ip2long() függvény IPv4 formátumú IP címmé alakítja az ip_cím paraméterben megadott szabványos, pontozott formátumú IP-t. Az IP címek valójában ebben a 4 byteos egész szám formátumban tárolódnak. Ha az ip_cím paraméter nem helyes, a függvény értékeként -1-et kapunk vissza. Vigyázat, a -1-et a PHP nem tekinti FALSE értéknek.

Példa 1. ip2long() Példa

<?php
$ip = gethostbyname("hu.php.net");
$out = "Az alábbi URL-ek egyenértékűek:<br>\n";
$out .= "http://hu.php.net/, http://".$ip."/, és http://".ip2long($ip)."/<br>\n";
echo $out;
?>

Megjegyzés: Mivel a PHP előjeles egésszám ábrázolást alkalmaz, és az IP címek negatív számokat eredményezhetnek ezáltal, szükséged lehet a sprintf() vagy printf() függvény "%u" formázó elemére. Ezáltal a megjelenített szám ábrázolása előjel nélküli lesz.

Eme második példa pedig azt mutatja meg, hogy a printf() segítségével hogy tudjuk ez a lekonvertált címet kiíratni:

Példa 2. IP cím kiíratása

<?php 
$ip = gethostbyname("hu.php.net"); 
$long = ip2long($ip);

if ($long === -1) {
    print 'Helytelen paraméter.';
} else {
    print $ip .   "\n";             // 212.75.128.75
    print $long . "\n";             // -733249461
    printf("%u\n", ip2long($ip));   // 3561717835
}
?>

Megjegyzés: Az ip2long() függvény a 255.255.255.255 IP címre -1 értéket fog visszaadni.

Lásd még: long2ip() és sprintf().

long2ip

(PHP 4 )

long2ip --  Négy byteon tárolt (IPv4) hálózatcímet alakít az Internet szabványnak megfelelő pontozott formára

Leírás

string long2ip ( int proper_address)

A long2ip() függvény pontozott formátumú (aaa.bbb.ccc.ddd) Internet címet hoz létre a paraméterben megadott valódi IP hálózati címből.

Lásd még: ip2long()!

openlog

(PHP 3, PHP 4 )

openlog -- A rendszer naplózóval való kapcsolat nyitása

Leírás

int openlog ( string ident, int option, int facility)

Az openlog() függvény segítségéval nyithatunk egy program számára kapcsolatot a rendszer naplózóval. Az ident argumentumban megadott szöveg minden naplóüzenet elejére kerül. Az option és a facility lehetséges értékei alant találhatóak. Az option paraméterrel jelezhetőek a különleges opciók, amik belejáthszhatnak a naplózás mikéntjébe. Kicsit lejjebb található róluk táblázat. A facility paraméterben adható meg, milyen csoporthoz tartozó program küldte ezt a naplóüzenetet. Azt, hogy milyen facility típussal hogy bánjon a syslog, azt a gépünk syslog konfigurációjában lehet részletezni. Az openlog() függvény használata nem szükségszerű, mivel a syslog() ezt amúgy is megteszi, ha szükség van rá. Ebben az esetben az ident paraméter FALSE lesz.

Táblázat 1. openlog() Opciók

KonstansLeírás
LOG_CONS bárminemű hiba esetén, ami a rendszer naplózó felé adatot küldés folyamán felmerül, küldje azt egyenesen a rendszer konzoljára
LOG_NDELAY azonnali kapcsolatnyitás a rendszer-naplózóhoz
LOG_ODELAY (alapértelmezett) várjon a csatlakozással, amíg az első naplóüzenet meg nem érkezik
LOG_PERRORa naplóüzeneteket az alapértelmezett hibakimenetre is küldje
LOG_PIDminden üzenethez mellékelje a processzazonosítót (PID) is
Ezen opciók közül egyet, de akár többet is fel lehet használni. Több opció megadása esetén az opciók közt 'vagy' kapcsolatot kell létrehozni. Amennyiben például egy azonnal nyitandó kapcsolat kell, ami írjon a konzolra és a PID-eket is mellékelje, azt igy kell megadni: LOG_CONS | LOG_NDELAY | LOG_PID

Táblázat 2. openlog() Szolgáltatás csoportok (facility paraméter)

KonstansLeírás
LOG_AUTH biztonsági/authorizációs üzenetek (ehelyett a LOG_AUTHPRIV-et használja, amely rendszerekben ez lehetséges)
LOG_AUTHPRIVbiytonsági/authorizációs üzenetek (privát)
LOG_CRONclock daemon (cron és at)
LOG_DAEMONegyéb rendszer daemon-ok
LOG_KERNkernel üzenetek
LOG_LOCAL0 ... LOG_LOCAL7helyi használatra fentartott, Windows alatt nem használható
LOG_LPRsoros nyomtató alrendszer
LOG_MAILlevél alrendszer
LOG_NEWSUSENET news alrendszer
LOG_SYSLOGa syslogd saját belső üzenetei
LOG_USERáltalános, felhasználó szinten történt bejegyzés
LOG_UUCPUUCP alrendszer

Megjegyzés: Windows alatt egyedül a LOG_USER naplóbejegyzés típus érvényes.

Lásd még: define_syslog_variables(), syslog() és closelog()!

pfsockopen

(PHP 3>= 3.0.7, PHP 4 )

pfsockopen --  Tartós Internet vagy Unix domain socket-kapcsolat megnyitása

Leírás

int pfsockopen ( string hostnév, int port [, int errno [, string errstr [, int timeout]]])

Teljességgel megegyezik eme függvény és a fsockopen(), csupán annyi különbséggel, hogy a pfsockopen() esetén a kapcsolat a php script futásának végeztével nem szűnik meg.

socket_get_status

socket_get_status --  A stream_get_meta_data() függvény egy álneve

Leírás

Ez a függvény a stream_get_meta_data() egy álneve.

socket_set_blocking

socket_set_blocking -- A stream_set_blocking() függvény egy álneve

Leírás

Ez a függvény a stream_set_blocking() egy álneve.

socket_set_timeout

socket_set_timeout -- A socket_set_timeout() függvény egy álneve

Leírás

Ez a függvény a socket_set_timeout() egy álneve.

syslog

(PHP 3, PHP 4 )

syslog -- Syslog üzenet létrehozása

Leírás

int syslog ( int prioritás, string üzenet)

A syslog() egy naplóüzenetet hoz létre, amit a rendszer naplózó rendszeren keresztül tesz közzé. A prioritás paraméter két dolog keverékéből jön, egyrészt az állapotból, másrészt a bejegyzési szintből, ennek részletezése az alant látható táblázatban látható. A másik paraméterben adható meg az üzenet konkrét szövege, amit egy az egyben továbbít, kivéve a %m karaktersor, ennek helyére az errno aktuális értékének megfelelő hibaüzenetet helyettesíti be.

Táblázat 1. syslog() prioritási szintek (csökkenő sorrendben)

KonstansLeírás
LOG_EMERGa rendszer használhatatlan
LOG_ALERTazonnali beavatkozás szükségeltetik
LOG_CRITkritikus állapot
LOG_ERRhibajellentést okozó állapot
LOG_WARNINGcsak figyelmeztetést okozó állapot
LOG_NOTICEnormál, de említésre méltó körülmény
LOG_INFOinformációs üzenet
LOG_DEBUGdebug szintű üzenet

Példa 1. A syslog() használata

<?php
define_syslog_variables();
// syslog nyitása, processz azonosítóstól. A log
// menjen ki az alapértelmezett hibakimenetre is,
// valamint a felhasználó által definiált naplózó
// mechanizmus is kapja meg a logot
openlog("myScripLog", LOG_PID | LOG_PERROR, LOG_LOCAL0);

// egy kis programkód

if (authorized_client()) {
    // itt lehet csinálni valami jogosultat :)
} else {
    // nem azonosított felhsználó!
    // a próbálkozás naplózásra kerül
    $access = date("Y/m/d H:i:s");
    
    syslog(LOG_WARNING,"Unauthorized client: $access $REMOTE_ADDR ($HTTP_USER_AGENT)");
}
closelog();
?>
Saját definiálású syslog kezelő felállításához érdemes a syslog.conf(5) Unix man oldalt olvasgatni. További információ a syslog többi állapotjelző lehetőségeiről a syslog(3) man oldalon található

Windows NT alatt a syslog emulálva van, az Event Log segítségével.

Megjegyzés: Windows alatt a LOG_LOCAL0 - LOG_LOCAL7 paraméterértékek nem használhatóak.

Lásd még: define_syslog_variables(), openlog() és closelog()!

LXIX. Ncurses terminal screen control functions

Bevezetés

ncurses (new curses) is a free software emulation of curses in System V Rel 4.0 (and above). It uses terminfo format, supports pads, colors, multiple highlights, form characters and function key mapping. Because of the interactive nature of this library, it will be of little use for writing Web applications, but may be useful when writing scripts meant using PHP from the command line.

Figyelem

Ez a kiterjesztés KÍSÉRLETI JELLEGGEL MŰKÖDIK. Ez azt jelenti, hogy minden itt dokumentált működés, beleértve a függvények nevét, működését vagy bármi más, amit a kiterjesztés kapcsán leírtunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a kiterjesztést csak a saját felelősségedre használd!

Ncurses is available for the following platforms:

  • AIX

  • BeOS

  • Cygwin

  • Digital Unix (aka OSF1)

  • FreeBSD

  • GNU/Linux

  • HPUX

  • IRIX

  • OS/2

  • SCO OpenServer

  • Solaris

  • SunOS


Követelmények

You need the ncurses libraries and headerfiles. Download the latest version from the ftp://ftp.gnu.org/pub/gnu/ncurses/ or from an other GNU-Mirror.


Telepítés

To get these functions to work, you have to compile the CGI or CLI version of PHP with --with-ncurses[=DIR].


Futásidejű beállítások

Az alábbi függvények viselkedése befolyásolható a php.ini segítségével.

Táblázat 1. Ncurses configuration options

NameDefaultChangeable
ncurses.value"42"PHP_INI_ALL
ncurses.string"foobar"PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().


Erőforrás típusok

Ez a kiterjesztés semmilyen erőforrás típust nem definiál.


Előre definiált állandók

Az itt listázott állandókat ez a kiterjesztés definiálja, és csak akkor elérhetőek, ha az adott kiterjesztés be van fordítva a PHP-be, vagy dinamikusan betöltött.


Error codes

On error ncurses functions return NCURSES_ERR.


Colors

Táblázat 2. ncurses color constants

constantmeaning
NCURSES_COLOR_BLACKno color (black)
NCURSES_COLOR_WHITEwhite
NCURSES_COLOR_REDred - supported when terminal is in color mode
NCURSES_COLOR_GREENgreen - supported when terminal is in color mod
NCURSES_COLOR_YELLOWyellow - supported when terminal is in color mod
NCURSES_COLOR_BLUEblue - supported when terminal is in color mod
NCURSES_COLOR_CYANcyan - supported when terminal is in color mod
NCURSES_COLOR_MAGENTAmagenta - supported when terminal is in color mod

Keys

Táblázat 3. ncurses key constants

constantmeaning
NCURSES_KEY_F0 - NCURSES_KEY_F64function keys F1 - F64
NCURSES_KEY_DOWNdown arrow
NCURSES_KEY_UPup arrow
NCURSES_KEY_LEFTleft arrow
NCURSES_KEY_RIGHTright arrow
NCURSES_KEY_HOMEhome key (upward+left arrow)
NCURSES_KEY_BACKSPACEbackspace
NCURSES_KEY_DLdelete line
NCURSES_KEY_ILinsert line
NCURSES_KEY_DCdelete character
NCURSES_KEY_ICinsert char or enter insert mode
NCURSES_KEY_EICexit insert char mode
NCURSES_KEY_CLEARclear screen
NCURSES_KEY_EOSclear to end of screen
NCURSES_KEY_EOLclear to end of line
NCURSES_KEY_SFscroll one line forward
NCURSES_KEY_SRscroll one line backward
NCURSES_KEY_NPAGEnext page
NCURSES_KEY_PPAGEprevious page
NCURSES_KEY_STABset tab
NCURSES_KEY_CTABclear tab
NCURSES_KEY_CATABclear all tabs
NCURSES_KEY_SRESETsoft (partial) reset
NCURSES_KEY_RESETreset or hard reset
NCURSES_KEY_PRINTprint
NCURSES_KEY_LLlower left
NCURSES_KEY_A1upper left of keypad
NCURSES_KEY_A3upper right of keypad
NCURSES_KEY_B2center of keypad
NCURSES_KEY_C1lower left of keypad
NCURSES_KEY_C3lower right of keypad
NCURSES_KEY_BTABback tab
NCURSES_KEY_BEGbeginning
NCURSES_KEY_CANCELcancel
NCURSES_KEY_CLOSEclose
NCURSES_KEY_COMMANDcmd (command)
NCURSES_KEY_COPYcopy
NCURSES_KEY_CREATEcreate
NCURSES_KEY_ENDend
NCURSES_KEY_EXITexit
NCURSES_KEY_FINDfind
NCURSES_KEY_HELPhelp
NCURSES_KEY_MARKmark
NCURSES_KEY_MESSAGEmessage
NCURSES_KEY_MOVEmove
NCURSES_KEY_NEXTnext
NCURSES_KEY_OPENopen
NCURSES_KEY_OPTIONSoptions
NCURSES_KEY_PREVIOUSprevious
NCURSES_KEY_REDOredo
NCURSES_KEY_REFERENCEref (reference)
NCURSES_KEY_REFRESHrefresh
NCURSES_KEY_REPLACEreplace
NCURSES_KEY_RESTARTrestart
NCURSES_KEY_RESUMEresume
NCURSES_KEY_SAVEsave
NCURSES_KEY_SBEGshiftet beg (beginning)
NCURSES_KEY_SCANCELshifted cancel
NCURSES_KEY_SCOMMANDshifted command
NCURSES_KEY_SCOPYshifted copy
NCURSES_KEY_SCREATEshifted create
NCURSES_KEY_SDCshifted delete char
NCURSES_KEY_SDLshifted delete line
NCURSES_KEY_SELECTselect
NCURSES_KEY_SENDshifted end
NCURSES_KEY_SEOLshifted end of line
NCURSES_KEY_SEXITshifted exit
NCURSES_KEY_SFINDshifted find
NCURSES_KEY_SHELPshifted help
NCURSES_KEY_SHOMEshifted home
NCURSES_KEY_SICshifted input
NCURSES_KEY_SLEFTshifted left arrow
NCURSES_KEY_SMESSAGEshifted message
NCURSES_KEY_SMOVEshifted move
NCURSES_KEY_SNEXTshifted next
NCURSES_KEY_SOPTIONSshifted options
NCURSES_KEY_SPREVIOUSshifted previous
NCURSES_KEY_SPRINTshifted print
NCURSES_KEY_SREDOshifted redo
NCURSES_KEY_SREPLACEshifted replace
NCURSES_KEY_SRIGHTshifted right arrow
NCURSES_KEY_SRSUMEshifted resume
NCURSES_KEY_SSAVEshifted save
NCURSES_KEY_SSUSPENDshifted suspend
NCURSES_KEY_UNDOundo
NCURSES_KEY_MOUSEmouse event has occurred
NCURSES_KEY_MAXmaximum key value

Mouse

Táblázat 4. mouse constants

Constantmeaning
NCURSES_BUTTON1_RELEASED - NCURSES_BUTTON4_RELEASEDbutton (1-4) released
NCURSES_BUTTON1_PRESSED - NCURSES_BUTTON4_PRESSEDbutton (1-4) pressed
NCURSES_BUTTON1_CLICKED - NCURSES_BUTTON4_CLICKEDbutton (1-4) clicked
NCURSES_BUTTON1_DOUBLE_CLICKED - NCURSES_BUTTON4_DOUBLE_CLICKEDbutton (1-4) double clicked
NCURSES_BUTTON1_TRIPLE_CLICKED - NCURSES_BUTTON4_TRIPLE_CLICKEDbutton (1-4) triple clicked
NCURSES_BUTTON_CTRLctrl pressed during click
NCURSES_BUTTON_SHIFTshift pressed during click
NCURSES_BUTTON_ALTalt pressed during click
NCURSES_ALL_MOUSE_EVENTSreport all mouse events
NCURSES_REPORT_MOUSE_POSITIONreport mouse position
Tartalom
ncurses_addch -- Add character at current position and advance cursor
ncurses_addchnstr -- Add attributed string with specified length at current position
ncurses_addchstr -- Add attributed string at current position
ncurses_addnstr -- Add string with specified length at current position
ncurses_addstr -- Output text at current position
ncurses_assume_default_colors -- Define default colors for color 0
ncurses_attroff -- Turn off the given attributes
ncurses_attron -- Turn on the given attributes
ncurses_attrset -- Set given attributes
ncurses_baudrate -- Returns baudrate of terminal
ncurses_beep -- Let the terminal beep
ncurses_bkgd -- Set background property for terminal screen
ncurses_bkgdset -- Control screen background
ncurses_border -- Draw a border around the screen using attributed characters
ncurses_bottom_panel --  Moves a visible panel to the bottom of the stack
ncurses_can_change_color -- Check if we can change terminals colors
ncurses_cbreak -- Switch of input buffering
ncurses_clear -- Clear screen
ncurses_clrtobot -- Clear screen from current position to bottom
ncurses_clrtoeol -- Clear screen from current position to end of line
ncurses_color_content --  Gets the RGB value for color
ncurses_color_set -- Set fore- and background color
ncurses_curs_set -- Set cursor state
ncurses_def_prog_mode -- Saves terminals (program) mode
ncurses_def_shell_mode -- Saves terminals (shell) mode
ncurses_define_key -- Define a keycode
ncurses_del_panel --  Remove panel from the stack and delete it (but not the associated window)
ncurses_delay_output -- Delay output on terminal using padding characters
ncurses_delch -- Delete character at current position, move rest of line left
ncurses_deleteln -- Delete line at current position, move rest of screen up
ncurses_delwin -- Delete a ncurses window
ncurses_doupdate -- Write all prepared refreshes to terminal
ncurses_echo -- Activate keyboard input echo
ncurses_echochar -- Single character output including refresh
ncurses_end -- Stop using ncurses, clean up the screen
ncurses_erase -- Erase terminal screen
ncurses_erasechar -- Returns current erase character
ncurses_filter -- 
ncurses_flash -- Flash terminal screen (visual bell)
ncurses_flushinp -- Flush keyboard input buffer
ncurses_getch -- Read a character from keyboard
ncurses_getmaxyx --  Returns the size of a window
ncurses_getmouse -- Reads mouse event
ncurses_getyx --  Returns the current cursor position for a window
ncurses_halfdelay -- Put terminal into halfdelay mode
ncurses_has_colors -- Check if terminal has colors
ncurses_has_ic -- Check for insert- and delete-capabilities
ncurses_has_il -- Check for line insert- and delete-capabilities
ncurses_has_key -- Check for presence of a function key on terminal keyboard
ncurses_hide_panel --  Remove panel from the stack, making it invisible
ncurses_hline -- Draw a horizontal line at current position using an attributed character and max. n characters long
ncurses_inch -- Get character and attribute at current position
ncurses_init_color -- Set new RGB value for color
ncurses_init_pair -- Allocate a color pair
ncurses_init -- Initialize ncurses
ncurses_insch -- Insert character moving rest of line including character at current position
ncurses_insdelln -- Insert lines before current line scrolling down (negative numbers delete and scroll up)
ncurses_insertln -- Insert a line, move rest of screen down
ncurses_insstr -- Insert string at current position, moving rest of line right
ncurses_instr -- Reads string from terminal screen
ncurses_isendwin -- Ncurses is in endwin mode, normal screen output may be performed
ncurses_keyok -- Enable or disable a keycode
ncurses_keypad --  Turns keypad on or off
ncurses_killchar -- Returns current line kill character
ncurses_longname -- Returns terminals description
ncurses_meta --  Enables/Disable 8-bit meta key information
ncurses_mouse_trafo --  Transforms coordinates
ncurses_mouseinterval -- Set timeout for mouse button clicks
ncurses_mousemask -- Sets mouse options
ncurses_move_panel --  Moves a panel so that it's upper-left corner is at [startx, starty]
ncurses_move -- Move output position
ncurses_mvaddch -- Move current position and add character
ncurses_mvaddchnstr -- Move position and add attributed string with specified length
ncurses_mvaddchstr -- Move position and add attributed string
ncurses_mvaddnstr -- Move position and add string with specified length
ncurses_mvaddstr -- Move position and add string
ncurses_mvcur -- Move cursor immediately
ncurses_mvdelch -- Move position and delete character, shift rest of line left
ncurses_mvgetch -- Move position and get character at new position
ncurses_mvhline -- Set new position and draw a horizontal line using an attributed character and max. n characters long
ncurses_mvinch -- Move position and get attributed character at new position
ncurses_mvvline -- Set new position and draw a vertical line using an attributed character and max. n characters long
ncurses_mvwaddstr -- Add string at new position in window
ncurses_napms -- Sleep
ncurses_new_panel --  Create a new panel and associate it with window
ncurses_newpad --  Creates a new pad (window)
ncurses_newwin -- Create a new window
ncurses_nl -- Translate newline and carriage return / line feed
ncurses_nocbreak -- Switch terminal to cooked mode
ncurses_noecho -- Switch off keyboard input echo
ncurses_nonl -- Do not translate newline and carriage return / line feed
ncurses_noqiflush -- Do not flush on signal characters
ncurses_noraw -- Switch terminal out of raw mode
ncurses_pair_content --  Gets the RGB value for color
ncurses_panel_above --  Returns the panel above panel. If panel is null, returns the bottom panel in the stack
ncurses_panel_below --  Returns the panel below panel. If panel is null, returns the top panel in the stack
ncurses_panel_window --  Returns the window associated with panel
ncurses_pnoutrefresh --  Copies a region from a pad into the virtual screen
ncurses_prefresh --  Copies a region from a pad into the virtual screen
ncurses_putp -- 
ncurses_qiflush -- Flush on signal characters
ncurses_raw -- Switch terminal into raw mode
ncurses_refresh -- Refresh screen
ncurses_replace_panel --  Replaces the window associated with panel
ncurses_reset_prog_mode --  Resets the prog mode saved by def_prog_mode
ncurses_reset_shell_mode --  Resets the shell mode saved by def_shell_mode
ncurses_resetty -- Restores saved terminal state
ncurses_savetty -- Saves terminal state
ncurses_scr_dump -- Dump screen content to file
ncurses_scr_init -- Initialize screen from file dump
ncurses_scr_restore -- Restore screen from file dump
ncurses_scr_set -- Inherit screen from file dump
ncurses_scrl -- Scroll window content up or down without changing current position
ncurses_show_panel --  Places an invisible panel on top of the stack, making it visible
ncurses_slk_attr -- Returns current soft label key attribute
ncurses_slk_attroff -- 
ncurses_slk_attron -- 
ncurses_slk_attrset -- 
ncurses_slk_clear -- Clears soft labels from screen
ncurses_slk_color -- Sets color for soft label keys
ncurses_slk_init -- Initializes soft label key functions
ncurses_slk_noutrefresh -- Copies soft label keys to virtual screen
ncurses_slk_refresh -- Copies soft label keys to screen
ncurses_slk_restore -- Restores soft label keys
ncurses_slk_set --  Sets function key labels
ncurses_slk_touch -- Forces output when ncurses_slk_noutrefresh is performed
ncurses_standend -- Stop using 'standout' attribute
ncurses_standout -- Start using 'standout' attribute
ncurses_start_color -- Start using colors
ncurses_termattrs -- Returns a logical OR of all attribute flags supported by terminal
ncurses_termname -- Returns terminals (short)-name
ncurses_timeout -- Set timeout for special key sequences
ncurses_top_panel --  Moves a visible panel to the top of the stack
ncurses_typeahead -- Specify different filedescriptor for typeahead checking
ncurses_ungetch -- Put a character back into the input stream
ncurses_ungetmouse -- Pushes mouse event to queue
ncurses_update_panels --  Refreshes the virtual screen to reflect the relations between panels in the stack.
ncurses_use_default_colors -- Assign terminal default colors to color id -1
ncurses_use_env -- Control use of environment information about terminal size
ncurses_use_extended_names -- Control use of extended names in terminfo descriptions
ncurses_vidattr -- 
ncurses_vline -- Draw a vertical line at current position using an attributed character and max. n characters long
ncurses_waddch --  Adds character at current position in a window and advance cursor
ncurses_waddstr --  Outputs text at current postion in window
ncurses_wattroff --  Turns off attributes for a window
ncurses_wattron --  Turns on attributes for a window
ncurses_wattrset --  Set the attributes for a window
ncurses_wborder --  Draws a border around the window using attributed characters
ncurses_wclear --  Clears window
ncurses_wcolor_set --  Sets windows color pairings
ncurses_werase --  Erase window contents
ncurses_wgetch --  Reads a character from keyboard (window)
ncurses_whline --  Draws a horizontal line in a window at current position using an attributed character and max. n characters long
ncurses_wmouse_trafo --  Transforms window/stdscr coordinates
ncurses_wmove --  Moves windows output position
ncurses_wnoutrefresh --  Copies window to virtual screen
ncurses_wrefresh -- Refresh window on terminal screen
ncurses_wstandend --  End standout mode for a window
ncurses_wstandout --  Enter standout mode for a window
ncurses_wvline --  Draws a vertical line in a window at current position using an attributed character and max. n characters long

ncurses_addch

(PHP 4 >= 4.1.0)

ncurses_addch -- Add character at current position and advance cursor

Description

int ncurses_addch ( int ch)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_addchnstr

(PHP 4 >= 4.2.0)

ncurses_addchnstr -- Add attributed string with specified length at current position

Description

int ncurses_addchnstr ( string s, int n)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_addchstr

(PHP 4 >= 4.2.0)

ncurses_addchstr -- Add attributed string at current position

Description

int ncurses_addchstr ( string s)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_addnstr

(PHP 4 >= 4.2.0)

ncurses_addnstr -- Add string with specified length at current position

Description

int ncurses_addnstr ( string s, int n)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_addstr

(PHP 4 >= 4.2.0)

ncurses_addstr -- Output text at current position

Description

int ncurses_addstr ( string text)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_assume_default_colors

(PHP 4 >= 4.2.0)

ncurses_assume_default_colors -- Define default colors for color 0

Description

int ncurses_assume_default_colors ( int fg, int bg)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_attroff

(PHP 4 >= 4.1.0)

ncurses_attroff -- Turn off the given attributes

Description

int ncurses_attroff ( int attributes)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_attron

(PHP 4 >= 4.1.0)

ncurses_attron -- Turn on the given attributes

Description

int ncurses_attron ( int attributes)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_attrset

(PHP 4 >= 4.1.0)

ncurses_attrset -- Set given attributes

Description

int ncurses_attrset ( int attributes)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_baudrate

(PHP 4 >= 4.1.0)

ncurses_baudrate -- Returns baudrate of terminal

Description

int ncurses_baudrate ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_beep

(PHP 4 >= 4.1.0)

ncurses_beep -- Let the terminal beep

Description

int ncurses_beep ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

ncurses_beep() sends an audible alert (bell) and if its not possible flashes the screen. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

See also ncurses_flash()

ncurses_bkgd

(PHP 4 >= 4.1.0)

ncurses_bkgd -- Set background property for terminal screen

Description

int ncurses_bkgd ( int attrchar)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_bkgdset

(PHP 4 >= 4.1.0)

ncurses_bkgdset -- Control screen background

Description

void ncurses_bkgdset ( int attrchar)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_border

(PHP 4 >= 4.2.0)

ncurses_border -- Draw a border around the screen using attributed characters

Description

int ncurses_border ( int left, int right, int top, int bottom, int tl_corner, int tr_corner, int bl_corner, int br_corner)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_bottom_panel

(PHP 4 >= 4.3.0)

ncurses_bottom_panel --  Moves a visible panel to the bottom of the stack

Description

int ncurses_bottom_panel ( resource panel)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_can_change_color

(PHP 4 >= 4.1.0)

ncurses_can_change_color -- Check if we can change terminals colors

Description

bool ncurses_can_change_color ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

The function ncurses_can_change_color() returns TRUE or FALSE, depending on whether the terminal has color capabilities and whether the programmer can change the colors.

ncurses_cbreak

(PHP 4 >= 4.1.0)

ncurses_cbreak -- Switch of input buffering

Description

bool ncurses_cbreak ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

ncurses_cbreak() disables line buffering and character processing (interrupt and flow control characters are unaffected), making characters typed by the user immediately available to the program.

ncurses_cbreak() returns TRUE or NCURSES_ERR if any error occurred.

See also: ncurses_nocbreak()

ncurses_clear

(PHP 4 >= 4.1.0)

ncurses_clear -- Clear screen

Description

bool ncurses_clear ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

ncurses_clear() clears the screen completely without setting blanks. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Note: ncurses_clear() clears the screen without setting blanks, which have the current background rendition. To clear screen with blanks, use ncurses_erase().

See also ncurses_erase().

ncurses_clrtobot

(PHP 4 >= 4.1.0)

ncurses_clrtobot -- Clear screen from current position to bottom

Description

bool ncurses_clrtobot ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

ncurses_clrtobot() erases all lines from cursor to end of screen and creates blanks. Blanks created by ncurses_clrtobot() have the current background rendition. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

See also ncurses_clear(), and ncurses_clrtoeol()

ncurses_clrtoeol

(PHP 4 >= 4.1.0)

ncurses_clrtoeol -- Clear screen from current position to end of line

Description

bool ncurses_clrtoeol ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

ncurses_clrtoeol() erases the current line from cursor position to the end. Blanks created by ncurses_clrtoeol() have the current background rendition. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

See also ncurses_clear(), and ncurses_clrtobot()

ncurses_color_content

(PHP 4 >= 4.3.0)

ncurses_color_content --  Gets the RGB value for color

Description

int ncurses_color_content ( int color, int &r, int &g, int &b)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_color_set

(PHP 4 >= 4.1.0)

ncurses_color_set -- Set fore- and background color

Description

int ncurses_color_set ( int pair)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_curs_set

(PHP 4 >= 4.1.0)

ncurses_curs_set -- Set cursor state

Description

int ncurses_curs_set ( int visibility)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_def_prog_mode

(PHP 4 >= 4.1.0)

ncurses_def_prog_mode -- Saves terminals (program) mode

Description

bool ncurses_def_prog_mode ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

ncurses_def_prog_mode() saves the current terminal modes for program (in curses) for use by ncurses_reset_prog_mode(). Returns FALSE on success, otherwise TRUE.

See also: ncurses_reset_prog_mode()

ncurses_def_shell_mode

(PHP 4 >= 4.1.0)

ncurses_def_shell_mode -- Saves terminals (shell) mode

Description

bool ncurses_def_shell_mode ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

ncurses_def_shell_mode() saves the current terminal modes for shell (not in curses) for use by ncurses_reset_shell_mode(). Returns FALSE on success, otherwise TRUE.

See also: ncurses_reset_shell_mode()

ncurses_define_key

(PHP 4 >= 4.2.0)

ncurses_define_key -- Define a keycode

Description

int ncurses_define_key ( string definition, int keycode)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_del_panel

(PHP 4 >= 4.3.0)

ncurses_del_panel --  Remove panel from the stack and delete it (but not the associated window)

Description

int ncurses_del_panel ( resource panel)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_delay_output

(PHP 4 >= 4.1.0)

ncurses_delay_output -- Delay output on terminal using padding characters

Description

int ncurses_delay_output ( int milliseconds)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_delch

(PHP 4 >= 4.1.0)

ncurses_delch -- Delete character at current position, move rest of line left

Description

bool ncurses_delch ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

ncurses_delch() deletes the character under the cursor. All characters to the right of the cursor on the same line are moved to the left one position and the last character on the line is filled with a blank. The cursor position does not change. Returns FALSE on success, otherwise TRUE.

See also: ncurses_deleteln()

ncurses_deleteln

(PHP 4 >= 4.1.0)

ncurses_deleteln -- Delete line at current position, move rest of screen up

Description

bool ncurses_deleteln ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

ncurses_deleteln() deletes the current line under cursorposition. All lines below the current line are moved up one line. The bottom line of window is cleared. Cursor position does not change. Returns FALSE on success, otherwise TRUE.

See also: ncurses_delch()

ncurses_delwin

(PHP 4 >= 4.1.0)

ncurses_delwin -- Delete a ncurses window

Description

int ncurses_delwin ( resource window)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_doupdate

(PHP 4 >= 4.1.0)

ncurses_doupdate -- Write all prepared refreshes to terminal

Description

bool ncurses_doupdate ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

ncurses_doupdate()() compares the virtual screen to the physical screen and updates the physical screen. This way is more effective than using multiple refresh calls. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

ncurses_echo

(PHP 4 >= 4.1.0)

ncurses_echo -- Activate keyboard input echo

Description

bool ncurses_echo ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

ncurses_echo() enables echo mode. All characters typed by user are echoed by ncurses_getch(). Returns FALSE on success, TRUE if any error occurred.

To disable echo mode use ncurses_noecho().

ncurses_echochar

(PHP 4 >= 4.1.0)

ncurses_echochar -- Single character output including refresh

Description

int ncurses_echochar ( int character)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_end

(PHP 4 >= 4.1.0)

ncurses_end -- Stop using ncurses, clean up the screen

Description

int ncurses_end ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_erase

(PHP 4 >= 4.1.0)

ncurses_erase -- Erase terminal screen

Description

bool ncurses_erase ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

ncurses_erase() fills the terminal screen with blanks. Created blanks have the current background rendition, set by ncurses_bkgd(). Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

See also ncurses_bkgd(), and ncurses_clear()

ncurses_erasechar

(PHP 4 >= 4.1.0)

ncurses_erasechar -- Returns current erase character

Description

string ncurses_erasechar ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

ncurses_erasechar() returns the current erase char character.

See also: ncurses_killchar()

ncurses_filter

(PHP 4 >= 4.1.0)

ncurses_filter -- 

Description

int ncurses_filter ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_flash

(PHP 4 >= 4.1.0)

ncurses_flash -- Flash terminal screen (visual bell)

Description

bool ncurses_flash ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

ncurses_flash() flashes the screen, and if its not possible, sends an audible alert (bell). Returns FALSE on success, otherwise TRUE.

See also: ncurses_beep()

ncurses_flushinp

(PHP 4 >= 4.1.0)

ncurses_flushinp -- Flush keyboard input buffer

Description

bool ncurses_flushinp ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

The ncurses_flushinp() throws away any typeahead that has been typed and has not yet been read by your program. Returns FALSE on success, otherwise TRUE.

ncurses_getch

(PHP 4 >= 4.1.0)

ncurses_getch -- Read a character from keyboard

Description

int ncurses_getch ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_getmaxyx

(PHP 4 >= 4.3.0)

ncurses_getmaxyx --  Returns the size of a window

Description

void ncurses_getmaxyx ( resource window, int &y, int &x)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_getmouse

(PHP 4 >= 4.2.0)

ncurses_getmouse -- Reads mouse event

Description

bool ncurses_getmouse ( array mevent)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

ncurses_getmouse() reads mouse event out of queue. Function ncurses_getmouse() will return ;FALSE if a mouse event is actually visible in the given window, otherwise it will return TRUE. Event options will be delivered in parameter mevent, which has to be an array, passed by reference (see example below). On success an associative array with following keys will be delivered:

  • "id" : Id to distinguish multiple devices

  • "x" : screen relative x-position in character cells

  • "y" : screen relative y-position in character cells

  • "z" : currently not supported

  • "mmask" : Mouse action

Példa 1. ncurses_getmouse() example

<?php
switch (ncurses_getch()){
  case NCURSES_KEY_MOUSE:
    if (!ncurses_getmouse(&$mevent)){
      if ($mevent["mmask"] & NCURSES_MOUSE_BUTTON1_PRESSED){
        $mouse_x = $mevent["x"]; // Save mouse position
        $mouse_y = $mevent["y"];
      }
    }
  break;

  default:
    /* .... */
}
?>

See also ncurses_ungetmouse()

ncurses_getyx

(PHP 4 >= 4.3.0)

ncurses_getyx --  Returns the current cursor position for a window

Description

void ncurses_getyx ( resource window, int &y, int &x)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_halfdelay

(PHP 4 >= 4.1.0)

ncurses_halfdelay -- Put terminal into halfdelay mode

Description

int ncurses_halfdelay ( int tenth)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_has_colors

(PHP 4 >= 4.1.0)

ncurses_has_colors -- Check if terminal has colors

Description

bool ncurses_has_colors ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

ncurses_has_colors() returns TRUE or FALSE depending on whether the terminal has color capacities.

See also: ncurses_can_change_color()

ncurses_has_ic

(PHP 4 >= 4.1.0)

ncurses_has_ic -- Check for insert- and delete-capabilities

Description

bool ncurses_has_ic ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

ncurses_has_ic() checks terminals insert- and delete capabilities. It returns TRUE when terminal has insert/delete-capabilities, otherwise FALSE.

See also: ncurses_has_il()

ncurses_has_il

(PHP 4 >= 4.1.0)

ncurses_has_il -- Check for line insert- and delete-capabilities

Description

bool ncurses_has_il ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

ncurses_has_il() checks terminals insert- and delete-line-capabilities. It returns TRUE when terminal has insert/delete-line capabilities, otherwise FALSE

See also: ncurses_has_ic()

ncurses_has_key

(PHP 4 >= 4.1.0)

ncurses_has_key -- Check for presence of a function key on terminal keyboard

Description

int ncurses_has_key ( int keycode)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_hide_panel

(PHP 4 >= 4.3.0)

ncurses_hide_panel --  Remove panel from the stack, making it invisible

Description

int ncurses_hide_panel ( resource panel)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_hline

(PHP 4 >= 4.2.0)

ncurses_hline -- Draw a horizontal line at current position using an attributed character and max. n characters long

Description

int ncurses_hline ( int charattr, int n)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_inch

(PHP 4 >= 4.1.0)

ncurses_inch -- Get character and attribute at current position

Description

string ncurses_inch ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

ncurses_inch() returns the character from the current position.

ncurses_init_color

(PHP 4 >= 4.2.0)

ncurses_init_color -- Set new RGB value for color

Description

int ncurses_init_color ( int color, int r, int g, int b)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_init_pair

(PHP 4 >= 4.1.0)

ncurses_init_pair -- Allocate a color pair

Description

int ncurses_init_pair ( int pair, int fg, int bg)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_init

(PHP 4 >= 4.1.0)

ncurses_init -- Initialize ncurses

Description

int ncurses_init ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_insch

(PHP 4 >= 4.1.0)

ncurses_insch -- Insert character moving rest of line including character at current position

Description

int ncurses_insch ( int character)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_insdelln

(PHP 4 >= 4.1.0)

ncurses_insdelln -- Insert lines before current line scrolling down (negative numbers delete and scroll up)

Description

int ncurses_insdelln ( int count)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_insertln

(PHP 4 >= 4.1.0)

ncurses_insertln -- Insert a line, move rest of screen down

Description

bool ncurses_insertln ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

ncurses_insertln() inserts a new line above the current line. The bottom line will be lost.

ncurses_insstr

(PHP 4 >= 4.2.0)

ncurses_insstr -- Insert string at current position, moving rest of line right

Description

int ncurses_insstr ( string text)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_instr

(PHP 4 >= 4.2.0)

ncurses_instr -- Reads string from terminal screen

Description

int ncurses_instr ( string buffer)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

ncurses_instr() returns the number of characters read from the current character position until end of line. buffer contains the characters. Attributes are stripped from the characters.

ncurses_isendwin

(PHP 4 >= 4.1.0)

ncurses_isendwin -- Ncurses is in endwin mode, normal screen output may be performed

Description

bool ncurses_isendwin ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

ncurses_isendwin() returns TRUE, if ncurses_endwin() has been called without any subsequent calls to ncurses_wrefresh(), otherwise FALSE.

See also ncurses_endwin() and ncurses_wrefresh().

ncurses_keyok

(PHP 4 >= 4.2.0)

ncurses_keyok -- Enable or disable a keycode

Description

int ncurses_keyok ( int keycode, bool enable)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_keypad

(PHP 4 >= 4.2.0)

ncurses_keypad --  Turns keypad on or off

Description

int ncurses_keypad ( resource window, bool bf)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_killchar

(PHP 4 >= 4.1.0)

ncurses_killchar -- Returns current line kill character

Description

bool ncurses_killchar ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

ncurses_killchar() returns the current line kill character.

See also: ncurses_erasechar()

ncurses_longname

(PHP 4 >= 4.2.0)

ncurses_longname -- Returns terminals description

Description

string ncurses_longname ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

ncurses_longname() returns a verbose description of the terminal. The description is truncated to 128 characters. On Error ncurses_longname() returns NULL.

See also: ncurses_termname()

ncurses_meta

(PHP 4 >= 4.3.0)

ncurses_meta --  Enables/Disable 8-bit meta key information

Description

long ncurses_meta ( resource window, bool 8bit)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_mouse_trafo

(PHP 4 >= 4.2.0)

ncurses_mouse_trafo --  Transforms coordinates

Description

bool ncurses_mouse_trafo ( int &y, int &x, bool toscreen)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_mouseinterval

(PHP 4 >= 4.1.0)

ncurses_mouseinterval -- Set timeout for mouse button clicks

Description

int ncurses_mouseinterval ( int milliseconds)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_mousemask

(PHP 4 >= 4.2.0)

ncurses_mousemask -- Sets mouse options

Description

int ncurses_mousemask ( int newmask, int oldmask)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Function ncurses_mousemask() will set mouse events to be reported. By default no mouse events will be reported. The function ncurses_mousemask() will return a mask to indicated which of the in parameter newmask specified mouse events can be reported. On complete failure, it returns 0. In parameter oldmask, which is passed by reference ncurses_mousemask() returns the previous value of mouse event mask. Mouse events are represented by NCURSES_KEY_MOUSE in the ncurses_wgetch() input stream. To read the event data and pop the event of of queue, call ncurses_getmouse().

As a side effect, setting a zero mousemask in newmask turns off the mouse pointer. Setting a non zero value turns mouse pointer on.

mouse mask options can be set with the following predefined constants:

  • NCURSES_BUTTON1_PRESSED

  • NCURSES_BUTTON1_RELEASED

  • NCURSES_BUTTON1_CLICKED

  • NCURSES_BUTTON1_DOUBLE_CLICKED

  • NCURSES_BUTTON1_TRIPLE_CLICKED

  • NCURSES_BUTTON2_PRESSED

  • NCURSES_BUTTON2_RELEASED

  • NCURSES_BUTTON2_CLICKED

  • NCURSES_BUTTON2_DOUBLE_CLICKED

  • NCURSES_BUTTON2_TRIPLE_CLICKED

  • NCURSES_BUTTON3_PRESSED

  • NCURSES_BUTTON3_RELEASED

  • NCURSES_BUTTON3_CLICKED

  • NCURSES_BUTTON3_DOUBLE_CLICKED

  • NCURSES_BUTTON3_TRIPLE_CLICKED

  • NCURSES_BUTTON4_PRESSED

  • NCURSES_BUTTON4_RELEASED

  • NCURSES_BUTTON4_CLICKED

  • NCURSES_BUTTON4_DOUBLE_CLICKED

  • NCURSES_BUTTON4_TRIPLE_CLICKED

  • NCURSES_BUTTON_SHIFT>

  • NCURSES_BUTTON_CTRL

  • NCURSES_BUTTON_ALT

  • NCURSES_ALL_MOUSE_EVENTS

  • NCURSES_REPORT_MOUSE_POSITION

Példa 1. ncurses_mousemask() example

<?php
$newmask = NCURSES_BUTTON1_CLICKED + NCURSES_BUTTON1_RELEASED;
$mask = ncurses_mousemask($newmask, &$oldmask);
if ($mask & $newmask){
  printf ("All specified mouse options will be supported\n");
}
?>

See also ncurses_getmouse(), ncurses_ungetmouse() and ncurese_getch().

ncurses_move_panel

(PHP 4 >= 4.3.0)

ncurses_move_panel --  Moves a panel so that it's upper-left corner is at [startx, starty]

Description

int ncurses_move_panel ( resource panel, int startx, int starty)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_move

(PHP 4 >= 4.1.0)

ncurses_move -- Move output position

Description

int ncurses_move ( int y, int x)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_mvaddch

(PHP 4 >= 4.2.0)

ncurses_mvaddch -- Move current position and add character

Description

int ncurses_mvaddch ( int y, int x, int c)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_mvaddchnstr

(PHP 4 >= 4.2.0)

ncurses_mvaddchnstr -- Move position and add attributed string with specified length

Description

int ncurses_mvaddchnstr ( int y, int x, string s, int n)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_mvaddchstr

(PHP 4 >= 4.2.0)

ncurses_mvaddchstr -- Move position and add attributed string

Description

int ncurses_mvaddchstr ( int y, int x, string s)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_mvaddnstr

(PHP 4 >= 4.2.0)

ncurses_mvaddnstr -- Move position and add string with specified length

Description

int ncurses_mvaddnstr ( int y, int x, string s, int n)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_mvaddstr

(PHP 4 >= 4.2.0)

ncurses_mvaddstr -- Move position and add string

Description

int ncurses_mvaddstr ( int y, int x, string s)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_mvcur

(PHP 4 >= 4.2.0)

ncurses_mvcur -- Move cursor immediately

Description

int ncurses_mvcur ( int old_y, int old_x, int new_y, int new_x)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_mvdelch

(PHP 4 >= 4.2.0)

ncurses_mvdelch -- Move position and delete character, shift rest of line left

Description

int ncurses_mvdelch ( int y, int x)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_mvgetch

(PHP 4 >= 4.2.0)

ncurses_mvgetch -- Move position and get character at new position

Description

int ncurses_mvgetch ( int y, int x)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_mvhline

(PHP 4 >= 4.2.0)

ncurses_mvhline -- Set new position and draw a horizontal line using an attributed character and max. n characters long

Description

int ncurses_mvhline ( int y, int x, int attrchar, int n)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_mvinch

(PHP 4 >= 4.2.0)

ncurses_mvinch -- Move position and get attributed character at new position

Description

int ncurses_mvinch ( int y, int x)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_mvvline

(no version information, might be only in CVS)

ncurses_mvvline -- Set new position and draw a vertical line using an attributed character and max. n characters long

Description

int ncurses_mvvline ( int y, int x, int attrchar, int n)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_mvwaddstr

(PHP 4 >= 4.2.0)

ncurses_mvwaddstr -- Add string at new position in window

Description

int ncurses_mvwaddstr ( resource window, int y, int x, string text)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_napms

(PHP 4 >= 4.1.0)

ncurses_napms -- Sleep

Description

int ncurses_napms ( int milliseconds)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_new_panel

(PHP 4 >= 4.3.0)

ncurses_new_panel --  Create a new panel and associate it with window

Description

resource ncurses_new_panel ( resource window)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_newpad

(PHP 4 >= 4.3.0)

ncurses_newpad --  Creates a new pad (window)

Description

resource ncurses_newpad ( int rows, int cols)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_newwin

(PHP 4 >= 4.1.0)

ncurses_newwin -- Create a new window

Description

int ncurses_newwin ( int rows, int cols, int y, int x)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_nl

(PHP 4 >= 4.1.0)

ncurses_nl -- Translate newline and carriage return / line feed

Description

bool ncurses_nl ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_nocbreak

(PHP 4 >= 4.1.0)

ncurses_nocbreak -- Switch terminal to cooked mode

Description

bool ncurses_nocbreak ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

ncurses_nocbreak() routine returns terminal to normal (cooked) mode. Initially the terminal may or may not in cbreak mode as the mode is inherited. Therefore a program should call ncurses_cbreak() and ncurses_nocbreak() explicitly. Returns TRUE if any error occurred, otherwise FALSE.

See also: ncurses_cbreak()

ncurses_noecho

(PHP 4 >= 4.1.0)

ncurses_noecho -- Switch off keyboard input echo

Description

bool ncurses_noecho ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

ncurses_noecho() prevents echoing of user typed characters. Returns TRUE if any error occurred, otherwise FALSE.

See also: ncurses_echo(), ncurses_getch()

ncurses_nonl

(PHP 4 >= 4.1.0)

ncurses_nonl -- Do not translate newline and carriage return / line feed

Description

bool ncurses_nonl ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_noqiflush

(PHP 4 >= 4.1.0)

ncurses_noqiflush -- Do not flush on signal characters

Description

int ncurses_noqiflush ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_noraw

(PHP 4 >= 4.1.0)

ncurses_noraw -- Switch terminal out of raw mode

Description

bool ncurses_noraw ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

ncurses_noraw() switches the terminal out of raw mode. Raw mode is similar to cbreak mode, in that characters typed are immediately passed through to the user program. The differences that are that in raw mode, the interrupt, quit, suspend and flow control characters are all passed through uninterpreted, instead of generating a signal. Returns TRUE if any error occurred, otherwise FALSE.

See also: ncurses_raw(), ncurses_cbreak(), ncurses_nocbreak()

ncurses_pair_content

(PHP 4 >= 4.3.0)

ncurses_pair_content --  Gets the RGB value for color

Description

int ncurses_pair_content ( int pair, int &f, int &b)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_panel_above

(PHP 4 >= 4.3.0)

ncurses_panel_above --  Returns the panel above panel. If panel is null, returns the bottom panel in the stack

Description

int ncurses_panel_above ( resource panel)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_panel_below

(PHP 4 >= 4.3.0)

ncurses_panel_below --  Returns the panel below panel. If panel is null, returns the top panel in the stack

Description

int ncurses_panel_below ( resource panel)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_panel_window

(PHP 4 >= 4.3.0)

ncurses_panel_window --  Returns the window associated with panel

Description

int ncurses_panel_window ( resource panel)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_pnoutrefresh

(PHP 4 >= 4.3.0)

ncurses_pnoutrefresh --  Copies a region from a pad into the virtual screen

Description

int ncurses_pnoutrefresh ( resource pad, int pminrow, int pmincol, int sminrow, int smincol, int smaxrow, int smaxcol)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_prefresh

(PHP 4 >= 4.3.0)

ncurses_prefresh --  Copies a region from a pad into the virtual screen

Description

int ncurses_prefresh ( resource pad, int pminrow, int pmincol, int sminrow, int smincol, int smaxrow, int smaxcol)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_putp

(PHP 4 >= 4.2.0)

ncurses_putp -- 

Description

int ncurses_putp ( string text)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_qiflush

(PHP 4 >= 4.1.0)

ncurses_qiflush -- Flush on signal characters

Description

int ncurses_qiflush ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_raw

(PHP 4 >= 4.1.0)

ncurses_raw -- Switch terminal into raw mode

Description

bool ncurses_raw ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

ncurses_raw() places the terminal in raw mode. Raw mode is similar to cbreak mode, in that characters typed are immediately passed through to the user program. The differences that are that in raw mode, the interrupt, quit, suspend and flow control characters are all passed through uninterpreted, instead of generating a signal. Returns TRUE if any error occurred, otherwise FALSE.

See also: ncurses_noraw(), ncurses_cbreak(), ncurses_nocbreak()

ncurses_refresh

(PHP 4 >= 4.1.0)

ncurses_refresh -- Refresh screen

Description

int ncurses_refresh ( int ch)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_replace_panel

(PHP 4 >= 4.3.0)

ncurses_replace_panel --  Replaces the window associated with panel

Description

int ncurses_replace_panel ( resource panel, resource window)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_reset_prog_mode

(PHP 4 >= 4.3.0)

ncurses_reset_prog_mode --  Resets the prog mode saved by def_prog_mode

Description

int ncurses_reset_prog_mode ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_reset_shell_mode

(PHP 4 >= 4.3.0)

ncurses_reset_shell_mode --  Resets the shell mode saved by def_shell_mode

Description

int ncurses_reset_shell_mode ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_resetty

(PHP 4 >= 4.1.0)

ncurses_resetty -- Restores saved terminal state

Description

bool ncurses_resetty ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Function ncurses_resetty() restores the terminal state, which was previously saved by calling ncurses_savetty(). This function always returns FALSE.

See also: ncurses_savetty()

ncurses_savetty

(PHP 4 >= 4.1.0)

ncurses_savetty -- Saves terminal state

Description

bool ncurses_savetty ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Function ncurses_savetty() saves the current terminal state. The saved terminal state can be restored with function ncurses_resetty(). ncurses_savetty() always returns FALSE.

See also: ncurses_resetty()

ncurses_scr_dump

(PHP 4 >= 4.2.0)

ncurses_scr_dump -- Dump screen content to file

Description

int ncurses_scr_dump ( string filename)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_scr_init

(PHP 4 >= 4.2.0)

ncurses_scr_init -- Initialize screen from file dump

Description

int ncurses_scr_init ( string filename)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_scr_restore

(PHP 4 >= 4.2.0)

ncurses_scr_restore -- Restore screen from file dump

Description

int ncurses_scr_restore ( string filename)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_scr_set

(PHP 4 >= 4.2.0)

ncurses_scr_set -- Inherit screen from file dump

Description

int ncurses_scr_set ( string filename)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_scrl

(PHP 4 >= 4.1.0)

ncurses_scrl -- Scroll window content up or down without changing current position

Description

int ncurses_scrl ( int count)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_show_panel

(PHP 4 >= 4.3.0)

ncurses_show_panel --  Places an invisible panel on top of the stack, making it visible

Description

int ncurses_show_panel ( resource panel)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_slk_attr

(PHP 4 >= 4.1.0)

ncurses_slk_attr -- Returns current soft label key attribute

Description

bool ncurses_slk_attr ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

ncurses_slk_attr() returns the current soft label key attribute. On error returns TRUE, otherwise FALSE.

ncurses_slk_attroff

(PHP 4 >= 4.1.0)

ncurses_slk_attroff -- 

Description

int ncurses_slk_attroff ( int intarg)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_slk_attron

(PHP 4 >= 4.1.0)

ncurses_slk_attron -- 

Description

int ncurses_slk_attron ( int intarg)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_slk_attrset

(PHP 4 >= 4.1.0)

ncurses_slk_attrset -- 

Description

int ncurses_slk_attrset ( int intarg)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_slk_clear

(PHP 4 >= 4.1.0)

ncurses_slk_clear -- Clears soft labels from screen

Description

bool ncurses_slk_clear ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

The function ncurses_slk_clear() clears soft label keys from screen. Returns TRUE on error, otherwise FALSE.

ncurses_slk_color

(PHP 4 >= 4.1.0)

ncurses_slk_color -- Sets color for soft label keys

Description

int ncurses_slk_color ( int intarg)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_slk_init

(PHP 4 >= 4.1.0)

ncurses_slk_init -- Initializes soft label key functions

Description

bool ncurses_slk_init ( int format)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Function ncurses_slk_init() must be called before ncurses_initscr() or ncurses_newterm() is called. If ncurses_initscr() eventually uses a line from stdscr to emulate the soft labels, then format determines how the labels are arranged of the screen. Setting format to 0 indicates a 3-2-3 arrangement of the labels, 1 indicates a 4-4 arrangement and 2 indicates the PC like 4-4-4 mode, but in addition an index line will be created.

ncurses_slk_noutrefresh

(PHP 4 >= 4.1.0)

ncurses_slk_noutrefresh -- Copies soft label keys to virtual screen

Description

bool ncurses_slk_noutrefresh ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_slk_refresh

(PHP 4 >= 4.1.0)

ncurses_slk_refresh -- Copies soft label keys to screen

Description

bool ncurses_slk_refresh ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

ncurses_slk_refresh() copies soft label keys from virtual screen to physical screen. Returns TRUE on error, otherwise FALSE.

ncurses_slk_restore

(PHP 4 >= 4.1.0)

ncurses_slk_restore -- Restores soft label keys

Description

bool ncurses_slk_restore ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

The function ncurses_slk_restore() restores the soft label keys after ncurses_slk_clear() has been performed.

ncurses_slk_set

(PHP 4 >= 4.2.0)

ncurses_slk_set --  Sets function key labels

Description

bool ncurses_slk_set ( int labelnr, string label, int format)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_slk_touch

(PHP 4 >= 4.1.0)

ncurses_slk_touch -- Forces output when ncurses_slk_noutrefresh is performed

Description

bool ncurses_slk_touch ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

The ncurses_slk_touch() function forces all the soft labels to be output the next time a ncurses_slk_noutrefresh() is performed.

ncurses_standend

(PHP 4 >= 4.1.0)

ncurses_standend -- Stop using 'standout' attribute

Description

int ncurses_standend ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_standout

(PHP 4 >= 4.1.0)

ncurses_standout -- Start using 'standout' attribute

Description

int ncurses_standout ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_start_color

(PHP 4 >= 4.1.0)

ncurses_start_color -- Start using colors

Description

int ncurses_start_color ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_termattrs

(PHP 4 >= 4.1.0)

ncurses_termattrs -- Returns a logical OR of all attribute flags supported by terminal

Description

bool ncurses_termattrs ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_termname

(PHP 4 >= 4.2.0)

ncurses_termname -- Returns terminals (short)-name

Description

string ncurses_termname ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

ncurses_termname() returns terminals shortname. The shortname is truncated to 14 characters. On error ncurses_termname() returns NULL.

See also: ncurses_longname()

ncurses_timeout

(PHP 4 >= 4.1.0)

ncurses_timeout -- Set timeout for special key sequences

Description

void ncurses_timeout ( int millisec)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_top_panel

(PHP 4 >= 4.3.0)

ncurses_top_panel --  Moves a visible panel to the top of the stack

Description

int ncurses_top_panel ( resource panel)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_typeahead

(PHP 4 >= 4.1.0)

ncurses_typeahead -- Specify different filedescriptor for typeahead checking

Description

int ncurses_typeahead ( int fd)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_ungetch

(PHP 4 >= 4.1.0)

ncurses_ungetch -- Put a character back into the input stream

Description

int ncurses_ungetch ( int keycode)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_ungetmouse

(PHP 4 >= 4.2.0)

ncurses_ungetmouse -- Pushes mouse event to queue

Description

bool ncurses_ungetmouse ( array mevent)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

ncurses_getmouse() pushes a KEY_MOUSE event onto the unput queue and associates with this event the given state sata and screen-relative character cell coordinates, specified in mevent. Event options will be specified in associative array mevent:

  • "id" : Id to distinguish multiple devices

  • "x" : screen relative x-position in character cells

  • "y" : screen relative y-position in character cells

  • "z" : currently not supported

  • "mmask" : Mouse action

ncurses_ungetmouse() returns FALSE on success, otherwise TRUE.

See also: ncurses_getmouse()

ncurses_update_panels

(PHP 4 >= 4.3.0)

ncurses_update_panels --  Refreshes the virtual screen to reflect the relations between panels in the stack.

Description

void ncurses_update_panels ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_use_default_colors

(PHP 4 >= 4.1.0)

ncurses_use_default_colors -- Assign terminal default colors to color id -1

Description

bool ncurses_use_default_colors ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_use_env

(PHP 4 >= 4.1.0)

ncurses_use_env -- Control use of environment information about terminal size

Description

void ncurses_use_env ( bool flag)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_use_extended_names

(PHP 4 >= 4.1.0)

ncurses_use_extended_names -- Control use of extended names in terminfo descriptions

Description

int ncurses_use_extended_names ( bool flag)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_vidattr

(PHP 4 >= 4.1.0)

ncurses_vidattr -- 

Description

int ncurses_vidattr ( int intarg)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_vline

(PHP 4 >= 4.2.0)

ncurses_vline -- Draw a vertical line at current position using an attributed character and max. n characters long

Description

int ncurses_vline ( int charattr, int n)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_waddch

(PHP 4 >= 4.3.0)

ncurses_waddch --  Adds character at current position in a window and advance cursor

Description

int ncurses_waddch ( resource window, int ch)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_waddstr

(PHP 4 >= 4.2.0)

ncurses_waddstr --  Outputs text at current postion in window

Description

int ncurses_waddstr ( resource window, string str [, int n])

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_wattroff

(PHP 4 >= 4.3.0)

ncurses_wattroff --  Turns off attributes for a window

Description

int ncurses_wattroff ( resource window, int attrs)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_wattron

(PHP 4 >= 4.3.0)

ncurses_wattron --  Turns on attributes for a window

Description

int ncurses_wattron ( resource window, int attrs)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_wattrset

(PHP 4 >= 4.3.0)

ncurses_wattrset --  Set the attributes for a window

Description

int ncurses_wattrset ( resource window, int attrs)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_wborder

(PHP 4 >= 4.3.0)

ncurses_wborder --  Draws a border around the window using attributed characters

Description

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)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_wclear

(PHP 4 >= 4.2.0)

ncurses_wclear --  Clears window

Description

int ncurses_wclear ( resource window)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_wcolor_set

(PHP 4 >= 4.2.0)

ncurses_wcolor_set --  Sets windows color pairings

Description

int ncurses_wcolor_set ( resource window, int color_pair)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_werase

(PHP 4 >= 4.3.0)

ncurses_werase --  Erase window contents

Description

long ncurses_werase ( resource window)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_wgetch

(PHP 4 >= 4.2.0)

ncurses_wgetch --  Reads a character from keyboard (window)

Description

int ncurses_wgetch ( resource window)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_whline

(PHP 4 >= 4.3.0)

ncurses_whline --  Draws a horizontal line in a window at current position using an attributed character and max. n characters long

Description

int ncurses_whline ( resource window, int charattr, int n)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_wmouse_trafo

(PHP 4 >= 4.2.0)

ncurses_wmouse_trafo --  Transforms window/stdscr coordinates

Description

bool ncurses_wmouse_trafo ( resource window, int &y, int &x, bool toscreen)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_wmove

(PHP 4 >= 4.2.0)

ncurses_wmove --  Moves windows output position

Description

int ncurses_wmove ( resource window, int y, int x)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_wnoutrefresh

(PHP 4 >= 4.2.0)

ncurses_wnoutrefresh --  Copies window to virtual screen

Description

int ncurses_wnoutrefresh ( resource window)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_wrefresh

(PHP 4 >= 4.2.0)

ncurses_wrefresh -- Refresh window on terminal screen

Description

int ncurses_wrefresh ( resource window)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_wstandend

(PHP 4 >= 4.3.0)

ncurses_wstandend --  End standout mode for a window

Description

int ncurses_wstandend ( resource window)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_wstandout

(PHP 4 >= 4.3.0)

ncurses_wstandout --  Enter standout mode for a window

Description

int ncurses_wstandout ( resource window)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ncurses_wvline

(PHP 4 >= 4.3.0)

ncurses_wvline --  Draws a vertical line in a window at current position using an attributed character and max. n characters long

Description

int ncurses_wvline ( resource window, int charattr, int n)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

LXX. Lotus Notes functions

Bevezetés

Figyelem

Ez a kiterjesztés KÍSÉRLETI JELLEGGEL MŰKÖDIK. Ez azt jelenti, hogy minden itt dokumentált működés, beleértve a függvények nevét, működését vagy bármi más, amit a kiterjesztés kapcsán leírtunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a kiterjesztést csak a saját felelősségedre használd!

Tartalom
notes_body -- Open the message msg_number in the specified mailbox on the specified server (leave serv
notes_copy_db -- Create a note using form form_name
notes_create_db -- Create a Lotus Notes database
notes_create_note -- Create a note using form form_name
notes_drop_db -- Drop a Lotus Notes database
notes_find_note -- Returns a note id found in database_name. Specify the name of the note. Leaving type bla
notes_header_info -- Open the message msg_number in the specified mailbox on the specified server (leave serv
notes_list_msgs -- Returns the notes from a selected database_name
notes_mark_read -- Mark a note_id as read for the User user_name
notes_mark_unread -- Mark a note_id as unread for the User user_name
notes_nav_create -- Create a navigator name, in database_name
notes_search -- Find notes that match keywords in database_name
notes_unread -- Returns the unread note id's for the current User user_name
notes_version -- Get the version Lotus Notes

notes_body

(PHP 4 >= 4.0.5)

notes_body -- Open the message msg_number in the specified mailbox on the specified server (leave serv

Description

array notes_body ( string server, string mailbox, int msg_number)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

notes_copy_db

(PHP 4 >= 4.0.5)

notes_copy_db -- Create a note using form form_name

Description

string notes_copy_db ( string from_database_name, string to_database_name)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

notes_create_db

(PHP 4 >= 4.0.5)

notes_create_db -- Create a Lotus Notes database

Description

bool notes_create_db ( string database_name)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

notes_create_note

(PHP 4 >= 4.0.5)

notes_create_note -- Create a note using form form_name

Description

string notes_create_note ( string database_name, string form_name)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

notes_drop_db

(PHP 4 >= 4.0.5)

notes_drop_db -- Drop a Lotus Notes database

Description

bool notes_drop_db ( string database_name)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

notes_find_note

(PHP 4 >= 4.0.5)

notes_find_note -- Returns a note id found in database_name. Specify the name of the note. Leaving type bla

Description

bool notes_find_note ( string database_name, string name [, string type])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

notes_header_info

(PHP 4 >= 4.0.5)

notes_header_info -- Open the message msg_number in the specified mailbox on the specified server (leave serv

Description

object notes_header_info ( string server, string mailbox, int msg_number)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

notes_list_msgs

(PHP 4 >= 4.0.5)

notes_list_msgs -- Returns the notes from a selected database_name

Description

bool notes_list_msgs ( string db)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

notes_mark_read

(PHP 4 >= 4.0.5)

notes_mark_read -- Mark a note_id as read for the User user_name

Description

string notes_mark_read ( string database_name, string user_name, string note_id)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

notes_mark_unread

(PHP 4 >= 4.0.5)

notes_mark_unread -- Mark a note_id as unread for the User user_name

Description

string notes_mark_unread ( string database_name, string user_name, string note_id)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

notes_nav_create

(PHP 4 >= 4.0.5)

notes_nav_create -- Create a navigator name, in database_name

Description

bool notes_nav_create ( string database_name, string name)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

notes_search

(PHP 4 >= 4.0.5)

notes_search -- Find notes that match keywords in database_name

Description

string notes_search ( string database_name, string keywords)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

notes_unread

(PHP 4 >= 4.0.5)

notes_unread -- Returns the unread note id's for the current User user_name

Description

string notes_unread ( string database_name, string user_name)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

notes_version

(PHP 4 >= 4.0.5)

notes_version -- Get the version Lotus Notes

Description

string notes_version ( string database_name)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

LXXI. NSAPI-specific Functions

Bevezetés

These functions are only available when running PHP as a NSAPI module in Netscape/iPlanet/SunONE webservers.


Telepítés

For PHP installation on Netscape/iPlanet/SunONE webservers see the NSAPI section in the installation chapter.


Futásidejű beállítások

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

Táblázat 1. NSAPI configuration options

NameDefaultChangeableFunction
nsapi.read_timeout60PHP_INI_ALLsets the time in seconds the plugin is waiting for POST data from the client


Erőforrás típusok

Ez a kiterjesztés semmilyen erőforrás típust nem definiál.


Előre definiált állandók

Ez a kiterjesztés semmilyen konstans értéket nem definiál.


Lásd még

NSAPI implements a subset of the functions from the Apache module for maximum compatibility.

Táblázat 2. Apache functions implemented by NSAPI

Apache function (only as alias)NSAPI functionDescription
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

Tartalom
nsapi_request_headers -- Fetch all HTTP request headers
nsapi_response_headers --  Fetch all HTTP response headers
nsapi_virtual -- Perform an NSAPI sub-request

nsapi_request_headers

(no version information, might be only in CVS)

nsapi_request_headers -- Fetch all HTTP request headers

Description

array nsapi_request_headers ( void )

nsapi_request_headers() returns an associative array of all the HTTP headers in the current request. This is only supported when PHP runs as a NSAPI module.

Példa 1. nsapi_request_headers() example

<?php
$headers = nsapi_request_headers();

foreach ($headers as $header => $value) {
    echo "$header: $value <br />\n";
}
?>

Megjegyzés: 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.

Megjegyzés: 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.

nsapi_response_headers

(no version information, might be only in CVS)

nsapi_response_headers --  Fetch all HTTP response headers

Description

array nsapi_response_headers ( void )

Returns an array of all NSAPI response headers. This functionality is only available in PHP version 4.3.3 and greater.

See also nsapi_request_headers() and headers_sent().

nsapi_virtual

(no version information, might be only in CVS)

nsapi_virtual -- Perform an NSAPI sub-request

Description

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

Megjegyzés: This function depends on a undocumented feature of the Netscape/iPlanet/SunONE 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 install section if you experience this problem.

LXXII. Unified ODBC functions

Bevezetés

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.

Megjegyzés: 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. The exception to this is iODBC. Building PHP with iODBC support enables you to use any ODBC-compliant drivers with your PHP applications. iODBC is maintained by OpenLink Software. More information on iODBC, as well as a HOWTO, is available at www.iodbc.org.


Követelmények

To access any of the supported databases you need to have the required libraries installed.


Telepítés

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

To disable unified ODBC support in PHP 3 add --disable-unified-odbc to your configure line. Only applicable if iODBC, Adabas, Solid, Velocis or a custom ODBC interface is enabled.

A PHP Windowsos változata beépített támogatással rendelkezik eme kiterjesztéshez. nincs szükség semmilyen kiterjesztés betöltésére, hogy az itt felsorolt függvnyeket használhasd.


Futásidejű beállítások

Az alábbi függvények viselkedése befolyásolható a php.ini segítségével.

Táblázat 1. Unified ODBC Configuration Options

NameDefaultChangeable
odbc.default_db *NULLPHP_INI_ALL
odbc.default_user *NULLPHP_INI_ALL
odbc.default_pw *NULLPHP_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

Megjegyzés: Entries marked with * are not implemented yet.

For further details and definition of the PHP_INI_* constants see ini_set().

Here's a short explanation of the configuration directives.

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.

odbc.defaultbinmode integer

Handling of binary data.


Erőforrás típusok

Ez a kiterjesztés semmilyen erőforrás típust nem definiál.


Előre definiált állandók

Az itt listázott állandókat ez a kiterjesztés definiálja, és csak akkor elérhetőek, ha az adott kiterjesztés be van fordítva a PHP-be, vagy dinamikusan betöltött.

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)

Tartalom
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 --  Returns a result identifier that can be used to fetch a list of columns and associated privileges
odbc_columns --  Lists the column names in specified tables. Returns a result identifier containing the information.
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 -- Synonym for odbc_exec()
odbc_error -- Get the last error code
odbc_errormsg -- Get the last error message
odbc_exec -- Prepare and execute a 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 -- Synonym for odbc_field_len()
odbc_field_scale -- Get the scale of a field
odbc_field_type -- Datatype of a field
odbc_foreignkeys --  Returns 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
odbc_free_result -- Free resources associated with a result
odbc_gettypeinfo --  Returns a result identifier containing 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 --  Returns a result identifier that can be used to fetch the column names that comprise the primary key for a table
odbc_procedurecolumns --  Retrieve information about parameters to procedures
odbc_procedures --  Get the list of procedures stored in a specific data source. Returns a result identifier containing the information.
odbc_result_all -- Print result as HTML table
odbc_result -- Get result data
odbc_rollback -- Rollback a transaction
odbc_setoption --  Adjust ODBC settings. Returns FALSE if an error occurs, otherwise TRUE.
odbc_specialcolumns --  Returns 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
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. Returns a result identifier containing the information.

odbc_autocommit

(PHP 3>= 3.0.6, PHP 4 )

odbc_autocommit -- Toggle autocommit behaviour

Description

bool odbc_autocommit ( resource connection_id [, bool OnOff])

Without the OnOff parameter, this function returns auto-commit status for connection_id. TRUE is returned if auto-commit is on, FALSE if it is off or an error occurs.

If OnOff is TRUE, auto-commit is enabled, if it is FALSE auto-commit is disabled. Returns TRUE on success, FALSE on failure.

By default, auto-commit is on for a connection. Disabling auto-commit is equivalent with starting a transaction.

See also odbc_commit() and odbc_rollback().

odbc_binmode

(PHP 3>= 3.0.6, PHP 4 )

odbc_binmode -- Handling of binary column data

Description

int odbc_binmode ( resource result_id, int mode)

(ODBC SQL types affected: BINARY, VARBINARY, LONGVARBINARY)

  • ODBC_BINMODE_PASSTHRU: Passthru BINARY data

  • ODBC_BINMODE_RETURN: Return as is

  • ODBC_BINMODE_CONVERT: Convert to char and return

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

Táblázat 1. LONGVARBINARY handling

binmodelongreadlenresult
ODBC_BINMODE_PASSTHRU0passthru
ODBC_BINMODE_RETURN0passthru
ODBC_BINMODE_CONVERT0passthru
ODBC_BINMODE_PASSTHRU0passthru
ODBC_BINMODE_PASSTHRU>0passthru
ODBC_BINMODE_RETURN>0return as is
ODBC_BINMODE_CONVERT>0return as char

If odbc_fetch_into() is used, passthru means that an empty string is returned for these columns.

If result_id is 0, the settings apply as default for new results.

Megjegyzés: Default for longreadlen is 4096 and binmode defaults to ODBC_BINMODE_RETURN. Handling of binary long columns is also affected by odbc_longreadlen()

odbc_close_all

(PHP 3>= 3.0.6, PHP 4 )

odbc_close_all -- Close all ODBC connections

Description

void odbc_close_all ( void )

odbc_close_all() will close down all connections to database server(s).

Megjegyzés: This function will fail if there are open transactions on a connection. This connection will remain open in this case.

odbc_close

(PHP 3>= 3.0.6, PHP 4 )

odbc_close -- Close an ODBC connection

Description

void odbc_close ( resource connection_id)

odbc_close() will close down the connection to the database server associated with the given connection identifier.

Megjegyzés: This function will fail if there are open transactions on this connection. The connection will remain open in this case.

odbc_columnprivileges

(PHP 4 )

odbc_columnprivileges --  Returns a result identifier that can be used to fetch a list of columns and associated privileges

Description

int odbc_columnprivileges ( resource connection_id [, string qualifier [, string owner [, string table_name [, string column_name]]]])

Lists columns and associated privileges for the given table. Returns an ODBC result identifier or FALSE on failure.

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.

The column_name argument accepts search patterns ('%' to match zero or more characters and '_' to match a single character).

odbc_columns

(PHP 4 )

odbc_columns --  Lists the column names in specified tables. Returns a result identifier containing the information.

Description

resource odbc_columns ( resource connection_id [, string qualifier [, string schema [, string table_name [, string column_name]]]])

Lists all columns in the requested range. Returns an ODBC result identifier or FALSE on failure.

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.

The schema, table_name and column_name arguments accept search patterns ('%' to match zero or more characters and '_' to match a single character).

See also odbc_columnprivileges() to retrieve associated privileges.

odbc_commit

(PHP 3>= 3.0.6, PHP 4 )

odbc_commit -- Commit an ODBC transaction

Description

bool odbc_commit ( resource connection_id)

odbc_commit() commits all pending transactions on the connection_id connection. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

odbc_connect

(PHP 3>= 3.0.6, PHP 4 )

odbc_connect -- Connect to a datasource

Description

resource odbc_connect ( string dsn, string user, string password [, int cursor_type])

Returns an ODBC connection id or 0 (FALSE) on error.

The connection id returned by this functions is needed by other ODBC functions. You can have multiple connections open at once. The optional fourth parameter 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.

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.

The following constants are defined for cursortype:

  • SQL_CUR_USE_IF_NEEDED

  • SQL_CUR_USE_ODBC

  • SQL_CUR_USE_DRIVER

  • SQL_CUR_DEFAULT

For persistent connections see odbc_pconnect().

odbc_cursor

(PHP 3>= 3.0.6, PHP 4 )

odbc_cursor -- Get cursorname

Description

string odbc_cursor ( resource result_id)

odbc_cursor will return a cursorname for the given result_id.

odbc_data_source

(PHP 4 >= 4.3.0)

odbc_data_source -- Returns information about a current connection

Description

resource odbc_data_source ( resource connection_id, constant fetch_type)

Returns FALSE on error, and an array upon success.

This function will return information about the active connection following the information from within the DSN. The connection_id is required to be a valid ODBC connection. 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.

odbc_do

(PHP 3>= 3.0.6, PHP 4 )

odbc_do -- Synonym for odbc_exec()

Description

resource odbc_do ( resource conn_id, string query)

odbc_do() will execute a query on the given connection.

odbc_error

(PHP 4 >= 4.0.5)

odbc_error -- Get the last error code

Description

string odbc_error ( [resource connection_id])

Returns a six-digit ODBC state, or an empty string if there has been no errors. If connection_id is specified, the last state of that connection is returned, else the last state of any connection is returned.

See also: odbc_errormsg() and odbc_exec().

odbc_errormsg

(PHP 4 >= 4.0.5)

odbc_errormsg -- Get the last error message

Description

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. If connection_id is specified, the last state of that connection is returned, else the last state of any connection is returned.

See also: odbc_error() and odbc_exec().

odbc_exec

(PHP 3>= 3.0.6, PHP 4 )

odbc_exec -- Prepare and execute a SQL statement

Description

resource odbc_exec ( resource connection_id, string query_string)

Returns FALSE on error. Returns an ODBC result identifier if the SQL command was executed successfully.

odbc_exec() will send an SQL statement to the database server specified by connection_id. This parameter must be a valid identifier returned by odbc_connect() or odbc_pconnect().

See also: odbc_prepare() and odbc_execute() for multiple execution of SQL statements.

odbc_execute

(PHP 3>= 3.0.6, PHP 4 )

odbc_execute -- Execute a prepared statement

Description

bool odbc_execute ( resource result_id [, array parameters_array])

Executes a statement prepared with odbc_prepare().Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad. The array parameters_array only needs to be given if you really have parameters in your statement.

Parameters in parameter_array will be substituted for placeholders in the prepared statement in order.

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.

Megjegyzés: As of PHP 4.1.1, this file reading functionality has the following restrictions:

  • File reading is not subject to any safe mode or open-basedir restrictions. This is fixed in PHP 4.2.0.

  • Remote files are not supported.

  • If you wish to store a string which actually begins and ends with single quotes, you must escape them or add a space or other non-single-quote character to the beginning or end of the parameter, which will prevent the parameter's 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()).

odbc_fetch_array

(PHP 4 >= 4.0.2)

odbc_fetch_array --  Fetch a result row as an associative array

Description

array odbc_fetch_array ( resource result [, int rownumber])

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

odbc_fetch_into

(PHP 3>= 3.0.6, PHP 4 )

odbc_fetch_into -- Fetch one result row into array

Description

bool odbc_fetch_into ( resource result_id [, int rownumber, array result_array])

resource odbc_fetch_into ( resource result_id, array result_array [, int rownumber])

Returns the number of columns in the result; FALSE on error. result_array must be passed by reference, but it 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.

As of PHP 4.0.5 the result_array does not need to be passed by reference any longer.

As of PHP 4.0.6 the rownumber cannot be passed as a constant, but rather as a variable.

As of PHP 4.2.0 the result_array and rownumber have been swapped. This allows the rownumber to be a constant again. This change will also be the last one to this function.

Példa 1. odbc_fetch_into() pre 4.0.6 example

<?php
$rc = odbc_fetch_into($res_id, $my_array);
?>

or

<?php
$rc = odbc_fetch_into($res_id, $row, $my_array);
       
$rc = odbc_fetch_into($res_id, 1, $my_array);
?>

Példa 2. odbc_fetch_into() 4.0.6 example

<?php
$rc = odbc_fetch_into($res_id, $my_array);
?>

or

<?php
$row = 1;
$rc = odbc_fetch_into($res_id, $row, $my_array);
?>

Példa 3. odbc_fetch_into() 4.2.0 example

<?php
$rc = odbc_fetch_into($res_id, $my_array);
?>

or

<?php
$rc = odbc_fetch_into($res_id, $my_array, 2);
?>

odbc_fetch_object

(PHP 4 >= 4.0.2)

odbc_fetch_object --  Fetch a result row as an object

Description

object odbc_fetch_object ( resource result [, int rownumber])

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

odbc_fetch_row

(PHP 3>= 3.0.6, PHP 4 )

odbc_fetch_row -- Fetch a row

Description

bool odbc_fetch_row ( resource result_id [, int row_number])

If odbc_fetch_row() was successful (there was a row), TRUE is returned. If there are no more rows, FALSE is returned.

odbc_fetch_row() fetches a row of the data that was returned by odbc_do() / odbc_exec(). After odbc_fetch_row() is called, the fields of that row can be accessed with odbc_result().

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.

odbc_field_len

(PHP 3>= 3.0.6, PHP 4 )

odbc_field_len -- Get the length (precision) of a field

Description

int odbc_field_len ( resource result_id, int field_number)

odbc_field_len() will return the length of the field referenced by number in the given ODBC result identifier. Field numbering starts at 1.

See also: odbc_field_scale() to get the scale of a floating point number.

odbc_field_name

(PHP 3>= 3.0.6, PHP 4 )

odbc_field_name -- Get the columnname

Description

string odbc_field_name ( resource result_id, int field_number)

odbc_field_name() will return the name of the field occupying the given column number in the given ODBC result identifier. Field numbering starts at 1. FALSE is returned on error.

odbc_field_num

(PHP 3>= 3.0.6, PHP 4 )

odbc_field_num -- Return column number

Description

int odbc_field_num ( resource result_id, string field_name)

odbc_field_num() will return the number of the column slot that corresponds to the named field in the given ODBC result identifier. Field numbering starts at 1. FALSE is returned on error.

odbc_field_precision

(PHP 4 )

odbc_field_precision -- Synonym for odbc_field_len()

Description

string odbc_field_precision ( resource result_id, int field_number)

odbc_field_precision() will return the precision of the field referenced by number in the given ODBC result identifier.

See also: odbc_field_scale() to get the scale of a floating point number.

odbc_field_scale

(PHP 4 )

odbc_field_scale -- Get the scale of a field

Description

string odbc_field_scale ( resource result_id, int field_number)

odbc_field_precision() will return the scale of the field referenced by number in the given ODBC result identifier.

odbc_field_type

(PHP 3>= 3.0.6, PHP 4 )

odbc_field_type -- Datatype of a field

Description

string odbc_field_type ( resource result_id, int field_number)

odbc_field_type() will return the SQL type of the field referenced by number in the given ODBC result identifier. Field numbering starts at 1.

odbc_foreignkeys

(PHP 4 )

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

Description

resource odbc_foreignkeys ( resource connection_id, string pk_qualifier, string pk_owner, string pk_table, string fk_qualifier, string fk_owner, string fk_table)

odbc_foreignkeys() retrieves information about foreign keys. Returns an ODBC result identifier or FALSE on failure.

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_free_result

(PHP 3>= 3.0.6, PHP 4 )

odbc_free_result -- Free resources associated with a result

Description

bool odbc_free_result ( resource result_id)

Always returns TRUE.

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. But, if you are sure you are not going to need the result data anymore in a script, you may call odbc_free_result(), and the memory associated with result_id will be freed.

Megjegyzés: If auto-commit is disabled (see odbc_autocommit()) and you call odbc_free_result() before committing, all pending transactions are rolled back.

odbc_gettypeinfo

(PHP 4 )

odbc_gettypeinfo --  Returns a result identifier containing information about data types supported by the data source.

Description

int odbc_gettypeinfo ( resource connection_id [, int data_type])

Retrieves information about data types supported by the data source. Returns an ODBC result identifier or FALSE on failure. The optional argument data_type can be used to restrict the information to a single data type.

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_longreadlen

(PHP 3>= 3.0.6, PHP 4 )

odbc_longreadlen -- Handling of LONG columns

Description

int odbc_longreadlen ( resource result_id, int length)

(ODBC SQL types affected: LONG, LONGVARBINARY) 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.

Megjegyzés: Handling of LONGVARBINARY columns is also affected by odbc_binmode().

odbc_next_result

(PHP 4 >= 4.0.5)

odbc_next_result --  Checks if multiple results are available

Description

bool odbc_next_result ( resource result_id)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

odbc_num_fields

(PHP 3>= 3.0.6, PHP 4 )

odbc_num_fields -- Number of columns in a result

Description

int odbc_num_fields ( resource result_id)

odbc_num_fields() will return the number of fields (columns) in an ODBC result. This function will return -1 on error. The argument is a valid result identifier returned by odbc_exec().

odbc_num_rows

(PHP 3>= 3.0.6, PHP 4 )

odbc_num_rows -- Number of rows in a result

Description

int odbc_num_rows ( resource result_id)

odbc_num_rows() will return the number of rows in an ODBC result. This function will return -1 on error. 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.

Note: Using odbc_num_rows() to determine the number of rows available after a SELECT will return -1 with many drivers.

odbc_pconnect

(PHP 3>= 3.0.6, PHP 4 )

odbc_pconnect -- Open a persistent database connection

Description

resource odbc_pconnect ( string dsn, string user, string password [, int cursor_type])

Returns an ODBC connection id or 0 (FALSE) on error. 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.

Megjegyzés: Persistent connections have no effect if PHP is used as a CGI program.

For information about the optional cursor_type parameter see the odbc_connect() function. For more information on persistent connections, refer to the PHP FAQ.

odbc_prepare

(PHP 3>= 3.0.6, PHP 4 )

odbc_prepare -- Prepares a statement for execution

Description

resource odbc_prepare ( resource connection_id, string query_string)

Returns FALSE on error.

Returns an ODBC result identifier if the SQL command was prepared successfully. The result identifier can be used later to execute the statement with odbc_execute().

odbc_primarykeys

(PHP 4 )

odbc_primarykeys --  Returns a result identifier that can be used to fetch the column names that comprise the primary key for a table

Description

resource odbc_primarykeys ( resource connection_id, string qualifier, string owner, string table)

Returns the column names that comprise the primary key for a table. Returns an ODBC result identifier or FALSE on failure.

The result set has the following columns:

  • TABLE_QUALIFIER

  • TABLE_OWNER

  • TABLE_NAME

  • COLUMN_NAME

  • KEY_SEQ

  • PK_NAME

odbc_procedurecolumns

(PHP 4 )

odbc_procedurecolumns --  Retrieve information about parameters to procedures

Description

resource odbc_procedurecolumns ( resource connection_id [, string qualifier [, string owner [, string proc [, string column]]]])

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 or FALSE on failure.

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.

The owner, proc and column arguments accept search patterns ('%' to match zero or more characters and '_' to match a single character).

odbc_procedures

(PHP 4 )

odbc_procedures --  Get the list of procedures stored in a specific data source. Returns a result identifier containing the information.

Description

resource odbc_procedures ( resource connection_id [, string qualifier [, string owner [, string name]]])

Lists all procedures in the requested range. Returns an ODBC result identifier or FALSE on failure.

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

The owner and name arguments accept search patterns ('%' to match zero or more characters and '_' to match a single character).

odbc_result_all

(PHP 3>= 3.0.6, PHP 4 )

odbc_result_all -- Print result as HTML table

Description

int odbc_result_all ( resource result_id [, string format])

Returns the number of rows in the result or FALSE on error.

odbc_result_all() will print all rows from a result identifier produced by odbc_exec(). The result is printed in HTML table format. With the optional string argument format, additional overall table formatting can be done.

odbc_result

(PHP 3>= 3.0.6, PHP 4 )

odbc_result -- Get result data

Description

string odbc_result ( resource result_id, mixed field)

Returns the contents of the field.

field 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. For example:

$item_3 = odbc_result($Query_ID, 3);
$item_val = odbc_result($Query_ID, "val");

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.

Field indices start from 1. Regarding the way binary or long column data is returned refer to odbc_binmode() and odbc_longreadlen().

odbc_rollback

(PHP 3>= 3.0.6, PHP 4 )

odbc_rollback -- Rollback a transaction

Description

int odbc_rollback ( resource connection_id)

Rolls back all pending statements on connection_id. Returns TRUE on success, FALSE on failure.

odbc_setoption

(PHP 3>= 3.0.6, PHP 4 )

odbc_setoption --  Adjust ODBC settings. Returns FALSE if an error occurs, otherwise TRUE.

Description

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

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

Parameter option is the option to set.

Parameter param is the value for the given option.

Példa 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_specialcolumns

(PHP 4 )

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

Description

resource odbc_specialcolumns ( resource connection_id, int type, string qualifier, string owner, string table, int scope, int nullable)

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 optimal column or set of columns that, by retrieving values from the column or columns, allows any row in the specified table to be uniquely identified.

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

The result set is ordered by SCOPE.

odbc_statistics

(PHP 4 )

odbc_statistics -- Retrieve statistics about a table

Description

resource odbc_statistics ( resource connection_id, string qualifier, string owner, string table_name, int unique, int accuracy)

Get statistics about a table and it's indexes. Returns an ODBC result identifier or FALSE on failure.

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_tableprivileges

(PHP 4 )

odbc_tableprivileges --  Lists tables and the privileges associated with each table

Description

int odbc_tableprivileges ( resource connection_id [, string qualifier [, string owner [, string name]]])

Lists tables in the requested range and the privileges associated with each table. Returns an ODBC result identifier or FALSE on failure.

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.

The owner and name arguments accept search patterns ('%' to match zero or more characters and '_' to match a single character).

odbc_tables

(PHP 3>= 3.0.17, PHP 4 )

odbc_tables --  Get the list of table names stored in a specific data source. Returns a result identifier containing the information.

Description

int odbc_tables ( resource connection_id [, string qualifier [, string owner [, string name [, string types]]]])

Lists all tables in the requested range. Returns an ODBC result identifier or FALSE on failure.

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.

The owner and name arguments accept search patterns ('%' to match zero or more characters and '_' to match a single character).

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

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.

See also odbc_tableprivileges() to retrieve associated privileges.

LXXIII. Object Aggregation/Composition Functions

Figyelem

Ez a kiterjesztés KÍSÉRLETI JELLEGGEL MŰKÖDIK. Ez azt jelenti, hogy minden itt dokumentált működés, beleértve a függvények nevét, működését vagy bármi más, amit a kiterjesztés kapcsán leírtunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a kiterjesztést csak a saját felelősségedre használd!


Bevezetés

In Object Oriented Programming, it is common to see the composition of simple classes (and/or instances) into a more complex one. This is a flexible strategy for building complicated objects and object hierarchies and can function as a dynamic alternative to multiple inheritance. There are two ways to perform class (and/or object) composition depending on the relationship between the composed elements: Association and Aggregation.

An Association is a composition of independently constructed and externally visible parts. When we associate classes or objects, each one keeps a reference to the ones it is associated with. When we associate classes statically, one class will contain a reference to an instance of the other class. For example:

Példa 1. Class association

<?php
class DateTime {
   
   function DateTime() 
   {
       // empty constructor
   }

   function now() 
   {
       return date("Y-m-d H:i:s");
   }
}

class Report {
   var $_dt;
   // more properties ...

   function Report() 
   {
       $this->_dt = new DateTime();
       // initialization code ...
   }

   function generateReport() 
   {
       $dateTime = $_dt->now();
       // more code ...
   }

   // more methods ...
}

$rep = new Report();
?>
We can also associate instances at runtime by passing a reference in a constructor (or any other method), which allow us to dynamically change the association relationship between objects. We will modify the example above to illustrate this point:

Példa 2. Object association

<?php
class DateTime {
   // same as previous example
}

class DateTimePlus {
   var $_format;
   
   function DateTimePlus($format="Y-m-d H:i:s") 
   {
       $this->_format = $format;
   }

   function now() 
   {
       return date($this->_format);
   }
}

class Report {
   var $_dt;    // we'll keep the reference to DateTime here
   // more properties ...

   function Report() 
   {
       // do some initialization
   }

   function setDateTime(&$dt) 
   {
       $this->_dt =& $dt;
   }

   function generateReport() 
   {
       $dateTime = $this->_dt->now();
       // more code ...
   }

   // more methods ...
}

$rep = new Report();
$dt = new DateTime();
$dtp = new DateTimePlus("l, F j, Y (h:i:s a, T)");

// generate report with simple date for web display
$rep->setDateTime(&$dt);
echo $rep->generateReport();

// later on in the code ...

// generate report with fancy date
$rep->setDateTime(&$dtp);
$output = $rep->generateReport();
// save $output in database
// ... etc ... 
?>

Aggregation, on the other hand, implies encapsulation (hidding) of the parts of the composition. We can aggregate classes by using a (static) inner class (PHP does not yet support inner classes), in this case the aggregated class definition is not accessible, except through the class that contains it. The aggregation of instances (object aggregation) involves the dynamic creation of subobjects inside an object, in the process, expanding the properties and methods of that object.

Object aggregation is a natural way of representing a whole-part relationship, (for example, molecules are aggregates of atoms), or can be used to obtain an effect equivalent to multiple inheritance, without having to permanently bind a subclass to two or more parent classes and their interfaces. In fact object aggregation can be more flexible, in which we can select what methods or properties to "inherit" in the aggregated object.


Példák

We define 3 classes, each implementing a different storage method:

Példa 3. storage_classes.inc

<?php
class FileStorage {
    var $data;

    function FileStorage($data) 
    {
        $this->data = $data;
    }
    
    function write($name) 
    {
        $fp = fopen(name, "w");
        fwrite($fp, $this->data);
        fclose($data);
    }
}

class WDDXStorage {
    var $data;
    var $version = "1.0";
    var $_id; // "private" variable

    function WDDXStorage($data) 
    {
        $this->data = $data;
        $this->_id = $this->_genID();
    }

    function store() 
    {
        if ($this->_id) {
            $pid = wddx_packet_start($this->_id);
            wddx_add_vars($pid, "this->data");
            $packet = wddx_packet_end($pid);
        } else {
            $packet = wddx_serialize_value($this->data);
        }
        $dbh = dba_open("varstore", "w", "gdbm");
        dba_insert(md5(uniqid("", true)), $packet, $dbh);
        dba_close($dbh);
    }

    // a private method
    function _genID() 
    {
        return md5(uniqid(rand(), true));
    }
}

class DBStorage {
    var $data;
    var $dbtype = "mysql";

    function DBStorage($data) 
    {
        $this->data = $data;
    }

    function save() 
    {
        $dbh = mysql_connect();
        mysql_select_db("storage", $dbh);
        $serdata = serialize($this->data);
        mysql_query("insert into vars ('$serdata',now())", $dbh);
        mysql_close($dbh);
    }
}

?>

We then instantiate a couple of objects from the defined classes, and perform some aggregations and deaggregations, printing some object information along the way:

Példa 4. test_aggregation.php

<?php
include "storageclasses.inc";

// some utilty functions

function p_arr($arr) 
{
    foreach ($arr as $k => $v)
        $out[] = "\t$k => $v";
    return implode("\n", $out);
}

function object_info($obj) 
{
    $out[] = "Class: " . get_class($obj);
    foreach (get_object_vars($obj) as $var=>$val) {
        if (is_array($val)) {
            $out[] = "property: $var (array)\n" . p_arr($val);
        } else {
            $out[] = "property: $var = $val";
        }
    }
    foreach (get_class_methods($obj) as $method) {
        $out[] = "method: $method";
    }
    return implode("\n", $out);
}


$data = array(M_PI, "kludge != cruft");

// we create some basic objects
$fs = new FileStorage($data);
$ws = new WDDXStorage($data);

// print information on the objects
echo "\$fs object\n";
echo object_info($fs) . "\n";
echo "\n\$ws object\n";
echo object_info($ws) . "\n";

// do some aggregation

echo "\nLet's aggregate \$fs to the WDDXStorage class\n";
aggregate($fs, "WDDXStorage");
echo "\$fs object\n";
echo object_info($fs) . "\n";

echo "\nNow let us aggregate it to the DBStorage class\n";
aggregate($fs, "DBStorage");
echo "\$fs object\n";
echo object_info($fs) . "\n";

echo "\nAnd finally deaggregate WDDXStorage\n";
deaggregate($fs, "WDDXStorage");
echo "\$fs object\n";
echo object_info($fs) . "\n";

?>

We will now consider the output to understand some of the side-effects and limitation of object aggregation in PHP. First, the newly created $fs and $ws objects give the expected output (according to their respective class declaration). Note that for the purposes of object aggregation, private elements of a class/object begin with an underscore character ("_"), even though there is not real distinction between public and private class/object elements in PHP.

$fs object
Class: filestorage
property: data (array)
    0 => 3.1415926535898
    1 => kludge != cruft
method: filestorage
method: write

$ws object
Class: wddxstorage
property: data (array)
    0 => 3.1415926535898
    1 => kludge != cruft
property: version = 1.0
property: _id = ID::9bb2b640764d4370eb04808af8b076a5
method: wddxstorage
method: store
method: _genid

We then aggregate $fs with the WDDXStorage class, and print out the object information. We can see now that even though nominally the $fs object is still of FileStorage, it now has the property $version, and the method store(), both defined in WDDXStorage. One important thing to note is that it has not aggregated the private elements defined in the class, which are present in the $ws object. Also absent is the constructor from WDDXStorage, which will not be logical to aggegate.

Let's aggregate $fs to the WDDXStorage class
$fs object
Class: filestorage
property: data (array)
    0 => 3.1415926535898
    1 => kludge != cruft
property: version = 1.0
method: filestorage
method: write
method: store

The proccess of aggregation is cummulative, so when we aggregate $fs with the class DBStorage, generating an object that can use the storage methods of all the defined classes.

Now let us aggregate it to the DBStorage class
$fs object
Class: filestorage
property: data (array)
    0 => 3.1415926535898
    1 => kludge != cruft
property: version = 1.0
property: dbtype = mysql
method: filestorage
method: write
method: store
method: save

Finally, the same way we aggregated properties and methods dynamically, we can also deaggregate them from the object. So, if we deaggregate the class WDDXStorage from $fs, we will obtain:

And deaggregate the WDDXStorage methods and properties
$fs object
Class: filestorage
property: data (array)
    0 => 3.1415926535898
    1 => kludge != cruft
property: dbtype = mysql
method: filestorage
method: write
method: save

One point that we have not mentioned above, is that the process of aggregation will not override existing properties or methods in the objects. For example, the class FileStorage defines a $data property, and the class WDDXStorage also defines a similar property which will not override the one in the object acquired during instantiation from the class FileStorage.

Tartalom
aggregate_info --  returns an associative array of the methods and properties from each class that has been aggregated to the object.
aggregate_methods_by_list --  selective dynamic class methods aggregation to an object
aggregate_methods_by_regexp --  selective class methods aggregation to an object using a regular expression
aggregate_methods --  dynamic class and object aggregation of methods
aggregate_properties_by_list --  selective dynamic class properties aggregation to an object
aggregate_properties_by_regexp --  selective class properties aggregation to an object using a regular expression
aggregate_properties --  dynamic aggregation of class properties to an object
aggregate --  dynamic class and object aggregation of methods and properties
aggregation_info -- Alias for aggregate_info()
deaggregate --  Removes the aggregated methods and properties from an object

aggregate_info

(PHP 5 CVS only)

aggregate_info --  returns an associative array of the methods and properties from each class that has been aggregated to the object.

Description

array aggregate_info ( object object)

Will return the aggregation information for a particular object as an associative array of arrays of methods and properties. The key for the main array is the name of the aggregated class.

For example the code below

Példa 1. Using aggregate_info()

<?php

class Slicer {
    var $vegetable;

    function Slicer($vegetable) 
    {
        $this->vegetable = $vegetable;
    }

    function slice_it($num_cuts) 
    {
        echo "Doing some simple slicing\n";
        for ($i=0; $i < $num_cuts; $i++) {
            // do some slicing
        }
    }
}

class Dicer {
    var $vegetable;
    var $rotation_angle = 90;   // degrees

    function Dicer($vegetable) 
    {
        $this->vegetable = $vegetable;
    }

    function dice_it($num_cuts) 
    {
        echo "Cutting in one direction\n";
        for ($i=0; $i < $num_cuts; $i++) {
            // do some cutting
        }
        $this->rotate($this->rotation_angle);
        echo "Cutting in a second direction\n";
        for ($i=0; $i < $num_cuts; $i++) {
            // do some more cutting
        }
    }

    function rotate($deg) 
    {
        echo "Now rotating {$this->vegetable} {$deg} degrees\n";
    }

    function _secret_super_dicing($num_cuts) 
    {
        // so secret we cannot show you ;-)
    }
}

$obj = new Slicer('onion');
aggregate($obj, 'Dicer');
print_r(aggregate_info($obj));
?>

Will produce the output

Array
(
    [dicer] => Array
        (
            [methods] => Array
                (
                    [0] => dice_it
                    [1] => rotate
                )

            [properties] => Array
                (
                    [0] => rotation_angle
                )

        )

)
As you can see, all properties and methods of the Dicer class have been aggregated into our new object, with the exception of the class constructor and the method _secret_super_dicing

See also aggregate(), aggregate_methods(), aggregate_methods_by_list(), aggregate_methods_by_regexp(), aggregate_properties(), aggregate_properties_by_list(), aggregate_properties_by_regexp(), deaggregate()

aggregate_methods_by_list

(PHP 4 >= 4.2.0)

aggregate_methods_by_list --  selective dynamic class methods aggregation to an object

Description

void aggregate_methods_by_list ( object object, string class_name, array methods_list [, bool exclude])

Aggregates methods from a class to an existing object using a list of method names. The optional paramater exclude is used to decide whether the list contains the names of methods to include in the aggregation (i.e. exclude is FALSE, which is the default value), or to exclude from the aggregation (exclude is TRUE).

The class constructor or methods whose names start with an underscore character (_), which are considered private to the aggregated class, are always excluded.

See also aggregate(), aggregate_info(), aggregate_methods(), aggregate_methods_by_regexp(), aggregate_properties(), aggregate_properties_by_list(), aggregate_properties_by_regexp(), deaggregate()

aggregate_methods_by_regexp

(PHP 4 >= 4.2.0)

aggregate_methods_by_regexp --  selective class methods aggregation to an object using a regular expression

Description

void aggregate_methods_by_regexp ( object object, string class_name, string regexp [, bool exclude])

Aggregates methods from a class to an existing object using a regular expresion to match method names. The optional paramater exclude is used to decide whether the regular expression will select the names of methods to include in the aggregation (i.e. exclude is FALSE, which is the default value), or to exclude from the aggregation (exclude is TRUE).

The class constructor or methods whose names start with an underscore character (_), which are considered private to the aggregated class, are always excluded.

See also aggregate(), aggregate_info(), aggregate_methods(), aggregate_methods_by_list(), aggregate_properties(), aggregate_properties_by_list(), aggregate_properties_by_regexp(), deaggregate()

aggregate_methods

(PHP 4 >= 4.2.0)

aggregate_methods --  dynamic class and object aggregation of methods

Description

void aggregate_methods ( object object, string class_name)

Aggregates all methods defined in a class to an existing object, except for the class constructor, or methods whose names start with an underscore character (_) which are considered private to the aggregated class.

See also aggregate(), aggregate_info(), aggregate_methods_by_list(), aggregate_methods_by_regexp(), aggregate_properties(), aggregate_properties_by_list(), aggregate_properties_by_regexp(), deaggregate()

aggregate_properties_by_list

(PHP 4 >= 4.2.0)

aggregate_properties_by_list --  selective dynamic class properties aggregation to an object

Description

void aggregate_properties_by_list ( object object, string class_name, array properties_list [, bool exclude])

Aggregates properties from a class to an existing object using a list of property names. The optional paramater exclude is used to decide whether the list contains the names of class properties to include in the aggregation (i.e. exclude is FALSE, which is the default value), or to exclude from the aggregation (exclude is TRUE).

The properties whose names start with an underscore character (_), which are considered private to the aggregated class, are always excluded.

See also aggregate(), aggregate_methods(), aggregate_methods_by_list(), aggregate_methods_by_regexp(), aggregate_properties(), aggregate_properties_by_regexp(), aggregate_info(), deaggregate()

aggregate_properties_by_regexp

(PHP 4 >= 4.2.0)

aggregate_properties_by_regexp --  selective class properties aggregation to an object using a regular expression

Description

void aggregate_properties_by_regexp ( object object, string class_name, string regexp [, bool exclude])

Aggregates properties from a class to an existing object using a regular expresion to match their names. The optional paramater exclude is used to decide whether the regular expression will select the names of class properties to include in the aggregation (i.e. exclude is FALSE, which is the default value), or to exclude from the aggregation (exclude is TRUE).

The properties whose names start with an underscore character (_), which are considered private to the aggregated class, are always excluded.

See also aggregate(), aggregate_methods(), aggregate_methods_by_list(), aggregate_methods_by_regexp(), aggregate_properties(), aggregate_properties_by_list(), aggregate_info(), deaggregate()

aggregate_properties

(PHP 4 >= 4.2.0)

aggregate_properties --  dynamic aggregation of class properties to an object

Description

void aggregate_properties ( object object, string class_name)

Aggregates all properties defined in a class to an existing object, except for properties whose names start with an underscore character (_) which are considered private to the aggregated class.

See also aggregate(), aggregate_methods(), aggregate_methods_by_list(), aggregate_methods_by_regexp(), aggregate_properties_by_list(), aggregate_properties_by_regexp(), aggregate_info(), deaggregate()

aggregate

(PHP 4 >= 4.2.0)

aggregate --  dynamic class and object aggregation of methods and properties

Description

void aggregate ( object object, string class_name)

Aggregates methods and properties defined in a class to an existing object. Methods and properties with names starting with an underscore character (_) are considered private to the aggregated class and are not used, constructors are also excluded from the aggregation procedure.

See also aggregate_info(), aggregate_methods(), aggregate_methods_by_list(), aggregate_methods_by_regexp(), aggregate_properties(), aggregate_properties_by_list(), aggregate_properties_by_regexp(), deaggregate()

aggregation_info

aggregation_info -- Alias for aggregate_info()

Description

This function is an alias of aggregate_info().

deaggregate

(PHP 4 >= 4.2.0)

deaggregate --  Removes the aggregated methods and properties from an object

Description

void deaggregate ( object object [, string class_name])

Removes the methods and properties from classes that were aggregated to an object. If the optional class_name parameters is passed, only those methods and properties defined in that class are removed, otherwise all aggregated methods and properties are eliminated.

See also aggregate(), aggregate_methods(), aggregate_methods_by_list(), aggregate_methods_by_regexp(), aggregate_properties(), aggregate_properties_by_list(), aggregate_properties_by_regexp(), aggregate_info()

LXXIV. Oracle 8 függvények

Ezekkel a függvényekkel az Oracle8 és Oracle7 adatbázisokat érheted el, az Oracle8 Call-Interface (OCI8) használatával. Az Oracle8 kliens könyvtárakra szükséged lesz, ha szeretnéd ezt a kiterjesztést használni.

Ez a kiterjesztés rugalmasabb, mint a hagyományos Oracle kiterjesztés. Lehetővé teszi globális és lokális PHP változók kötését Oracle értékekhez, teljes LOB, FILE és ROWID támogatással rendelkezik, és lehetővé teszi a felhasználó által megadott változók használatát.

Mielőtt elkezdenéd használni ezt a kiterjesztést, győződj meg róla, hogy az Oracle környezeti változók helyesen be vannak állítva az Oracle és a webszerver felhasználó számára. Az értékek, amiket esetleg be kell állítanod a kövezkezők:

  • ORACLE_HOME

  • ORACLE_SID

  • LD_PRELOAD

  • LD_LIBRARY_PATH

  • NLS_LANG

  • ORA_NLS33

Miután beállítottad a könyezeti változókat a webszerver felhasználó számára, add hozzá a webszerver felhasználót (nobody, www) az oracle csoporthoz.

Ha a webszerver nem indul el, vagy lefagy induláskor: Ellenőrizd, hogy az Apache szervert a pthread könyvtárral fordítottad-e:

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

Ha a libpthread nincs bent a listában, újra kell telepítened az Apache szervert:

# cd /usr/src/apache_1.3.xx
# make clean
# LIBS=-lpthread ./config.status
# make
# make install

Példa 1. OCI tippek

<?php
// A tippeket sergo@bacup.ru küldte be

// Használd az OCI_DEFAULT opciót a végrehajtásnál,
// ha késleltetni szeternéd a végrehjtást
OCIExecute($stmt, OCI_DEFAULT);

// Lekérdezett adatok használatához (fetch után):

$result = OCIResult($stmt, $n);
if (is_object($result)) { $result = $result->load(); }

// INSERT vagy UPDATE parancsokhoz:

$sql = "insert into table (mezo1, mezo2) values (mezo1 = 'érték',
 mezo2 = empty_clob()) returning mezo2 into :mezo2";
OCIParse($conn, $sql);
$clob = OCINewDescriptor($conn, OCI_D_LOB);
OCIBindByName($stmt, ":mezo2", &$clob, -1, OCI_B_CLOB);
OCIExecute($stmt, OCI_DEFAULT);
$clob->save("valami szöveg");
OCICommit($conn);

?>

Könnyen elérheted a tárolt eljárásokat, éppen úgy, mint parancssorból.

Példa 2. Tárolt eljárások használata

<?php
// webmaster@remoterealty.com küldte be a következő kódot:

$sth = OCIParse ( $dbh, "begin sp_newaddress( :cimid, '$keresztnev',
 '$csaladinev', '$ceg', '$cim1', '$cim2', '$varos', '$megye',
 '$irszam', '$orszag', :hibakod );end;" );

// Ez a parancs meghívja az sp_newaddress nevű tárolt eljárást,
// a :cimid ki és bemeneti változóval és a :hibakod kimeneti
// változóval. Ezután a változó kötéseket kell elvégezni:

   OCIBindByName ( $sth, ":cimid", $cimid, 10 );
   OCIBindByName ( $sth, ":hibakod", $hibakod, 10 );
   OCIExecute ( $sth );

?>

Tartalom
OCIBindByName --  PHP változó kötése egy Oracle értékhez
OCICancel -- Kurzorral olvasás befejezése
ocicloselob -- Closes lob descriptor
OCICollAppend -- [Eddig] nem dokumentált
OCICollAssign -- [Eddig] nem dokumentált
OCICollAssignElem -- [Eddig] nem dokumentált
OCICollGetElem -- [Eddig] nem dokumentált
OCICollMax -- [Eddig] nem dokumentált
OCICollSize -- [Eddig] nem dokumentált
OCICollTrim -- [Eddig] nem dokumentált
OCIColumnIsNULL -- NULL értékű mező azonosítása
OCIColumnName -- Oszlop neve egy eredménytáblában
OCIColumnPrecision -- [Eddig] nem dokumentált
OCIColumnScale -- [Eddig] nem dokumentált
OCIColumnSize -- Oszlop mérete egy eredménytáblában
OCIColumnType -- Oszlop adattípusa egy eredménytáblában
OCIColumnTypeRaw -- [Eddig] nem dokumentált
OCICommit -- Függőben lévő tranzakciók végrehajtása
OCIDefineByName --  PHP változó használata a definiálási lépésben egy SELECT számára
OCIError -- A legutóbbi parancs / kapcsolat / általános hiba visszaadása
OCIExecute -- Parancs futtatása
OCIFetch -- A következő eredmény sor lekérdezése
OCIFetchInto -- A következő sor lekérdezése tömbbe
OCIFetchStatement -- Miden eredménysor lekérdezése egy tömbbe
OCIFreeCollection -- [Eddig] nem dokumentált
OCIFreeCursor --  Kurzorhoz rendelt erőforrások felszabadítása
OCIFreeDesc -- Felszabadít egy LOB leírót
OCIFreeStatement --  Parancshoz rendelt erőforrások felszabadítása
OCIInternalDebug --  A belső debug kimenet engedélyezése / letiltása
OCILoadLob -- [Eddig] nem dokumentált
OCILogOff -- Oracle kapcsolat bontása
OCILogon -- Oracle adatbázis kapcsolat létesítése
OCINewCollection -- [Eddig] nem dokumentált
OCINewCursor --  Új kurzor (parancs eredmény kezelő) megnyitása
OCINewDescriptor --  Egy új üres LOB vagy FILE leírót hoz létre
OCINLogon -- Új Oracle adatbázis kapcsolat létrehozása
OCINumCols --  Az eredményoszlopok száma egy eredménytáblában
OCIParse -- SQL lekérdezés feldolgozása, parancs visszaadása
OCIPLogon -- Oracle adatbáziscsatlakozás állandó kapcsolattal
OCIResult -- Mező értékének visszaadása lekérdezett sorból
OCIRollback -- Függőben lévő tranzakciók visszavonása
OCIRowCount -- Az érintett sorok száma
OCISaveLob -- [Eddig] nem dokumentált
OCISaveLobFile -- [Eddig] nem dokumentált
OCIServerVersion -- Szerver verzió információ visszaadása
OCISetPrefetch -- Az előzetesen lehívott sorok számának beállítása
OCIStatementType -- OCI parancs típusát adja vissza
OCIWriteLobToFile -- [Eddig] nem dokumentált
ociwritetemporarylob -- Writes temporary blob

OCIBindByName

(PHP 3>= 3.0.4, PHP 4 )

OCIBindByName --  PHP változó kötése egy Oracle értékhez

Leírás

int OCIBindByName ( int stmt, string ph_name, mixed & variable, int length [, int type])

Az OCIBindByName() a variable paraméterben megadott PHP változót köti a ph_name paraméterben megadott Oracle értékez (placeholder-hez). Akár bemeneti, akár kimeneti értékként kerül felhasználásra, ez futásidőben dől el, és a szükséges tárolási kapacitás lefoglalásra kerül. A length paraméter adja meg a kötés maximális méretét. Ha a length paramétert -1 értékkel adod meg, az OCIBindByName() a variable paraméterben megadott változó aktuális hosszát veszi maximum méretnek.

Ha absztrakt adattípust kell kötnöd (például LOB, ROWID vagy BFILE), először az OCINewDescriptor() függvényt kell használnod. A length paraméternek nincs jelentősége absztrakt adattípusok használatakor, mindenképpen -1 értékre kell állítani ebben az esetben. A type paraméter adja meg az Oracle-nek, hogy milyen leírót szeretnél használni. Lehetséges értékek: OCI_B_FILE (Binary-File), OCI_B_CFILE (Character-File), OCI_B_CLOB (Character-LOB), OCI_B_BLOB (Binary-LOB) és OCI_B_ROWID (ROWID).

Példa 1. OCIBindByName

<?php
/* OCIBindByName példa - thies@thieso.net (980221)
  Három rekord felvétele a "dolgozok" táblába, és a ROWID
  használata az adatok frissítésére rögtön a felvitel után.
*/

$conn = OCILogon("scott","tiger");

$stmt = OCIParse($conn,"insert into dolgozok (dolgozoid, dnev) ".
					   "values (:dolgozoid,:dnev) ".
					   "returning ROWID into :rid");

$adatok = array(1111 => "Larry", 2222 => "Bill", 3333 => "Jim");

$rowid = OCINewDescriptor($conn, OCI_D_ROWID);

OCIBindByName($stmt,":dolgozoid",&$dolgozoid, 32);
OCIBindByName($stmt,":dnev",     &$dnev,      32);
OCIBindByName($stmt,":rid",      &$rowid,     -1, OCI_B_ROWID);

$update = OCIParse($conn,
              "update dolgozok set fizetes = :fizetes ".
              "where ROWID = :rid");
OCIBindByName($update,":rid",     &$rowid,     -1, OCI_B_ROWID);
OCIBindByName($update,":fizetes", &$fizetes,   32);

$fizetes = 10000;

while (list($dolgozoid,$dnev) = each($adatok)) {
	OCIExecute($stmt);
	OCIExecute($update);
} 

$rowid->free();

OCIFreeStatement($update);
OCIFreeStatement($stmt);

$stmt = OCIParse($conn,"select * from dolgozok where dolgozoid in (1111,2222,3333)");
OCIExecute($stmt);
while (OCIFetchInto($stmt, &$tomb, OCI_ASSOC)) {
	var_dump($tomb);
}
OCIFreeStatement($stmt);

/* Töröljük a "szemetünket" a dolgozok táblából.... */
$stmt = OCIParse($conn,"delete from dolgozok where dolgozoid in (1111,2222,3333)");
OCIExecute($stmt);
OCIFreeStatement($stmt);

OCILogoff($conn);
?>

Figyelem

Nem jó ötlet a "magic quotes" szolgáltatást, és az OciBindByName() függvényt egyszerre használni, mivel semmilyen átalakítás nem szükséges a változókon, és bármilyen extra idézőjel, ami az értékekben megjelenik az adatbázisba kerül. Az OciBindByName() nem tud különbséget tenni a korábban a karaktersorozatban lévő és a "magic quotes" átalakítás során bekerült idézőjelek között.

OCICancel

(PHP 3>= 3.0.8, PHP 4 )

OCICancel -- Kurzorral olvasás befejezése

Leírás

int OCICancel ( int stmt)

Ha nem szeretnél több adatot olvasni egy kurzorral, hívd meg ezt a függényt.

ocicloselob

(no version information, might be only in CVS)

ocicloselob -- Closes lob descriptor

Description

bool ocicloselob ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

OCICollAppend

(PHP 4 >= 4.0.6)

OCICollAppend -- [Eddig] nem dokumentált

Leírás

string OCICollAppend ( object collection, object object)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

OCICollAssign

(PHP 4 >= 4.0.6)

OCICollAssign -- [Eddig] nem dokumentált

Leírás

string OCICollAssign ( object collection, object object)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

OCICollAssignElem

(PHP 4 >= 4.0.6)

OCICollAssignElem -- [Eddig] nem dokumentált

Leírás

string OCICollAssignElem ( object collection, string ndx, string val)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

OCICollGetElem

(PHP 4 >= 4.0.6)

OCICollGetElem -- [Eddig] nem dokumentált

Leírás

string OCICollGetElem ( object collection, string ndx)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

OCICollMax

(PHP 4 >= 4.0.6)

OCICollMax -- [Eddig] nem dokumentált

Leírás

string OCICollMax ( object collection)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

OCICollSize

(PHP 4 >= 4.0.6)

OCICollSize -- [Eddig] nem dokumentált

Leírás

string OCICollSize ( object collection)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

OCICollTrim

(PHP 4 >= 4.0.6)

OCICollTrim -- [Eddig] nem dokumentált

Leírás

string OCICollTrim ( object collection, int num)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

OCIColumnIsNULL

(PHP 3>= 3.0.4, PHP 4 )

OCIColumnIsNULL -- NULL értékű mező azonosítása

Leírás

int OCIColumnIsNULL ( int stmt, mixed column)

Az OCIColumnIsNULL() TRUE értéket ad vissza, ha a visszaadott column mező az stmt eredménytáblájában NULL értékű. Használhatod az oszlop sorszámot (1-től számozva), vagy az oszlop nevét a col paraméterben.

OCIColumnName

(PHP 3>= 3.0.4, PHP 4 )

OCIColumnName -- Oszlop neve egy eredménytáblában

Leírás

string OCIColumnName ( int stmt, int col)

Az OCIColumnName() visszaadja a col paraméterben megadott oszlop nevét. A col egy sorszám, a számozás 1-től kezdődik.

Példa 1. OCIColumnName

<?php   
    print "<HTML><PRE>\n";   
    $conn = OCILogon("scott", "tiger");
    $stmt = OCIParse($conn,"select * from dolgozok");
    OCIExecute($stmt);
    print "<TABLE BORDER=\"1\">";
    print "<TR>";
    print "<TH>Név</TH>";
    print "<TH>Típus</TH>";
    print "<TH>Méret</TH>";
    print "</TR>";
    $oszlopszam = OCINumCols($stmt);
    for ( $i = 1; $i <= $oszlopszam; $i++ ) {
        $oszlopnev   = OCIColumnName($stmt,$i);
        $oszloptipus = OCIColumnType($stmt,$i);
        $oszlopmeret = OCIColumnSize($stmt,$i);
        print "<TR>";
        print "<TD>$oszlopnev</TD>";
        print "<TD>$oszloptipus</TD>";
        print "<TD>$oszlopmeret</TD>";
        print "</TR>";
    }
    print "</TABLE>\n"; 
    OCIFreeStatement($stmt);  
    OCILogoff($conn);   
    print "</PRE>";
    print "</HTML>\n"; 
?>

Lásd még OCINumCols(), OCIColumnType() és OCIColumnSize().

OCIColumnPrecision

(PHP 4 )

OCIColumnPrecision -- [Eddig] nem dokumentált

Leírás

int OCIColumnPrecision ( int stmt, int col)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

OCIColumnScale

(PHP 4 )

OCIColumnScale -- [Eddig] nem dokumentált

Leírás

int OCIColumnScale ( int stmt, int col)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

OCIColumnSize

(PHP 3>= 3.0.4, PHP 4 )

OCIColumnSize -- Oszlop mérete egy eredménytáblában

Leírás

int OCIColumnSize ( int stmt, mixed column)

Az OCIColumnSize() az Oracle által visszaadott oszlop mérettel tér vissza. Használhatod az oszlop sorszámot (1-től számozva), vagy az oszlop nevét a col paraméterben.

Példa 1. OCIColumnSize

<?php   
    print "<HTML><PRE>\n";   
    $conn = OCILogon("scott", "tiger");
    $stmt = OCIParse($conn,"select * from dolgozok");
    OCIExecute($stmt);
    print "<TABLE BORDER=\"1\">";
    print "<TR>";
    print "<TH>Név</TH>";
    print "<TH>Típus</TH>";
    print "<TH>Méret</TH>";
    print "</TR>";
    $oszlopszam = OCINumCols($stmt);
    for ( $i = 1; $i <= $oszlopszam; $i++ ) {
        $oszlopnev   = OCIColumnName($stmt,$i);
        $oszloptipus = OCIColumnType($stmt,$i);
        $oszlopmeret = OCIColumnSize($stmt,$i);
        print "<TR>";
        print "<TD>$oszlopnev</TD>";
        print "<TD>$oszloptipus</TD>";
        print "<TD>$oszlopmeret</TD>";
        print "</TR>";
    }
    print "</TABLE>\n"; 
    OCIFreeStatement($stmt);  
    OCILogoff($conn);   
    print "</PRE>";
    print "</HTML>\n"; 
?>

Lásd még OCINumCols(), OCIColumnName() és OCIColumnSize().

OCIColumnType

(PHP 3>= 3.0.4, PHP 4 )

OCIColumnType -- Oszlop adattípusa egy eredménytáblában

Leírás

mixed OCIColumnType ( int stmt, int col)

Az OCIColumnType() az adott sorszámú (1-től számozva) oszlop adattípusát adja vissza.

Példa 1. OCIColumnType

<?php   
    print "<HTML><PRE>\n";   
    $conn = OCILogon("scott", "tiger");
    $stmt = OCIParse($conn,"select * from dolgozok");
    OCIExecute($stmt);
    print "<TABLE BORDER=\"1\">";
    print "<TR>";
    print "<TH>Név</TH>";
    print "<TH>Típus</TH>";
    print "<TH>Méret</TH>";
    print "</TR>";
    $oszlopszam = OCINumCols($stmt);
    for ( $i = 1; $i <= $oszlopszam; $i++ ) {
        $oszlopnev   = OCIColumnName($stmt,$i);
        $oszloptipus = OCIColumnType($stmt,$i);
        $oszlopmeret = OCIColumnSize($stmt,$i);
        print "<TR>";
        print "<TD>$oszlopnev</TD>";
        print "<TD>$oszloptipus</TD>";
        print "<TD>$oszlopmeret</TD>";
        print "</TR>";
    }
    print "</TABLE>\n"; 
    OCIFreeStatement($stmt);  
    OCILogoff($conn);   
    print "</PRE>";
    print "</HTML>\n"; 
?>

Lásd még OCINumCols(), OCIColumnName() és OCIColumnSize().

OCIColumnTypeRaw

(PHP 4 )

OCIColumnTypeRaw -- [Eddig] nem dokumentált

Leírás

mixed OCIColumnTypeRaw ( int stmt, int col)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

OCICommit

(PHP 3>= 3.0.7, PHP 4 )

OCICommit -- Függőben lévő tranzakciók végrehajtása

Leírás

int OCICommit ( int connection)

Az OCICommit() minden a connection Oracle kapcsolaton függőben lévő tranzakciót végrehajt.

OCIDefineByName

(PHP 3>= 3.0.7, PHP 4 )

OCIDefineByName --  PHP változó használata a definiálási lépésben egy SELECT számára

Leírás

int OCIDefineByName ( int stmt, string Column-Name, mixed variable [, int type])

Az OCIDefineByName() SQL oszlopok lekérdezését köti felhasználó által definiált PHP változókhoz. Figyelj arra, hogy az Oracle CSUPA NAGYBETŰS neveket használ, de ennek ellenére írhatsz a SELECT-ben kisbetűs neveket is. Az OCIDefineByName() függvény a Column-Name paraméterben a helyes nagybetűs írást várja. Ha olyan változót definiálsz, ami nem létezik a SELECT eredménytáblájában, semmilyen hibát sem kapsz!

Ha absztrakt adattípust kell definiálnod (például LOB, ROWID vagy BFILE), először az OCINewDescriptor() függvényt kell használnod. Lásd még az OCIBindByName() függvényt.

Példa 1. OCIDefineByName

<?php
/* OCIDefineByName példa - thies@thieso.net (980219) */

$conn = OCILogon("scott","tiger");

$stmt = OCIParse($conn,"select dolgozoid, dnev from dolgozok");

/* ennek az ociexecute ELŐTT KELL szerepelnie! */

OCIDefineByName($stmt, "DOLGOZOID", $dolgozoid);
OCIDefineByName($stmt, "DNEV",      $dnev);

OCIExecute($stmt);

while (OCIFetch($stmt)) {
    echo "Dolgozó azonosító:" . $dolgozoid . "\n";
    echo "Dolgozó név:"       . $dnev      . "\n";
}

OCIFreeStatement($stmt);
OCILogoff($conn);
?>

OCIError

(PHP 3>= 3.0.7, PHP 4 )

OCIError -- A legutóbbi parancs / kapcsolat / általános hiba visszaadása

Leírás

array OCIError ( [int stmt|conn|global])

Az OCIError() a legutóbbi hibát adja vissza. Ha az opcionális stmt|conn|global paramétert nem adod meg, a legutóbbi hibát kapod. Ha nem volt hiba, FALSE értéket kapsz. Az OCIError() egy asszociatív tömbben adja vissza a hibát. Ebben a tömbben a code az Oracle hibakód, a message az Oracle hibaüzenet karaktersorozat.

OCIExecute

(PHP 3>= 3.0.4, PHP 4 )

OCIExecute -- Parancs futtatása

Leírás

int OCIExecute ( int statement [, int mode])

Az OCIExecute() futtat egy korábban feldolgozott parancsot. (Lásd az OCIParse() függvényt.) Az opcionális mode paraméterrel tudod beállítani a végrehajtás módját. Az alapértelmezés az OCI_COMMIT_ON_SUCCESS. Ha nem szeretnéd, hogy a parancs rögtön egy tranzakció végrehajtást is végezzen, add meg az OCI_DEFAULT módot.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

OCIFetch

(PHP 3>= 3.0.4, PHP 4 )

OCIFetch -- A következő eredmény sor lekérdezése

Leírás

int OCIFetch ( int statement)

Az OCIFetch() lekérdezi a következő eredménytábla sort, és egy belső eredmény bufferbe helyezi. SELECT parancsok eredménytábláján használható.

OCIFetchInto

(PHP 3>= 3.0.4, PHP 4 )

OCIFetchInto -- A következő sor lekérdezése tömbbe

Leírás

int OCIFetchInto ( int stmt, array & result [, int mode])

Az OCIFetchInto() lekérdezi a következő sort, és a result tömbbe tölti be. SELECT parancsok eredménytábláján használható. A függvény felülírja a result korábbi tartalmát, ha volt ilyen. Alapértelmezésben a result egy számindexes tömb lesz minden mezőértékkel, ami nem NULL.

A mode paraméterrel tudod szabályozni a result szerkezetét és tartalmát. Több opciót is megadhatsz, egyszerű összeadással, például írhatod, hogy OCI_ASSOC + OCI_RETURN_NULLS. A használható opciók:

OCI_ASSOC Asszociatív tömb formátum.
OCI_NUM Számindexes tömb formátum (alapértelmezés).
OCI_RETURN_NULLS A NULL értékű mezők visszaadása.
OCI_RETURN_LOBS A LOB érték visszaadása a leíró helyett.

OCIFetchStatement

(PHP 3>= 3.0.8, PHP 4 )

OCIFetchStatement -- Miden eredménysor lekérdezése egy tömbbe

Leírás

int OCIFetchStatement ( int stmt, array & variable)

Az OCIFetchStatement() lekérdezi az összes eredménysort, és egy PHP tömbbe helyezi. A függvény a lekrédezett sorok számával tér vissza.

Példa 1. OCIFetchStatement

<?php
/* OCIFetchStatement példa - mbritton@verinet.com (990624) */

$conn = OCILogon("scott","tiger");

$stmt = OCIParse($conn,"select * from dolgozok");

OCIExecute($stmt);

$sorokszama = OCIFetchStatement($stmt, $tabla);
if ( $sorokszama > 0 ) {
   print "<TABLE BORDER=\"1\">\n";
   print "<TR>\n";
   while ( list( $kulcs, $ertek ) = each( $tabla ) ) {
      print "<TH>$kulcs</TH>\n";
   }
   print "</TR>\n";
   
   for ( $i = 0; $i < $sorokszama; $i++ ) {
      reset($tabla);
      print "<TR>\n";
      while ( $mezo = each($tabla) ) {   
         $adat = $mezo['value'];
         print "<TD>$adat[$i]</TD>\n";
      }
      print "</TR>\n";
   }
   print "</TABLE>\n";
} else {
   echo "Nincs adat a táblában<BR>\n";
}      
print "$sorokszama sort sikerült lekérdezni<BR>\n";
 
OCIFreeStatement($stmt);
OCILogoff($conn);
?>

OCIFreeCollection

(PHP 4 >= 4.1.0)

OCIFreeCollection -- [Eddig] nem dokumentált

Leírás

string OCIFreeCollection ( object lob)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

OCIFreeCursor

(PHP 3>= 3.0.8, PHP 4 )

OCIFreeCursor --  Kurzorhoz rendelt erőforrások felszabadítása

Leírás

int OCIFreeCursor ( int stmt)

Az OCIFreeCursor() TRUE értéket ad siker, FALSE értéket ad kudarc esetén.

OCIFreeDesc

(PHP 4 )

OCIFreeDesc -- Felszabadít egy LOB leírót

Leírás

int OCIFreeDesc ( object lob)

Az OCIFreeDesc() TRUE értéket ad siker, FALSE értéket ad kudarc esetén.

OCIFreeStatement

(PHP 3>= 3.0.5, PHP 4 )

OCIFreeStatement --  Parancshoz rendelt erőforrások felszabadítása

Leírás

int OCIFreeStatement ( int stmt)

Az OCIFreeStatement() TRUE értéket ad siker, FALSE értéket ad kudarc esetén.

OCIInternalDebug

(PHP 3>= 3.0.4, PHP 4 )

OCIInternalDebug --  A belső debug kimenet engedélyezése / letiltása

Leírás

void OCIInternalDebug ( int onoff)

Az OCIInternalDebug() engedélyezi a belső debug kimenetet ha az onoff paramétert 1 értékre állítod. Tiltásra a 0 értékkel van lehetőség.

OCILoadLob

(PHP 4 )

OCILoadLob -- [Eddig] nem dokumentált

Leírás

string OCILoadLob ( object lob)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

OCILogOff

(PHP 3>= 3.0.4, PHP 4 )

OCILogOff -- Oracle kapcsolat bontása

Leírás

int OCILogOff ( int connection)

Az OCILogOff() függvény lezár egy Oracle kapcsolatot.

OCILogon

(PHP 3>= 3.0.4, PHP 4 )

OCILogon -- Oracle adatbázis kapcsolat létesítése

Leírás

int OCILogon ( string username, string password [, string db])

Az OCILogon() egy kapcsolat azonosítóval tér vissza, amire a legtöbb OCI hívásban szükséged lesz. Az opcionális harmadik paraméter vagy a helyi Oracle példány nevét adja meg, vagy egy tnsnames.ora bejegyzést, amihez csatlakozni szeretnél. Ha nem adod meg ezt a paramétert, a PHP az ORACLE_SID (Oracle példány) vagy a TWO_TASK (tnsnames.ora) környezeti változókat használja, hogy eldöntse melyik adatbázishoz kell csatlakozni.

Az OCILogon() által visszaadott kapcsolatot az aktuális oldalon megosztva használja a PHP. Ez azt jelenti, hogy a tranzakciók végrehjatása vagy visszavonása minden nyitott tranzakcióra vonatkozik az adott oldalon, még akkor is, ha több adatbázis kapcsolattal is rendelkezel.

Ez a példa bemutatja a kapcsolatok megosztását.

Példa 1. OCILogon

<?php
print "<HTML><PRE>";
$db = "";

$c1 = ocilogon("scott","tiger",$db);
$c2 = ocilogon("scott","tiger",$db);

function create_table($conn)
{ $stmt = ociparse($conn,"create table scott.hello (proba varchar2(64))");
  ociexecute($stmt);
  echo $conn." tábla létrehozva\n\n";
}

function drop_table($conn)
{ $stmt = ociparse($conn,"drop table scott.hello");
  ociexecute($stmt);
  echo $conn." tábla törölve\n\n";
}

function insert_data($conn)
{ $stmt = ociparse($conn,"insert into scott.hello
            values('$conn' || ' ' || to_char(sysdate,'DD-MON-YY HH24:MI:SS'))");
  ociexecute($stmt,OCI_DEFAULT);
  echo $conn." beillesztés végrehajtva\n\n";
}

function delete_data($conn)
{ $stmt = ociparse($conn,"delete from scott.hello");
  ociexecute($stmt,OCI_DEFAULT);
  echo $conn." törlés végrehajtva\n\n";
}

function commit($conn)
{ ocicommit($conn);
  echo $conn." tranzakció végrehajtva\n\n";
}

function rollback($conn)
{ ocirollback($conn);
  echo $conn." tranzakció visszavonva\n\n";
}

function select_data($conn)
{ $stmt = ociparse($conn,"select * from scott.hello");
  ociexecute($stmt,OCI_DEFAULT);
  echo $conn."----select végrehajtása\n\n";
  while (ocifetch($stmt))
    echo $conn." <".ociresult($stmt,"PROBA").">\n\n";
  echo $conn."----kész\n\n";
}

create_table($c1);
insert_data($c1);   // Új sor beillesztése c1 felhasználásával
insert_data($c2);   // Új sor beillesztése c2 felhasználásával

select_data($c1);   // Mindkét insert eredményét megkapjuk
select_data($c2);   

rollback($c1);      // Visszavonjuk a c1-en végzett műveletet

select_data($c1);   // Mindkét műveletet visszavontuk
select_data($c2);   

insert_data($c2);   // Sor beillesztése c2-vel
commit($c2);        // Tranzakció végrehajtása c2-vel

select_data($c1);   // A c2 beillesztés eredményét visszakapjuk

delete_data($c1);   // A c1-el töröljük a sorokat
select_data($c1);   // Egy sor sincs
select_data($c2);   // Egy sor sincs
commit($c1);        // A c1-el végrehajtjuk a tranzakciót

select_data($c1);   // Egy sor sincs
select_data($c2);   // Egy sor sincs

drop_table($c1);
print "</PRE></HTML>";
?>

Lásd még OCIPLogon() és OCINLogon().

OCINewCollection

(PHP 4 >= 4.0.6)

OCINewCollection -- [Eddig] nem dokumentált

Leírás

string OCINewCollection ( int conn, string tdo [, string shema])

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

OCINewCursor

(PHP 3>= 3.0.8, PHP 4 )

OCINewCursor --  Új kurzor (parancs eredmény kezelő) megnyitása

Leírás

int OCINewCursor ( int conn)

Az OCINewCursor() egy új eredménytábla kezelő kurzort nyit meg a megadott kapcsolaton.

Példa 1. REF CURSOR használata egy tárolt eljárásból

<?php   
// feltesszük, hogy az info.kimenet tárolt eljárásod egy "ref cursor"-t
// ad vissza az :adat-ban

$conn = OCILogon("scott","tiger");
$kurzor = OCINewCursor($conn);
$stmt = OCIParse($conn,"begin info.kimenet(:adat); end;");

ocibindbyname($stmt,"adat", &$kurzor, -1, OCI_B_CURSOR);
ociexecute($stmt);
ociexecute($kurzor);

while (OCIFetchInto($kurzor, &$adat)) {
    var_dump($adat);
}
 
OCIFreeStatement($stmt);
OCIFreeCursor($kurzor);
OCILogoff($conn);
?>

Példa 2. REF CURSOR használata select parancsban

<?php   
print "<HTML><BODY>";
$conn = OCILogon("scott","tiger");
$szamlalo_kurzor =
    "CURSOR(select count(dolgozoid) dolgozo_szam from dolgozok " .
    "where dolgozok.reszleg = reszleg.reszlegid) as DSZAM from reszleg";
$stmt = OCIParse($conn,"select reszlegid,rnev,$szamlalo_kurzor");

ociexecute($stmt);
print "<TABLE BORDER=\"1\">";
print "<TR>";
print "<TH>RÉSZLEG NÉV</TH>";
print "<TH>RÉSZLEG SZÁM</TH>";
print "<TH>DOLGOZÓK SZÁMA</TH>";
print "</TR>";

while (OCIFetchInto($stmt, &$adat, OCI_ASSOC)) {
    print "<TR>";
    $rnev  = $adat["RNEV"];
    $rszam = $adat["RESZLEGID"];
    print "<TD>$rnev</TD>";
    print "<TD>$rszam</TD>";
    ociexecute($adat["DSZAM"]);
    while (OCIFetchInto($adat["DSZAM"], &$reszadat, OCI_ASSOC)) {
        $dszam = $reszadat["DOLGOZO_SZAM"];
        print  "<TD>$dszam</TD>";
    }
    print "</TR>";
}
print "</TABLE>";
print "</BODY></HTML>";
OCIFreeStatement($stmt);
OCILogoff($conn);
?>

OCINewDescriptor

(PHP 3>= 3.0.7, PHP 4 )

OCINewDescriptor --  Egy új üres LOB vagy FILE leírót hoz létre

Leírás

string OCINewDescriptor ( int connection [, int type])

Az OCINewDescriptor() tárterületet foglal le leírók vagy LOB lokátorok tárolására. A type lehetséges értékei OCI_D_FILE, OCI_D_LOB és OCI_D_ROWID. LOB leírók esetén a a load, save és savefile metódusokat használhatod, a BFILE csak a load metódust támogatja. Lásd a második példa használati tippjeit.

Példa 1. OCINewDescriptor

<?php
    /* Ez a program űrlapból történő meghíváshoz készült.
     * A $felhasznalo, $jelszo, $tabla, $where és $commitmeret
     * értékeket várja az űrlapból. A program letörli a kiválasztott
     * sorokat a ROWID felhasználásval, és minden $commitmeret sor
     * után egy tranzakció végrehajtást eszközöl. Használd óvatosan,
     * a műveletek nem visszavonhatóak.
     */
    $conn = OCILogon($felhasznalo, $jelszo);
    $stmt = OCIParse($conn,"select rowid from $tabla $where");
    $rowid = OCINewDescriptor($conn,OCI_D_ROWID);
    OCIDefineByName($stmt,"ROWID",&$rowid);
    OCIExecute($stmt);
    while ( OCIFetch($stmt) ) {
       $sorokszama = OCIRowCount($stmt);
       $delete = OCIParse($conn,"delete from $tabla where ROWID = :rid");
       OCIBindByName($delete,":rid",&$rowid,-1,OCI_B_ROWID);
       OCIExecute($delete);
       print "$sorokszama\n";
       if ( ($sorokszama % $commitmeret) == 0 ) {
           OCICommit($conn);
       }
    }
    $sorokszama = OCIRowCount($stmt);
    print "$sorokszama sor törölve...\n";
    OCIFreeStatement($stmt);
    OCILogoff($conn);
?>
<?php
    /* Ez a program LOB mezőbe állomány feltöltést mutat be.
     * Az űrlapmező, amit a példa feltételez a következő:
     * <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="Feltöltés"> - <input type="reset">
</form>
<?php
  } else {

     // $lob_upload tartalmazza a feltöltött file ideiglenes állomány nevét

     // lásd még az állomány feltöltésről szóló részt biztonságos
     // file feltöltés példák érdekében

     $conn = OCILogon($felhasznalo, $jelszo);
     $lob = OCINewDescriptor($conn, OCI_D_LOB);
     $stmt = OCIParse($conn,"insert into $tabla (id, a_blob) 
               values(my_seq.NEXTVAL, EMPTY_BLOB()) returning a_blob into :a_blob");
     OCIBindByName($stmt, ':a_blob', &$lob, -1, OCI_B_BLOB);
     OCIExecute($stmt, OCI_DEFAULT);
     if($lob->savefile($lob_upload)){
        OCICommit($conn);
        echo "A Blob feltöltése sikeres\n";
     }else{
        echo "Nem sikerült feltölteni a Blobot\n";
     }
     OCIFreeDesc($lob);
     OCIFreeStatement($stmt);
     OCILogoff($conn);
  }
?>

Példa 2. OCINewDescriptor

<?php   
    /* PL/SQL tárolt eljárások hívása, amik clobs bemeneti paramétereket
     * tartalmaznak (PHP 4 >= 4.0.6). 
     *
     * PROCEDURE adat_mentes
     *   Argumentum neve                Típus                   KI/BE  Alapérték
     *   ------------------------------ ----------------------- ------ ---------
     *   KULCS                          NUMBER(38)              BE
     *   ADAT                           CLOB                    BE
     *
     */

    $conn = OCILogon($felhasznalo, $jelszo);
    $stmt = OCIParse($conn, "begin adat_mentes(:kulcs, :adat); end;");
    $clob = OCINewDescriptor($conn, OCI_D_LOB);
	OCIBindByName($stmt, ':kulcs', $kulcs);
	OCIBindByName($stmt, ':adat',  $clob, -1, OCI_B_CLOB);
	$clob->WriteTemporary($adat);
	OCIExecute($stmt, OCI_DEFAULT);
	OCICommit($conn);
	$clob->close();
	$clob->free();
	OCIFreeStatement($stmt);
?>

OCINLogon

(PHP 3>= 3.0.8, PHP 4 )

OCINLogon -- Új Oracle adatbázis kapcsolat létrehozása

Leírás

int OCINLogon ( string username, string password [, string db])

Az OCINLogon() egy új Oracle 8 adatbázis kapcsolatot hoz létre, és bejelentkezik. Az opcionális harmadik paraméter vagy a helyi Oracle példány nevét adja meg, vagy egy tnsnames.ora bejegyzést, amihez csatlakozni szeretnél. Ha nem adod meg ezt a paramétert, a PHP az ORACLE_SID (Oracle példány) vagy a TWO_TASK (tnsnames.ora) környezeti változókat használja, hogy eldöntse melyik adatbázishoz kell csatlakozni.

Az OCINLogon() mindenképpen egy új kapcsolatot hoz létre. Erre akkor van szükséged, ha el kell különítened a tranzakcióidat egymástól. Alapértelmezésben a kapcsolatokat a PHP megosztja egy oldalon belül, ha az OCILogon() függvényt használod. Az OCIPLogon() használata esetén pedig már a web szerver process szintjén érvényesül a megosztás. Ha több kapcsolatod van az OCINLogon() függvénnyel megnyitva, minden tranzakció végrehajtás és visszavonás cska az adott kapcsolatra vonatkozik.

A következő példa bemutatja a kapcsolatok elkülönülését.

Példa 1. OCINLogon

<?php
print "<HTML><PRE>";
$db = "";

$c1 = ocilogon("scott","tiger",$db);
$c2 = ocinlogon("scott","tiger",$db);

function create_table($conn)
{ $stmt = ociparse($conn,"create table scott.hello (proba varchar2(64))");
  ociexecute($stmt);
  echo $conn." tábla létrehozva\n\n";
}

function drop_table($conn)
{ $stmt = ociparse($conn,"drop table scott.hello");
  ociexecute($stmt);
  echo $conn." tábla törölve\n\n";
}

function insert_data($conn)
{ $stmt = ociparse($conn,"insert into scott.hello
            values('$conn' || ' ' || to_char(sysdate,'DD-MON-YY HH24:MI:SS'))");
  ociexecute($stmt,OCI_DEFAULT);
  echo $conn." beillesztés végrehajtva\n\n";
}

function delete_data($conn)
{ $stmt = ociparse($conn,"delete from scott.hello");
  ociexecute($stmt,OCI_DEFAULT);
  echo $conn." törlés végrehajtva\n\n";
}

function commit($conn)
{ ocicommit($conn);
  echo $conn." tranzakció végrehajtva\n\n";
}

function rollback($conn)
{ ocirollback($conn);
  echo $conn." tranzakció visszavonva\n\n";
}

function select_data($conn)
{ $stmt = ociparse($conn,"select * from scott.hello");
  ociexecute($stmt,OCI_DEFAULT);
  echo $conn."----select végrehajtása\n\n";
  while (ocifetch($stmt))
    echo $conn." <".ociresult($stmt,"PROBA").">\n\n";
  echo $conn."----kész\n\n";
}

create_table($c1);
insert_data($c1);

select_data($c1);   
select_data($c2);   

rollback($c1);      

select_data($c1);   
select_data($c2);   

insert_data($c2);   
commit($c2);        

select_data($c1);   

delete_data($c1);   
select_data($c1);   
select_data($c2);   
commit($c1);        

select_data($c1);
select_data($c2);

drop_table($c1);
print "</PRE></HTML>";
?>

Lásd még OCILogon() és OCIPLogon().

OCINumCols

(PHP 3>= 3.0.4, PHP 4 )

OCINumCols --  Az eredményoszlopok száma egy eredménytáblában

Leírás

int OCINumCols ( int stmt)

Az OCINumCols() visszaadja az eredménytábla oszlopainak a számát.

Példa 1. OCINumCols

<?php   
    print "<HTML><PRE>\n";
    $conn = OCILogon("scott", "tiger");
    $stmt = OCIParse($conn,"select * from dolgozok");
    OCIExecute($stmt);
    while ( OCIFetch($stmt) ) {
        print "\n";
        $ncols = OCINumCols($stmt);
        for ( $i = 1; $i <= $ncols; $i++ ) {
            $oszlop_neve  = OCIColumnName($stmt,$i);
            $mezo_erteke = OCIResult($stmt,$i);
            print $oszlop_neve . ': ' . $mezo_erteke . "\n";
        }
        print "\n";
    }
    OCIFreeStatement($stmt);
    OCILogoff($conn);
    print "</PRE>";
    print "</HTML>\n";
?>

OCIParse

(PHP 3>= 3.0.4, PHP 4 )

OCIParse -- SQL lekérdezés feldolgozása, parancs visszaadása

Leírás

int OCIParse ( int conn, string query)

Az OCIParse() feldolgozz a query paraméterben megadott SQL lekérdezést a conn kapcsolaton. A parancs azonosítóval tér vissza, ha a lekérdezés érvényes volt, FALSE értéket ad egyébként. A query paramétert bármilyen érvényes SQL parancs vagy PL/SQL blokk lehet.

OCIPLogon

(PHP 3>= 3.0.8, PHP 4 )

OCIPLogon -- Oracle adatbáziscsatlakozás állandó kapcsolattal

Leírás

int OCIPLogon ( string username, string password [, string db])

Az OCIPLogon() egy állandó (persistent) adatbázis kapcsolatot hoz létre az Oracle8 adatbázishoz, és bejelentkezik. Az opcionális harmadik paraméter vagy a helyi Oracle példány nevét adja meg, vagy egy tnsnames.ora bejegyzést, amihez csatlakozni szeretnél. Ha nem adod meg ezt a paramétert, a PHP az ORACLE_SID (Oracle példány) vagy a TWO_TASK (tnsnames.ora) környezeti változókat használja, hogy eldöntse melyik adatbázishoz kell csatlakozni.

Lásd még OCILogon() és OCINLogon().

OCIResult

(PHP 3>= 3.0.4, PHP 4 )

OCIResult -- Mező értékének visszaadása lekérdezett sorból

Leírás

mixed OCIResult ( int statement, mixed column)

Az OCIResult() a column oszlopban lévő adatot adja vissza az aktuális sorban. Lásd az OCIFetch() függvényt. Az OCIResult() mindent karaktersorozatként ad vissza, kivéve az absztrakt adattípusokat (ROWID, LOB és FILE típusok).

OCIRollback

(PHP 3>= 3.0.7, PHP 4 )

OCIRollback -- Függőben lévő tranzakciók visszavonása

Leírás

int OCIRollback ( int connection)

Az OCIRollback() minden a connection Oracle kapcsolaton függőben lévő tranzakciót visszavon.

OCIRowCount

(PHP 3>= 3.0.7, PHP 4 )

OCIRowCount -- Az érintett sorok száma

Leírás

int OCIRowCount ( int statement)

Az OCIRowCount() visszaadja az érintett sorok számát például egy update parancs után. Ez a függvény nem adja vissza a select lekérdezés által visszaadott sorok számát!

Példa 1. OCIRowCount

<?php
    print "<HTML><PRE>";
    $conn = OCILogon("scott","tiger");
    $stmt = OCIParse($conn,"create table dolgozok2 as select * from dolgozok");
    OCIExecute($stmt);
    print OCIRowCount($stmt) . " sor beillesztve.<BR>";
    OCIFreeStatement($stmt);
    $stmt = OCIParse($conn,"delete from dolgozok2");
    OCIExecute($stmt);
    print OCIRowCount($stmt) . " sor törölve.<BR>";
    OCICommit($conn);
    OCIFreeStatement($stmt);
    $stmt = OCIParse($conn,"drop table dolgozok2");
    OCIExecute($stmt);
    OCIFreeStatement($stmt);
    OCILogOff($conn);
    print "</PRE></HTML>";
?>

OCISaveLob

(PHP 4 )

OCISaveLob -- [Eddig] nem dokumentált

Leírás

string OCISaveLob ( object lob)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

OCISaveLobFile

(PHP 4 )

OCISaveLobFile -- [Eddig] nem dokumentált

Leírás

string OCISaveLobFile ( object lob)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

OCIServerVersion

(PHP 3>= 3.0.4, PHP 4 )

OCIServerVersion -- Szerver verzió információ visszaadása

Leírás

string OCIServerVersion ( int conn)

Példa 1. OCIServerVersion

<?php
   $conn = OCILogon("scott","tiger");
   print "Szerver verzió: " . OCIServerVersion($conn);
   OCILogOff($conn);
?>

OCISetPrefetch

(PHP 3>= 3.0.12, PHP 4 )

OCISetPrefetch -- Az előzetesen lehívott sorok számának beállítása

Leírás

int OCISetPrefetch ( int stmt, int rows)

Beállítja az előzetesen lehívott sorok számát. Az alapértelmezés 1 sor.

OCIStatementType

(PHP 3>= 3.0.5, PHP 4 )

OCIStatementType -- OCI parancs típusát adja vissza

Leírás

string OCIStatementType ( int stmt)

Az OCIStatementType() a parancs típusát adja vissza. A következők a lehetséges visszatérési értékek:

  1. "SELECT"

  2. "UPDATE"

  3. "DELETE"

  4. "INSERT"

  5. "CREATE"

  6. "DROP"

  7. "ALTER"

  8. "BEGIN"

  9. "DECLARE"

  10. "UNKNOWN"

Példa 1. OCIStatementType() példák

<?php
    print "<HTML><PRE>";
    $conn = OCILogon("scott","tiger");
    $sql  = "delete from dolgozok where reszleg = 10";
   
    $stmt = OCIParse($conn,$sql);
    if ( OCIStatementType($stmt) == "DELETE" ) {
        die "Nincs jogod törölni ebből a táblából<BR>";
    }
   
    OCILogoff($conn);
    print "</PRE></HTML>";
?>

OCIWriteLobToFile

(PHP 4 )

OCIWriteLobToFile -- [Eddig] nem dokumentált

Leírás

void OCIWriteLobToFile ( object lob [, string filename [, int start [, int lenght]]])

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

ociwritetemporarylob

(no version information, might be only in CVS)

ociwritetemporarylob -- Writes temporary blob

Description

bool ociwritetemporarylob ( string var [, int lob_type])

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

LXXV. OpenSSL functions

Bevezetés

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.


Követelmények

In order to use the OpenSSL functions you need to install the OpenSSL package. PHP-4.0.4pl1 requires OpenSSL >= 0.9.6, but PHP-4.0.5 and greater will also work with OpenSSL >= 0.9.5.


Telepítés

To use PHP's OpenSSL support you must also compile PHP --with-openssl[=DIR].

Note to Win32 Users: In order to enable this module on a Windows environment, you must copy libeay32.dll from the DLL folder of the PHP/Win32 binary package to the SYSTEM32 folder of your windows machine. (Ex: C:\WINNT\SYSTEM32 or C:\WINDOWS\SYSTEM32)

Additionally, if you are planning to use the key generation and certificate signing functions, you will need to install a valid openssl.cnf on your system. As of PHP 4.3.0, we include a sample configuration file in the openssl folder of our win32 binary distribution. If you are using PHP 4.2.0 or later and are missing the file, you can obtain it from the OpenSSL home page or by downloading the PHP 4.3.0 release and using the configuration file from there.

Note to Win32 Users: 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.


Futásidejű beállítások

Ez a kiterjesztés semmilyen konfigurációs beállításokat nem definiál a php.ini állományban.


Erőforrás típusok


Key/Certificate parameters

Quite a few of the openssl functions require a key or a certificate parameter. PHP 4.0.5 and earlier have to use a key or certificate resource returned by one of the openssl_get_xxx functions. Later versions may use one of the following methods:

  • Certificates

    1. An X.509 resource returned from openssl_x509_read()

    2. A string having the format file://path/to/cert.pem; the named file must contain a PEM encoded certificate

    3. A string containing the content of a certificate, PEM encoded

  • Public/Private Keys

    1. A key resource returned from openssl_get_publickey() or openssl_get_privatekey()

    2. For public keys only: an X.509 resource

    3. A string having the format file://path/to/file.pem - the named file must contain a PEM encoded certificate/private key (it may contain both)

    4. A string containing the content of a certificate/key, PEM encoded

    5. For private keys, you may also use the syntax array($key, $passphrase) where $key represents a key specified using the file:// or textual content notation above, and $passphrase represents a string containing the passphrase for that private key


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.


Előre definiált állandók

Az itt listázott állandókat ez a kiterjesztés definiálja, és csak akkor elérhetőek, ha az adott kiterjesztés be van fordítva a PHP-be, vagy dinamikusan betöltött.


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)


Padding flags

OPENSSL_PKCS1_PADDING (integer)

OPENSSL_SSLV23_PADDING (integer)

OPENSSL_NO_PADDING (integer)

OPENSSL_PKCS1_OAEP_PADDING (integer)


Key types

OPENSSL_KEYTYPE_RSA (integer)

OPENSSL_KEYTYPE_DSA (integer)

OPENSSL_KEYTYPE_DH (integer)


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:

Táblázat 1. PKCS7 CONSTANTS

ConstantDescription
PKCS7_TEXTAdds 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_BINARYNormally 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 options is present, no translation occurs. This is useful when handling binary data which may not be in MIME format.
PKCS7_NOINTERNWhen 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_NOVERIFYDo not verify the signers certificate of a signed message.
PKCS7_NOCHAINDo not chain verification of signers certificates: that is don't use the certificates in the signed message as untrusted CAs.
PKCS7_NOCERTSWhen 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_NOATTRNormally 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_DETACHEDWhen 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_NOSIGSDon't try and verify the signatures on a message

Megjegyzés: These constants were added in 4.0.6.

Tartalom
openssl_csr_export_to_file -- Exports a CSR to a file
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_error_string -- Return openSSL error message
openssl_free_key -- Free key resource
openssl_get_privatekey -- Get a private key
openssl_get_publickey -- Extract public key from certificate and prepare it for use
openssl_open -- Open sealed data
openssl_pkcs7_decrypt -- Decrypts an S/MIME encrypted message
openssl_pkcs7_encrypt -- Encrypt an S/MIME message
openssl_pkcs7_sign -- sign an S/MIME message
openssl_pkcs7_verify -- Verifies the signature of an S/MIME signed message
openssl_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_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_seal -- Seal (encrypt) data
openssl_sign -- Generate signature
openssl_verify -- Verify signature
openssl_x509_check_private_key -- Checks if a private key corresponds to a certificate
openssl_x509_checkpurpose -- Verifies if a certificate can be used for a particular purpose
openssl_x509_export_to_file -- Exports a certificate to file
openssl_x509_export -- Exports a certificate as a string
openssl_x509_free -- Free certificate resource
openssl_x509_parse -- Parse an X509 certificate and return the information as an array
openssl_x509_read -- Parse an X.509 certificate and return a resource identifier for it

openssl_csr_export_to_file

(PHP 4 >= 4.2.0)

openssl_csr_export_to_file -- Exports a CSR to a file

Description

bool openssl_csr_export_to_file ( resource csr, string outfilename [, bool notext])

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.

The optional parameter notext affects the verbosity of the output; if it is FALSE then additional human-readable information is included in the output. The default value of notext is TRUE.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

See also openssl_csr_export(), openssl_csr_new() and openssl_csr_sign().

openssl_csr_export

(PHP 4 >= 4.2.0)

openssl_csr_export -- Exports a CSR as a string

Description

bool openssl_csr_export ( resource csr, string &out [, bool notext])

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.

The optional parameter notext affects the verbosity of the output; if it is FALSE then additional human-readable information is included in the output. The default value of notext is TRUE.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

See also openssl_csr_export_to_file(), openssl_csr_new() and openssl_csr_sign().

openssl_csr_new

(PHP 4 >= 4.2.0)

openssl_csr_new -- Generates a CSR

Description

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

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.

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.

Megjegyzés: You need to have a valid openssl.cnf installed for this function to operate correctly. See the notes under the installation section for more information.

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.

Táblázat 1. Configuration overrides

configargs keytypeopenssl.conf equivalentdescription
digest_algstringdefault_mdSelects which digest method to use
x509_extensionsstringx509_extensionsSelects which extensions should be used when creating an x509 certificate
req_extensionsstringreq_extensionsSelects which extensions should be used when creating a CSR
private_key_bitsstringdefault_bitsSpecifies how many bits should be used to generate a private key
private_key_typeintegernoneSpecifies 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_keybooleanencrypt_keyShould an exported key (with passphrase) be encrypted?

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Példa 1. openssl_csr_new() example - 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_sign

(PHP 4 >= 4.2.0)

openssl_csr_sign -- Sign a CSR with another certificate (or itself) and generate a certificate

Description

resource openssl_csr_sign ( mixed csr, mixed cacert, mixed priv_key, int days [, array configargs [, int serial]])

openssl_csr_sign() generates an x509 certificate resource from the csr previously generated by openssl_csr_new(), but 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(). The generated certificate will be signed by cacert. If cacert is NULL, the generated certificate will be a self-signed certificate. priv_key is the private key that corresponds to cacert. days specifies the length of time for which the generated certificate will be valid, in days. You can finetune the CSR signing by configargs. See openssl_csr_new() for more information about configargs. Since PHP 4.3.3 you can specify the serial number of issued certificate by serial. In earlier versions, it was always 0.

Returns an x509 certificate resource on success, FALSE on failure.

Megjegyzés: You need to have a valid openssl.cnf installed for this function to operate correctly. See the notes under the installation section for more information.

Példa 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 it's private key
$cacert = "file://path/to/ca.crt";
$privkey = array("file://path/to/ca.key", "your_ca_key_passphrase");

$userscert = 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_error_string

(PHP 4 >= 4.0.6)

openssl_error_string -- Return openSSL error message

Description

mixed openssl_error_string ( void )

Returns an error message string, or FALSE if there are no more error messages to return.

openssl_error_string() returns the last error from the openSSL library. Error messages are stacked, so this function should be called multiple times to collect all of the information.

Példa 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_free_key

(PHP 4 >= 4.0.4)

openssl_free_key -- Free key resource

Description

void openssl_free_key ( resource key_identifier)

openssl_free_key() frees the key associated with the specified key_identifier from memory.

openssl_get_privatekey

(PHP 4 >= 4.0.4)

openssl_get_privatekey -- Get a private key

Description

resource openssl_get_privatekey ( mixed key [, string passphrase])

This is an alias for openssl_pkey_get_private().

openssl_get_publickey

(PHP 4 >= 4.0.4)

openssl_get_publickey -- Extract public key from certificate and prepare it for use

Description

resource openssl_get_publickey ( mixed certificate)

This is an alias for openssl_pkey_get_public().

openssl_open

(PHP 4 >= 4.0.4)

openssl_open -- Open sealed data

Description

bool openssl_open ( string sealed_data, string &open_data, string env_key, mixed priv_key_id)

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad. If successful the opened data is returned in open_data.

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.

Példa 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);
?>

See also openssl_seal().

openssl_pkcs7_decrypt

(PHP 4 >= 4.0.6)

openssl_pkcs7_decrypt -- Decrypts an S/MIME encrypted message

Description

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 it's associated private key specified by recipcert and recipkey.

The decrypted message is output to the file specified by outfilename

Példa 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_pkcs7_encrypt

(PHP 4 >= 4.0.6)

openssl_pkcs7_encrypt -- Encrypt an S/MIME message

Description

bool openssl_pkcs7_encrypt ( string infile, string outfile, mixed recipcerts, array headers [, int flags])

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, which is either a lone X.509 certificate, or an array of X.509 certificates. headers is an array of headers that will be prepended to the data after it has been encrypted. flags can be used to specify options that affect the encoding process - see PKCS7 constants. headers can be either an associative array keyed by header name, or an indexed array, where each element contains a single header line.

Példa 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_sign

(PHP 4 >= 4.0.6)

openssl_pkcs7_sign -- sign an S/MIME message

Description

bool openssl_pkcs7_sign ( string infilename, string outfilename, mixed signcert, mixed privkey, array headers [, int flags [, string extracerts]])

openssl_pkcs7_sign() takes the contents of the file named infilename and signs them using the certificate and it's matching private key specified by signcert and privkey parameters.

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 can be used to alter the output - see PKCS7 constants - if not specified, it defaults to PKCS7_DETACHED.

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.

Példa 1. openssl_pkcs7_sign() example

<?php
// the message you want to sign so that recipient can be sure it was you that
// sent it
$data = <<<EOD

You have my authorization to spend $10,000 on dinner expenses.

The CEO
EOD;
// save message to file
$fp = fopen("msg.txt", "w");
fwrite($fp, $data);
fclose($fp);
// encrypt it
if (openssl_pkcs7_sign("msg.txt", "signed.txt", "mycert.pem",
    array("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_verify

(PHP 4 >= 4.0.6)

openssl_pkcs7_verify -- Verifies the signature of an S/MIME signed message

Description

bool openssl_pkcs7_verify ( string filename, int flags [, string outfilename [, array cainfo [, string extracerts]]])

openssl_pkcs7_verify() reads the S/MIME message contained in the filename specified by filename and examines the digital signature. It 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.

flags can be used to affect how the signature is verified - see PKCS7 constants for more information.

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.

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.

If the extracerts is specified, it is the filename of a file containing a bunch of certificates to use as untrusted CAs.

openssl_pkey_export_to_file

(PHP 4 >= 4.2.0)

openssl_pkey_export_to_file -- Gets an exportable representation of a key into a file

Description

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. The key can be optionally protected by a passphrase. 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. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Megjegyzés: You need to have a valid openssl.cnf installed for this function to operate correctly. See the notes under the installation section for more information.

openssl_pkey_export

(PHP 4 >= 4.2.0)

openssl_pkey_export -- Gets an exportable representation of a key into a string

Description

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). The key is optionally protected by passphrase. 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. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Megjegyzés: You need to have a valid openssl.cnf installed for this function to operate correctly. See the notes under the installation section for more information.

openssl_pkey_get_private

(PHP 4 >= 4.2.0)

openssl_pkey_get_private -- Get a private key

Description

resource openssl_get_privatekey ( mixed key [, string passphrase])

Returns a positive key resource identifier on success, or FALSE on error.

openssl_get_privatekey() parses key and prepares it for use by other functions. 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.

The optional parameter passphrase must be used if the specified key is encrypted (protected by a passphrase).

openssl_pkey_get_public

(PHP 4 >= 4.2.0)

openssl_pkey_get_public -- Extract public key from certificate and prepare it for use

Description

resource openssl_pkey_get_public ( mixed certificate)

Returns a positive key resource identifier on success, or FALSE on error.

openssl_get_publickey() extracts the public key from certificate and prepares it for use by other functions. certificate can be one of the following:

  1. an X.509 certificate resource

  2. a string having the format file://path/to/file.pem. The named file must contain a PEM encoded certificate/private key (it may contain both).

  3. A PEM formatted private key.

openssl_pkey_new

(PHP 4 >= 4.2.0)

openssl_pkey_new -- Generates a new private key

Description

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(). You can finetune the key generation (such as specifying the number of bits) using configargs. See openssl_csr_new() for more information about configargs.

Megjegyzés: You need to have a valid openssl.cnf installed for this function to operate correctly. See the notes under the installation section for more information.

openssl_private_decrypt

(PHP 4 >= 4.0.6)

openssl_private_decrypt -- Decrypts data with private key

Description

bool openssl_private_decrypt ( string data, string &decrypted, mixed key [, int padding])

openssl_private_decrypt() decrypts data that was previous encrypted via openssl_private_encrypt() and stores the result into decrypted. key must be the private key corresponding that was used to encrypt the data. padding defaults to OPENSSL_PKCS1_PADDING, but can also be one of OPENSSL_SSLV23_PADDING, OPENSSL_PKCS1_OAEP_PADDING OPENSSL_NO_PADDING.

openssl_private_encrypt

(PHP 4 >= 4.0.6)

openssl_private_encrypt -- Encrypts data with private key

Description

bool openssl_private_encrypt ( string data, string &crypted, mixed key [, int padding])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

openssl_public_decrypt

(PHP 4 >= 4.0.6)

openssl_public_decrypt -- Decrypts data with public key

Description

bool openssl_public_decrypt ( string data, string &crypted, resource key [, int padding])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

openssl_public_encrypt

(PHP 4 >= 4.0.6)

openssl_public_encrypt -- Encrypts data with public key

Description

bool openssl_public_encrypt ( string data, string &crypted, mixed key [, int padding])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

openssl_seal

(PHP 4 >= 4.0.4)

openssl_seal -- Seal (encrypt) data

Description

int openssl_seal ( string data, string &sealed_data, array &env_keys, array pub_key_ids)

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.

openssl_seal() seals (encrypts) data by using RC4 with a randomly generated secret key. The key is encrypted with each of the public keys associated with the identifiers in pub_key_ids and each encrypted key is returned in env_keys. This means that one can send sealed data to multiple recipients (provided one has obtained their public keys). Each recipient must receive both the sealed data and the envelope key that was encrypted with the recipient's public key.

Példa 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);
?>

See also openssl_open().

openssl_sign

(PHP 4 >= 4.0.4)

openssl_sign -- Generate signature

Description

bool openssl_sign ( string data, string signature, mixed priv_key_id)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad. If successful the signature is returned in signature.

openssl_sign() computes a signature for the specified data by using SHA1 for hashing followed by encryption using the private key associated with priv_key_id. Note that the data itself is not encrypted.

Példa 1. openssl_sign() example

<?php
// $data is assumed to contain the data to be signed

// fetch private key from file and ready it
$fp = fopen("/src/openssl-0.9.6/demos/sign/key.pem", "r");
$priv_key = fread($fp, 8192);
fclose($fp);
$pkeyid = openssl_get_privatekey($priv_key);

// compute signature
openssl_sign($data, $signature, $pkeyid);

// free the key from memory
openssl_free_key($pkeyid);
?>

See also openssl_verify().

openssl_verify

(PHP 4 >= 4.0.4)

openssl_verify -- Verify signature

Description

int openssl_verify ( string data, string signature, mixed pub_key_id)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Returns 1 if the signature is correct, 0 if it is incorrect, and -1 on error.

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.

Példa 1. openssl_verify() example

<?php
// $data and $signature are assumed to contain the data and the signature

// fetch public key from certificate and ready it
$fp = fopen("/src/openssl-0.9.6/demos/sign/cert.pem", "r");
$cert = fread($fp, 8192);
fclose($fp);
$pubkeyid = openssl_get_publickey($cert);

// state whether signature is okay or not
$ok = openssl_verify($data, $signature, $pubkeyid);
if ($ok == 1) {
    echo "good";
} elseif ($ok == 0) {
    echo "bad";
} else {
    echo "ugly, error checking signature";
}
// free the key from memory
openssl_free_key($pubkeyid);
?>

See also openssl_sign().

openssl_x509_check_private_key

(PHP 4 >= 4.2.0)

openssl_x509_check_private_key -- Checks if a private key corresponds to a certificate

Description

bool openssl_x509_check_private_key ( mixed cert, mixed key)

openssl_x509_check_private_key() returns TRUE if key is the private key that corresponds to cert, or FALSE otherwise.

openssl_x509_checkpurpose

(PHP 4 >= 4.0.6)

openssl_x509_checkpurpose -- Verifies if a certificate can be used for a particular purpose

Description

bool openssl_x509_checkpurpose ( mixed x509cert, int purpose, array cainfo [, string untrustedfile])

Returns TRUE if the certificate can be used for the intended purpose, FALSE if it cannot, or -1 on error.

openssl_x509_checkpurpose() examines the certificate specified by x509cert to see if it can be used for the purpose specified by purpose.

cainfo should be an array of trusted CA files/dirs as described in Certificate Verification.

untrustedfile, if specified, is the name of a PEM encoded file holding certificates that can be used to help verify the certificate, although no trust in placed in the certificates that come from that file.

Táblázat 1. openssl_x509_checkpurpose() purposes

ConstantDescription
X509_PURPOSE_SSL_CLIENTCan the certificate be used for the client side of an SSL connection?
X509_PURPOSE_SSL_SERVERCan the certificate be used for the server side of an SSL connection?
X509_PURPOSE_NS_SSL_SERVERCan the cert be used for Netscape SSL server?
X509_PURPOSE_SMIME_SIGNCan the cert be used to sign S/MIME email?
X509_PURPOSE_SMIME_ENCRYPTCan the cert be used to encrypt S/MIME email?
X509_PURPOSE_CRL_SIGNCan the cert be used to sign a certificate revocation list (CRL)?
X509_PURPOSE_ANYCan the cert be used for Any/All purposes?
These options are not bitfields - you may specify one only!

openssl_x509_export_to_file

(PHP 4 >= 4.2.0)

openssl_x509_export_to_file -- Exports a certificate to file

Description

bool openssl_x509_export_to_file ( mixed x509, string outfilename [, bool notext])

openssl_x509_export_to_file() stores x509 into a file named by outfilename in a PEM encoded format.

The optional parameter notext affects the verbosity of the output; if it is FALSE then additional human-readable information is included in the output. The default value of notext is TRUE.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

openssl_x509_export

(PHP 4 >= 4.2.0)

openssl_x509_export -- Exports a certificate as a string

Description

bool openssl_x509_export ( mixed x509, string &output [, bool notext])

openssl_x509_export() stores x509 into a string named by output in a PEM encoded format.

The optional parameter notext affects the verbosity of the output; if it is FALSE then additional human-readable information is included in the output. The default value of notext is TRUE.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

openssl_x509_free

(PHP 4 >= 4.0.6)

openssl_x509_free -- Free certificate resource

Description

void openssl_x509_free ( resource x509cert)

openssl_x509_free() frees the certificate associated with the specified x509cert resource from memory.

openssl_x509_parse

(PHP 4 >= 4.0.6)

openssl_x509_parse -- Parse an X509 certificate and return the information as an array

Description

array openssl_x509_parse ( mixed x509cert [, bool shortnames])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

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

The structure of the returned data is (deliberately) not yet documented, as it is still subject to change.

openssl_x509_read

(PHP 4 >= 4.0.6)

openssl_x509_read -- Parse an X.509 certificate and return a resource identifier for it

Description

resource openssl_x509_read ( mixed x509certdata)

openssl_x509_read() parses the certificate supplied by x509certdata and returns a resource identifier for it.

LXXVI. Oracle függvények

Tartalom
Ora_Bind -- PHP változó kötése egy Oracle paraméterhez
Ora_Close -- Oracle kurzor bezárása
Ora_ColumnName -- Oracle eredményoszlop nevét adja vissza
Ora_ColumnSize -- Oracle eredményoszlop méretét adja vissza
Ora_ColumnType -- Oracle eredményoszlop típusát adja vissza
Ora_Commit -- Oracle tranzakció végrehajtása
Ora_CommitOff -- Automatikus végrehajtás letiltása
Ora_CommitOn -- Automatikus végrehajtás engedélyezése
Ora_Do -- Parse, Exec és Fetch egyben
Ora_Error -- Oracle hibaüzenet lekérése
Ora_ErrorCode -- Oracle hibakód lekérdezése
Ora_Exec -- Feldolgozott parancs végrehajtása egy Oracle kurzoron
Ora_Fetch_Into -- Sor betöltése megadott eredmény tömbbe
Ora_Fetch -- Egy adatsor lekérdezése egy kurzorról
Ora_GetColumn -- Adat lekérése egy lekérdezett oszlopból
Ora_Logoff -- Oracle kapcsolat lezárása
Ora_Logon -- Oracle kapcsolat megnyitása
Ora_Numcols -- Az oszlopok száma egy eredménytáblában
Ora_Numrows -- A sorok száma egy eredménytáblában
Ora_Open -- Oracle kurzor megnyitása
Ora_Parse -- SQL kifejezés feldolgozása
Ora_pLogon --  Állandó Oracle kapcsolat megnyitása
Ora_Rollback -- Visszavon egy tranzakciót

Ora_Bind

(PHP 3, PHP 4 )

Ora_Bind -- PHP változó kötése egy Oracle paraméterhez

Leírás

int ora_bind ( int cursor, string PHP variable name, string SQL parameter name, int length [, int type])

TRUE értékkel tér vissza, ha sikeres a kötés, egyébként FALSE értéket ad. A hibáról további részleteket az ora_error() és ora_errorcode() függvényekkel lehet megtudni.

Ez a függvény összeköti a megnevezett PHP változót egy SQL paraméterrel. Az SQL paraméternek ":név" formátumúnak kell lennie. Az opcionális típus paraméterrel lehet meghatározni, hogy az SQL paraméter egy bemeneti/kimeneti (0, alapértelmezett), bemeneti (1), vagy kimeneti (2) paraméter. A PHP 3.0.1 verziójától az ORA_BIND_INOUT, ORA_BIND_IN és ORA_BIND_OUT konstansokat is lehet a számok helyett használni.

Az ora_bind() függvényt az ora_parse() után és az ora_exec() előtt kell meghívni. A bemeneti értékeket az összekapcsolt PHP változóknak való értékadással lehet megadni, az ora_exec() meghívása után pedig az összekapcsolt PHP változók tartalmazzák majd a kimeneti értékeket, ha vannak kimeneti értékek.

<?php
ora_parse($curs, "declare tmp INTEGER; begin tmp := :in; :out := tmp; :x := 7.77; end;");
ora_bind ($curs, "result", ":x",   $len, 2);
ora_bind ($curs, "input",  ":in",  5,    1);
ora_bind ($curs, "output", ":out", 5,    2);
$input = 765;
ora_exec($curs);
echo "Result: $result<br>Out: $output<br>In: $input";
?>

Ora_Close

(PHP 3, PHP 4 )

Ora_Close -- Oracle kurzor bezárása

Leírás

int ora_close ( int cursor)

TRUE értékkel tér vissza, ha sikeres a lezárás. Ellenkező esetben FALSE értéket ad. A hibáról további részleteket az ora_error() és ora_errorcode() függvényekkel lehet megtudni.

Ez a függvény lezár egy adat kurzort, amit az ora_open() függvénnyel nyitottál.

Ora_ColumnName

(PHP 3, PHP 4 )

Ora_ColumnName -- Oracle eredményoszlop nevét adja vissza

Leírás

string Ora_ColumnName ( int cursor, int column)

Visszaadja a column mező/oszlop nevét, amelyen a cursor kurzor áll. A visszaadott név csupa nagybetűkből áll. Az első oszlop sorszáma a nulla.

Ora_ColumnSize

(PHP 3, PHP 4 )

Ora_ColumnSize -- Oracle eredményoszlop méretét adja vissza

Leírás

int Ora_ColumnSize ( int cursor, int column)

Visszaadja a column mező/oszlop méretét, amelyen a cursor kurzor áll. Az első oszlop sorszáma a nulla.

Ora_ColumnType

(PHP 3, PHP 4 )

Ora_ColumnType -- Oracle eredményoszlop típusát adja vissza

Leírás

string Ora_ColumnType ( int cursor, int column)

Visszaadja a column mező/oszlop Oracle adattípusát, amelyen a cursor kurzor áll. Az első oszlop sorszáma a nulla. A visszaadott típus a következők valamelyike lesz:

"VARCHAR2"
"VARCHAR"
"CHAR"
"NUMBER"
"LONG"
"LONG RAW"
"ROWID"
"DATE"
"kurzor"

Ora_Commit

(PHP 3, PHP 4 )

Ora_Commit -- Oracle tranzakció végrehajtása

Leírás

int ora_commit ( int conn)

TRUE értéket ad vissza, ha sikeres, egyébként FALSE értékkel tér vissza. A hibáról további részleteket az ora_error() és ora_errorcode() függvényekkel lehet megtudni.

Ez a függvény végrehajt egy Oracle tranzakciót. A tranzakciót úgy definiálhatjuk, mint az adott kapcsolaton bekövetkezett változásokat a legutolsó végrehajtás/visszavonás vagy a kapcsolat létrejötte óta, feltéve, hogy a változások automatikus végrehjatása ki volt kapcsolva.

Ora_CommitOff

(PHP 3, PHP 4 )

Ora_CommitOff -- Automatikus végrehajtás letiltása

Leírás

int ora_commitoff ( int conn)

TRUE értéket ad vissza, ha sikeres, egyébként FALSE értéket kapunk. A hibáról további részleteket az ora_error() és ora_errorcode() függvényekkel lehet megtudni.

Ez a függvény kikapcsolja az ora_exec() utáni automatikus végrehajtást.

Ora_CommitOn

(PHP 3, PHP 4 )

Ora_CommitOn -- Automatikus végrehajtás engedélyezése

Leírás

int ora_commiton ( int conn)

Ez a függvény bekapcsolja az automatikus elküldést minden ora_exec() után az adott kapcsolaton.

TRUE értéket ad vissza, ha sikeres, egyébként FALSE értéket kapunk. A hibáról további részleteket az ora_error() és ora_errorcode() függvényekkel lehet megtudni.

Ora_Do

(PHP 3, PHP 4 )

Ora_Do -- Parse, Exec és Fetch egyben

Leírás

int ora_do ( int conn, string query)

Ez a függvény egy gyors kombinációja az ora_parse(), ora_exec() és ora_fetch() függvényeknek. Feldolgoz és végrehajt egy parancsot, majd letölti az első eredmény sort.

TRUE értéket ad vissza, ha sikeres, egyébként FALSE értéket kapunk. A hibáról további részleteket az ora_error() és ora_errorcode() függvényekkel lehet megtudni.

Lásd még az ora_parse(),ora_exec(), és ora_fetch() függvényeket.

Ora_Error

(PHP 3, PHP 4 )

Ora_Error -- Oracle hibaüzenet lekérése

Leírás

string Ora_Error ( int cursor_or_connection)

Hibaüzenetet ad vissza az XXX-NNNNN formában, ahol XXX a hiba forrása, NNNNN pedig a hiba azonosítója.

Megjegyzés: A csatlakozás azonosítók támogatása a 3.0.4 verzióban került a nyelvbe.

Az Oracle Unix verzióin egy hibáról a következőképpen lehet részleteket megtudni: $ oerr ora 00001 00001, 00000, "unique constraint (%s.%s) violated" // *Cause: An update or insert statement attempted to insert a duplicate key // For Trusted ORACLE configured in DBMS MAC mode, you may see // this message if a duplicate entry exists at a different level. // *Action: Either remove the unique restriction or do not insert the key

Ora_ErrorCode

(PHP 3, PHP 4 )

Ora_ErrorCode -- Oracle hibakód lekérdezése

Leírás

int Ora_ErrorCode ( int cursor_or_connection)

Az adott kurzoron, vagy kapcsolaton végrehajtott utolsó parancs hibakódját adja vissza.

Megjegyzés: A csatlakozás azonosítók támogatása a 3.0.4 verzióban került a nyelvbe.

Ora_Exec

(PHP 3, PHP 4 )

Ora_Exec -- Feldolgozott parancs végrehajtása egy Oracle kurzoron

Leírás

int ora_exec ( int cursor)

TRUE értéket ad vissza, ha sikeres, egyébként FALSE értéket kapunk. A hibáról további részleteket az ora_error() és ora_errorcode() függvényekkel lehet megtudni.

Lásd még ora_parse(), ora_fetch() és ora_do().

Ora_Fetch_Into

(PHP 3, PHP 4 )

Ora_Fetch_Into -- Sor betöltése megadott eredmény tömbbe

Leírás

int ora_fetch_into ( int cursor, array result [, int flags])

Az Ora_Fetch_Into() egy sort tölt be a második paraméterben megadott tömbbe.

Példa 1. Oracle sor betöltése tömbbe

<?php
array($results);
ora_fetch_into($cursor, &$results);
echo $results[0];
echo $results[1];
?>
Fontos, hogy a tömböt referencia szerint kell átadnod.

Lásd még az ora_parse(), ora_exec(), ora_fetch() és ora_do() függvényeket.

Ora_Fetch

(PHP 3, PHP 4 )

Ora_Fetch -- Egy adatsor lekérdezése egy kurzorról

Leírás

int ora_fetch ( int cursor)

TRUE értéket ad vissza, ha sikeres (lekérdezett egy sort), FALSE értéket kapunk, ha nincs több sor, vagy hiba lépett fel. A hibáról további részleteket az ora_error() és ora_errorcode() függvényekkel lehet megtudni. Ha nam volt hiba, a ora_errorcode() nullát ad vissza.

Lehív egy sornyi adatot a megadott kurzoron.

Lásd még az ora_parse(), ora_exec() és ora_do() függvényeket.

Ora_GetColumn

(PHP 3, PHP 4 )

Ora_GetColumn -- Adat lekérése egy lekérdezett oszlopból

Leírás

mixed ora_getcolumn ( int cursor, mixed column)

Az oszlophoz tartozó adatatot adja vissza. Ha hiba lép fel, FALSE értékkel tér vissza, és az ora_errorcode() nem-nulla értéke jelzi a hibát. Azonban a függvény adhat vissza FALSE értékű, de nem boolean típusú értéket is, még akkor is, ha nem történt hiba, (pl: NULL eredmény, üres sztring, az érték 0, a sztring "0").

Lekérdezi egy oszlop, vagy függvény-eredmény értékét.

Ora_Logoff

(PHP 3, PHP 4 )

Ora_Logoff -- Oracle kapcsolat lezárása

Leírás

int ora_logoff ( int conn)

TRUE értéket ad vissza, ha sikeres, egyébként FALSE értéket kapunk. A hibáról további részleteket az ora_error() és ora_errorcode() függvényekkel lehet megtudni.

Kilépteti a felhasználót és bontja a szerverrel a kapcsolatot.

Lásd még az ora_logon() függvényt.

Ora_Logon

(PHP 3, PHP 4 )

Ora_Logon -- Oracle kapcsolat megnyitása

Leírás

int ora_logon ( string user, string password)

Létrehoz egy kapcsolatot a PHP és egy Oracle adatbázis szerver között, a felhasználónév és jelszó felhasználásával.

A kapcsolatokat az SQL*Net segítségével is létre lehet hozni, a felhasználó TNS név megadásával:

$conn = Ora_Logon("user<emphasis>@TNSNAME</emphasis>", "pass");

Amennyiben nem ASCII karakteres adattal kell dolgoznod, mindenképpen gondoskodj róla, hogy az NLS_LANG be legyen állítva a környezetben. Szerver modulok esetén a szerver környzetében kell beállítnai a szerver indítása előtt.

A függvény egy csatlakozás azonosítót ad vissza siker esetén, vagy FALSE értéket kudarc esetén. A hibáról további részleteket az ora_error() és ora_errorcode() függvényekkel lehet megtudni.

Ora_Numcols

(PHP 3, PHP 4 )

Ora_Numcols -- Az oszlopok száma egy eredménytáblában

Leírás

int ora_numcols ( int cursor_ind)

Az ora_numcols() visszaadja az eredméyntáblában lévő oszlopok számát. Értelmes eredményt csak egy parse/exec/fetch függvényhívási sorozat után ad.

Lásd még az ora_parse(), ora_exec(), ora_fetch() és ora_do() függvényeket.

Ora_Numrows

(PHP 3, PHP 4 )

Ora_Numrows -- A sorok száma egy eredménytáblában

Leírás

int ora_numrows ( int cursor_ind)

Az ora_numrows() a sorok számát adja vissza egy eredménytáblában.

Ora_Open

(PHP 3, PHP 4 )

Ora_Open -- Oracle kurzor megnyitása

Leírás

int ora_open ( int conn)

Megnyit egy a csatlakozással társított Oracle kurzort.

Visszaadja a kurzor azonosítóját (kurzor indexét), vagy FALSE értéket hiba esetén. A hibáról további részleteket az ora_error() és ora_errorcode() függvényekkel lehet megtudni.

Ora_Parse

(PHP 3, PHP 4 )

Ora_Parse -- SQL kifejezés feldolgozása

Leírás

int ora_parse ( int cursor_ind, string sql_statement, int defer)

Ez a függvény feldolgoz egy SQL kifejezést, vagy egy PL/SQL blokkot és társítja a megadott kurzorral.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Lásd még az ora_exec(), ora_fetch() és ora_do() függvényeket.

Ora_pLogon

(PHP 3, PHP 4 )

Ora_pLogon --  Állandó Oracle kapcsolat megnyitása

Leírás

int ora_plogon ( string user, string pass)

Állandó kapcsolatot hoz létre a PHP és egy Oracle adatbázis között az adott felhasználónévvel és jelszóval.

Lásd még az ora_logon() függvényt.

Ora_Rollback

(PHP 3, PHP 4 )

Ora_Rollback -- Visszavon egy tranzakciót

Leírás

int ora_rollback ( int conn)

Az Ora_Rollback() visszavon egy Oracle tranzakciót. Lásd még az ora_commit() függvényt a tranzakció leírásáért.

TRUE értéket ad vissza, ha sikeres, egyébként FALSE értéket kapunk. A hibáról további részleteket az ora_error() és ora_errorcode() függvényekkel lehet megtudni.

LXXVII. Ovrimos SQL functions

Bevezetés

Ovrimos SQL Server, is a client/server, transactional RDBMS combined with Web capabilities and fast transactions.

Megjegyzés: Ez a kiterjesztés nem működik Windows operációs rendszereken!


Követelmények

You'll need to install the sqlcli library available in the Ovrimos SQL Server distribution.


Telepítés

To enable Ovrimos support in PHP just compile PHP with the --with-ovrimos[=DIR] parameter to your configure line. DIR is the Ovrimos' libsqlcli install directory.


Futásidejű beállítások

Ez a kiterjesztés semmilyen konfigurációs beállításokat nem definiál a php.ini állományban.


Erőforrás típusok


Példák

Példa 1. Connect to Ovrimos SQL Server and select from a system table

<?php
$conn = ovrimos_connect("server.domain.com", "8001", "admin", "password");
if ($conn != 0) {
    echo "Connection ok!";
    $res = ovrimos_exec($conn, "select table_id, table_name from sys.tables");
    if ($res != 0) {
        echo "Statement ok!";
        ovrimos_result_all($res);
        ovrimos_free_result($res);
    }
    ovrimos_close($conn);
}
?>
This will just connect to an Ovrimos SQL server.

Tartalom
ovrimos_close -- Closes the connection to ovrimos
ovrimos_commit -- Commits the transaction
ovrimos_connect -- Connect to the specified database
ovrimos_cursor -- Returns the name of the cursor
ovrimos_exec -- Executes an SQL statement
ovrimos_execute -- Executes a prepared SQL statement
ovrimos_fetch_into -- Fetches a row from the result set
ovrimos_fetch_row -- Fetches a row from the result set
ovrimos_field_len -- Returns the length of the output column
ovrimos_field_name -- Returns the output column name
ovrimos_field_num --  Returns the (1-based) index of the output column
ovrimos_field_type --  Returns the (numeric) type of the output column
ovrimos_free_result -- Frees the specified result_id
ovrimos_longreadlen --  Specifies how many bytes are to be retrieved from long datatypes
ovrimos_num_fields -- Returns the number of columns
ovrimos_num_rows --  Returns the number of rows affected by update operations
ovrimos_prepare -- Prepares an SQL statement
ovrimos_result_all --  Prints the whole result set as an HTML table
ovrimos_result -- Retrieves the output column
ovrimos_rollback -- Rolls back the transaction

ovrimos_close

(PHP 4 >= 4.0.3)

ovrimos_close -- Closes the connection to ovrimos

Description

void ovrimos_close ( int connection)

ovrimos_close() is used to close the specified connection to Ovrimos. This has the effect of rolling back uncommitted transactions.

ovrimos_commit

(PHP 4 >= 4.0.3)

ovrimos_commit -- Commits the transaction

Description

bool ovrimos_commit ( int connection_id)

ovrimos_commit() is used to commit the transaction. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

ovrimos_connect

(PHP 4 >= 4.0.3)

ovrimos_connect -- Connect to the specified database

Description

int ovrimos_connect ( string host, string db, string user, string password)

ovrimos_connect() is used to connect to the specified database.

ovrimos_connect() returns a connection id (greater than 0) or 0 for failure. The meaning of host and db are those used everywhere in Ovrimos APIs. host is a host name or IP address and db is either a database name, or a string containing the port number.

Példa 1. ovrimos_connect() Example

<?php
$conn = ovrimos_connect("server.domain.com", "8001", "admin", "password");
if ($conn != 0) {
    echo "Connection ok!";
    $res=ovrimos_exec($conn, "select table_id, table_name from sys.tables");
    if ($res != 0) {
        echo "Statement ok!";
        ovrimos_result_all($res);
        ovrimos_free_result($res);
    }
    ovrimos_close($conn);
}
?>
The above example will connect to the database and print out the specified table.

ovrimos_cursor

(PHP 4 >= 4.0.3)

ovrimos_cursor -- Returns the name of the cursor

Description

string ovrimos_cursor ( int result_id)

ovrimos_cursor() returns the name of the cursor. Useful when wishing to perform positioned updates or deletes.

ovrimos_exec

(PHP 4 >= 4.0.3)

ovrimos_exec -- Executes an SQL statement

Description

int ovrimos_exec ( int connection_id, string query)

ovrimos_exec() executes an SQL statement (query or update) and returns a result_id or FALSE. Evidently, the SQL statement should not contain parameters.

ovrimos_execute

(PHP 4 >= 4.0.3)

ovrimos_execute -- Executes a prepared SQL statement

Description

bool ovrimos_execute ( int result_id [, array parameters_array])

ovrimos_execute() executes a prepared statement. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad. If the prepared statement contained parameters (question marks in the statement), the correct number of parameters should be passed in an array. Notice that I don't follow the PHP convention of placing just the name of the optional parameter inside square brackets. I couldn't bring myself on liking it.

ovrimos_fetch_into

(PHP 4 >= 4.0.3)

ovrimos_fetch_into -- Fetches a row from the result set

Description

bool ovrimos_fetch_into ( int result_id, array result_array [, string how [, int rownumber]])

ovrimos_fetch_into() fetches a row from the result set into result_array, which should be passed by reference. Which row is fetched is determined by the two last parameters. how is one of Next (default), Prev, First, Last, Absolute, corresponding to forward direction from current position, backward direction from current position, forward direction from the start, backward direction from the end and absolute position from the start (essentially equivalent to 'first' but needs 'rownumber'). Case is not significant. rownumber is optional except for absolute positioning. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Példa 1. A fetch into example

<?php
$conn=ovrimos_connect("neptune", "8001", "admin", "password");
if ($conn!=0) {
    echo "Connection ok!";
    $res=ovrimos_exec($conn, "select table_id, table_name from sys.tables");
    if ($res != 0) {
        echo "Statement ok!";
        if (ovrimos_fetch_into($res, &$row)) {
            list($table_id, $table_name) = $row;
            echo "table_id=" . $table_id . ", table_name=" . $table_name . "\n";
            if (ovrimos_fetch_into($res, &$row)) {
                list($table_id, $table_name) = $row;
                echo "table_id=" . $table_id . ", table_name=" . $table_name . "\n";
            } else {
                echo "Next: error\n";
            }
        } else {
            echo "First: error\n";
        }
        ovrimos_free_result($res);
    }
    ovrimos_close($conn);
}
?>
This example will fetch a row.

ovrimos_fetch_row

(PHP 4 >= 4.0.3)

ovrimos_fetch_row -- Fetches a row from the result set

Description

bool ovrimos_fetch_row ( int result_id [, int how [, int row_number]])

ovrimos_fetch_row() fetches a row from the result set. Column values should be retrieved with other calls. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Példa 1. A fetch row example

<?php
$conn = ovrimos_connect("remote.host", "8001", "admin", "password");
if ($conn != 0) {
    echo "Connection ok!";
    $res=ovrimos_exec($conn, "select table_id, table_name from sys.tables");
    if ($res != 0) {
        echo "Statement ok!";
        if (ovrimos_fetch_row($res, "First")) {
            $table_id = ovrimos_result($res, 1);
            $table_name = ovrimos_result($res, 2);
            echo "table_id=" . $table_id . ", table_name=" . $table_name . "\n";
            if (ovrimos_fetch_row($res, "Next")) {
                $table_id = ovrimos_result($res, "table_id");
                $table_name = ovrimos_result($res, "table_name");
                echo "table_id=" . $table_id . ", table_name=" . $table_name . "\n";
            } else {
                echo "Next: error\n";
            }
        } else {
            echo "First: error\n";
        }
        ovrimos_free_result($res);
    }
    ovrimos_close($conn);
}
?>
This will fetch a row and print the result.

ovrimos_field_len

(PHP 4 >= 4.0.3)

ovrimos_field_len -- Returns the length of the output column

Description

int ovrimos_field_len ( int result_id, int field_number)

ovrimos_field_len() is used to get the length of the output column with number field_number (1-based), in result result_id.

ovrimos_field_name

(PHP 4 >= 4.0.3)

ovrimos_field_name -- Returns the output column name

Description

string ovrimos_field_name ( int result_id, int field_number)

ovrimos_field_name() returns the output column name at the (1-based) index specified.

ovrimos_field_num

(PHP 4 >= 4.0.3)

ovrimos_field_num --  Returns the (1-based) index of the output column

Description

int ovrimos_field_num ( int result_id, string field_name)

ovrimos_field_num() returns the (1-based) index of the output column specified by field_name, or FALSE.

ovrimos_field_type

(PHP 4 >= 4.0.3)

ovrimos_field_type --  Returns the (numeric) type of the output column

Description

int ovrimos_field_type ( int result_id, int field_number)

ovrimos_field_type() returns the (numeric) type of the output column at the (1-based) index specified by field_number.

ovrimos_free_result

(PHP 4 >= 4.0.3)

ovrimos_free_result -- Frees the specified result_id

Description

bool ovrimos_free_result ( int result_id)

ovrimos_free_result() frees the specified result_id. Returns TRUE.

ovrimos_longreadlen

(PHP 4 >= 4.0.3)

ovrimos_longreadlen --  Specifies how many bytes are to be retrieved from long datatypes

Description

bool ovrimos_longreadlen ( int result_id, int length)

ovrimos_longreadlen() specifies how many bytes are to be retrieved from long datatypes (long varchar and long varbinary). Default is zero. It currently sets this parameter the specified result set. Returns TRUE.

ovrimos_num_fields

(PHP 4 >= 4.0.3)

ovrimos_num_fields -- Returns the number of columns

Description

int ovrimos_num_fields ( int result_id)

ovrimos_num_fields() returns the number of columns in a result_id resulting from a query.

ovrimos_num_rows

(PHP 4 >= 4.0.3)

ovrimos_num_rows --  Returns the number of rows affected by update operations

Description

int ovrimos_num_rows ( int result_id)

ovrimos_num_rows() returns the number of rows affected by update operations.

ovrimos_prepare

(PHP 4 >= 4.0.3)

ovrimos_prepare -- Prepares an SQL statement

Description

int ovrimos_prepare ( int connection_id, string query)

ovrimos_prepare() prepares an SQL statement and returns a result_id (or FALSE on failure).

Példa 1. Connect to Ovrimos SQL Server and prepare a statement

<?php
$conn=ovrimos_connect("db_host", "8001", "admin", "password");
if ($conn!=0) {
    echo "Connection ok!";
    $res=ovrimos_prepare($conn, "select table_id, table_name 
                                  from sys.tables where table_id=1");
    if ($res != 0) {
        echo "Prepare ok!";
        if (ovrimos_execute($res)) {
            echo "Execute ok!\n";
            ovrimos_result_all($res);
        } else {
            echo "Execute not ok!";
        }
        ovrimos_free_result($res);
    } else {
        echo "Prepare not ok!\n";
    }
    ovrimos_close($conn);
}
?>
This will connect to Ovrimos SQL Server, prepare a statement and the execute it.

ovrimos_result_all

(PHP 4 >= 4.0.3)

ovrimos_result_all --  Prints the whole result set as an HTML table

Description

int ovrimos_result_all ( int result_id [, string format])

ovrimos_result_all() prints the whole result set as an HTML table. Returns the number of rows in the generated table.

Példa 1. Prepare a statement, execute, and view the result

<?php
$conn = ovrimos_connect("db_host", "8001", "admin", "password");
if ($conn != 0) {
    echo "Connection ok!";
    $res = ovrimos_prepare($conn, "select table_id, table_name 
                                    from sys.tables where table_id = 7");
    if ($res != 0) {
        echo "Prepare ok!";
        if (ovrimos_execute($res, array(3))) {
            echo "Execute ok!\n";
            ovrimos_result_all($res);
        } else {
            echo "Execute not ok!";
        }
        ovrimos_free_result($res);
    } else {
        echo "Prepare not ok!\n";
    }
    ovrimos_close($conn);
}
?>
This will execute an SQL statement and print the result in an HTML table.

Példa 2. ovrimos_result_all() with meta-information

<?php
$conn = ovrimos_connect("db_host", "8001", "admin", "password");
if ($conn != 0) {
    echo "Connection ok!";
    $res = ovrimos_exec($conn, "select table_id, table_name 
                                 from sys.tables where table_id = 1");
    if ($res != 0) {
        echo "Statement ok! cursor=" . ovrimos_cursor($res) . "\n";
        $colnb = ovrimos_num_fields($res);
        echo "Output columns=" . $colnb . "\n";
        for ($i=1; $i <= $colnb; $i++) {
            $name = ovrimos_field_name($res, $i);
            $type = ovrimos_field_type($res, $i);
            $len = ovrimos_field_len($res, $i);  
            echo "Column " . $i . " name=" . $name . " type=" . $type . " len=" . $len . "\n";
        }
        ovrimos_result_all($res);
        ovrimos_free_result($res);
    }
    ovrimos_close($conn);
}
?>

Példa 3. ovrimos_result_all() example

<?php
$conn = ovrimos_connect("db_host", "8001", "admin", "password");
if ($conn != 0) {
    echo "Connection ok!";
    $res = ovrimos_exec($conn, "update test set i=5");
    if ($res != 0) {
        echo "Statement ok!";
        echo ovrimos_num_rows($res)." rows affected\n";
        ovrimos_free_result($res);
    }
    ovrimos_close($conn);
}
?>

ovrimos_result

(PHP 4 >= 4.0.3)

ovrimos_result -- Retrieves the output column

Description

string ovrimos_result ( int result_id, mixed field)

ovrimos_result() retrieves the output column specified by field, either as a string or as an 1-based index. Returns FALSE on failure.

ovrimos_rollback

(PHP 4 >= 4.0.3)

ovrimos_rollback -- Rolls back the transaction

Description

bool ovrimos_rollback ( int connection_id)

ovrimos_rollback() is used to roll back the transaction. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

LXXVIII. Kimenet Szabályozó Függvények

Bevezetés

A kimenet szabályozó függvények teszik lehetővé, hogy teljes kontrolt szerezzünk afelett, mikor kerüljön a PHP parancsfájl futásának eredménye a kimenetre. Azaz Apache modulként például mikor adja azt át ezt a webszervernek. Hasznos ez akkor, amikor fejlécadatokat akarunk még létrehozni/módosítani, miközben már a html lap genegrálásának közepén járunk. Eme kimenetvezérlő függvények nincsenek hatással a header() vagy a setcookie() által létrehozott fejléc adatokra, csakis a törzsben található, echo() vagy egyéb függvények által generált kimenetre, valamint a php kódon kívüli statikus részekre.


Követelmények

Az itt leírt függvények használatához semmilyen külső függvénykönyvtár megléte nem szükségeltetik.


Futásidejű beállítások

Ez a kiterjesztés semmilyen konfigurációs beállításokat nem definiál a php.ini állományban.


Telepítés

Semmilyen telepítés nem szükséges ezen függvények használatához, a PHP alapelemei.


Erőforrás típusok

Ez a kiterjesztés semmilyen erőforrás típust nem definiál.


Előre definiált állandók

Ez a kiterjesztés semmilyen konstans értéket nem definiál.


Példák

Példa 1. Kimenet Szabályzás Példa

<?php

ob_start();
echo "Szia\n";

setcookie ("sutineve", "sutiadat");

ob_end_flush();

?>

A fenti példában az echo által generált szöveg a pufferben várakozik mindaddig, amíg egy ob_end_flush() parancs nem érkezik. Mindeközben a setcookie() által generált fejlécsor minden hiba nélül elmegy a böngésző felé (ez amúgy lehetetlen volna, mivel az echo már a webszerver felé küldött adatok törzsébe dolgozna, így a fejlécbe írni már lehetetlenség lenne).

Megjegyzés: 4.3-ra való váltáskor (4.1 vagy 4.2 változatokról indulva) érdemes meggyőződni arról, hogy a php.ini beállításai között az implicit_flush OFF értéket vesz-e fel. Ez egy korábbi hibának köszönhető, és előfordulhat így, hogy az ob_start()() utáni kimenet nem marad rejtve.


Lásd még

Lásd még: header() és setcookie().

Tartalom
flush -- A kimeneti puffer üritése
ob_clean --  A kimeneti puffer törlése
ob_end_clean --  A kimeneti puffer törlése, és egyidejűleg a pufferelés kikapcsolása
ob_end_flush --  A kimeneti puffer ürítése (kiküldése), és a kimeneti pufferelés lekapcsolása
ob_flush --  A kimeneti puffer ürítése (kiküldése)
ob_get_clean --  Get current buffer contents and delete current output buffer
ob_get_contents --  A kimeneti puffer tartalmának kinyerése
ob_get_flush --  Flush the output buffer, return it as a string and turn off output buffering
ob_get_length --  A kimeneti puffer aktuális méretének kiolvasása
ob_get_level --  Visszaadja a vizsgált puffer egymásba ágyazottsági szintjét.
ob_get_status --  Get status of output buffers
ob_gzhandler --  ob_start függvényhez használatos, kimenet gzip-elő függvény
ob_implicit_flush --  Az implicit pufferürítés ki-be kapcsolása
ob_list_handlers --  List all output handlers in use
ob_start -- A kimenet pufferelés bekapcsolása
output_add_rewrite_var --  Add URL rewriter values
output_reset_rewrite_vars --  Reset URL rewriter values

flush

(PHP 3, PHP 4 )

flush -- A kimeneti puffer üritése

Leírás

void flush ( void )

Ezzel a függvénnyel tudjuk kényszeríteni a PHP kimenetét esetlegesen pufferelő programnak (ez lehet a CGI réteg, avagyon a webszerver például), hogy azonnal ürítse ezt a puffert. Gyakorlatilag ez annyit jelent, hogy az adatok azonnal elindulnak a böngésző felé.

A flush() nincs hatással a PHP saját pufferelési rendszerére, sem a böngésző esetleges pufferelési mechanizmusára.

Bizonyos szerverek, példának okáért a Win32 alatt futók ennek ellenére is pufferelik a PHP-től kapott kimenetet, amíg annak futása be nem fejeződik.

Az Apache szerver moduljai, mint például a mod_gzip is rendelkezhetnek saját pufferelési rendszerrel. Ezáltal lehetséges, hogy a flush() meghívása nem eredményez azonnali adatküldést a böngésző felé.

Az is lehetséges még, hogy a böngésző maga puffereli a kapott adatokat. Például a Netscape a kapott html-t átmenetileg tárolja, amíg egy sorvége jellel nem találkozik, vagy egy html címke kezdetét nem látja. Emellett a táblázatokat csak a </table> zárócímke megérkezése után rajzolja ki.

ob_clean

(PHP 4 >= 4.2.0)

ob_clean --  A kimeneti puffer törlése

Leírás

void ob_clean ( void )

E függvény alkalmazásával teljesen megsemmisíthetjük a kimeneti puffer tartalmát.

Ezt alkalmazva nem szűnik meg a kimeneti puffer, az ob_end_clean() függvénnyel ellentétben.

Lásd még: ob_flush(), ob_end_flush() és ob_end_clean().

ob_end_clean

(PHP 4 )

ob_end_clean --  A kimeneti puffer törlése, és egyidejűleg a pufferelés kikapcsolása

Leírás

void ob_end_clean ( void )

E függvény alkalmazásával teljesen megsemmisíthetjük a kimeneti puffer tartalmát, valamint megszüntethetjük a pufferelést is egyben.

Lásd még: ob_start(), ob_clean() és ob_end_flush().

ob_end_flush

(PHP 4 )

ob_end_flush --  A kimeneti puffer ürítése (kiküldése), és a kimeneti pufferelés lekapcsolása

Leírás

void ob_end_flush ( void )

E függvény elküldi a kimeneti puffer tartamát a kimenetre, majd kikapcsolja a pufferelést. Ha szükség lenne még a puffer tartalmára esetleges későbbi műveletekhez, az ob_get_contents() függvény segítségével tudjuk változóba menteni azt, mielőtt még az ob_end_flush() meghívásra kerülne.

Lásd még: ob_start(), ob_get_contents(), ob_flush() és ob_end_clean().

ob_flush

(PHP 4 >= 4.2.0)

ob_flush --  A kimeneti puffer ürítése (kiküldése)

Leírás

void ob_flush ( void )

E függvény elküldi a kimeneti puffer tartamát a kimenetre, Ha szükség lenne még a puffer tartalmára esetleges későbbi műveletekhez, az ob_get_contents() függvény segítségével tudod változóba menteni azt, mielőtt még az ob_flush() meghívásra kerülne.

Ezt alkalmazva nem szűnik meg a kimeneti puffer, az ob_end_flush() függvénnyel ellentétben.

Lásd még: ob_get_contents(), ob_clean(), ob_end_flush(), és ob_end_clean().

ob_get_clean

(PHP 4 >= 4.3.0)

ob_get_clean --  Get current buffer contents and delete current output buffer

Description

string ob_get_clean ( void )

This will return the contents of the output buffer and end output buffering. If output buffering isn't active then FALSE is returned. ob_get_clean() essentially executes both ob_get_contents() and ob_end_clean().

Példa 1. A simple ob_get_clean() example

<?php

ob_start();

echo "Hello World";

$out = ob_get_clean();
$out = strtolower($out);

var_dump($out);
?>

Our example will output:

string(11) "hello world"

See also ob_start() and ob_get_contents().

ob_get_contents

(PHP 4 )

ob_get_contents --  A kimeneti puffer tartalmának kinyerése

Leírás

string ob_get_contents ( void )

A kimeneti puffer tartalmát adja vissza, vagy FALSE értéket, ha a kimeneti puffer mechanizmus nem aktív.

Lásd még: ob_start() és ob_get_length().

ob_get_flush

(PHP 4 >= 4.3.0)

ob_get_flush --  Flush the output buffer, return it as a string and turn off output buffering

Description

string ob_get_flush ( void )

ob_get_flush() flushs the output buffer, return it as a string and turns off output buffering. ob_get_flush() returns FALSE if no buffering is active.

Megjegyzés: This function is similar to ob_end_flush(), except that this function returns the buffer as a string.

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

The above example will output:

Array
(
    [0] => default output handler
)
Array
(
)

See also ob_end_clean(), ob_end_flush() and ob_list_handlers().

ob_get_length

(PHP 4 >= 4.0.2)

ob_get_length --  A kimeneti puffer aktuális méretének kiolvasása

Leírás

string ob_get_length ( void )

Ezzel a függvénnyel tudjuk megállapítani, milyen méretű jelenleg a kimeneti puffer, azaz mennyi kiküldésre váró adat van benne. Ha nem aktív a kimeneti pufferelés a visszatérési érték FALSE lesz.

Lásd még: ob_start() és ob_get_contents().

ob_get_level

(PHP 4 >= 4.2.0)

ob_get_level --  Visszaadja a vizsgált puffer egymásba ágyazottsági szintjét.

Leírás

int ob_get_level ( void )

Több, egymásba ágyazott pufferelést is aktiválhatunk egy php oldalon belül. Ekkor ezzel a függvénnyel tudjuk egy pufferől megállapítani annak beágyazottsági mélységét.

Lásd még: ob_start() és ob_get_contents().

ob_get_status

(PHP 4 >= 4.2.0)

ob_get_status --  Get status of output buffers

Description

array ob_get_status ( [bool full_status])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

This will return the current status of output buffers. It returns array contains buffer status or FALSE for error.

See also ob_get_level().

ob_gzhandler

(PHP 4 >= 4.0.4)

ob_gzhandler --  ob_start függvényhez használatos, kimenet gzip-elő függvény

Leírás

string ob_gzhandler ( string puffer [, int mód])

Megjegyzés: A mód paraméter a 4.0.5-ös PHP verziótól felfele használható.

Az ob_gzhandler() függvény arra lett létrehozva, hogy az ob_start() második paramétereként megadva megpróbálkozzon gzip tömörítettre alakítva továbbítani a kimeneti puffert. Próbálkozásról azért van csak szó, mert ezt a kódolást csak akkor hajtja végre, ha a böngésző elfogadja ezt a formátumot. Ezt az információt HTTP kérés fejlécében küldi a böngésző, "Accept-Encoding" név alatt. Ha van ilyen információ a böngészőről, és ennek értéke "gzip" vagy "deflate", ennek megfelelően küldi a hozzá való "Content-Type" fejlécet és a kódolt weblapot. Ez böngészőfüggetlen meoldás, hisz a böngésző maga közli, hogy hajlandó-e ilyen formában adatot fogadni, vagy sem.

Példa 1. ob_gzhandler() Példa

<?php

ob_start("ob_gzhandler");

?>
<html>
<body>
<p>Ez egy tömörített oldal lesz (talán). :)
</html>
</body>

Lásd még: ob_start() és ob_end_flush().

ob_implicit_flush

(PHP 4 )

ob_implicit_flush --  Az implicit pufferürítés ki-be kapcsolása

Leírás

void ob_implicit_flush ( [int flag])

Az ob_implicit_flush() segítségével kapcsolható be vagy ki az implicit pufferürítés. Az itt flag néven nevezett opcionális paraméter elhagyása esetén a függvény hívása bekapcsolást jelent, amúgy értéke "on" vagy "off" kell legyen. Ha az implicit pufferürítés be van kapcsolva, minden olyan mívelet után amely kimenetet generál, meghívódik a flush() függvény, ezáltal a webszerver minden PHP kimeneti parancs után továbbítani fogja azonnal a böngésző fele az adott dokumentumrészletet. Ekkor a flush() hívogatására természetszerűleg nincs szükség.

Ha bekapcsoljuk ezt az implicit pufferürítési opciót aktív kimeneti pufferelés közben, tehát már volt meghívva ob_start() függvény, ez a kimeneti puffer azonnali kiküldésre kerül. Emellett a pufferelés le is kapcsolódik, mintha egy ob_end_flush() függvényhívást alkalmaztunk volna.

Lásd még: flush(), ob_start(), és ob_end_flush().

ob_list_handlers

(PHP 4 >= 4.3.0)

ob_list_handlers --  List all output handlers in use

Description

array ob_list_handlers ( void )

This will return an array with the output handlers in use (if any). If output_buffering is enabled, ob_list_handlers() will return "default output handler".

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

The above example will output:

Array
(
    [0] => default output handler
)
Array
(
    [0] => ob_gzhandler
)

See also ob_end_clean(), ob_end_flush(), ob_get_flush(), and ob_start().

ob_start

(PHP 4 )

ob_start -- A kimenet pufferelés bekapcsolása

Leírás

void ob_start ( [string output_callback])

Ezzel a függvénnyel kapcsolhatjuk be a PHP saját belső kimenet pufferelési mechanizmusát. Ameddig a kimenet pufferelés be van kapcsolva, a fejlécadatokon kívül semmiféle kimenet nem hagyja el a PHP háza tájékát, az egy belső pufferben tárolódik.

Ennek a puffernek a tartalma az ob_get_contents() függvény segítségével változóba másolható. Ha végül szeretnénk a puffer tartalmát kiadni a php kezéből, akkor jön szóba az ob_end_flush(). Ha valamiért menet közben úgy döntünk, a puffer tartalma mégis felesleges, az ob_end_clean() csendben és titokban megsemmisíti a pufferünket tartalmastól, nem hagyja el egy bájt sem ekkor a php-t.

Az itt output_callback néven nevezett második, opcionális paraméter segítségével megadhatunk egy függvényt, melynek egy string típusú adatot kell paraméterként fogadnia, és ugyancsak stringet kell visszaadnia. Ez a megadható függvény akkor hívódik meg, amikor az ob_end_flush() meghívásra kerül, vagy a script végeztével a kimeneti puffer ürítésekor, automatikusan. Ekkor megkapja ez az output_callback paraméterben megadott függvény a puffer tartalmát, ezzel eljátszhadozhat, majd visszaadja a játszadozás eredményét, és ez kerül végül a php kimenetére.

Megjegyzés: A 4.0.4-es PHP verziótól felfele létezik egy ob_gzhandler() nevű beépített php függvény, mely segítségével gz tömörített formában küldhetjük el adatainkat a böngésző fele. Az ob_gzhandler() erre csak akkor vetemedik, ha úgy találja, a böngésző ezt a gzip kódolt formátumot elfogadja. Ezt a függvényt tehát az ob_start() második paramétereként megadva használhatjuk fel.

A pufferek egymásba ágyazhatóak, azaz miközben már van aktív kimeneti pufferünk, hozhatunk létre még egyet. Viszont ez esetben biztosnak kell lennünk abban, hogy az ob_end_flush() megfelelő számban meg legyen hívva. Ha több output_callback is meg van ilyenkor adva, mindegyik pufferhez másfajta, akkor azok mind sorban végrehajtódnak az egymásba ágyazottság sorrendjében.

Az ob_end_clean(), ob_end_flush(), ob_clean(), ob_flush() és ob_start() nem hívható "callback" függvényekből. Ha callback függvényből hívod ezeket, a viselkedés nem definiált. Ha törölni szeretnéd egy buffer tartalmát, ad vissza "" (üres karaktersorozatot) a callback függvényből.

Példa 1. Felhasználó által írt puffermódosító függvény használata

<?php

function callback($buffer) {

  // minden sört borra cserélünk
  return (ereg_replace("Sörre", "Borra", $buffer));

}

ob_start("callback");

?>
<html>
<body>
<p>Sörre bor, mindenkor!
</body>
</html>

<?php

ob_end_flush();

?>

A következő kimenet jön létre:

<html>
<body>
<p>Borra bor, mindenkor!
</body>
</html>

Lásd még: ob_get_contents(), ob_end_flush(), ob_end_clean(), ob_implicit_flush() és ob_gzhandler().

output_add_rewrite_var

(PHP 4 >= 4.3.0)

output_add_rewrite_var --  Add URL rewriter values

Description

bool output_add_rewrite_var ( string name, string value)

This function rewrite the URLs and forms with the given variable.

Megjegyzés: This function buffers the output.

Példa 1. output_add_rewrite_var() example

<?php
output_add_rewrite_var('var', 'value');

// a link
echo '<a href="file.php">link</a>';

// a form
echo '<form action="script.php" method="post">
<input type="text" name="var2" />
</form>';

print_r(ob_list_handlers());
?>

The above example will output:

<a href="file.php?var=value">link</a>

<form action="script.php" method="post">
<input type="hidden" name="var" value="value" />
<input type="text" name="var2" />
</form>

Array
(
    [0] => URL-Rewriter
)

See also output_reset_rewrite_vars(), ob_flush() and ob_list_handlers().

output_reset_rewrite_vars

(PHP 4 >= 4.3.0)

output_reset_rewrite_vars --  Reset URL rewriter values

Description

bool output_reset_rewrite_vars ( void )

This function resets the URL rewriter and undo the changes made by output_add_rewrite_var() and/or by session_start() that are still in the buffer.

Példa 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>';
?>

The above example will output:

<a href="file.php?PHPSESSID=xxx&var=value">link</a>
<a href="file.php">link</a>

See also output_add_rewrite_var(), ob_flush(), ob_list_handlers() and session_start().

LXXIX. Object property and method call overloading

Bevezetés

The purpose of this extension is to allow overloading of object property access and method calls. Only one function is defined in this extension, overload() which takes the name of the class that should have this functionality enabled. The class named has to define appropriate methods if it wants to have this functionality: __get(), __set() and __call() respectively for getting/setting a property, or calling a method. This way overloading can be selective. Inside these handler functions the overloading is disabled so you can access object properties normally.

Figyelem

Ez a kiterjesztés KÍSÉRLETI JELLEGGEL MŰKÖDIK. Ez azt jelenti, hogy minden itt dokumentált működés, beleértve a függvények nevét, működését vagy bármi más, amit a kiterjesztés kapcsán leírtunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a kiterjesztést csak a saját felelősségedre használd!


Követelmények

Az itt leírt függvények használatához semmilyen külső függvénykönyvtár megléte nem szükségeltetik.


Telepítés

In order to use these functions, you must compile PHP with the --enable-overload option. Starting with PHP 4.3.0 this extension is enabled by default. You can disable overload support with --disable--overload.

A PHP Windowsos változata beépített támogatással rendelkezik eme kiterjesztéshez. nincs szükség semmilyen kiterjesztés betöltésére, hogy az itt felsorolt függvnyeket használhasd.

Megjegyzés: Builtin support for overload is available with PHP 4.3.0.


Futásidejű beállítások

Ez a kiterjesztés semmilyen konfigurációs beállításokat nem definiál a php.ini állományban.


Erőforrás típusok

Ez a kiterjesztés semmilyen erőforrás típust nem definiál.


Előre definiált állandók

Ez a kiterjesztés semmilyen konstans értéket nem definiál.


Példák

Some simple examples on using the overload() function:

Példa 1. Overloading a PHP class

<?php

class OO {
    var $a = 111;
    var $elem = array('b' => 9, 'c' => 42);

    // Callback method for getting a property
    function __get($prop_name, &$prop_value) 
    {
        if (isset($this->elem[$prop_name])) {
            $prop_value = $this->elem[$prop_name];
            return true;
        } else {
            return false;
        }
    }

    // Callback method for setting a property
    function __set($prop_name, $prop_value) 
    {
        $this->elem[$prop_name] = $prop_value;
        return true;
    }
}

// Here we overload the OO object
overload('OO');

$o = new OO;
echo "\$o->a: $o->a\n"; // print: $o->a:
echo "\$o->b: $o->b\n"; // print: $o->b: 9
echo "\$o->c: $o->c\n"; // print: $o->c: 42
echo "\$o->d: $o->d\n"; // print: $o->d:

// add a new item to the $elem array in OO
$o->x = 56; 

// instantiate stdclass (it is built-in in PHP 4)
// $val is not overloaded!
$val = new stdclass;
$val->prop = 555;

// Set "a" to be an array with the $val object in it
// But __set() will put this in the $elem array
$o->a = array($val);
var_dump($o->a[0]->prop);

?>

Figyelem

As this is an experimental extension, not all things work. There is no __call() support currently, you can only overload the get and set operations for properties. You cannot invoke the original overloading handlers of the class, and __set() only works to one level of property access.

Tartalom
overload -- Enable property and method call overloading for a class

overload

(4.2.0 - 4.3.2 only)

overload -- Enable property and method call overloading for a class

Description

void overload ( [string class_name])

The overload() function will enable property and method call overloading for a class identified by class_name. See an example in the introductory section of this part.

LXXX. PDF functions

Bevezetés

The PDF functions in PHP can create PDF files using the PDFlib library created by Thomas Merz.

The documentation in this section is only meant to be an overview of the available functions in the PDFlib library and should not be considered an exhaustive reference. Please consult the documentation included in the source distribution of PDFlib for the full and detailed explanation of each function here. It provides a very good overview of what PDFlib is capable of doing and contains the most up-to-date documentation of all functions.

All of the functions in PDFlib and the PHP module have identical function names and parameters. You will need to understand some of the basic concepts of PDF and PostScript to efficiently use this extension. All lengths and coordinates are measured in PostScript points. There are generally 72 PostScript points to an inch, but this depends on the output resolution. Please see the PDFlib documentation included with the source distribution of PDFlib for a more thorough explanation of the coordinate system used.

Please note that most of the PDF functions require a pdfdoc as its first parameter. Please see the examples below for more information.

Megjegyzés: If you're interested in alternative free PDF generators that do not utilize external PDF libraries, see this related FAQ.


Követelmények

PDFlib is available for download at http://www.pdflib.com/products/pdflib/index.html, but requires that you purchase a license for commercial use. The JPEG and TIFF libraries are required to compile this extension.


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 3.0 or greater is supported by PHP 3.0.19 and later.


Telepítés

To get these functions to work, you have to compile PHP with --with-pdflib[=DIR]. DIR is the PDFlib base install directory, defaults to /usr/local. In addition you can specify the jpeg, tiff, and pnglibrary for PDFlib to use, which is optional for PDFlib 4.x. To do so add to your configure line the options --with-jpeg-dir[=DIR] --with-png-dir[=DIR] --with-tiff-dir[=DIR].

When using version 3.x of PDFlib, you should configure PDFlib with the option --enable-shared-pdflib.


Futásidejű beállítások

Ez a kiterjesztés semmilyen konfigurációs beállításokat nem definiál a php.ini állományban.


Confusion with old PDFlib versions

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 manual (V3.00 or greater) are supported by PHP 4 with exactly the same meaning and the same parameters. Only the return values may differ from the PDFlib manual, because the PHP convention of returning FALSE was adopted. For compatibility reasons, this binding for PDFlib still supports the old 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.

Táblázat 1. Deprecated functions and their replacements

Old functionReplacement
pdf_put_image()Not needed anymore.
pdf_execute_image()Not needed anymore.
pdf_get_annotation()pdf_get_bookmark() using the same parameters.
pdf_get_font()pdf_get_value() passing "font" as the second parameter.
pdf_get_fontsize()pdf_get_value() passing "fontsize" as the second parameter.
pdf_get_fontname()pdf_get_parameter() passing "fontname" as the second parameter.
pdf_set_info_creator()pdf_set_info() passing "Creator" as the second parameter.
pdf_set_info_title()pdf_set_info() passing "Title" as the second parameter.
pdf_set_info_subject()pdf_set_info() passing "Subject" as the second parameter.
pdf_set_info_author()pdf_set_info() passing "Author" as the second parameter.
pdf_set_info_keywords()pdf_set_info() passing "Keywords" as the second parameter.
pdf_set_leading()pdf_set_value() passing "leading" as the second parameter.
pdf_set_text_rendering()pdf_set_value() passing "textrendering" as the second parameter.
pdf_set_text_rise()pdf_set_value() passing "textrise" as the second parameter.
pdf_set_horiz_scaling()pdf_set_value() passing "horizscaling" as the second parameter.
pdf_set_text_matrix()Not available anymore
pdf_set_char_spacing()pdf_set_value() passing "charspacing" as the second parameter.
pdf_set_word_spacing()pdf_set_value() passing "wordspacing" as the second parameter.
pdf_set_transition()pdf_set_parameter() passing "transition" as the second parameter.
pdf_open()pdf_new() plus an subsequent call of pdf_open_file()
pdf_set_font()pdf_findfont() plus an subsequent call of pdf_setfont()
pdf_set_duration()pdf_set_value() passing "duration" as the second parameter.
pdf_open_gif()pdf_open_image_file() passing "gif" as the second parameter.
pdf_open_jpeg()pdf_open_image_file() passing "jpeg" as the second parameter.
pdf_open_tiff()pdf_open_image_file() passing "tiff" as the second parameter.
pdf_open_png()pdf_open_image_file() passing "png" as the second parameter.
pdf_get_image_width()pdf_get_value() passing "imagewidth" as the second parameter and the image as the third parameter.
pdf_get_image_height()pdf_get_value() passing "imageheight" as the second parameter and the image as the third parameter.


Példák

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 creates test.pdf with one page. The page contains the text "Times Roman outlined" in an outlined, 30pt font. The text is also underlined.

Példa 1. Creating a PDF document with PDFlib

<?php
$pdf = pdf_new();
pdf_open_file($pdf, "test.pdf");
pdf_set_info($pdf, "Author", "Uwe Steinmann");
pdf_set_info($pdf, "Title", "Test for PHP wrapper of PDFlib 2.0");
pdf_set_info($pdf, "Creator", "See Author");
pdf_set_info($pdf, "Subject", "Testing");
pdf_begin_page($pdf, 595, 842);
pdf_add_outline($pdf, "Page 1");
$font = pdf_findfont($pdf, "Times New Roman", "winansi", 1);
pdf_setfont($pdf, $font, 10);
pdf_set_value($pdf, "textrendering", 1);
pdf_show_xy($pdf, "Times Roman outlined", 50, 750);
pdf_moveto($pdf, 50, 740);
pdf_lineto($pdf, 330, 740);
pdf_stroke($pdf);
pdf_end_page($pdf);
pdf_close($pdf);
pdf_delete($pdf);
echo "<A HREF=getpdf.php>finished</A>";
?>
The script getpdf.php just returns the pdf document.

Példa 2. Outputting a precalculated PDF

<?php
$len = filesize($filename);
header("Content-type: application/pdf");
header("Content-Length: $len");
header("Content-Disposition: inline; filename=foo.pdf");
readfile($filename);
?>

The PDFlib distribution contains a more complex example which creates a page with an analog clock. Here we use the in-memory creation feature of PDFlib to alleviate the need to use temporary files. The example was converted to PHP from the PDFlib example. (The same example is available in the CLibPDF documentation.)

Példa 3. pdfclock example from PDFlib distribution

<?php
$radius = 200;
$margin = 20;
$pagecount = 10;

$pdf = pdf_new();

if (!pdf_open_file($pdf, "")) {
    echo error;
    exit;
};

pdf_set_parameter($pdf, "warning", "true");

pdf_set_info($pdf, "Creator", "pdf_clock.php");
pdf_set_info($pdf, "Author", "Uwe Steinmann");
pdf_set_info($pdf, "Title", "Analog Clock");

while ($pagecount-- > 0) {
    pdf_begin_page($pdf, 2 * ($radius + $margin), 2 * ($radius + $margin));

    pdf_set_parameter($pdf, "transition", "wipe");
    pdf_set_value($pdf, "duration", 0.5);
  
    pdf_translate($pdf, $radius + $margin, $radius + $margin);
    pdf_save($pdf);
    pdf_setrgbcolor($pdf, 0.0, 0.0, 1.0);

    /* minute strokes */
    pdf_setlinewidth($pdf, 2.0);
    for ($alpha = 0; $alpha < 360; $alpha += 6) {
        pdf_rotate($pdf, 6.0);
        pdf_moveto($pdf, $radius, 0.0);
        pdf_lineto($pdf, $radius-$margin/3, 0.0);
        pdf_stroke($pdf);
    }

    pdf_restore($pdf);
    pdf_save($pdf);

    /* 5 minute strokes */
    pdf_setlinewidth($pdf, 3.0);
    for ($alpha = 0; $alpha < 360; $alpha += 30) { 
        pdf_rotate($pdf, 30.0);
        pdf_moveto($pdf, $radius, 0.0);
        pdf_lineto($pdf, $radius-$margin, 0.0);
        pdf_stroke($pdf);
    }

    $ltime = getdate();

    /* draw hour hand */
    pdf_save($pdf);
    pdf_rotate($pdf,-(($ltime['minutes']/60.0)+$ltime['hours']-3.0)*30.0);
    pdf_moveto($pdf, -$radius/10, -$radius/20);
    pdf_lineto($pdf, $radius/2, 0.0);
    pdf_lineto($pdf, -$radius/10, $radius/20);
    pdf_closepath($pdf);
    pdf_fill($pdf);
    pdf_restore($pdf);

    /* draw minute hand */
    pdf_save($pdf);
    pdf_rotate($pdf,-(($ltime['seconds']/60.0)+$ltime['minutes']-15.0)*6.0);
    pdf_moveto($pdf, -$radius/10, -$radius/20);
    pdf_lineto($pdf, $radius * 0.8, 0.0);
    pdf_lineto($pdf, -$radius/10, $radius/20);
    pdf_closepath($pdf);
    pdf_fill($pdf);
    pdf_restore($pdf);

    /* draw second hand */
    pdf_setrgbcolor($pdf, 1.0, 0.0, 0.0);
    pdf_setlinewidth($pdf, 2);
    pdf_save($pdf);
    pdf_rotate($pdf, -(($ltime['seconds'] - 15.0) * 6.0));
    pdf_moveto($pdf, -$radius/5, 0.0);
    pdf_lineto($pdf, $radius, 0.0);
    pdf_stroke($pdf);
    pdf_restore($pdf);

    /* draw little circle at center */
    pdf_circle($pdf, 0, 0, $radius/30);
    pdf_fill($pdf);

    pdf_restore($pdf);

    pdf_end_page($pdf);

    # to see some difference
    sleep(1);
}

pdf_close($pdf);

$buf = pdf_get_buffer($pdf);
$len = strlen($buf);

header("Content-type: application/pdf");
header("Content-Length: $len");
header("Content-Disposition: inline; filename=foo.pdf");
echo $buf;

pdf_delete($pdf);
?>


Lásd még

Megjegyzés: An alternative PHP module for PDF document creation based on FastIO's ClibPDF is available. Please see the ClibPDF section for details. Note that ClibPDF has a slightly different API than PDFlib.

Tartalom
pdf_add_annotation -- Deprecated: Adds annotation
pdf_add_bookmark -- Adds bookmark for current page
pdf_add_launchlink -- Add a launch annotation for current page
pdf_add_locallink -- Add a link annotation for current page
pdf_add_note -- Sets annotation for current page
pdf_add_outline -- Deprecated: Adds bookmark for current page
pdf_add_pdflink -- Adds file link annotation for current page
pdf_add_thumbnail -- Adds thumbnail for current page
pdf_add_weblink -- Adds weblink for current page
pdf_arc -- Draws an arc (counterclockwise)
pdf_arcn -- Draws an arc (clockwise)
pdf_attach_file -- Adds a file attachment for current page
pdf_begin_page -- Starts new page
pdf_begin_pattern -- Starts new pattern
pdf_begin_template -- Starts new template
pdf_circle -- Draws a circle
pdf_clip -- Clips to current path
pdf_close_image -- Closes an image
pdf_close_pdi_page --  Close the page handle
pdf_close_pdi --  Close the input PDF document
pdf_close -- Closes a pdf resource
pdf_closepath_fill_stroke -- Closes, fills and strokes current path
pdf_closepath_stroke -- Closes path and draws line along path
pdf_closepath -- Closes path
pdf_concat -- Concatenate a matrix to the CTM
pdf_continue_text -- Outputs text in next line
pdf_curveto -- Draws a curve
pdf_delete -- Deletes a PDF object
pdf_end_page -- Ends a page
pdf_end_pattern -- Finish pattern
pdf_end_template -- Finish template
pdf_endpath -- Deprecated: Ends current path
pdf_fill_stroke -- Fills and strokes current path
pdf_fill -- Fills current path
pdf_findfont -- Prepare font for later use with pdf_setfont().
pdf_get_buffer -- Fetch the buffer containing the generated PDF data.
pdf_get_font -- Deprecated: font handling
pdf_get_fontname -- Deprecated: font handling
pdf_get_fontsize -- Deprecated: font handling
pdf_get_image_height -- Deprecated: returns height of an image
pdf_get_image_width -- Deprecated: Returns width of an image
pdf_get_majorversion --  Returns the major version number of the PDFlib
pdf_get_minorversion --  Returns the minor version number of the PDFlib
pdf_get_parameter -- Gets certain parameters
pdf_get_pdi_parameter -- Get some PDI string parameters
pdf_get_pdi_value -- Gets some PDI numerical parameters
pdf_get_value -- Gets certain numerical value
pdf_initgraphics -- Resets graphic state
pdf_lineto -- Draws a line
pdf_makespotcolor -- Makes a spotcolor
pdf_moveto -- Sets current point
pdf_new -- Creates a new pdf resource
pdf_open_CCITT -- Opens a new image file with raw CCITT data
pdf_open_file -- Opens a new pdf object
pdf_open_gif -- Deprecated: Opens a GIF image
pdf_open_image_file -- Reads an image from a file
pdf_open_image -- Versatile function for images
pdf_open_jpeg -- Deprecated: Opens a JPEG image
pdf_open_memory_image -- Opens an image created with PHP's image functions
pdf_open_pdi_page --  Prepare a page
pdf_open_pdi --  Opens a PDF file
pdf_open_png --  Deprecated: Opens a PNG image
pdf_open_tiff -- Deprecated: Opens a TIFF image
pdf_open -- Deprecated: Open a new pdf object
pdf_place_image -- Places an image on the page
pdf_place_pdi_page -- Places an image on the page
pdf_rect -- Draws a rectangle
pdf_restore -- Restores formerly saved environment
pdf_rotate -- Sets rotation
pdf_save -- Saves the current environment
pdf_scale -- Sets scaling
pdf_set_border_color -- Sets color of border around links and annotations
pdf_set_border_dash -- Sets dash style of border around links and annotations
pdf_set_border_style -- Sets style of border around links and annotations
pdf_set_char_spacing -- Deprecated: Sets character spacing
pdf_set_duration -- Deprecated: Sets duration between pages
pdf_set_font -- Deprecated: Selects a font face and size
pdf_set_horiz_scaling -- Sets horizontal scaling of text
pdf_set_info_author --  Deprecated: Fills the author field of the document
pdf_set_info_creator --  Deprecated: Fills the creator field of the document
pdf_set_info_keywords --  Deprecated: Fills the keywords field of the document
pdf_set_info_subject --  Deprecated: Fills the subject field of the document
pdf_set_info_title --  Deprecated: Fills the title field of the document
pdf_set_info -- Fills a field of the document information
pdf_set_leading -- Deprecated: Sets distance between text lines
pdf_set_parameter -- Sets certain parameters
pdf_set_text_matrix -- Deprecated: Sets the text matrix
pdf_set_text_pos -- Sets text position
pdf_set_text_rendering -- Deprecated: Determines how text is rendered
pdf_set_text_rise -- Deprecated: Sets the text rise
pdf_set_value -- Sets certain numerical value
pdf_set_word_spacing -- Deprecated: Sets spacing between words
pdf_setcolor -- Sets fill and stroke color
pdf_setdash -- Sets dash pattern
pdf_setflat -- Sets flatness
pdf_setfont -- Set the current font
pdf_setgray_fill -- Sets filling color to gray value
pdf_setgray_stroke -- Sets drawing color to gray value
pdf_setgray -- Sets drawing and filling color to gray value
pdf_setlinecap -- Sets linecap parameter
pdf_setlinejoin -- Sets linejoin parameter
pdf_setlinewidth -- Sets line width
pdf_setmatrix -- Sets current transformation matrix
pdf_setmiterlimit -- Sets miter limit
pdf_setpolydash -- Deprecated: Sets complicated dash pattern
pdf_setrgbcolor_fill -- Sets filling color to rgb color value
pdf_setrgbcolor_stroke -- Sets drawing color to rgb color value
pdf_setrgbcolor -- Sets drawing and filling color to rgb color value
pdf_show_boxed -- Output text in a box
pdf_show_xy -- Output text at given position
pdf_show -- Output text at current position
pdf_skew -- Skews the coordinate system
pdf_stringwidth -- Returns width of text using current font
pdf_stroke -- Draws line along path
pdf_translate -- Sets origin of coordinate system

pdf_add_annotation

pdf_add_annotation -- Deprecated: Adds annotation

Description

This function is deprecated, use pdf_add_note() instead.

pdf_add_bookmark

(PHP 4 >= 4.0.1)

pdf_add_bookmark -- Adds bookmark for current page

Description

int pdf_add_bookmark ( resource pdfdoc, string text [, int parent [, int open]])

Add a nested bookmark under parent, or a new top-level bookmark if parent = 0. Returns a bookmark descriptor which may be used as parent for subsequent nested bookmarks. If open = 1, child bookmarks will be folded out, and invisible if open = 0.

Példa 1. pdf_add_bookmark() example

<?php
// create a new PDF

$pdf = pdf_new();
pdf_open_file($pdf);
pdf_set_info($pdf, "Author", "Bob Nijman");

// begin a new page
pdf_begin_page($pdf, 300, 300);

// add a top-level bookmark
$bookmark = pdf_add_bookmark($pdf, "People");

// add a nested bookmark
pdf_add_bookmark($pdf, "Rasmus", $bookmark);

// and some text
pdf_set_font($pdf, "Helvetica", 20, "host");
$text = "This is R's page";
$width = pdf_stringwidth($pdf, $text);
pdf_set_text_pos($pdf, (300-$width)/2, 100);
pdf_show($pdf, $text);

// close the page and the PDF
pdf_end_page($pdf); 
pdf_close($pdf);

?>

pdf_add_launchlink

(PHP 4 >= 4.0.5)

pdf_add_launchlink -- Add a launch annotation for current page

Description

bool pdf_add_launchlink ( resource pdfdoc, float llx, float lly, float urx, float ury, string filename)

Adds a link to a web resource specified by filename. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

See also pdf_add_locallink().

pdf_add_locallink

(PHP 4 >= 4.0.5)

pdf_add_locallink -- Add a link annotation for current page

Description

bool pdf_add_locallink ( resource pdfdoc, float lowerleftx, float lowerlefty, float upperrightx, float upperrighty, int page, string dest)

Add a link annotation to a target within the current PDF file. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

dest is the zoom setting on the destination page, it can be one of retain, fitpage, fitwidth, fitheight or fitbbox.

See also pdf_add_launchlink().

pdf_add_note

(PHP 4 >= 4.0.5)

pdf_add_note -- Sets annotation for current page

Description

bool pdf_add_note ( resource pdfdoc, float llx, float lly, float urx, float ury, string contents, string title, string icon, int open)

Sets an annotation for the current page. icon is one of comment, insert, note, paragraph, newparagraph, key, or help. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

pdf_add_outline

pdf_add_outline -- Deprecated: Adds bookmark for current page

Description

This function is deprecated, use pdf_add_bookmark() instead.

pdf_add_pdflink

(PHP 3>= 3.0.12, PHP 4 )

pdf_add_pdflink -- Adds file link annotation for current page

Description

bool pdf_add_pdflink ( resource pdfdoc, float bottom_left_x, float bottom_left_y, float up_right_x, float up_right_y, string filename, int page, string dest)

Add a file link annotation (to a PDF target). Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

See also pdf_add_locallink() and pdf_add_weblink().

pdf_add_thumbnail

(PHP 4 >= 4.0.5)

pdf_add_thumbnail -- Adds thumbnail for current page

Description

bool pdf_add_thumbnail ( resource pdfdoc, int image)

Adds an existing image as thumbnail for the current page. Thumbnail images must not be wider or higher than 106 pixels. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

See also pdf_open_image(), pdf_open_image_file(), pdf_open_memory_image().

pdf_add_weblink

(PHP 3>= 3.0.12, PHP 4 )

pdf_add_weblink -- Adds weblink for current page

Description

bool pdf_add_weblink ( resource pdfdoc, float lowerleftx, float lowerlefty, float upperrightx, float upperrighty, string url)

Add a weblink annotation to a target url on the Web. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

pdf_arc

(PHP 3>= 3.0.6, PHP 4 )

pdf_arc -- Draws an arc (counterclockwise)

Description

bool pdf_arc ( resource pdfdoc, float x, float y, float r, float alpha, float beta)

Add a counterclockwise circular arc from alpha to beta degrees with center (x; y) and radius r. Actual drawing of the circle is performed by the next stroke or fill operation.

Példa 1. pdf_arcn() example

<?php
// prepare document
$pdf = pdf_new();
pdf_open_file($pdf, "");
pdf_begin_page($pdf, 595, 842);

// an outlined arc
pdf_arc($pdf, 200, 700, 100, 0, 90);
pdf_stroke($pdf);

// a filled arc
pdf_arc($pdf, 200, 700, 50, 0, 90);
pdf_fill($pdf);

// an outlined and filled arc
pdf_setcolor($pdf, "fill", "gray", 0.8);
pdf_arc($pdf, 400, 700, 50, 0, 90);
pdf_fill_stroke($pdf);

// finish document
pdf_end_page($pdf);
pdf_close($pdf);

header("Content-type: application/pdf");
echo pdf_get_buffer($pdf);

pdf_delete($pdf);
?>

See also: pdf_arcn(), pdf_circle(), pdf_stroke(), pdf_fill() and pdf_fill_stroke().

pdf_arcn

(PHP 4 >= 4.0.5)

pdf_arcn -- Draws an arc (clockwise)

Description

bool pdf_arcn ( resource pdfdoc, float x, float y, float r, float alpha, float beta)

Add a clockwise circular arc from alpha to beta degrees with center (x; y) and radius r. Actual drawing of the circle is performed by the next stroke or fill operation.

Példa 1. pdf_arcn() example

<?php

// prepare document
$pdf = pdf_new();
pdf_open_file($pdf, "");
pdf_begin_page($pdf, 595, 842);

// an outlined arcn
pdf_arcn($pdf, 200, 700, 100, 0, 90);
pdf_stroke($pdf);

// a filled arcn
pdf_arcn($pdf, 200, 700, 50, 0, 90);
pdf_fill($pdf);

// an outlined and filled arcn
pdf_setcolor($pdf, "fill", "gray", 0.8);
pdf_arcn($pdf, 400, 700, 50, 0, 90);
pdf_fill_stroke($pdf);

// finish document
pdf_end_page($pdf);
pdf_close($pdf);

header("Content-type: application/pdf");
echo pdf_get_buffer($pdf);

pdf_delete($pdf);
?>

See also: pdf_arc(), pdf_circle(), pdf_stroke(), pdf_fill() and pdf_fillstroke().

pdf_attach_file

(PHP 4 >= 4.0.5)

pdf_attach_file -- Adds a file attachment for current page

Description

bool pdf_attach_file ( resource pdfdoc, float llx, float lly, float urx, float ury, string filename, string description, string author, string mimetype, string icon)

Add a file attachment annotation. icon is one of graph, paperclip, pushpin, or tag. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Megjegyzés: Only the 'Full' Acrobat software will be able to display these file attachments. All other PDF viewers will either show nothing or display a question mark.

pdf_begin_page

(PHP 3>= 3.0.6, PHP 4 )

pdf_begin_page -- Starts new page

Description

bool pdf_begin_page ( resource pdfdoc, float width, float height)

Add a new page to the document. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad. The width and height are specified in points, which are 1/72 of an inch.

Táblázat 1. Common Page Sizes in Points

namesize
A02380✗3368
A11684✗2380
A21190✗1684
A3842✗1190
A4595✗842
A5421✗595
A6297✗421
B5501✗709
letter (8.5"✗11")612✗792
legal (8.5"✗14")612✗1008
ledger (17"✗11")1224✗792
11"✗17"792✗1224

See also pdf_end_page().

pdf_begin_pattern

(PHP 4 >= 4.0.5)

pdf_begin_pattern -- Starts new pattern

Description

int pdf_begin_pattern ( resource pdfdoc, float width, float height, float xstep, float ystep, int painttype)

Starts a new pattern definition and returns a pattern handle. width, and height define the bounding box for the pattern. xstep and ystep give the repeated pattern offsets. painttype=1 means that the pattern has its own colour settings whereas a value of 2 indicates that the current colour is used when the pattern is applied.

See also pdf_end_pattern().

pdf_begin_template

(PHP 4 >= 4.0.5)

pdf_begin_template -- Starts new template

Description

int pdf_begin_template ( resource pdfdoc, float width, float height)

Start a new template definition.

pdf_circle

(PHP 3>= 3.0.6, PHP 4 )

pdf_circle -- Draws a circle

Description

bool pdf_circle ( resource pdfdoc, float x, float y, float r)

Add a circle with center (x, y) and radius r to the current page. Actual drawing of the circle is performed by the next stroke or fill operation.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Példa 1. pdf_circle() example

<?php
// prepare document
$pdf = pdf_new();
pdf_open_file($pdf, "");
pdf_begin_page($pdf, 595, 842);

// an outlined circle
pdf_circle($pdf, 200, 700, 100);
pdf_stroke($pdf);

	// a filled circle
pdf_circle($pdf, 200, 700, 50);
pdf_fill($pdf);

// an outlined and filled circle
pdf_setcolor($pdf, "fill", "gray", 0.3);
pdf_circle($pdf, 400, 700, 50);
pdf_fill_stroke($pdf);

// finish document
pdf_end_page($pdf);
pdf_close($pdf);

header("Content-type: application/pdf");
echo pdf_get_buffer($pdf);

pdf_delete($pdf);
?>

See also: pdf_arc(), pdf_arcn(), pdf_curveto(), pdf_stroke(), pdf_fill() and pdf_fill_stroke().

pdf_clip

(PHP 3>= 3.0.6, PHP 4 )

pdf_clip -- Clips to current path

Description

bool pdf_clip ( resource pdfdoc)

Use the current path as clipping path. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

pdf_close_image

(PHP 3>= 3.0.7, PHP 4 )

pdf_close_image -- Closes an image

Description

void pdf_close_image ( resource pdfdoc, int image)

Close an image retrieved with the pdf_open_image() function.

pdf_close_pdi_page

(PHP 4 >= 4.0.5)

pdf_close_pdi_page --  Close the page handle

Description

bool pdf_close_pdi_page ( resource pdfdoc, int pagehandle)

Close the page handle, and free all page-related resources. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

pdf_close_pdi

(PHP 4 >= 4.0.5)

pdf_close_pdi --  Close the input PDF document

Description

bool pdf_close_pdi ( resource pdfdoc, int dochandle)

Close all open page handles, and close the input PDF document. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

See also pdf_open_pdi().

pdf_close

(PHP 3>= 3.0.6, PHP 4 )

pdf_close -- Closes a pdf resource

Description

bool pdf_close ( resource pdfdoc)

Close the generated PDF file, and free all document-related resources. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

See also pdf_new().

pdf_closepath_fill_stroke

(PHP 3>= 3.0.6, PHP 4 )

pdf_closepath_fill_stroke -- Closes, fills and strokes current path

Description

bool pdf_closepath_fill_stroke ( resource pdfdoc)

Close the path, fill, and stroke it. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

See also pdf_closepath() and pdf_closepath_stroke().

pdf_closepath_stroke

(PHP 3>= 3.0.6, PHP 4 )

pdf_closepath_stroke -- Closes path and draws line along path

Description

bool pdf_closepath_stroke ( resource pdfdoc)

Close the path, and stroke it. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

See also pdf_closepath() and pdf_closepath_fil_stroke().

pdf_closepath

(PHP 3>= 3.0.6, PHP 4 )

pdf_closepath -- Closes path

Description

bool pdf_closepath ( resource pdfdoc)

Close the current path. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

See also pdf_closepath_stroke() and pdf_closepath_fil_stroke().

pdf_concat

(PHP 4 >= 4.0.5)

pdf_concat -- Concatenate a matrix to the CTM

Description

bool pdf_concat ( resource pdfdoc, float a, float b, float c, float d, float e, float f)

Concatenate a matrix to the CTM. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

pdf_continue_text

(PHP 3>= 3.0.6, PHP 4 )

pdf_continue_text -- Outputs text in next line

Description

bool pdf_continue_text ( resource pdfdoc, string text)

Print text at the next line. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

pdf_curveto

(PHP 3>= 3.0.6, PHP 4 )

pdf_curveto -- Draws a curve

Description

bool pdf_curveto ( resource pdfdoc, float x1, float y1, float x2, float y2, float x3, float y3)

Draw a Bezier curve from the current point, using 3 more control points. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

pdf_delete

(PHP 4 >= 4.0.5)

pdf_delete -- Deletes a PDF object

Description

bool pdf_delete ( resource pdfdoc)

Delete the PDF resource, and free all internal resources. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

See also pdf_new().

pdf_end_page

(PHP 3>= 3.0.6, PHP 4 )

pdf_end_page -- Ends a page

Description

bool pdf_end_page ( resource pdfdoc)

Finish the page. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

See also pdf_begin_page().

pdf_end_pattern

(PHP 4 >= 4.0.5)

pdf_end_pattern -- Finish pattern

Description

bool pdf_end_pattern ( resource pdfdoc)

Finish the pattern definition. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

See also pdf_begin_pattern().

pdf_end_template

(PHP 4 >= 4.0.5)

pdf_end_template -- Finish template

Description

bool pdf_end_template ( resource pdfdoc)

Finish the template definition. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

pdf_endpath

pdf_endpath -- Deprecated: Ends current path

Description

This function is deprecated, use one of the pdf_stroke(), pdf_clip() or pdf_closepath_fill_stroke() functions instead.

pdf_fill_stroke

(PHP 3>= 3.0.6, PHP 4 )

pdf_fill_stroke -- Fills and strokes current path

Description

bool pdf_fill_stroke ( resource pdfdoc)

Fill and stroke the path with the current fill and stroke color. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

See also pdf_setcolor().

pdf_fill

(PHP 3>= 3.0.6, PHP 4 )

pdf_fill -- Fills current path

Description

bool pdf_fill ( resource pdfdoc)

Fill the interior of the path with the current fill color. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

See also pdf_setcolor().

pdf_findfont

(PHP 4 >= 4.0.5)

pdf_findfont -- Prepare font for later use with pdf_setfont().

Description

int pdf_findfont ( resource pdfdoc, string fontname, string encoding [, int embed])

Prepare a font for later use with pdf_setfont(). The metrics will be loaded, and if embed is nonzero, the font file will be checked, but not yet used. encoding is one of builtin, macroman, winansi, host, a user-defined encoding name or the name of a CMap.

pdf_findfont() returns a font handle or FALSE on error.

Példa 1. pdf_findfont() example

<?php

$font = pdf_findfont($pdf, "Times New Roman", "winansi", 1);
if ($font) {
    pdf_setfont($pdf, $font, 10);
}

?>

pdf_get_buffer

(PHP 4 >= 4.0.5)

pdf_get_buffer -- Fetch the buffer containing the generated PDF data.

Description

string pdf_get_buffer ( resource pdfdoc)

Get the contents of the PDF output buffer. The result must be used by the client before calling any other PDFlib function.

pdf_get_font

pdf_get_font -- Deprecated: font handling

Description

This function is deprecated, use pdf_get_value() instead.

pdf_get_fontname

pdf_get_fontname -- Deprecated: font handling

Description

This function is deprecated, use pdf_get_parameter() instead.

pdf_get_fontsize

pdf_get_fontsize -- Deprecated: font handling

Description

This function is deprecated, use pdf_get_value() instead.

pdf_get_image_height

pdf_get_image_height -- Deprecated: returns height of an image

Description

This function is deprecated, use pdf_get_value() instead.

pdf_get_image_width

pdf_get_image_width -- Deprecated: Returns width of an image

Description

This function is deprecated, use pdf_get_value() instead.

pdf_get_majorversion

(PHP 4 >= 4.2.0)

pdf_get_majorversion --  Returns the major version number of the PDFlib

Description

int pdf_get_majorversion ( void )

Returns the major version number of the PDFlib.

See also pdf_get_minorversion().

pdf_get_minorversion

(PHP 4 >= 4.2.0)

pdf_get_minorversion --  Returns the minor version number of the PDFlib

Description

int pdf_get_minorversion ( void )

Returns the minor version number of the PDFlib.

See also pdf_get_majorversion().

pdf_get_parameter

(PHP 4 >= 4.0.1)

pdf_get_parameter -- Gets certain parameters

Description

string pdf_get_parameter ( resource pdfdoc, string key [, float modifier])

Get the contents of some PDFlib parameter with string type.

pdf_get_pdi_parameter

(PHP 4 >= 4.0.5)

pdf_get_pdi_parameter -- Get some PDI string parameters

Description

string pdf_get_pdi_parameter ( resource pdfdoc, string key, int document, int page, int index)

Get the contents of some PDI document parameter with string type.

pdf_get_pdi_value

(PHP 4 >= 4.0.5)

pdf_get_pdi_value -- Gets some PDI numerical parameters

Description

string pdf_get_pdi_value ( resource pdfdoc, string key, int doc, int page, int index)

Get the contents of some PDI document parameter with numerical type.

pdf_get_value

(PHP 4 >= 4.0.1)

pdf_get_value -- Gets certain numerical value

Description

float pdf_get_value ( resource pdfdoc, string key [, float modifier])

Get the contents of some PDFlib parameter with float type.

pdf_initgraphics

(PHP 4 >= 4.0.5)

pdf_initgraphics -- Resets graphic state

Description

bool pdf_initgraphics ( resource pdfdoc)

Reset all implicit color and graphics state parameters to their defaults. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

pdf_lineto

(PHP 3>= 3.0.6, PHP 4 )

pdf_lineto -- Draws a line

Description

bool pdf_lineto ( resource pdfdoc, float x, float y)

Draw a line from the current point to (x, y). Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

pdf_makespotcolor

(PHP 4 >= 4.0.5)

pdf_makespotcolor -- Makes a spotcolor

Description

bool pdf_makespotcolor ( resource pdfdoc, string spotname)

Make a named spot color from the current color. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

See also pdf_setcolor().

pdf_moveto

(PHP 3>= 3.0.6, PHP 4 )

pdf_moveto -- Sets current point

Description

bool pdf_moveto ( resource pdfdoc, float x, float y)

Set the current point to (x, y. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Megjegyzés: The current point for graphics and the current text output position are maintained separately. See pdf_set_text_pos() to set the text output position.

pdf_new

(PHP 4 >= 4.0.5)

pdf_new -- Creates a new pdf resource

Description

resource pdf_new ( )

Create a new PDF resource, using default error handling and memory management.

See also pdf_close().

pdf_open_CCITT

(PHP 4 >= 4.0.5)

pdf_open_CCITT -- Opens a new image file with raw CCITT data

Description

int pdf_open_CCITT ( resource pdfdoc, string filename, int width, int height, int BitReverse, int k, int Blackls1)

Open a raw CCITT image.

pdf_open_file

(PHP 4 >= 4.0.5)

pdf_open_file -- Opens a new pdf object

Description

bool pdf_open_file ( resource pdfdoc [, string filename])

Create a new PDF file using the supplied file name. If filename is empty the PDF document will be generated in memory instead of on file. The result must be fetched by the client with the pdf_get_buffer() function. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

The following example shows how to create a pdf document in memory and how to output it correctly.

Példa 1. Creating a PDF document in memory

<?php

$pdf = pdf_new();

pdf_open_file($pdf);
pdf_begin_page($pdf, 595, 842);
pdf_set_font($pdf, "Times-Roman", 30, "host");
pdf_set_value($pdf, "textrendering", 1);
pdf_show_xy($pdf, "A PDF document created in memory!", 50, 750);
pdf_end_page($pdf);
pdf_close($pdf);

$data = pdf_get_buffer($pdf);

header("Content-type: application/pdf");
header("Content-disposition: inline; filename=test.pdf");
header("Content-length: " . strlen($data));

echo $data;

?>

pdf_open_gif

pdf_open_gif -- Deprecated: Opens a GIF image

Description

This function is deprecated, use pdf_open_image() instead.

pdf_open_image_file

(PHP 3 CVS only, PHP 4 )

pdf_open_image_file -- Reads an image from a file

Description

int pdf_open_image_file ( resource pdfdoc, string imagetype, string filename [, string stringparam [, string intparam]])

Open an image file. Supported types are jpeg, tiff, gif, and png. stringparam is either , mask, masked, or page. intparamis either 0, the image id of the applied mask, or the page.

pdf_open_image

(PHP 4 >= 4.0.5)

pdf_open_image -- Versatile function for images

Description

int pdf_open_image ( resource PDF-document, string imagetype, string source, string data, long length, int width, int height, int components, int bpc, string params)

Use image data from a variety of data sources. Supported types are jpeg, ccitt, raw. Supported sources are memory, fileref, url. len is only used when type is raw, params is only used when type is ccitt.

pdf_open_jpeg

pdf_open_jpeg -- Deprecated: Opens a JPEG image

Description

This function is deprecated, use pdf_open_image() instead.

pdf_open_memory_image

(PHP 3>= 3.0.10, PHP 4 )

pdf_open_memory_image -- Opens an image created with PHP's image functions

Description

int pdf_open_memory_image ( resource pdfdoc, resource image)

The pdf_open_memory_image() function takes an image created with the PHP's image functions and makes it available for the pdf resource. The function returns a pdf image identifier.

Példa 1. Including a memory image

<?php
$im = imagecreate(100, 100);
$col = imagecolorallocate($im, 80, 45, 190);
imagefill($im, 10, 10, $col);
$pim = pdf_open_memory_image($pdf, $im);
imagedestroy($im);
pdf_place_image($pdf, $pim, 100, 100, 1);
pdf_close_image($pdf, $pim);
?>

See also pdf_close_image() and pdf_place_image().

pdf_open_pdi_page

(PHP 4 >= 4.0.5)

pdf_open_pdi_page --  Prepare a page

Description

int pdf_open_pdi_page ( resource pdfdoc, int dochandle, int pagenumber, string pagelabel)

Prepare a page for later use with pdf_place_image()

pdf_open_pdi

(PHP 4 >= 4.0.5)

pdf_open_pdi --  Opens a PDF file

Description

int pdf_open_pdi ( resource pdfdoc, string filename, string stringparam, int intparam)

Opens an existing PDF document and prepares it for later use.

See also pdf_close_pdi().

pdf_open_png

pdf_open_png --  Deprecated: Opens a PNG image

Description

This function is deprecated, use pdf_open_image() instead.

pdf_open_tiff

pdf_open_tiff -- Deprecated: Opens a TIFF image

Description

This function is deprecated, use pdf_open_image() instead.

pdf_open

pdf_open -- Deprecated: Open a new pdf object

Description

This function is deprecated, use pdf_new() plus pdf_open_file() instead.

pdf_place_image

(PHP 3>= 3.0.7, PHP 4 )

pdf_place_image -- Places an image on the page

Description

bool pdf_place_image ( resource pdfdoc, int image, float x, float y, float scale)

Place an image with the lower left corner at (x, y), and scale it. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

pdf_place_pdi_page

(PHP 4 >= 4.0.6)

pdf_place_pdi_page -- Places an image on the page

Description

bool pdf_place_pdi_page ( resource pdfdoc, int page, float x, float y, float sx, float sy)

Place a PDI page with the lower left corner at (x, y), and scale it. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

pdf_rect

(PHP 3>= 3.0.6, PHP 4 )

pdf_rect -- Draws a rectangle

Description

bool pdf_rect ( resource pdfdoc, float x, float y, float width, float height)

Draw a (width * height) rectangle at lower left (x, y). Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

pdf_restore

(PHP 3>= 3.0.6, PHP 4 )

pdf_restore -- Restores formerly saved environment

Description

bool pdf_restore ( resource pdfdoc)

Restore the most recently saved graphics state. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

pdf_rotate

(PHP 3>= 3.0.6, PHP 4 )

pdf_rotate -- Sets rotation

Description

bool pdf_rotate ( resource pdfdoc, float phi)

Rotate the coordinate system by phi degrees. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

pdf_save

(PHP 3>= 3.0.6, PHP 4 )

pdf_save -- Saves the current environment

Description

bool pdf_save ( resource pdfdoc)

Save the current graphics state. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

pdf_scale

(PHP 3>= 3.0.6, PHP 4 )

pdf_scale -- Sets scaling

Description

bool pdf_scale ( resource pdfdoc, float x-scale, float y-scale)

Scale the coordinate system. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

pdf_set_border_color

(PHP 3>= 3.0.12, PHP 4 )

pdf_set_border_color -- Sets color of border around links and annotations

Description

bool pdf_set_border_color ( resource pdfdoc, float red, float green, float blue)

Set the border color for all kinds of annotations. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

pdf_set_border_dash

(PHP 4 >= 4.0.1)

pdf_set_border_dash -- Sets dash style of border around links and annotations

Description

bool pdf_set_border_dash ( resource pdfdoc, float black, float white)

Sets the border dash style for all kinds of annotations. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

See also pdf_setdash().

pdf_set_border_style

(PHP 3>= 3.0.12, PHP 4 )

pdf_set_border_style -- Sets style of border around links and annotations

Description

bool pdf_set_border_style ( resource pdfdoc, string style, float width)

Sets the border style for all kinds of annotations. style is solid or dashed. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

pdf_set_char_spacing

pdf_set_char_spacing -- Deprecated: Sets character spacing

Description

This function is deprecated, use pdf_set_value() instead.

pdf_set_duration

pdf_set_duration -- Deprecated: Sets duration between pages

Description

This function is deprecated, use pdf_set_value() instead.

pdf_set_font

pdf_set_font -- Deprecated: Selects a font face and size

Description

This function is deprecated, use pdf_findfont() plus pdf_setfont() instead.

pdf_set_horiz_scaling

pdf_set_horiz_scaling -- Sets horizontal scaling of text

Description

This function is deprecated, use pdf_set_value() instead.

pdf_set_info_author

pdf_set_info_author --  Deprecated: Fills the author field of the document

Description

This function is deprecated, use pdf_set_info() instead.

pdf_set_info_creator

pdf_set_info_creator --  Deprecated: Fills the creator field of the document

Description

This function is deprecated, use pdf_set_info() instead.

pdf_set_info_keywords

pdf_set_info_keywords --  Deprecated: Fills the keywords field of the document

Description

This function is deprecated, use pdf_set_info() instead.

pdf_set_info_subject

pdf_set_info_subject --  Deprecated: Fills the subject field of the document

Description

This function is deprecated, use pdf_set_info() instead.

pdf_set_info_title

pdf_set_info_title --  Deprecated: Fills the title field of the document

Description

This function is deprecated, use pdf_set_info() instead.

pdf_set_info

(PHP 4 >= 4.0.1)

pdf_set_info -- Fills a field of the document information

Description

bool pdf_set_info ( resource pdfdoc, string key, string value)

Fill document information field key with value. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad. key is one of Subject, Title, Creator, Author, Keywords, or a user-defined key.

pdf_set_leading

pdf_set_leading -- Deprecated: Sets distance between text lines

Description

This function is deprecated, use pdf_set_value() instead.

pdf_set_parameter

(PHP 4 )

pdf_set_parameter -- Sets certain parameters

Description

bool pdf_set_parameter ( resource pdfdoc, string key, string value)

Sets some PDFlib parameters with string type. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

pdf_set_text_matrix

pdf_set_text_matrix -- Deprecated: Sets the text matrix

Description

This function is deprecated, use pdf_set_paramter() instead.

pdf_set_text_pos

(PHP 3>= 3.0.6, PHP 4 )

pdf_set_text_pos -- Sets text position

Description

bool pdf_set_text_pos ( resource pdfdoc, float x, float y)

Set the text output position specified by x and y. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

pdf_set_text_rendering

pdf_set_text_rendering -- Deprecated: Determines how text is rendered

Description

This function is deprecated, use pdf_set_value() instead.

pdf_set_text_rise

pdf_set_text_rise -- Deprecated: Sets the text rise

Description

This function is deprecated, use pdf_set_value() instead.

pdf_set_value

(PHP 4 >= 4.0.1)

pdf_set_value -- Sets certain numerical value

Description

bool pdf_set_value ( resource pdfdoc, string key, float value)

Set the value of some PDFlib parameter with float type. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

pdf_set_word_spacing

pdf_set_word_spacing -- Deprecated: Sets spacing between words

Description

This function is deprecated, use pdf_set_value() instead.

pdf_setcolor

(PHP 4 >= 4.0.5)

pdf_setcolor -- Sets fill and stroke color

Description

bool pdf_setcolor ( resource pdfdoc, string type, string colorspace, float c1 [, float c2 [, float c3 [, float c4]]])

Set the current color space and color. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad. The parameter type can be fill, stroke or both to specify that the color is set for filling, stroking or both filling and stroking. The parameter colorspace can be gray, rgb, cmyk, spot or pattern. The parameters c1, c2, c3 and c4 represent the color components for the color space specified by colorspace. Except as otherwise noted, the color components are floating-point values that range from 0 to 1.

For gray only c1 is used.

For rgb parameters c1, c2, and c3 specify the red, green and blue values respectively.

<?php
// Set fill and stroke colors to white.
pdf_setcolor($pdf, "both", "rgb", 1, 1, 1);
?>

For cmyk, parameters c1, c2, c3, and c4 are the cyan, magenta, yellow and black values, respectively.

<?php
// Set fill and stroke colors to black.
pdf_setcolor($pdf, "both", "cmyk", 0, 0, 0, 1);
?>

For spot, c1 should be a spot color handles returned by pdf_makespotcolor() and c2 is a tint value between 0 and 1.

For pattern, c1 should be a pattern handle returned by pdf_begin_pattern().

pdf_setdash

(PHP 3>= 3.0.6, PHP 4 )

pdf_setdash -- Sets dash pattern

Description

bool pdf_setdash ( resource pdfdoc, float b, float w)

Set the current dash pattern to b black and w white units. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

pdf_setflat

(PHP 3>= 3.0.6, PHP 4 )

pdf_setflat -- Sets flatness

Description

bool pdf_setflat ( resource pdfdoc, float flatness)

Sets the flatness to a value between 0 and 100 inclusive. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

pdf_setfont

(PHP 4 >= 4.0.5)

pdf_setfont -- Set the current font

Description

bool pdf_setfont ( resource pdfdoc, int font, float size)

Set the current font in the given size, using a font handle returned by pdf_findfont(). Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

See also pdf_findfont().

pdf_setgray_fill

(PHP 3>= 3.0.6, PHP 4 )

pdf_setgray_fill -- Sets filling color to gray value

Description

bool pdf_setgray_fill ( resource pdfdoc, float gray)

Set the current fill color to a gray value between 0 and 1 inclusive. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Megjegyzés: PDFlib V4.0: Deprecated, use pdf_setcolor() instead.

pdf_setgray_stroke

(PHP 3>= 3.0.6, PHP 4 )

pdf_setgray_stroke -- Sets drawing color to gray value

Description

bool pdf_setgray_stroke ( resource pdfdoc, float gray)

Set the current stroke color to a gray value between 0 and 1 inclusive. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Megjegyzés: PDFlib V4.0: Deprecated, use pdf_setcolor() instead.

pdf_setgray

(PHP 3>= 3.0.6, PHP 4 )

pdf_setgray -- Sets drawing and filling color to gray value

Description

bool pdf_setgray ( resource pdfdoc, float gray)

Set the current fill and stroke color. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Megjegyzés: PDFlib V4.0: Deprecated, use pdf_setcolor() instead.

pdf_setlinecap

(PHP 3>= 3.0.6, PHP 4 )

pdf_setlinecap -- Sets linecap parameter

Description

void pdf_setlinecap ( resource pdfdoc, int linecap)

Set the linecap parameter to a value between 0 and 2 inclusive.

pdf_setlinejoin

(PHP 3>= 3.0.6, PHP 4 )

pdf_setlinejoin -- Sets linejoin parameter

Description

bool pdf_setlinejoin ( resource pdfdoc, int value)

Sets the line join parameter to a value between 0 and 2 inclusive. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

pdf_setlinewidth

(PHP 3>= 3.0.6, PHP 4 )

pdf_setlinewidth -- Sets line width

Description

void pdf_setlinewidth ( resource pdfdoc, float width)

Sets the current linewidth to width. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

pdf_setmatrix

(PHP 4 >= 4.0.5)

pdf_setmatrix -- Sets current transformation matrix

Description

bool pdf_setmatrix ( resource pdfdoc, float a, float b, float c, float d, float e, float f)

Explicitly set the current transformation matrix. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

pdf_setmiterlimit

(PHP 3>= 3.0.6, PHP 4 )

pdf_setmiterlimit -- Sets miter limit

Description

bool pdf_setmiterlimit ( resource pdfdoc, float miter)

Set the miter limit to a value greater than or equal to 1. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

pdf_setpolydash

pdf_setpolydash -- Deprecated: Sets complicated dash pattern

Description

This function is deprecated, use pdf_setdash() instead.

pdf_setrgbcolor_fill

(PHP 3>= 3.0.6, PHP 4 )

pdf_setrgbcolor_fill -- Sets filling color to rgb color value

Description

bool pdf_setrgbcolor_fill ( resource pdfdoc, float red_value, float green_value, float blue_value)

Set the current fill color to the supplied RGB values. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Megjegyzés: PDFlib V4.0: Deprecated, use pdf_setcolor() instead.

pdf_setrgbcolor_stroke

(PHP 3>= 3.0.6, PHP 4 )

pdf_setrgbcolor_stroke -- Sets drawing color to rgb color value

Description

bool pdf_setrgbcolor_stroke ( resource pdfdoc, float red_value, float green_value, float blue_value)

Set the current stroke color to the supplied RGB values. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Megjegyzés: PDFlib V4.0: Deprecated, use pdf_setcolor() instead.

pdf_setrgbcolor

(PHP 3>= 3.0.6, PHP 4 )

pdf_setrgbcolor -- Sets drawing and filling color to rgb color value

Description

bool pdf_setrgbcolor ( resource pdfdoc, float red_value, float green_value, float blue_value)

Set the current fill and stroke color to the supplied RGB values. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Megjegyzés: PDFlib V4.0: Deprecated, use pdf_setcolor() instead.

pdf_show_boxed

(PHP 4 )

pdf_show_boxed -- Output text in a box

Description

int pdf_show_boxed ( resource pdfdoc, string text, float left, float top, float width, float height, string mode [, string feature])

Format text in the current font and size into the supplied text box according to the requested formatting mode, which must be one of left, right, center, justify or fulljustify. If width and height are 0, only a single line is placed at the point (left, top) in the requested mode.

Returns the number of characters that did not fit in the specified box. Returns 0 if all characters fit or the width and height parameters were set to 0 for single-line formatting.

pdf_show_xy

(PHP 3>= 3.0.6, PHP 4 )

pdf_show_xy -- Output text at given position

Description

bool pdf_show_xy ( resource pdfdoc, string text, float x, float y)

Print text in the current font at ( x, y). Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

pdf_show

(PHP 3>= 3.0.6, PHP 4 )

pdf_show -- Output text at current position

Description

bool pdf_show ( resource pdfdoc, string text)

Print text in the current font and size at the current position. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

pdf_skew

(PHP 4 )

pdf_skew -- Skews the coordinate system

Description

bool pdf_skew ( resource pdfdoc, float alpha, float beta)

Skew the coordinate system in x and y direction by alpha and beta degrees. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

pdf_stringwidth

(PHP 3>= 3.0.6, PHP 4 )

pdf_stringwidth -- Returns width of text using current font

Description

float pdf_stringwidth ( resource pdfdoc, string text [, int font [, float size]])

Returns the width of text using the last font set by pdf_setfont(). If the optional parameters font and size are specified, the width will be calculated using that font and size instead. Please note that font is a font handle returned by pdf_findfont().

Megjegyzés: Both the font and size parameters must be used together.

See also pdf_setfont() and pdf_findfont().

pdf_stroke

(PHP 3>= 3.0.6, PHP 4 )

pdf_stroke -- Draws line along path

Description

bool pdf_stroke ( resource pdfdoc)

Stroke the path with the current color and line width, and clear it. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

pdf_translate

(PHP 3>= 3.0.6, PHP 4 )

pdf_translate -- Sets origin of coordinate system

Description

bool pdf_translate ( resource pdfdoc, float tx, float ty)

Translate the origin of the coordinate system.

LXXXI. Verisign Payflow Pro functions

Bevezetés

This extension allows you to process credit cards and other financial transactions using Verisign Payment Services, formerly known as Signio (http://www.verisign.com/products/payflow/pro/index.html).

When using these functions, you may omit calls to pfpro_init() and pfpro_cleanup() as this extension will do so automatically if required. However the functions are still available in case you are processing a number of transactions and require fine control over the library. You may perform any number of transactions using pfpro_process() between the two.

These functions were added in PHP 4.0.2.

Megjegyzés: These functions only provide a link to Verisign Payment Services. Be sure to read the Payflow Pro Developers Guide for full details of the required parameters.

Megjegyzés: Ez a kiterjesztés nem működik Windows operációs rendszereken!


Követelmények

You will require the appropriate SDK for your platform, which may be downloaded from within the manager interface once you have registered. If you are going to use this extension in an SSL-enabled webserver or with other SSL components (such as the CURL+SSL extension) you MUST get the beta SDK.

Once you have downloaded the SDK you should copy the files from the lib directory of the distribution. Copy the header file pfpro.h to /usr/local/include and the library file libpfpro.so to /usr/local/lib.


Telepítés

These functions are only available if PHP has been compiled with the --with-pfpro[=DIR] option.


Futásidejű beállítások

Az alábbi függvények viselkedése befolyásolható a php.ini segítségével.

Táblázat 1. Verisign Payflow Pro configuration options

NameDefaultChangeable
pfpro.defaulthost/PFPRO_VERSION < 3 "test.signio.com"PHP_INI_ALL
pfpro.defaulthost"test-payflow.verisign.com"PHP_INI_ALL
pfpro.defaultport"443"PHP_INI_ALL
pfpro.defaulttimeout"30"PHP_INI_ALL
pfpro.proxyaddress""PHP_INI_ALL
pfpro.proxyport""PHP_INI_ALL
pfpro.proxylogon""PHP_INI_ALL
pfpro.proxypassword""PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().


Erőforrás típusok

Ez a kiterjesztés semmilyen erőforrás típust nem definiál.


Előre definiált állandók

Ez a kiterjesztés semmilyen konstans értéket nem definiál.

Tartalom
pfpro_cleanup -- Shuts down the Payflow Pro library
pfpro_init -- Initialises the Payflow Pro library
pfpro_process_raw -- Process a raw transaction with Payflow Pro
pfpro_process -- Process a transaction with Payflow Pro
pfpro_version -- Returns the version of the Payflow Pro software

pfpro_cleanup

(PHP 4 >= 4.0.2)

pfpro_cleanup -- Shuts down the Payflow Pro library

Description

void pfpro_cleanup ( void )

pfpro_cleanup() is used to shutdown the Payflow Pro library cleanly. It should be called after you have processed any transactions and before the end of your script. However you may omit this call, in which case this extension will automatically call pfpro_cleanup() after your script terminates.

See also pfpro_init().

pfpro_init

(PHP 4 >= 4.0.2)

pfpro_init -- Initialises the Payflow Pro library

Description

void pfpro_init ( void )

pfpro_init() is used to initialise the Payflow Pro library. You may omit this call, in which case this extension will automatically call pfpro_init() before the first transaction.

See also pfpro_cleanup().

pfpro_process_raw

(PHP 4 >= 4.0.2)

pfpro_process_raw -- Process a raw transaction with Payflow Pro

Description

string pfpro_process_raw ( string parameters [, string address [, int port [, int timeout [, string proxy_address [, int proxy_port [, string proxy_logon [, string proxy_password]]]]]]])

Returns: A string containing the response.

pfpro_process_raw() processes a raw transaction string with Payflow Pro. You should really use pfpro_process() instead, as the encoding rules of these transactions are non-standard.

The first parameter in this case is a string containing the raw transaction request. All other parameters are the same as with pfpro_process(). The return value is a string containing the raw response.

Megjegyzés: Be sure to read the Payflow Pro Developers Guide for full details of the required parameters and encoding rules. You would be well advised to use pfpro_process() instead.

Példa 1. Payflow Pro raw example

<?php

pfpro_init();

$response = pfpro_process_raw("USER=mylogin&PWD[5]=m&ndy&PARTNER=VeriSign&TRXTYPE=S&TENDER=C&AMT=1.50&ACCT=4111111111111111&EXPDATE=0904");

if (!$response) {
  die("Couldn't establish link to Verisign.\n");
}

echo "Verisign raw response was " . $response;

pfpro_cleanup();

?>

pfpro_process

(PHP 4 >= 4.0.2)

pfpro_process -- Process a transaction with Payflow Pro

Description

array pfpro_process ( array parameters [, string address [, int port [, int timeout [, string proxy_address [, int proxy_port [, string proxy_logon [, string proxy_password]]]]]]])

Returns: An associative array containing the response

pfpro_process() processes a transaction with Payflow Pro. The first parameter is an associative array containing keys and values that will be encoded and passed to the processor.

The second parameter is optional and specifies the host to connect to. By default this is "test.signio.com", so you will certainly want to change this to "connect.signio.com" in order to process live transactions.

The third parameter specifies the port to connect on. It defaults to 443, the standard SSL port.

The fourth parameter specifies the timeout to be used, in seconds. This defaults to 30 seconds. Note that this timeout appears to only begin once a link to the processor has been established and so your script could potentially continue for a very long time in the event of DNS or network problems.

The fifth parameter, if required, specifies the hostname of your SSL proxy. The sixth parameter specifies the port to use.

The seventh and eighth parameters specify the logon identity and password to use on the proxy.

The function returns an associative array of the keys and values in the response.

Megjegyzés: Be sure to read the Payflow Pro Developers Guide for full details of the required parameters.

Példa 1. Payflow Pro example

<?php

pfpro_init();

$transaction = array('USER'    => 'mylogin',
                     'PWD'     => 'mypassword',
                     'PARTNER' => 'VeriSign',
                     'TRXTYPE' => 'S',
                     'TENDER'  => 'C',
                     'AMT'     => 1.50,
                     'ACCT'    => '4111111111111111',
                     'EXPDATE' => '0904'
                    );

$response = pfpro_process($transaction);

if (!$response) {
  die("Couldn't establish link to Verisign.\n");
}

echo "Verisign response code was " . $response['RESULT'];
echo ", which means: " . $response['RESPMSG'] . "\n";

echo "\nThe transaction request: ";
print_r($transaction);

echo "\nThe response: ";
print_r($response);

pfpro_cleanup();

?>

pfpro_version

(PHP 4 >= 4.0.2)

pfpro_version -- Returns the version of the Payflow Pro software

Description

string pfpro_version ( void )

pfpro_version() returns the version string of the Payflow Pro library. At the time of writing, this was L211.

LXXXII. PHP Options&Information

Bevezetés

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.


Követelmények

Az itt leírt függvények használatához semmilyen külső függvénykönyvtár megléte nem szükségeltetik.


Telepítés

Semmilyen telepítés nem szükséges ezen függvények használatához, a PHP alapelemei.


Futásidejű beállítások

Az alábbi függvények viselkedése befolyásolható a php.ini segítségével.

Táblázat 1. PHP Options/Inf Configuration Options

NameDefaultChangeable
assert.active"1"PHP_INI_ALL
assert.bail"0"PHP_INI_ALL
assert.warning"1"PHP_INI_ALL
assert.callbackNULLPHP_INI_ALL
assert.quiet_eval"0"PHP_INI_ALL
enable_dl"1"PHP_INI_SYSTEM
max_execution_time"30"PHP_INI_ALL
magic_quotes_gpc"1"PHP_INI_PERDIR|PHP_INI_SYSTEM
magic_quotes_runtime"0"PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().

Here's a short explanation of the configuration directives.

assert.active boolean

Enable assert() evaluation.

assert.bail boolean

Terminate script execution on failed assertions.

assert.warning boolean

Issue a PHP warning for each failed assertion.

assert.callback string

user function to call on failed assertions

assert.quiet_eval boolean

Use the current setting of error_reporting() during assertion expression evaluation. If enabled, no errors are shown (implicit error_reporting(0)) while evaluation. If disabled, errors are shown according to the settings of error_reporting()

enable_dl boolean

This directive is really only useful in the Apache module version of PHP. You can turn dynamic loading of PHP extensions with dl() on and off per virtual server or per directory.

The main reason for turning dynamic loading off is security. With dynamic loading, it's possible to ignore all open_basedir restrictions. The default is to allow dynamic loading, except when using safe mode. In safe mode, 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.

The maximum execution time is not affected by system calls, the sleep() function, etc. Please see the set_time_limit() function for more details.

You can not change this setting with ini_set() when running in safe mode. The only workaround is to turn off safe mode or by changing the time limit in the php.ini.

magic_quotes_gpc boolean

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.

Megjegyzés: 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

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.


Erőforrás típusok

Ez a kiterjesztés semmilyen erőforrás típust nem definiál.


Előre definiált állandók

Az itt felsorolt konstansok mindig elérthetőek, mivel részei a PHP alaptelepítésének.

Táblázat 2. Pre-defined phpcredits() constants

ConstantValueDescription
CREDITS_GROUP1A list of the core developers
CREDITS_GENERAL2 General credits: Language design and concept, PHP 4.0 authors and SAPI module.
CREDITS_SAPI4 A list of the server API modules for PHP, and their authors.
CREDITS_MODULES8 A list of the extension modules for PHP, and their authors.
CREDITS_DOCS16 The credits for the documentation team.
CREDITS_FULLPAGE32 Usually used in combination with the other flags. Indicates that the a complete stand-alone HTML page needs to be printed including the information indicated by the other flags.
CREDITS_QA64 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.

Táblázat 3. phpinfo() constants

ConstantValueDescription
INFO_GENERAL1 The configuration line, php.ini location, build date, Web Server, System and more.
INFO_CREDITS2 PHP 4 Credits. See also phpcredits().
INFO_CONFIGURATION4 Current Local and Master values for PHP directives. See also ini_get().
INFO_MODULES8 Loaded modules and their respective settings.
INFO_ENVIRONMENT16 Environment Variable information that's also available in $_ENV.
INFO_VARIABLES32 Shows all predefined variables from EGPCS (Environment, GET, POST, Cookie, Server).
INFO_LICENSE64 PHP License information. See also the license faq.
INFO_ALL-1 Shows all of the above. This is the default value.

ASSERT_ACTIVE (integer)

ASSERT_CALLBACK (integer)

ASSERT_BAIL (integer)

ASSERT_WARNING (integer)

ASSERT_QUIET_EVAL (integer)

Tartalom
assert_options -- Set/get the various assert flags
assert -- Checks if assertion is FALSE
dl -- egy PHP kiterjesztés betöltése futásidőben
extension_loaded -- Visszaadja, hogy a megadott kiterjesztés be van-e töltve
get_cfg_var --  Visszaadja egy PHP konfigurációs beállítás értékét.
get_current_user --  Az aktuális PHP script tulajdonosának a nevét adja vissza.
get_defined_constants --  Returns an associative array with the names of all the constants and their values
get_extension_funcs --  Visszaadja egy megadott modul függvényeinek a nevét
get_include_path --  Gets the current include_path configuration option
get_included_files --  Visszaad egy tömböt a filenevekkel, amiket a include_once()-al használtál
get_loaded_extensions --  Visszaad egy tömböt, ami tartalmazza a fordított és betöltött modulok nevét
get_magic_quotes_gpc --  A 'magic_quotes_gpc' beállítás aktuális értékét adja vissza.
get_magic_quotes_runtime --  A 'magic_quotes_runtime' beállítás aktuális értékét adja vissza.
get_required_files --  Visszaad egy tömböt a filenevekkel, amiket a require_once()-al használtál
getenv -- Egy környezeti változó értékét adja vissza
getlastmod -- Visszaadja az oldal legutóbbi módosításának idejét.
getmygid -- Get PHP script owner's GID
getmyinode -- Visszaadja az aktuális oldal inode-ját.
getmypid -- Visszaadja a PHP process ID-jét.
getmyuid -- Visszadja a PHP script tulajdonosának userID-ját
getopt -- Gets options from the command line argument list
getrusage -- Visszadja az aktuális erőforrás-terheltségeket
ini_alter -- Alias of 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
main -- Dummy for main()
memory_get_usage -- Returns the amount of memory allocated to PHP
php_ini_scanned_files -- Return a list of .ini files parsed from the additional ini dir
php_logo_guid -- Visszaadja a logo guid-t.
php_sapi_name --  Visszaadja, hogy milyen módon fut a PHP
php_uname --  Returns information about the operating system PHP was built on
phpcredits -- Prints out the credits for PHP
phpinfo -- Rengeteg PHP információt ad vissza.
phpversion -- Visszadja az aktuális PHP verziószámot.
putenv -- Beállíja egy környezeti változó értékét.
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 --  Beállítja az aktív értéket a magic_quotes_runtime-hoz.
set_time_limit -- Beállítja a maximális futási időt
version_compare --  Compares two "PHP-standardized" version number strings
zend_logo_guid -- Visszaadja a Zend logo guid-t.
zend_version -- Gets the version of the current Zend engine

assert_options

(PHP 4 )

assert_options -- Set/get the various assert flags

Description

mixed assert_options ( int what [, mixed value])

Using assert_options() you may set the various assert() control options or just query their current settings.

Táblázat 1. Assert Options

optionini-parameterdefaultdescription
ASSERT_ACTIVEassert.active1enable assert() evaluation
ASSERT_WARNINGassert.warning1issue a PHP warning for each failed assertion
ASSERT_BAILassert.bail0terminate execution on failed assertions
ASSERT_QUIET_EVALassert.quiet_eval0 disable error_reporting during assertion expression evaluation
ASSERT_CALLBACKassert.callback(NULL)user function to call on failed assertions

assert_options() will return the original setting of any option or FALSE on errors.

assert

(PHP 4 )

assert -- Checks if assertion is FALSE

Description

int assert ( mixed assertion)

assert() will check the given assertion and take appropriate action if its result is FALSE.

If the assertion is given as a string it will be evaluated as PHP code by assert(). The advantages of a string assertion are less overhead when assertion checking is off and messages containing the assertion expression when an assertion fails. This means that if you pass a boolean condition as assertion this condition will not show up as parameter to the assertion function which you may have defined with the assert_options() function, the condition is converted to a string before calling that handler function, and the boolean FALSE is converted as the empty string.

Assertions should be used as a debugging feature only. You may use them for sanity-checks that test for conditions that should always be TRUE and that indicate some programming errors if not or to check for the presence of certain features like extension functions or certain system limits and features.

Assertions should not be used for normal runtime operations like input parameter checks. As a rule of thumb your code should always be able to work correctly if assertion checking is not activated.

The behavior of assert() may be configured by assert_options() or by .ini-settings described in that functions manual page.

The assert_options() function and/or ASSERT_CALLBACK configuration directive allow a callback function to be set to handle failed assertions.

assert() callbacks are particularly useful for building automated test suites because they allow you to easily capture the code passed to the assertion, along with information on where the assertion was made. While this information can be captured via other methods, using assertions makes it much faster and easier!

The callback function should accept three arguments. The first argument will contain the file the assertion failed in. The second argument will contain the line the assertion failed on and the third argument will contain the expression that failed (if any - literal values such as 1 or "two" will not be passed via this argument)

Példa 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("")');
?>

dl

(PHP 3, PHP 4 )

dl -- egy PHP kiterjesztés betöltése futásidőben

Leírás

int dl ( string library)

Betölti azt a PHP kiterjesztést, amit a library paraméterben adtál meg. Lásd még az extension_dir konfigurációs direktívát.

extension_loaded

(PHP 3>= 3.0.10, PHP 4 )

extension_loaded -- Visszaadja, hogy a megadott kiterjesztés be van-e töltve

Leírás

bool extension_loaded ( string name)

Igazat ad vissza ha a name paraméterben megadott kiterjesztés be van töltve. A különböző kiterjesztések neveit a phpinfo() függvénnyel is kiderítheted.

Lásd még: phpinfo().

Megjegyzés: Ez a függvény a 3.0.10-es verzióval került a nyelvbe.

get_cfg_var

(PHP 3, PHP 4 )

get_cfg_var --  Visszaadja egy PHP konfigurációs beállítás értékét.

Leírás

string get_cfg_var ( string varname)

Visszaadja a varname paraméterben megadott konfigurációs beállítás értékét, vagy FALSE értéket, ha hiba keletkezik.

Nem adja vissza a fordításkor beállított értékeket, vagy az Apache konfigurációs file-ból beolvasottakat (php3_configuration_option illetve php_configuration_option direktívák).

Ha le szeretnéd ellenőrizni, hogy a rendszer egy konfigurációs file-t használ, próbáld meg a cfg_file_path értéket lekérdezni. Ha ez elérhető, akkor egy konfigurációs file-t használ a PHP.

get_current_user

(PHP 3, PHP 4 )

get_current_user --  Az aktuális PHP script tulajdonosának a nevét adja vissza.

Leírás

string get_current_user ( void )

Visszaadja az aktuális PHP script tulajdonosának user nevét.

Lásd még: getmyuid(), getmypid(), getmyinode(), és getlastmod().

get_defined_constants

(PHP 4 >= 4.1.0)

get_defined_constants --  Returns an associative array with the names of all the constants and their values

Description

array get_defined_constants ( void )

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

For example the line below:

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

will print a list like:

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
)

See also get_loaded_extensions(), get_defined_functions(), and get_defined_vars().

get_extension_funcs

(PHP 4 )

get_extension_funcs --  Visszaadja egy megadott modul függvényeinek a nevét

Leírás

array get_extension_funcs ( string module_name)

Ez a függvény visszaadja egy tömbben az összes függvény nevét, amit a module_name modul definiál.

Például az alábbi sorok

print_r(get_extension_funcs("xml"));
print_r(get_extension_funcs("gd"));

ki fogják írni az xml és gd modulok függvényeinek neveit értelemszerűen.

Lásd még: get_loaded_extensions()

get_include_path

(PHP 4 >= 4.3.0)

get_include_path --  Gets the current include_path configuration option

Description

string get_include_path ( void )

Gets the current include_path configuration option value.

Példa 1. get_include_path() example

<?php
// Works as of PHP 4.3.0
echo get_include_path();

// Works in all PHP versions
echo ini_get('include_path');
?>

See also ini_get(), restore_include_path(), set_include_path(), and include().

get_included_files

(PHP 4 )

get_included_files --  Visszaad egy tömböt a filenevekkel, amiket a include_once()-al használtál

Leírás

array get_included_files ( void )

Ez a függvény visszaadja egy asszociatív tömbben a file-ok neveit, amiket a scriptedbe töltöttél az include_once() használatával. A tömb indexei a filenevek, ahogy az include_once()-al használtad őket, a ".php" kiterjesztés nélkül.

Megjegyzés: A PHP 4.0.1pl2-ben ez a függvény feltételezi, hogy az include_once-al beszúrt file-ok a ".php" kiterjesztéssel rendelkeznek. Más kiterjesztéssel a függvény nem fog működni.

Lásd még: require_once(), include_once(), get_required_files()

get_loaded_extensions

(PHP 4 )

get_loaded_extensions --  Visszaad egy tömböt, ami tartalmazza a fordított és betöltött modulok nevét

Leírás

array get_loaded_extensions ( void )

Ez a függvény visszaadja a PHP-be fordított és a betöltött modulok neveit egy tömmbben

Például az alábbi sor

print_r(get_loaded_extensions());

egy ilyen listát ír ki:

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
)

Lásd még: get_extension_funcs()

get_magic_quotes_gpc

(PHP 3>= 3.0.6, PHP 4 )

get_magic_quotes_gpc --  A 'magic_quotes_gpc' beállítás aktuális értékét adja vissza.

Leírás

long get_magic_quotes_gpc ( void )

Visszaadja az aktív konfigurációs beállítást a magic_quotes_gpc-hez. (0 ha ki van kapcsolva, 1 ha be van kapcsolva).

Lásd még: get_magic_quotes_runtime() és set_magic_quotes_runtime().

get_magic_quotes_runtime

(PHP 3>= 3.0.6, PHP 4 )

get_magic_quotes_runtime --  A 'magic_quotes_runtime' beállítás aktuális értékét adja vissza.

Leírás

long get_magic_quotes_runtime ( void )

Visszaadja az aktív konfigurációs beállítást a magic_quotes_runtime-hoz. (0 ha ki van kapcsolva, 1 ha be van kapcsolva).

Lásd még: get_magic_quotes_gpc() és set_magic_quotes_runtime().

get_required_files

(PHP 4 )

get_required_files --  Visszaad egy tömböt a filenevekkel, amiket a require_once()-al használtál

Leírás

array get_required_files ( void )

Ez a függvény visszaadja egy asszociatív tömbben a file-ok neveit, amiket a scriptedbe töltöttél a require_once() használatával. A tömb indexei a filenevek, ahogy a require_once()-al használtad őket, a ".php" kiterjesztés nélkül.

Az alábbi példa

Példa 1. A require-al és include-al behívott file-ok

<?php

require_once("local.php");
require_once("../inc/global.php");

for ($i=1; $i<5; $i++)
  include "util".$i."php";

echo "Required_once files\n";
print_r(get_required_files());

echo "Included_once files\n";
print_r(get_included_files());
?>
ezt a kimenetet generálja:

Required_once files
Array
(
    [local] => local.php 
    [../inc/global] => /full/path/to/inc/global.php
)

Included_once files
Array
(
    [util1] => util1.php 
    [util2] => util2.php 
    [util3] => util3.php 
    [util4] => util4.php 
)

Megjegyzés: A PHP 4.0.1pl2-ben ez a függvény feltételezi, hogy a required_once-al beszúrt file-ok a ".php" kiterjesztéssel rendelkeznek. Más kiterjesztéssel a függvény nem fog működni.

Lásd még: require_once(), include_once(), get_included_files()

getenv

(PHP 3, PHP 4 )

getenv -- Egy környezeti változó értékét adja vissza

Leírás

string getenv ( string varname)

Visszaadja a varname környezeti változó értékét, vagy FALSE értéket hiba esetén.

$ipcim = getenv("REMOTE_ADDR"); // visszaadja az IP cimét a látogatónak

Az összes környezeti változót a phpinfo() listázza ki. Ha mélyebben bele szeretnél merülni a témába, nézd meg a CGI specifikációt, különösen a környezeti változókról szóló oldalt.

getlastmod

(PHP 3, PHP 4 )

getlastmod -- Visszaadja az oldal legutóbbi módosításának idejét.

Leírás

int getlastmod ( void )

Visszaadja az oldal legutóbbi módosításának idejét. A visszaadott érték egy Unix timestamp, azért alkalmas pl. a date() függvény bemeneteként való alkalmazásra. FALSE értékkel tér vissza hiba esetén.

Példa 1. getlastmod() példa

// kiírja pl., hogy 'Legutóbbi módosítás: 2000. 07. 30. 16:49:43.'
echo "Legutóbbi módosítás: ".date( "Y. m. d. H:i:s.", getlastmod() );

Lásd még: date(), getmyuid(), get_current_user(), getmyinode() és getmypid().

getmygid

(PHP 4 >= 4.1.0)

getmygid -- Get PHP script owner's GID

Description

int getmygid ( void )

Returns the group ID of the current script, or FALSE on error.

See also getmyuid(), getmypid(), get_current_user(), getmyinode(), and getlastmod().

getmyinode

(PHP 3, PHP 4 )

getmyinode -- Visszaadja az aktuális oldal inode-ját.

Leírás

int getmyinode ( void )

Visszaadja az aktuális PHP oldal inode-ját, vagy FALSE értéket hiba esetén.

Lásd még: getmyuid(), get_current_user(), getmypid() és getlastmod().

Megjegyzés: Ez a függvény természetesen nem működik Windows alatt.

getmypid

(PHP 3, PHP 4 )

getmypid -- Visszaadja a PHP process ID-jét.

Leírás

int getmypid ( void )

Visszaadja az aktuális PHP process ID-t, vagy FALSE értéket hiba esetén.

Amikor a PHP szerver modulként üzemel, egy script több meghívása nem garantált, hogy más ID-t kap.

Lásd még: getmyuid(), get_current_user(), getmyinode() és getlastmod().

getmyuid

(PHP 3, PHP 4 )

getmyuid -- Visszadja a PHP script tulajdonosának userID-ját

Leírás

int getmyuid ( void )

Visszaadja az aktuális script UID-ját, vagy FALSE értéket hiba esetén.

Lásd még: getmypid(), get_current_user(), getmyinode() és getlastmod().

getopt

(PHP 4 >= 4.3.0)

getopt -- Gets options from the command line argument list

Description

array getopt ( string options)

Returns an associative array of option / argument pairs based on the options format specified in options, or FALSE on an error.

<?php
// parse the command line ($GLOBALS['argv'])
$options = getopt("f:hp:");
?>

The options parameter may contain the following elements: individual characters, and characters followed by a colon to indicate an option argument is to follow. For example, an option string x recognizes an option -x, and an option string x: recognizes an option and argument -x argument. It does not matter if an argument has leading white space.

This function will return an array of option / argument pairs. If an option does not have an argument, the value will be set to FALSE.

Megjegyzés: Ez a függvény nem működik Windows operációs rendszereken!

getrusage

(PHP 3>= 3.0.7, PHP 4 )

getrusage -- Visszadja az aktuális erőforrás-terheltségeket

Leírás

array getrusage ( [int who])

Ez egy felület a getrusage(2)-hez. Egy asszociatív tömböt ad vissza, ami a rendszerhívás által adott adatokat tartalmazza. Ha a who 1, a getrusage az RUSAGE_CHILDREN-el hívódik meg.

Minden bejegyzés a dokumentált elem nevekkel érhető el.

Példa 1. Getrusage példa

$dat = getrusage();
echo $dat["ru_nswap"];         # swap-ek száma
echo $dat["ru_majflt"];        # page fault-ok száma
echo $dat["ru_utime.tv_sec"];  # felhasznált user idő (másodpercek)
echo $dat["ru_utime.tv_usec"]; # felhasznált user idő (egymilliomod másodperc)
Lásd a rendszered manpage-ét bővebb információért.

ini_alter

ini_alter -- Alias of ini_set()

Description

This function is an alias of ini_set().

ini_get_all

(PHP 4 >= 4.2.0)

ini_get_all -- Gets all configuration options

Description

array ini_get_all ( [string extension])

Returns all the registered configuration options as an associative array. If the optional extension parameter is set, returns only options specific for that extension.

The returned array uses the directive name as the array key, with elements of that array being global_value (set in php.ini), local_value (perhaps set with ini_set() or .htaccess), and access (the access level). See the manual section on configuration changes for information on what access levels mean.

Megjegyzés: It's possible for a directive to have multiple access levels, which is why access shows the appropriate bitmask values.

Példa 1. A ini_get_all() example

<?php
$inis = ini_get_all();

print_r($inis);

?>

Partial output may look like:

Array
(
    [allow_call_time_pass_reference] => Array
    (
        [global_value] => 1
        [local_value] => 1
        [access] => 6
    )
    [allow_url_fopen] => Array
    (
        [global_value] => 1
        [local_value] => 1
        [access] => 7
    )

    ...

)

See also: ini_get(), ini_restore(), ini_set(), get_loaded_extensions(), and phpinfo().

ini_get

(PHP 4 )

ini_get -- Gets the value of a configuration option

Description

string ini_get ( string varname)

Returns the value of the configuration option on success. Failure, such as querying for a non-existant value, will return an empty string.

When querying boolean values: A boolean ini value of off will be returned as an empty string while a boolean ini value of on will be returned as "1".

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, NOT its integer equivalent. Attempting normal arithmetic functions on these values will not have otherwise expected results.

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

?>

This script will produce:

display_errors = 1
register_globals = 0
post_max_size = 8M
post_max_size+1 = 9

See also get_cfg_var(), ini_get_all(), ini_restore(), and ini_set().

ini_restore

(PHP 4 )

ini_restore -- Restores the value of a configuration option

Description

string ini_restore ( string varname)

Restores a given configuration option to its original value.

See also ini_get(), ini_get_all(), and ini_set().

ini_set

(PHP 4 )

ini_set -- Sets the value of a configuration option

Description

string ini_set ( string varname, string newvalue)

Sets the value of the given configuration option. Returns the old value on success, FALSE on failure. The configuration option will keep this new value during the script's execution, and will be restored at the script's ending.

Not all the available options can be changed using ini_set(). Below is a table with a list of all PHP options (as of PHP 4.2.0), indicating which ones can be changed/set and at what level.

Táblázat 1. Configuration options

NameDefaultChangeable
com.allow_dcom"0"PHP_INI_SYSTEM
com.autoregister_typelib"0"PHP_INI_SYSTEM
com.autoregister_verbose"0"PHP_INI_SYSTEM
com.autoregister_casesensitive"1"PHP_INI_SYSTEM
com.typelib_file""PHP_INI_SYSTEM
crack.default_dictionaryNULLPHP_INI_SYSTEM
exif.encode_unicode"ISO-8859-15"PHP_INI_ALL
exif.decode_unicode_motorola"UCS-2BE"PHP_INI_ALL
exif.decode_unicode_intel"UCS-2LE"PHP_INI_ALL
exif.encode_jis""PHP_INI_ALL
exif.decode_jis_motorola"JIS"PHP_INI_ALL
exif.decode_jis_intel"JIS"PHP_INI_ALL
fbsql.allow_persistent"1"PHP_INI_SYSTEM
fbsql.generate_warnings"0"PHP_INI_SYSTEM
fbsql.autocommit"1"PHP_INI_SYSTEM
fbsql.max_persistent"-1"PHP_INI_SYSTEM
fbsql.max_links"128"PHP_INI_SYSTEM
fbsql.max_connections"128"PHP_INI_SYSTEM
fbsql.max_results"128"PHP_INI_SYSTEM
fbsql.batchSize"1000"PHP_INI_SYSTEM
fbsql.default_hostNULLPHP_INI_SYSTEM
fbsql.default_user"_SYSTEM"PHP_INI_SYSTEM
fbsql.default_password""PHP_INI_SYSTEM
fbsql.default_database""PHP_INI_SYSTEM
fbsql.default_database_password""PHP_INI_SYSTEM
hwapi.allow_persistent"0"PHP_INI_SYSTEM
hyperwave.allow_persistent"0"PHP_INI_SYSTEM
hyperwave.default_port"418"PHP_INI_ALL
iconv.input_encodingICONV_INPUT_ENCODINGPHP_INI_ALL
iconv.output_encodingICONV_OUTPUT_ENCODINGPHP_INI_ALL
iconv.internal_encodingICONV_INTERNAL_ENCODINGPHP_INI_ALL
ifx.allow_persistent"1"PHP_INI_SYSTEM
ifx.max_persistent"-1"PHP_INI_SYSTEM
ifx.max_links"-1"PHP_INI_SYSTEM
ifx.default_hostNULLPHP_INI_SYSTEM
ifx.default_userNULLPHP_INI_SYSTEM
ifx.default_passwordNULLPHP_INI_SYSTEM
ifx.blobinfile"1"PHP_INI_ALL
ifx.textasvarchar"0"PHP_INI_ALL
ifx.byteasvarchar"0"PHP_INI_ALL
ifx.charasvarchar"0"PHP_INI_ALL
ifx.nullformat"0"PHP_INI_ALL
ingres.allow_persistent"1"PHP_INI_SYSTEM
ingres.max_persistent"-1"PHP_INI_SYSTEM
ingres.max_links"-1"PHP_INI_SYSTEM
ingres.default_databaseNULLPHP_INI_ALL
ingres.default_userNULLPHP_INI_ALL
ingres.default_passwordNULLPHP_INI_ALL
ibase.allow_persistent"1"PHP_INI_SYSTEM
ibase.max_persistent"-1"PHP_INI_SYSTEM
ibase.max_links"-1"PHP_INI_SYSTEM
ibase.default_userNULLPHP_INI_ALL
ibase.default_passwordNULLPHP_INI_ALL
ibase.timestampformat"%m/%d/%Y%H:%M:%S"PHP_INI_ALL
ibase.dateformat"%m/%d/%Y"PHP_INI_ALL
ibase.timeformat"%H:%M:%S"PHP_INI_ALL
java.class.pathNULLPHP_INI_ALL
java.homeNULLPHP_INI_ALL
java.library.pathNULLPHP_INI_ALL
java.libraryJAVALIBPHP_INI_ALL
java.libraryNULLPHP_INI_ALL
ldap.max_links"-1"PHP_INI_SYSTEM
mbstring.detect_orderNULLPHP_INI_ALL
mbstring.http_inputNULLPHP_INI_ALL
mbstring.http_outputNULLPHP_INI_ALL
mbstring.internal_encodingNULLPHP_INI_ALL
mbstring.substitute_characterNULLPHP_INI_ALL
mbstring.func_overload"0"PHP_INI_SYSTEM
mcrypt.algorithms_dirNULLPHP_INI_ALL
mcrypt.modes_dirNULLPHP_INI_ALL
mime_magic.magicfile"/usr/share/misc/magic.mime"PHP_INI_SYSTEM
mssql.allow_persistent"1"PHP_INI_SYSTEM
mssql.max_persistent"-1"PHP_INI_SYSTEM
mssql.max_links"-1"PHP_INI_SYSTEM
mssql.max_procs"25"PHP_INI_ALL
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
mssql.textsize"-1"PHP_INI_ALL
mssql.textlimit"-1"PHP_INI_ALL
mssql.batchsize"0"PHP_INI_ALL
mssql.datetimeconvert"1"PHP_INI_ALL
mssql.secure_connection"0"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.default_hostNULLPHP_INI_ALL
mysql.default_userNULLPHP_INI_ALL
mysql.default_passwordNULLPHP_INI_ALL
mysql.default_portNULLPHP_INI_ALL
mysql.default_socketNULLPHP_INI_ALL
ncurses.value"42"PHP_INI_ALL
ncurses.string"foobar"PHP_INI_ALL
odbc.allow_persistent"1"PHP_INI_SYSTEM
odbc.max_persistent"-1"PHP_INI_SYSTEM
odbc.max_links"-1"PHP_INI_SYSTEM
odbc.default_dbNULLPHP_INI_ALL
odbc.default_userNULLPHP_INI_ALL
odbc.default_pwNULLPHP_INI_ALL
odbc.defaultlrl"4096"PHP_INI_ALL
odbc.defaultbinmode"1"PHP_INI_ALL
odbc.check_persistent"1"PHP_INI_SYSTEM
pfpro.defaulthost"test.signio.com" 
pfpro.defaulthost"test-payflow.verisign.com" 
pfpro.defaultport"443"PHP_INI_ALL
pfpro.defaulttimeout"30"PHP_INI_ALL
pfpro.proxyaddress""PHP_INI_ALL
pfpro.proxyport""PHP_INI_ALL
pfpro.proxylogon""PHP_INI_ALL
pfpro.proxypassword""PHP_INI_ALL
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
pgsql.ignore_notice"0"PHP_INI_ALL
pgsql.log_notice"0"PHP_INI_ALL
session.save_path"/tmp"PHP_INI_ALL
session.name"PHPSESSID"PHP_INI_ALL
session.save_handler"files"PHP_INI_ALL
session.auto_start"0"PHP_INI_ALL
session.gc_probability"1"PHP_INI_ALL
session.gc_divisor"100"PHP_INI_ALL
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
session.use_cookies"1"PHP_INI_ALL
session.use_only_cookies"0"PHP_INI_ALL
session.referer_check""PHP_INI_ALL
session.entropy_file""PHP_INI_ALL
session.entropy_length"0"PHP_INI_ALL
session.cache_limiter"nocache"PHP_INI_ALL
session.cache_expire"180"PHP_INI_ALL
session.use_trans_sid"0"PHP_INI_SYSTEM|PHP_INI_PERDIR
session.encode_sources"globals,track"PHP_INI_ALL
assert.active"1"PHP_INI_ALL
assert.bail"0"PHP_INI_ALL
assert.warning"1"PHP_INI_ALL
assert.callbackNULLPHP_INI_ALL
assert.quiet_eval"0"PHP_INI_ALL
safe_mode_protected_env_varsSAFE_MODE_PROTECTED_ENV_VARSPHP_INI_SYSTEM
safe_mode_allowed_env_varsSAFE_MODE_ALLOWED_ENV_VARSPHP_INI_SYSTEM
url_rewriter.tags"a=href,area=href,frame=src,form=fakeentry"PHP_INI_ALL
sybct.allow_persistent"1"PHP_INI_SYSTEM
sybct.max_persistent"-1"PHP_INI_SYSTEM
sybct.max_links"-1"PHP_INI_SYSTEM
sybct.min_server_severity"10"PHP_INI_ALL
sybct.min_client_severity"10"PHP_INI_ALL
sybct.hostnameNULLPHP_INI_ALL
vpopmail.directory""PHP_INI_ALL
zlib.output_compression"0"PHP_INI_SYSTEM|PHP_INI_PERDIR
zlib.output_compression_level"-1"PHP_INI_ALL
define_syslog_variables"0"PHP_INI_ALL
highlight.bgHL_BG_COLORPHP_INI_ALL
highlight.commentHL_COMMENT_COLORPHP_INI_ALL
highlight.defaultHL_DEFAULT_COLORPHP_INI_ALL
highlight.htmlHL_HTML_COLORPHP_INI_ALL
highlight.keywordHL_KEYWORD_COLORPHP_INI_ALL
highlight.stringHL_STRING_COLORPHP_INI_ALL
allow_call_time_pass_reference"1"PHP_INI_SYSTEM|PHP_INI_PERDIR
asp_tags"0"PHP_INI_SYSTEM|PHP_INI_PERDIR
display_errors"1"PHP_INI_ALL
display_startup_errors"0"PHP_INI_ALL
enable_dl"1"PHP_INI_SYSTEM
expose_php"1"PHP_INI_SYSTEM
html_errors"1"PHP_INI_ALL
xmlrpc_errors"0"PHP_INI_SYSTEM
xmlrpc_error_number"0"PHP_INI_ALL
ignore_user_abort"0"PHP_INI_ALL
implicit_flush"0"PHP_INI_ALL
log_errors"0"PHP_INI_ALL
log_errors_max_len"1024"PHP_INI_ALL
ignore_repeated_errors"0"PHP_INI_ALL
ignore_repeated_source"0"PHP_INI_ALL
magic_quotes_gpc"1"PHP_INI_PERDIR|PHP_INI_SYSTEM
magic_quotes_runtime"0"PHP_INI_ALL
magic_quotes_sybase"0"PHP_INI_ALL
output_buffering"0"PHP_INI_PERDIR|PHP_INI_SYSTEM
output_handlerNULLPHP_INI_PERDIR|PHP_INI_SYSTEM
register_argc_argv"1"PHP_INI_PERDIR|PHP_INI_SYSTEM
register_globals"0"PHP_INI_PERDIR|PHP_INI_SYSTEM
safe_mode"1"PHP_INI_SYSTEM
safe_mode"0"PHP_INI_SYSTEM
safe_mode_include_dirNULLPHP_INI_SYSTEM
safe_mode_gid"0"PHP_INI_SYSTEM
short_open_tagDEFAULT_SHORT_OPEN_TAGPHP_INI_SYSTEM|PHP_INI_PERDIR
sql.safe_mode"0"PHP_INI_SYSTEM
track_errors"0"PHP_INI_ALL
y2k_compliance"0"PHP_INI_ALL
unserialize_callback_funcNULLPHP_INI_ALL
arg_separator.output"&"PHP_INI_ALL
arg_separator.input"&"PHP_INI_SYSTEM|PHP_INI_PERDIR
auto_append_fileNULLPHP_INI_SYSTEM|PHP_INI_PERDIR
auto_prepend_fileNULLPHP_INI_SYSTEM|PHP_INI_PERDIR
doc_rootNULLPHP_INI_SYSTEM
default_charsetSAPI_DEFAULT_CHARSETPHP_INI_ALL
default_mimetypeSAPI_DEFAULT_MIMETYPEPHP_INI_ALL
error_logNULLPHP_INI_ALL
extension_dirPHP_EXTENSION_DIRPHP_INI_SYSTEM
gpc_order"GPC"PHP_INI_ALL
include_pathPHP_INCLUDE_PATHPHP_INI_ALL
max_execution_time"30"PHP_INI_ALL
open_basedirNULLPHP_INI_SYSTEM
safe_mode_exec_dir"1"PHP_INI_SYSTEM
upload_max_filesize"2M"PHP_INI_SYSTEM|PHP_INI_PERDIR
file_uploads"1"PHP_INI_SYSTEM
post_max_size"8M"PHP_INI_SYSTEM|PHP_INI_PERDIR
upload_tmp_dirNULLPHP_INI_SYSTEM
user_dirNULLPHP_INI_SYSTEM
variables_orderNULLPHP_INI_ALL
error_append_stringNULLPHP_INI_ALL
error_prepend_stringNULLPHP_INI_ALL
SMTP"localhost"PHP_INI_ALL
smtp_port25PHP_INI_ALL
browscapNULLPHP_INI_SYSTEM
error_reportingNULLPHP_INI_ALL
memory_limit"8M"PHP_INI_ALL
precision"14"PHP_INI_ALL
sendmail_fromNULLPHP_INI_ALL
sendmail_pathDEFAULT_SENDMAIL_PATHPHP_INI_SYSTEM
disable_classes""php.ini only
disable_functions""php.ini only
allow_url_fopen"1"PHP_INI_ALL
always_populate_raw_post_data"0"PHP_INI_SYSTEM|PHP_INI_PERDIR
xbithack"0"PHP_INI_ALL
engine"1"PHP_INI_ALL
last_modified"0"PHP_INI_ALL
child_terminate"0"PHP_INI_ALL
async_send"0"PHP_INI_ALL

Táblázat 2. Definition of PHP_INI_* constants

ConstantValueMeaning
PHP_INI_USER1Entry can be set in user scripts
PHP_INI_PERDIR2 Entry can be set in php.ini, .htaccess or httpd.conf
PHP_INI_SYSTEM4 Entry can be set in php.ini or httpd.conf
PHP_INI_ALL7Entry can be set anywhere

See also: get_cfg_var(), ini_get(), ini_get_all(), and ini_restore()

main

main -- Dummy for main()

Description

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. Please add a user comment below that mentions what PHP function caused the error that linked to main() and it will be fixed and properly documented.

Táblázat 1. Known errors that point to main()

Function nameNo longer points here as of
include()4.3.2
include_once()4.3.2
require()4.3.2
require_once()4.3.2

See also html_errors and display_errors.

memory_get_usage

(PHP 4 >= 4.3.2)

memory_get_usage -- Returns the amount of memory allocated to PHP

Description

int memory_get_usage ( void )

Returns the amount of memory, in bytes, that's currently being allocated to your PHP script.

memory_get_usage() will only be defined if your PHP is compiled with the --enable-memory-limit configuration option.

Példa 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

?>

See also memory_limit.

php_ini_scanned_files

(PHP 4 >= 4.3.0)

php_ini_scanned_files -- Return a list of .ini files parsed from the additional ini dir

Description

string php_ini_scanned_files ( void )

php_ini_scanned_files() returns a comma-separated list of configuration files parsed after php.ini. These files are found in a directory defined by the --with-config-file-scan-dir. option which is set during compilation.

Returns a comma-separated string of .ini files on success. If the directive --with-config-files-scan-dir wasn't set, FALSE is returned. If it was set and the directory was empty, an empty string is returned. If a file is unrecognizable, the file will still make it into the returned string but a PHP error will also result. This PHP error will be seen both at compile time and while using php_ini_scanned_files().

The returned configuration files also include the path as declared in the --with-config-file-scan-dir directive. Also, each comma is followed by a newline.

Példa 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";
        }
    }
}
?>

See also ini_set() and phpinfo().

php_logo_guid

(PHP 4 )

php_logo_guid -- Visszaadja a logo guid-t.

Leírás

string php_logo_guid ( void )

Megjegyzés: Ez a függvény a PHP 4 Beta 4 verzióban került a nyelvbe.

php_sapi_name

(PHP 4 >= 4.0.1)

php_sapi_name --  Visszaadja, hogy milyen módon fut a PHP

Leírás

string php_sapi_name ( void )

A php_sapi_name() visszad egy kisbetűs string-et, ami megadja, hogy milyen felület van a szerver és a PHP között (Server API, SAPI). CGI PHP esetében, ez a string "cgi", Apache mod_php esetén "apache", stb.

Példa 1. php_sapi_name() példa

$inter_type = php_sapi_name();
if ($inter_type == "cgi")
    print "Te CGI PHP-t használsz\n";
else
    print "Te nem CGI PHP-t használsz\n";

php_uname

(PHP 4 >= 4.0.2)

php_uname --  Returns information about the operating system PHP was built on

Description

string php_uname ( void )

php_uname() returns a string with a description of the operating system PHP is built on. If you're just wanting the name of the operating system, consider using the PHP_OS constant.

Példa 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:

Példa 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;      // ;
?>

See also phpversion(), php_sapi_name(), and phpinfo().

phpcredits

(PHP 4 )

phpcredits -- Prints out the credits for PHP

Description

void phpcredits ( [int flag])

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. flag is optional, and it defaults to CREDITS_ALL. To generate a custom credits page, you may want to use the flag parameter. For example to print the general credits, you will use somewhere in your code:

<?php
phpcredits(CREDITS_GENERAL);
?>

And if you want to print the core developers and the documentation group, in a page of its own, you will use:

<?php
phpcredits(CREDITS_GROUP + CREDITS_DOCS + CREDITS_FULLPAGE);
?>

And if you feel like embedding all the credits in your page, then code like the one below will do it:

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

Táblázat 1. Pre-defined phpcredits() flags

namedescription
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_DOCSThe credits for the documentation team
CREDITS_FULLPAGE Usually used in combination with the other flags. Indicates that the a complete stand-alone HTML page needs to be printed including the information indicated by the other flags.
CREDITS_GENERAL General credits: Language design and concept, PHP 4.0 authors and SAPI module.
CREDITS_GROUPA 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

See also phpinfo(), phpversion() and php_logo_guid().

phpinfo

(PHP 3, PHP 4 )

phpinfo -- Rengeteg PHP információt ad vissza.

Leírás

int phpinfo ( void )

Rengeteg hasznos információt ad vissza a PHP aktuális állapotáról. Ez magában foglalja a PHP konfigurációs beállításait, a kiterjesztéseket, a PHP verziószámát, szerver és környezeti információkat (ha a PHP szerver modulként működik), a PHP környezeti információit, operációs rendszer verziószámot, elérési utakat, php3.ini (php.ini PHP 4 esetén) beállításokat, helyi konfigurációs beállításokat, HTTP fejléceket, és a GNU Public Licence-et.

Lásd még: phpversion().

phpversion

(PHP 3, PHP 4 )

phpversion -- Visszadja az aktuális PHP verziószámot.

Leírás

string phpversion ( void )

Visszad egy stringet, ami az éppen futó PHP feldolgozó verzóját mutatja.

Példa 1. phpversion() példa

// Kiírja, hogy pl. 'Aktuális PHP verzió: 4.0.0'
echo "Aktuális PHP verzió: ".phpversion();

Lásd még: phpinfo().

putenv

(PHP 3, PHP 4 )

putenv -- Beállíja egy környezeti változó értékét.

Leírás

void putenv ( string setting)

Hozzáadja a setting beállítást a szerver környezethez.

Példa 1. Egy környezeti változó beállítása

putenv("EGYEDIID=$egyediid");

restore_include_path

(PHP 4 >= 4.3.0)

restore_include_path --  Restores the value of the include_path configuration option

Description

void restore_include_path ( void )

Restores the include_path configuration option back to its original master value as set in php.ini

Példa 1. restore_include_path() example

<?php

echo get_include_path();  // .:/usr/local/lib/php

set_include_path('/inc');

echo get_include_path();  // /inc

// Works as of PHP 4.3.0
restore_include_path();

// Works in all PHP versions
ini_restore('include_path');

echo get_include_path();  // .:/usr/local/lib/php

?>

See also ini_restore(), set_include_path(), get_include_path(), and include().

set_include_path

(PHP 4 >= 4.3.0)

set_include_path --  Sets the include_path configuration option

Description

string set_include_path ( string new_include_path)

Sets the include_path configuration option for the duration of the script. Returns the old include_path on success or FALSE on failure.

Példa 1. set_include_path() example

<?php
// Works as of PHP 4.3.0
set_include_path('/inc');

// Works in all PHP versions
ini_set('include_path', '/inc');
?>

See also ini_set(), get_include_path(), restore_include_path(), and include().

set_magic_quotes_runtime

(PHP 3>= 3.0.6, PHP 4 )

set_magic_quotes_runtime --  Beállítja az aktív értéket a magic_quotes_runtime-hoz.

Leírás

long set_magic_quotes_runtime ( int new_setting)

Beállítja az aktív konfigurációs értéket a magic_quotes_runtime-hoz. (0 kikapcsolja, 1 bekapcsolja).

Lásd még: get_magic_quotes_gpc(), get_magic_quotes_runtime().

set_time_limit

(PHP 3, PHP 4 )

set_time_limit -- Beállítja a maximális futási időt

Leírás

void set_time_limit ( int seconds)

Beállítja, hogy mennyi másodperc adott maximálisan egy script futásához. Ha ezt az értéket a script eléri, fatális hiba keletkezik. Az alapérték 30 másodperc, vagy ha létezik, akkor a max_execution_time érték, amit a konfigurációs file-ban állíthatsz be. Ha nulla az értéke, nincs időkorlát.

Amikor meghívod, a set_time_limit() újraindítja az időmérést NULLáról. Ez azt jelenti, hogy 30 másodperces alapbeállítással a script futásának 25. másodpercében átállítod ezt egy set_time_limit(20) hívással, a script végülis összesen 45 másodpercig futhat.

Azonban a set_time_limit()-nek nincs hatása, ha 'safe mode'-ot használsz. Ilyenkor nincs más mód, mint kikapcsolni a 'safe mode'-ot, vagy átállítani a konfigurációs file-ban ezt az értéket.

version_compare

(PHP 4 >= 4.1.0)

version_compare --  Compares two "PHP-standardized" version number strings

Description

int version_compare ( string version1, string version2 [, string operator])

version_compare() compares two "PHP-standardized" version number strings. This is useful if you would like to write programs working only on some versions of PHP.

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.

The function first replaces _, - and + with a dot . in the version strings and also inserts dots . before and after any non number so that for example '4.3.2RC1' becomes '4.3.2.RC.1'. Then it splits the results like if you were using explode('.', $ver). Then it compares the parts starting from left to right. If a part contains special version strings these are handled in the following order: dev < alpha = a < beta = b < RC < pl. 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.

If you specify the third optional operator argument, you can test for a particular relationship. The possible operators are: <, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne respectively. Using this argument, the function will return 1 if the relationship is the one specified by the operator, 0 otherwise.

Példa 1. version_compare() example

<?php
// prints -1
echo version_compare("4.0.4", "4.0.6");

// these all print 1
echo version_compare("4.0.4", "4.0.6", "<");
echo version_compare("4.0.6", "4.0.6", "eq");
?>

zend_logo_guid

(PHP 4 )

zend_logo_guid -- Visszaadja a Zend logo guid-t.

Leírás

string zend_logo_guid ( void )

Megjegyzés: Ez a függvény a PHP 4 Beta 4 verzióban került a nyelvbe.

zend_version

(PHP 4 )

zend_version -- Gets the version of the current Zend engine

Description

string zend_version ( void )

Returns a string containing the version of the currently running Zend Engine.

Példa 1. zend_version() example

<?php
// prints e.g. 'Zend engine version: 1.0.4'
echo "Zend engine version: " . zend_version();
?>

See also phpinfo(), phpcredits(), php_logo_guid(), and phpversion().

LXXXIII. POSIX functions

Bevezetés

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. POSIX.1 for example defined the open(), read(), write() and close() functions, too, which traditionally have been part of PHP 3 for a long time. Some more system specific functions have not been available before, though, and this module tries to remedy this by providing easy access to these functions.

Figyelem

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.

Megjegyzés: Ez a kiterjesztés nem működik Windows operációs rendszereken!


Telepítés

POSIX functions are enabled by default. You can disable POSIX-like functions with --disable-posix.


Lásd még

The section about Process Control Functions maybe of interest for you.

Tartalom
posix_ctermid -- Get path name of controlling terminal
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_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_setegid --  Set the effective GID of the current process
posix_seteuid --  Set the effective UID of the current process
posix_setgid --  Set the GID of the current process
posix_setpgid -- set process group id for job control
posix_setsid -- Make the current process a session leader
posix_setuid --  Set the UID of the current process
posix_strerror --  Retrieve the system error message associated with the given errno.
posix_times -- Get process times
posix_ttyname -- Determine terminal device name
posix_uname -- Get system name

posix_ctermid

(PHP 3>= 3.0.13, PHP 4 )

posix_ctermid -- Get path name of controlling terminal

Description

string posix_ctermid ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

posix_get_last_error

(PHP 4 >= 4.2.0)

posix_get_last_error --  Retrieve the error number set by the last posix function that failed.

Description

int posix_get_last_error ( void )

Returns the errno (error number) set by the last posix function that failed. If no errors exist, 0 is returned. If you're wanting the system error message associated with the errno, use posix_strerror().

See also posix_strerror().

posix_getcwd

(PHP 3>= 3.0.13, PHP 4 )

posix_getcwd -- Pathname of current directory

Description

string posix_getcwd ( void )

posix_getcwd() returns the absolute pathname of the script's current working directory. posix_getcwd() returns FALSE on error.

posix_getegid

(PHP 3>= 3.0.10, PHP 4 )

posix_getegid --  Return the effective group ID of the current process

Description

int posix_getegid ( void )

Return the numeric effective group ID of the current process. See also posix_getgrgid() for information on how to convert this into a useable group name.

posix_geteuid

(PHP 3>= 3.0.10, PHP 4 )

posix_geteuid --  Return the effective user ID of the current process

Description

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.

posix_getgid

(PHP 3>= 3.0.10, PHP 4 )

posix_getgid --  Return the real group ID of the current process

Description

int posix_getgid ( void )

Return the numeric real group ID of the current process. See also posix_getgrgid() for information on how to convert this into a useable group name.

posix_getgrgid

(PHP 3>= 3.0.13, PHP 4 )

posix_getgrgid -- Return info about a group by group id

Description

array posix_getgrgid ( int gid)

Returns an array of information about a group and FALSE on failure. If gid isn't a number then NULL is returned and an E_WARNING level error is generated.

Példa 1. Example use of posix_getgrgid()

<?php

$groupid   = posix_getegid();
$groupinfo = posix_getgrgid($groupid);

print_r($groupinfo);

?>

An example output:

Array
(
    [name]    => toons
    [passwd]  => x
    [members] => Array 
        ( 
            [0] => tom
            [1] => jerry
        )
    [gid]     => 42
)

Megjegyzés: As of PHP 4.2.0, members is returned as an array of member usernames in the group. Before this time it was simply an integer (the number of members in the group) and the member names were returned with numerical indices.

See also posix_getegid(), filegroup(), stat(), and safe_mode_gid.

posix_getgrnam

(PHP 3>= 3.0.13, PHP 4 )

posix_getgrnam -- Return info about a group by name

Description

array posix_getgrnam ( string name)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

posix_getgroups

(PHP 3>= 3.0.10, PHP 4 )

posix_getgroups --  Return the group set of the current process

Description

array posix_getgroups ( void )

Returns an array of integers containing the numeric group ids of the group set of the current process. See also posix_getgrgid() for information on how to convert this into useable group names.

posix_getlogin

(PHP 3>= 3.0.13, PHP 4 )

posix_getlogin -- Return login name

Description

string posix_getlogin ( void )

Returns the login name of the user owning the current process. See posix_getpwnam() for information how to get more information about this user.

posix_getpgid

(PHP 3>= 3.0.10, PHP 4 )

posix_getpgid -- Get process group id for job control

Description

int posix_getpgid ( int pid)

Returns the process group identifier of the process pid.

This is not a POSIX function, but is common on BSD and System V systems. If your system does not support this function at system level, this PHP function will always return FALSE.

posix_getpgrp

(PHP 3>= 3.0.10, PHP 4 )

posix_getpgrp --  Return the current process group identifier

Description

int posix_getpgrp ( void )

Return the process group identifier of the current process. See POSIX.1 and the getpgrp(2) manual page on your POSIX system for more information on process groups.

posix_getpid

(PHP 3>= 3.0.10, PHP 4 )

posix_getpid -- Return the current process identifier

Description

int posix_getpid ( void )

Return the process identifier of the current process.

posix_getppid

(PHP 3>= 3.0.10, PHP 4 )

posix_getppid -- Return the parent process identifier

Description

int posix_getppid ( void )

Return the process identifier of the parent process of the current process.

posix_getpwnam

(PHP 3>= 3.0.13, PHP 4 )

posix_getpwnam -- Return info about a user by username

Description

array posix_getpwnam ( string username)

Returns an associative array containing information about a user referenced by an alphanumeric username, passed in the username parameter.

The array elements returned are:

Táblázat 1. The user information array

ElementDescription
name The name element contains the username of the user. This is a short, usually less than 16 character "handle" of the user, not her 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.

posix_getpwuid

(PHP 3>= 3.0.13, PHP 4 )

posix_getpwuid -- Return info about a user by user id

Description

array posix_getpwuid ( int uid)

Returns an associative array containing information about a user referenced by a numeric user ID, passed in the uid parameter.

The array elements returned are:

Táblázat 1. The user information array

ElementDescription
name The name element contains the username of the user. This is a short, usually less than 16 character "handle" of the user, not her 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.

posix_getrlimit

(PHP 3>= 3.0.10, PHP 4 )

posix_getrlimit -- Return info about system resource limits

Description

array posix_getrlimit ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

posix_getsid

(PHP 3>= 3.0.10, PHP 4 )

posix_getsid -- Get the current sid of the process

Description

int posix_getsid ( int pid)

Return the sid of the process pid. If pid is 0, the sid of the current process is returned.

This is not a POSIX function, but is common on System V systems. If your system does not support this function at system level, this PHP function will always return FALSE.

posix_getuid

(PHP 3>= 3.0.10, PHP 4 )

posix_getuid --  Return the real user ID of the current process

Description

int posix_getuid ( void )

Return the numeric real user ID of the current process. See also posix_getpwuid() for information on how to convert this into a useable username.

posix_isatty

(PHP 3>= 3.0.13, PHP 4 )

posix_isatty --  Determine if a file descriptor is an interactive terminal

Description

bool posix_isatty ( int fd)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

posix_kill

(PHP 3>= 3.0.13, PHP 4 )

posix_kill -- Send a signal to a process

Description

bool posix_kill ( int pid, int sig)

Send the signal sig to the process with the process identifier pid. Returns FALSE, if unable to send the signal, TRUE otherwise.

See also the kill(2) manual page of your POSIX system, which contains additional information about negative process identifiers, the special pid 0, the special pid -1, and the signal number 0.

posix_mkfifo

(PHP 3>= 3.0.13, PHP 4 )

posix_mkfifo --  Create a fifo special file (a named pipe)

Description

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.

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

Megjegyzés: Ha a safe mode be van kapcsolva, a PHP ellenőrzi, hogy a könyvtár, amelyben dolgozni szeretnél, ugyanazzal a felhasználói azonosítóval (UID) rendelkezik-e, mint az éppen futó program.

posix_setegid

(PHP 4 >= 4.0.2)

posix_setegid --  Set the effective GID of the current process

Description

bool posix_setegid ( int gid)

Set the effective group ID of the current process. This is a privileged function and you need appropriate privileges (usually root) on your system to be able to perform this function.

Returns TRUE on success, FALSE otherwise.

posix_seteuid

(PHP 4 >= 4.0.2)

posix_seteuid --  Set the effective UID of the current process

Description

bool posix_seteuid ( int uid)

Set the real user ID of the current process. This is a privileged function and you need appropriate privileges (usually root) on your system to be able to perform this function.

Returns TRUE on success, FALSE otherwise. See also posix_setgid().

posix_setgid

(PHP 3>= 3.0.13, PHP 4 )

posix_setgid --  Set the GID of the current process

Description

bool posix_setgid ( int gid)

Set the real group ID of the current process. This is a privileged function and you need appropriate privileges (usually root) on your system to be able to perform this function. The appropriate order of function calls is posix_setgid() first, posix_setuid() last.

Returns TRUE on success, FALSE otherwise.

posix_setpgid

(PHP 3>= 3.0.13, PHP 4 )

posix_setpgid -- set process group id for job control

Description

int posix_setpgid ( int pid, int pgid)

Let the process pid join the process group pgid. See POSIX.1 and the setsid(2) manual page on your POSIX system for more informations on process groups and job control. Returns TRUE on success, FALSE otherwise.

posix_setsid

(PHP 3>= 3.0.13, PHP 4 )

posix_setsid -- Make the current process a session leader

Description

int posix_setsid ( void )

Make the current process a session leader. See POSIX.1 and the setsid(2) manual page on your POSIX system for more informations on process groups and job control. Returns the session id.

posix_setuid

(PHP 3>= 3.0.13, PHP 4 )

posix_setuid --  Set the UID of the current process

Description

bool posix_setuid ( int uid)

Set the real user ID of the current process. This is a privileged function and you need appropriate privileges (usually root) on your system to be able to perform this function.

Returns TRUE on success, FALSE otherwise. See also posix_setgid().

posix_strerror

(PHP 4 >= 4.2.0)

posix_strerror --  Retrieve the system error message associated with the given errno.

Description

string posix_strerror ( int errno)

Returns the POSIX system error message associated with the given errno. If errno is 0, then the string "Success" is returned. The function posix_get_last_error() is used for retrieving the last POSIX errno.

See also posix_get_last_error().

posix_times

(PHP 3>= 3.0.13, PHP 4 )

posix_times -- Get process times

Description

array posix_times ( void )

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.

posix_ttyname

(PHP 3>= 3.0.13, PHP 4 )

posix_ttyname -- Determine terminal device name

Description

string posix_ttyname ( int fd)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

posix_uname

(PHP 3>= 3.0.10, PHP 4 )

posix_uname -- Get system name

Description

array posix_uname ( void )

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

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.

Posix requires that you must not make any assumptions about the format of the values, e.g. you cannot rely on three digit version numbers or anything else returned by this function.

LXXXIV. PostgreSQL függvények

Postgres, amit eredetileg a UC Berkeley Computer Science Department fejlesztett ki, úttörő volt az objektum-relációs adatmodellek területén, és most elérhetővé válik több kereskedelmi adatbázisban is. Támogatja az SQL92/SQL3 nyelv használatát, tranzakciók integritását és a típusok kiterjeszthetőségét. A PostgreSQL egy public-domain, nyílt forrású leszármazottja ennek az eredeti Berkeley kódnak.

A PostgreSQL ingyenes. A legújabb verzió a www.PostgreSQL.org címen érhető el.

A 6.3 verzió óta (03/02/1998) a PostgreSQL unix socketeket használ. A lenti táblázat mutatja az új kapcsolatteremtési lehetőségeket. Ez a socket a /tmp/.s.PGSQL.5432 néven érhető el. Ezt az opciót a postmaster parancs '-i' kapcsolójával érheted el, a jelentése pedig: "figyeld a TCP/IP socketeket is úgy, mint a unix socketeket".

Táblázat 1. Postmaster és a PHP

PostmasterPHPÁllapot
postmaster &pg_connect("", "", "", "", "dbname");OK
postmaster -i &pg_connect("", "", "", "", "dbname");OK
postmaster &pg_connect("localhost", "", "", "", "dbname"); Unable to connect to PostgreSQL server: connectDB() failed: Is the postmaster running and accepting TCP/IP (with -i) connection at 'localhost' on port '5432'? in /path/to/file.php3 on line 20. vagyis: Nem lehet kapcsolódni a PostgreSQL szerverhez: a connectDB() hívás meghiúsult. Fut a postmaster, és fogadja a TCP/IP kapcsolatokat (-i) a helyi gépen az 5432-es porton? a /elérési_út/a/file.php3 a 20-as sorban
postmaster -i &pg_connect("localhost", "", "", "", "dbname");OK

A következőképp is kezdhetsz kapcsolatot: $conn = pg_Connect("host=localhost port=5432 dbname=chris");

Annak érdekében, hogy használhassunk nagy objektum felületet (lo), szükséges az egészet egy tranzakciós blokkba foglalni. A tranzakciós blokk egy begin-nel kezdődik, és ha a tranzakció érvényes, egy commit-tal vagy egy end-del végződik. Ha a tranzakció meghiúsul, akkor rollback vagy abort paranccsal kell végződnie.

Példa 1. Nagy objektumok használata

<?php
    $database = pg_Connect ("", "", "", "", "jacarta");
    pg_exec ($database, "begin");
    $oid = pg_locreate ($database);
    echo ("$oid\n");
    $handle = pg_loopen ($database, $oid, "w");
    echo ("$handle\n");
    pg_lowrite ($handle, "gaga");
    pg_loclose ($handle);
    pg_exec ($database, "commit");
?>

Tartalom
pg_affected_rows -- Returns number of affected records (tuples)
pg_cancel_query --  Cancel asynchronous query
pg_client_encoding --  Gets the client encoding
pg_Close -- lezár egy PostgreSQL kapcsolatot
pg_Connect -- megnyit egy kapcsolatot
pg_connection_busy --  Get connection is busy or not
pg_connection_reset --  Reset connection (reconnect)
pg_connection_status --  Get connection status
pg_convert --  Convert associative array value 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 -- adatbázis neve
pg_delete --  Deletes records.
pg_end_copy -- Sync with PostgreSQL backend
pg_escape_bytea --  Escape binary for bytea type
pg_escape_string --  Escape string for text/char type
pg_fetch_all -- Fetches all rows from a result as an array
pg_Fetch_Array -- beolvas egy sort egy tömbbe
pg_fetch_assoc -- Fetch a row as an associative array
pg_Fetch_Object -- sor beolvasása objektumként
pg_fetch_result -- Returns values from a result resource
pg_Fetch_Row -- következő sor beolvasása numerikusan indexelt tömbbe
pg_field_is_null -- Test if a field is 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_type --  Returns the type name for the corresponding field number
pg_free_result -- Free result memory
pg_get_notify -- Ping database connection
pg_get_pid -- Ping database connection
pg_get_result --  Get asynchronous query result
pg_Host -- A hostnevet adja vissza
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 object'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 of large object
pg_lo_tell --  Returns current position of large object
pg_lo_unlink -- Delete a large object
pg_lo_write -- Write a large object
pg_meta_data --  Get meta data for table.
pg_num_fields -- Returns the number of fields
pg_num_rows -- Returns the number of rows
pg_Options -- Returns options
pg_pConnect --  Tartós adatbázis-kapcsolatot hoz létre
pg_ping -- Ping database connection
pg_Port -- Melyik porton van a kapcsolat
pg_put_line -- Send a NULL-terminated string to PostgreSQL backend
pg_query -- Execute a query
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_query --  Sends asynchronous query
pg_set_client_encoding --  Set the client encoding
pg_trace -- PostgreSQL szerver kapcsolatot követ nyomon
pg_tty -- A tty nevét adja vissza
pg_unescape_bytea --  Unescape binary for bytea type
pg_untrace -- Abbahagyja az adott kapcsolat nyomkövetését
pg_update --  Update table.

pg_affected_rows

(PHP 4 >= 4.2.0)

pg_affected_rows -- Returns number of affected records (tuples)

Description

int pg_affected_rows ( resource result)

pg_affected_rows() returns the number of tuples (instances/records/rows) affected by INSERT, UPDATE, and DELETE queries executed by pg_query(). If no tuple is affected by this function, it will return 0.

Példa 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";
?>

Megjegyzés: This function used to be called pg_cmdtuples().

See also pg_query() and pg_num_rows().

pg_cancel_query

(PHP 4 >= 4.2.0)

pg_cancel_query --  Cancel asynchronous query

Description

bool pg_cancel_query ( resource connection)

pg_cancel_query() cancel asynchronous query sent by pg_send_query(). You cannot cancel query executed by pg_query().

See also pg_send_query() and pg_connection_busy().

pg_client_encoding

(PHP 3 CVS only, PHP 4 >= 4.0.3)

pg_client_encoding --  Gets the client encoding

Description

string pg_client_encoding ( [resource connection])

pg_client_encoding() returns the client encoding as the string. The returned string should be either : SQL_ASCII, EUC_JP, EUC_CN, EUC_KR, EUC_TW, UNICODE, MULE_INTERNAL, LATINX (X=1...9), KOI8, WIN, ALT, SJIS, BIG5, WIN1250.

Megjegyzés: This function requires PHP-4.0.3 or higher and PostgreSQL-7.0 or higher. If libpq is compiled without multibyte encoding support, pg_set_client_encoding() always return "SQL_ASCII". Supported encoding depends on PostgreSQL version. Refer to PostgreSQL manual for details to enable multibyte support and encoding supported.

The function used to be called pg_clientencoding().

See also pg_set_client_encoding().

pg_Close

(PHP 3, PHP 4 )

pg_Close -- lezár egy PostgreSQL kapcsolatot

Leírás

bool pg_close ( int connection)

Hamissal tér vissza, ha a connection érvénytelen kapcsolatazonosító, egyébként igazzal. Lezárja az adott azonosítójú kapcsolatot a PostgreSQL adatbázissal.

pg_Connect

(PHP 3, PHP 4 )

pg_Connect -- megnyit egy kapcsolatot

Leírás

int pg_connect ( string host, string port, string options, string tty, string dbname)

Sikeres végrehajtás esetén egy kapcsolat-azonosítóval tér vissza, vagy hamissal, ha a kapcsolat nem hozható létre. Kapcsolatot nyit egy PostgreSQL adatbázishoz. Az összes argumentum változó-interpolált, beleértve a porszámot is. Az options és a tty argumentumok opcionálisak, vagyis elhagyhatók. Ez a függvény egy kapcsolat-azonosítóval tér vissza, mely más PostgreSQL függvények használatához szükséges. Egyszerre több kapcsolatot is tudsz nyitni.

Kapcsolat létrehozására alkalmas az alábbi parancs is: $conn = pg_connect("dbname=marliese port=5432"); A dbname és a port paraméter mellett még használható a host, tty, options, user és a password.

Lásd még a pg_pConnect() függvényt.

pg_connection_busy

(PHP 4 >= 4.2.0)

pg_connection_busy --  Get connection is busy or not

Description

bool pg_connection_busy ( resource connection)

pg_connection_busy() returns TRUE if the connection is busy. If it is busy, a previous query is still executing. If pg_get_result() is called, it will be blocked.

Példa 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';
    }
?>

See also pg_connection_status() and pg_get_result().

pg_connection_reset

(PHP 4 >= 4.2.0)

pg_connection_reset --  Reset connection (reconnect)

Description

bool pg_connection_reset ( resource connection)

pg_connection_reset() resets the connection. It is useful for error recovery. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Példa 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";
    }
?>

See also pg_connect(), pg_pconnect() and pg_connection_status().

pg_connection_status

(PHP 4 >= 4.2.0)

pg_connection_status --  Get connection status

Description

int pg_connection_status ( resource connection)

pg_connection_status() returns a connection status. Possible statuses are PGSQL_CONNECTION_OK and PGSQL_CONNECTION_BAD. The return value 0 as integer indicates a valid connection.

Példa 1. pg_connection_status() example

<?php
    $dbconn = pg_connect("dbname=publisher") or die("Could not connect");
    $stat = pg_connection_status($dbconn);
    if ($stat === 0) {
        echo 'Connection status ok';
    } else {
        echo 'Connection status bad';
    }    
?>

See also pg_connection_busy().

pg_convert

(PHP 4 >= 4.3.0)

pg_convert --  Convert associative array value into suitable for SQL statement.

Description

array pg_convert ( resource connection, string table_name, array assoc_array [, int options])

pg_convert() checks and converts the values in assoc_array into suitable values for use in a 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 as well as the fieldvalues in table_name must match the indices and values of assoc_array. Returns an array with the converted values on success, FALSE otherwise.

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

See also pg_meta_data().

pg_copy_from

(PHP 4 >= 4.2.0)

pg_copy_from --  Insert records into a table from an array

Description

bool pg_copy_from ( resource connection, string table_name, array rows [, string delimiter [, string null_as]])

pg_copy_from() insert records into a table from rows. It issues COPY FROM SQL command internally to insert records. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

See also pg_copy_to().

pg_copy_to

(PHP 4 >= 4.2.0)

pg_copy_to --  Copy a table to an array

Description

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. The resulting array is returned. It returns FALSE on failure.

See also pg_copy_from().

pg_DBname

(PHP 3, PHP 4 )

pg_DBname -- adatbázis neve

Leírás

string pg_dbname ( int connection)

Az adott kapcsolatazonosítójú PostgreSQL adatbázisnevével tér vissza, vagy hamissal, ha a kapcsolat-azonosító érvénytelen.

pg_delete

(PHP 4 >= 4.3.0)

pg_delete --  Deletes records.

Description

mixed pg_delete ( resource connection, string table_name, array assoc_array [, int options])

pg_delete() deletes record condition specified by assoc_array which has field=>value. If option is specified, pg_convert() is applied to assoc_array with specified option.

Példa 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";
    }
?>

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

See also pg_convert().

pg_end_copy

(PHP 4 >= 4.0.3)

pg_end_copy -- Sync with PostgreSQL backend

Description

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. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

For further details and an example, see also pg_put_line().

pg_escape_bytea

(PHP 4 >= 4.2.0)

pg_escape_bytea --  Escape binary for bytea type

Description

string pg_escape_bytea ( string data)

pg_escape_bytea() escapes string for bytea datatype. It returns escaped string.

Megjegyzés: When you SELECT bytea type, PostgreSQL returns octal byte value prefixed by \ (e.g. \032). Users are supposed to convert back to binary format by yourself.

This function requires PostgreSQL 7.2 or later. With PostgreSQL 7.2.0 and 7.2.1, bytea type must be casted 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 cast. Exception is when client and backend character encoding does not match, there may be multi-byte stream error. User must cast to bytea to avoid this error.

See also pg_unescape_bytea() and pg_escape_string().

pg_escape_string

(PHP 4 >= 4.2.0)

pg_escape_string --  Escape string for text/char type

Description

string pg_escape_string ( string data)

pg_escape_string() escapes string for text/char datatype. It returns escaped string for PostgreSQL. Use of this function is recommended instead of addslashes().

Megjegyzés: This function requires PostgreSQL 7.2 or later.

See also pg_escape_bytea()

pg_fetch_all

(PHP 4 >= 4.3.0)

pg_fetch_all -- Fetches all rows from a result as an array

Description

array pg_fetch_all ( resource result)

pg_fetch_all() returns an array that contains all rows (tuples/records) in result resource. It returns FALSE, if there are no rows.

Példa 1. PostgreSQL fetch all

<?php 
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
    echo "An error occured.\n";
    exit;
}

$result = pg_query($conn, "SELECT * FROM authors");
if (!$result) {
    echo "An error occured.\n";
    exit;
}

$arr = pg_fetch_all($result);

var_dump($arr);

?>

See also pg_fetch_row(), pg_fetch_array(), pg_fetch_object() and pg_fetch_result().

pg_Fetch_Array

(PHP 3>= 3.0.1, PHP 4 )

pg_Fetch_Array -- beolvas egy sort egy tömbbe

Leírás

array pg_fetch_array ( int result, int row [, int result_type])

Az adatbázis következő sorával tér vissza tömb formában, vagy hamissal, ha már nincs több sor.

A pg_fetch_array() függvény a pg_fetch_row() kiterjesztett változata. Amellett, hogy a tömb numerikusan indexelhető, az adatokat asszociatív indexszel is tárolja a mezőneveket használva kulcsnak.

A harmadik, result_type nevű argumentum a következő értékeket veheti fel: PGSQL_ASSOC, PGSQL_NUM, and PGSQL_BOTH.

Megjegyzés: A result_type paraméter a PHP 4.0-ás változatában került a nyelvbe.

Jó tudni, hogy a pg_fetch_array() használata NEM jelentősen lassabb, mint a pg_fetch_row() használata, míg az eredmény érthetőbb.

További részletekért lásd még a pg_fetch_row() függvényt.

Példa 1. A pg_fetch_array használata

<?php 
$conn = pg_pconnect("","","","","publisher");
if (!$conn) {
    echo "Hiba történt.\n";
    exit;
}

$result = pg_Exec ($conn, "SELECT * FROM authors");
if (!$result) {
    echo "Hiba történt.\n";
    exit;
}

$arr = pg_fetch_array ($result, 0);
echo $arr[0] . " <- array\n"; #hiba < kell!!!

$arr = pg_fetch_array ($result, 1);
echo $arr["author"] . " <- array\n"; # itt is
?>

pg_fetch_assoc

(PHP 4 >= 4.3.0)

pg_fetch_assoc -- Fetch a row as an associative array

Description

array pg_fetch_assoc ( resource result [, int row])

pg_fetch_assoc() returns an associative array that corresponds to the fetched row (tuples/records). It returns FALSE, if there are no more rows.

pg_fetch_assoc() is equivalent to calling pg_fetch_array() with PGSQL_ASSOC for the optional third parameter. It only returns an associative array. If you need the numeric indices, use pg_fetch_row().

row is row (record) number to be retrieved. First row is 0.

pg_fetch_assoc() is NOT significantly slower than using pg_fetch_row(), while it provides a significant ease of use.

Példa 1. pg_fetch_assoc() example

<?php 
$conn = pg_connect("dbname=publisher");
if (!$conn) {
    echo "An error occured.\n";
    exit;
}

$result = pg_query($conn, "SELECT id, author, email FROM authors");
if (!$result) {
    echo "An error occured.\n";
    exit;
}

while ($row = pg_fetch_assoc($result)) {
    echo $row['id'];
    echo $row['author'];
    echo $row['email'];
}
?>

See also pg_fetch_row(), pg_fetch_array(), pg_fetch_object() and pg_fetch_result().

pg_Fetch_Object

(PHP 3>= 3.0.1, PHP 4 )

pg_Fetch_Object -- sor beolvasása objektumként

Leírás

object pg_fetch_object ( int result, int row [, int result_type])

Egy objektummal tér vissza, aminek a tulajdonságai megegyeznek a beolvasott sor mezőivel, hamissal, ha nincs több sor.

pg_fetch_object() hasonló a pg_fetch_array()-hoz, egy különbséget kivéve - objektummal tér vissza, nem tömbbel. Vagyis adatot csak mezőnevekkel érhetsz el, indexszel (számokkal) nem (a számok ugyanis illegális mezőnevek).

A harmadik, result_type nevű argumentum a következő értékeket veheti fel: PGSQL_ASSOC, PGSQL_NUM, and PGSQL_BOTH.

Megjegyzés: A result_type paraméter a PHP 4.0-ás változatában került a nyelvbe.

Sebesség szempontjából, a függvény azonos a pg_fetch_array() függvénnyel, és majdnem olyan gyors, mint a pg_fetch_row() (a különbség jelentéktelen).

Lásd még a pg_fetch_array() és a pg_fetch_row() függvényeket.

Példa 1. pg_fetch_object alkalmazása

<?php 
$database = "verlag";
$db_conn = pg_connect ("localhost", "5432", "", "", $database);
if (!$db_conn): ?>
    <H1>Nem lehet kapcsolódni a <? echo $database ?> nevű adatbázishoz.</H1> <?
    exit;
endif;

$qu = pg_exec ($db_conn, "SELECT * FROM verlag ORDER BY autor");
$row = 0; // A postgresnek kell egy sorszámláló, ami más adatbáziskezelőnél talán nem

while ($data = pg_fetch_object ($qu, $row)):
    echo $data->autor." (";
    echo $data->jahr ."): ";
    echo $data->titel."<BR>";
    $row++;
endwhile; ?>

<PRE><?php
$fields[] = Array ("autor", "Author");
$fields[] = Array ("jahr",  "  Year");
$fields[] = Array ("titel", " Title");

$row= 0; // A postgresnek kell egy sorszámláló, ami más adatbáziskezelőnél talán nem
while ($data = pg_fetch_object ($qu, $row)):
    echo "----------\n";
    reset ($fields);
    while (list (,$item) = each ($fields)):
        echo $item[1].": ".$data->$item[0]."\n";
    endwhile;
    $row++;
endwhile;
echo "----------\n"; ?>
</PRE> <?php
pg_freeResult ($qu);
pg_close ($db_conn);
?>

pg_fetch_result

(PHP 4 >= 4.2.0)

pg_fetch_result -- Returns values from a result resource

Description

mixed pg_fetch_result ( resource result, int row, mixed field)

pg_fetch_result() returns values from a result resource returned by pg_query(). row is integer. field is field name (string) or field index (integer). The row and field specify what cell in the table of results to return. Row numbering starts from 0. Instead of naming the field, you may use the field index as an unquoted number. Field indices start from 0.

PostgreSQL has many built in types and only the basic ones are directly supported here. All forms of integer types are returned as integer values. All forms of float, and real types are returned as float values. 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.

pg_Fetch_Row

(PHP 3>= 3.0.1, PHP 4 )

pg_Fetch_Row -- következő sor beolvasása numerikusan indexelt tömbbe

Leírás

array pg_fetch_row ( int result, int row)

A beolvasott sorral tér vissza numerikusan indexelt (hagyományos) tömb formájában, vagy hamissal, ha nincs több sor.

A pg_fetch_row() függvény betölti a megadott eredmény-azonosítónak megfelelő sort. Az eredményt eredmény formában adja vissza. Az egyes oszlopokat indexszel (számmal) lehet elérni. Az első oszlop indexe 0.

A pg_fetch_row() egymás utáni alkalmazásával az eredményhalmaz következő sorát kapjuk, amíg van következő sor, majd hamist, ha már nincs több sor.

Lásd még a pg_fetch_array(), pg_fetch_object() és a pg_result() függvényeket.

Példa 1. pg_fetch_row alkalmazás

<?php 
$conn = pg_pconnect("","","","","publisher");
if (!$conn) {
    echo "Gáz van.\n";
    exit;
}

$result = pg_Exec ($conn, "SELECT * FROM authors");
if (!$result) {
    echo "Baj van, nagy baj van.\n";
    exit;
}

$row = pg_fetch_row ($result, 0);
echo $row[0] . " <- row\n";  # < helyett valami más kell

$row = pg_fetch_row ($result, 1);
echo $row[0] . " <- row\n"; # itt is

$row = pg_fetch_row ($result, 2);
echo $row[1] . " <- row\n"; # detto
?>

pg_field_is_null

(PHP 4 >= 4.2.0)

pg_field_is_null -- Test if a field is NULL

Description

int pg_field_is_null ( resource result, int row, mixed field)

pg_field_is_null() tests if a field is NULL or not. It returns 1 if the field in the given row is NULL. It returns 0 if the field in the given row is NOT NULL. Field can be specified as column index (number) or fieldname (string). Row numbering starts at 0.

Példa 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";
      }
   }
?>

Megjegyzés: This function used to be called pg_fieldisnull().

pg_field_name

(PHP 4 >= 4.2.0)

pg_field_name -- Returns the name of a field

Description

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.

Példa 1. Getting informations 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";
    }
?>

The above example would produce the following output:

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

Megjegyzés: This function used to be called pg_fieldname().

See also pg_field_num().

pg_field_num

(PHP 4 >= 4.2.0)

pg_field_num -- Returns the field number of the named field

Description

int pg_field_num ( resource result, string field_name)

pg_field_num() will return the number of the column (field) slot that corresponds to the field_name in the given PostgreSQL result resource. Field numbering starts at 0. This function will return -1 on error.

See the example given at the pg_field_name() page.

Megjegyzés: This function used to be called pg_fieldnum().

See also pg_field_name().

pg_field_prtlen

(PHP 4 >= 4.2.0)

pg_field_prtlen -- Returns the printed length

Description

int pg_field_prtlen ( resource result, int row_number, string field_name)

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 -1 on an error.

See the example given at the pg_field_name() page.

Megjegyzés: This function used to be called pg_fieldprtlen().

See also pg_field_size().

pg_field_size

(PHP 4 >= 4.2.0)

pg_field_size --  Returns the internal storage size of the named field

Description

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. Field numbering starts at 0. A field size of -1 indicates a variable length field. This function will return FALSE on error.

See the example given at the pg_field_name() page.

Megjegyzés: This function used to be called pg_fieldsize().

See also pg_field_prtlen() and pg_field_type().

pg_field_type

(PHP 4 >= 4.2.0)

pg_field_type --  Returns the type name for the corresponding field number

Description

string pg_field_type ( resource result, int field_number)

pg_field_type() returns a string containing the type name of the given field_number in the given PostgreSQL result resource. Field numbering starts at 0.

See the example given at the pg_field_name() page.

Megjegyzés: This function used to be called pg_fieldtype().

See also pg_field_prtlen() and pg_field_name().

pg_free_result

(PHP 4 >= 4.2.0)

pg_free_result -- Free result memory

Description

bool pg_free_result ( resource result)

pg_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. But, if you are sure you are not going to need the result data anymore in a script, you may call pg_free_result() with the result resource as an argument and the associated result memory will be freed. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Megjegyzés: This function used to be called pg_freeresult().

See also pg_query().

pg_get_notify

(PHP 4 >= 4.3.0)

pg_get_notify -- Ping database connection

Description

array pg_get_notify ( resource connection [, int result_type])

pg_get_notify() gets notify message sent by NOTIFY SQL command. To receive notify messages, LISTEN SQL command must be issued. If there is notify message on the connection, array contains message name and backend PID is returned. If there is no message, FALSE is returned.

See also pg_get_pid()

Példa 1. PostgreSQL NOTIFY message

<?php 
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
    echo "An error occured.\n";
    exit;
}

// Listen 'author_updated' message from other processes
pg_query($conn, 'LISTEN author_updated;');
$notify = pg_get_notify($conn);
if (!$notify) {
    echo "No messages\n";
} else {
    print_r($notify);
}
?>

pg_get_pid

(PHP 4 >= 4.3.0)

pg_get_pid -- Ping database connection

Description

int pg_get_pid ( resource connection)

pg_get_pid() gets backend (database server process) PID. PID is useful to check if NOTIFY message is sent from other process or not.

Példa 1. PostgreSQL backend PID

<?php 
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
    echo "An error occured.\n";
    exit;
}

// Backend process PID. Use PID with pg_get_notify()
$pid = pg_get_pid($conn);
?>

See also pg_get_notify().

pg_get_result

(PHP 4 >= 4.2.0)

pg_get_result --  Get asynchronous query result

Description

resource pg_get_result ( [resource connection])

pg_get_result() get result resource from async query executed by pg_send_query(). pg_send_query() can send multiple queries to PostgreSQL server and pg_get_result() is used to get query result one by one. It returns result resource. If there is no more results, it returns FALSE.

pg_Host

(PHP 3, PHP 4 )

pg_Host -- A hostnevet adja vissza

Leírás

string pg_host ( int connection_id)

A pg_Host() függvény az adott kapcsolat-azonosítójú PostgreSQL host nevét adja vissza.

pg_insert

(PHP 4 >= 4.3.0)

pg_insert --  Insert array into table.

Description

bool pg_insert ( resource connection, string table_name, array assoc_array [, int options])

pg_insert() inserts the values of assoc_array into the table specified by table_name. table_name must at least have as many columns as assoc_array has elements. The fieldnames as well as the fieldvalues in table_name must match the indices and values of assoc_array. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad. If options is specified, pg_insert() is applied to assoc_array with specified option.

Példa 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";
    }
?>

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

See also pg_convert().

pg_last_error

(PHP 4 >= 4.2.0)

pg_last_error -- Get the last error message string of a connection

Description

string pg_last_error ( [resource connection])

pg_last_error() returns the last error message for given connection.

Error messages may be overwritten by internal PostgreSQL(libpq) function calls. It may not return appropriate error message, if multiple errors are occurred inside a PostgreSQL module function.

Use pg_result_error(), pg_result_status() and pg_connection_status() for better error handling.

Megjegyzés: This function used to be called pg_errormessage().

See also pg_result_error().

pg_last_notice

(PHP 4 >= 4.0.6)

pg_last_notice --  Returns the last notice message from PostgreSQL server

Description

string pg_last_notice ( resource connection)

pg_last_notice() returns the last notice message from the PostgreSQL server specified by connection. The PostgreSQL server sends notice messages in several cases, e.g. if the transactions can't be continued. With pg_last_notice(), you can avoid issuing useless queries, by checking whether the notice is related to the transaction or not.

Figyelem

This function is EXPERIMENTAL and it is not fully implemented yet. pg_last_notice() was added in PHP 4.0.6. However, PHP 4.0.6 has problem with notice message handling. Use of the PostgreSQL module with PHP 4.0.6 is not recommended even if you are not using pg_last_notice().

This function is fully implemented in PHP 4.3.0. PHP earlier than PHP 4.3.0 ignores database connection parameter.

Notice message tracking can be set to optional by setting 1 for pgsql.ignore_notice in php.ini from PHP 4.3.0.

Notice message logging can be set to optional by setting 0 for pgsql.log_notice in php.ini from PHP 4.3.0. Unless pgsql.ignore_notice is set to 0, notice message cannot be logged.

See also pg_query() and pg_last_error().

pg_last_oid

(PHP 4 >= 4.2.0)

pg_last_oid -- Returns the last object's oid

Description

int pg_last_oid ( resource result)

pg_last_oid() is used to retrieve the oid assigned to an inserted tuple (record) if the result resource is used from the last command sent via pg_query() and was an SQL INSERT. Returns a positive integer if there was a valid oid. It returns FALSE if an error occurs or the last command sent via pg_query() was not an INSERT or INSERT is failed.

OID field became an optional field from PostgreSQL 7.2. When OID field is not defined in a table, programmer must use pg_result_status() to check if record is is inserted successfully or not.

Megjegyzés: This function used to be called pg_getlastoid().

See also pg_query() and pg_result_status()

pg_lo_close

(PHP 4 >= 4.2.0)

pg_lo_close -- Close a large object

Description

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 (lo) interface, it is necessary to enclose it within a transaction block.

Megjegyzés: This function used to be called pg_loclose().

See also pg_lo_open(), pg_lo_create() and pg_lo_import().

pg_lo_create

(PHP 4 >= 4.2.0)

pg_lo_create -- Create a large object

Description

int pg_lo_create ( resource connection)

pg_lo_create() creates a Large Object and returns the oid of the large object. connection specifies a valid database connection opened by pg_connect() or pg_pconnect(). 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). It returns large object oid, otherwise it returns FALSE if an error occurred.

To use the large object (lo) interface, it is necessary to enclose it within a transaction block.

Megjegyzés: This function used to be called pg_locreate().

pg_lo_export

(PHP 4 >= 4.2.0)

pg_lo_export -- Export a large object to file

Description

bool pg_lo_export ( [resource connection, int oid, string pathname])

The oid argument specifies oid of the large object to export and the pathname argument specifies the pathname of the file. It returns FALSE if an error occurred, TRUE otherwise.

To use the large object (lo) interface, it is necessary to enclose it within a transaction block.

Megjegyzés: This function used to be called pg_loexport().

See also pg_lo_import().

pg_lo_import

(PHP 4 >= 4.2.0)

pg_lo_import -- Import a large object from file

Description

int pg_lo_import ( [resource connection, string pathname])

In versions before PHP 4.2.0 the syntax of this function was different, see the following definition:

int pg_lo_import ( string pathname [, resource connection])

The pathname argument specifies the pathname of the file to be imported as a large object. It returns FALSE if an error occurred, oid of the just created large object otherwise.

To use the large object (lo) interface, it is necessary to enclose it within a transaction block.

Megjegyzés: Ha a safe mode be van kapcsolva, a PHP ellenőrzi, hogy az állományok vagy könyvtárak, amelyekkel dolgozni szeretnél, ugyanazzal a felhasználói azonosítóval (UID) rendelkeznek-e, mint az éppen futó program.

Megjegyzés: This function used to be called pg_loimport().

See also pg_lo_export() and pg_lo_open().

pg_lo_open

(PHP 4 >= 4.2.0)

pg_lo_open -- Open a large object

Description

resource pg_lo_open ( resource connection, int oid, string mode)

pg_lo_open() opens a Large Object and returns large object resource. The resource encapsulates information about the connection. oid specifies a valid large object oid and mode can be either "r", "w", or "rw". It returns FALSE if there is an error.

Figyelem

Do not close the database connection before closing the large object resource.

To use the large object (lo) interface, it is necessary to enclose it within a transaction block.

Megjegyzés: This function used to be called pg_loopen().

See also pg_lo_close() and pg_lo_create().

pg_lo_read_all

(PHP 4 >= 4.2.0)

pg_lo_read_all --  Reads an entire large object and send straight to browser

Description

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. It returns number of bytes read. It returns FALSE, if an error occurred.

To use the large object (lo) interface, it is necessary to enclose it within a transaction block.

Megjegyzés: This function used to be called pg_loreadall().

See also pg_lo_read().

pg_lo_read

(PHP 4 >= 4.2.0)

pg_lo_read -- Read a large object

Description

string pg_lo_read ( resource large_object, int len)

pg_lo_read() reads at most len bytes from a large object and returns it as a string. large_object specifies a valid large object resource andlen specifies the maximum allowable size of the large object segment. It returns FALSE if there is an error.

To use the large object (lo) interface, it is necessary to enclose it within a transaction block.

Megjegyzés: This function used to be called pg_loread().

See also pg_lo_read_all().

pg_lo_seek

(PHP 4 >= 4.2.0)

pg_lo_seek --  Seeks position of large object

Description

bool pg_lo_seek ( resource large_object, int offset [, int whence])

pg_lo_seek() seeks position of large object resource. whence is PGSQL_SEEK_SET, PGSQL_SEEK_CUR or PGSQL_SEEK_END.

See also pg_lo_tell().

pg_lo_tell

(PHP 4 >= 4.2.0)

pg_lo_tell --  Returns current position of large object

Description

int pg_lo_tell ( resource large_object)

pg_lo_tell() returns current position (offset from the beginning of large object).

See also pg_lo_seek().

pg_lo_unlink

(PHP 4 >= 4.2.0)

pg_lo_unlink -- Delete a large object

Description

bool pg_lo_unlink ( resource connection, int oid)

pg_lo_unlink() deletes a large object with the oid. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

To use the large object (lo) interface, it is necessary to enclose it within a transaction block.

Megjegyzés: This function used to be called pg_lo_unlink().

See also pg_lo_create() and pg_lo_import().

pg_lo_write

(PHP 4 >= 4.2.0)

pg_lo_write -- Write a large object

Description

int pg_lo_write ( resource large_object, string data)

pg_lo_write() writes at most to a large object from a variable data and returns the number of bytes actually written, or FALSE in the case of an error. large_object is a large object resource from pg_lo_open().

To use the large object (lo) interface, it is necessary to enclose it within a transaction block.

Megjegyzés: This function used to be called pg_lowrite().

See also pg_lo_create() and pg_lo_open().

pg_meta_data

(PHP 4 >= 4.3.0)

pg_meta_data --  Get meta data for table.

Description

array pg_meta_data ( resource connection, string table_name)

pg_meta_data() returns table definition for table_name as an array. If there is error, it returns FALSE

Példa 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>';
    }
?>

The above example would produce the following output:

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

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

See also pg_convert().

pg_num_fields

(PHP 4 >= 4.2.0)

pg_num_fields -- Returns the number of fields

Description

int pg_num_fields ( resource result)

pg_num_fields() returns the number of fields (columns) in a PostgreSQL result. The argument is a result resource returned by pg_query(). This function will return -1 on error.

Megjegyzés: This function used to be called pg_numfields().

See also pg_num_rows() and pg_affected_rows().

pg_num_rows

(PHP 4 >= 4.2.0)

pg_num_rows -- Returns the number of rows

Description

int pg_num_rows ( resource result)

pg_num_rows() will return the number of rows in a PostgreSQL result resource. result is a query result resource returned by pg_query(). This function will return -1 on error.

Megjegyzés: Use pg_affected_rows() to get number of rows affected by INSERT, UPDATE and DELETE query.

Megjegyzés: This function used to be called pg_numrows().

See also pg_num_fields() and pg_affected_rows().

pg_Options

(PHP 3, PHP 4 )

pg_Options -- Returns options

Leírás

string pg_options ( int connection_id)

A pg_Options() függvény egy stringgel tér vissza, amiben az adott PostgreSQL azonosító kapcsolat opcióit tartalmazza.

pg_pConnect

(PHP 3, PHP 4 )

pg_pConnect --  Tartós adatbázis-kapcsolatot hoz létre

Leírás

int pg_pconnect ( string host, string port, string options, string tty, string dbname)

Siker esetén egy kapcsolat-indexszel tér vissza, vagy hamissal, ha a kapcsolat nem hozható létre. Tartós kapcsolatot nyit a PostgreSQL adatbázishoz. Minden paraméternek idézőjelezettnek kell lennie, beleértve a portszámot. Az options és a tty paraméterek elhagyhatók. A függvény egy olyan kapcsolat-azonosítóval tér vissza, amely szükséges más PostgreSQL függvények végrehajtásához. Egyszerre több tartós kapcsolatod is lehet nyitva egyszerre. [Hát igen, ez a Postgres még a valós életet is túlszárnyalja...] Lásd még a pg_Connect() függvényt.

Kapcsolat a következő módon is létrehozható: $conn = pg_pconnect("dbname=marliese port=5432"); Egyéb paraméterek dbname és port are[???] host, tty, options, user és password.

pg_ping

(PHP 4 >= 4.3.0)

pg_ping -- Ping database connection

Description

bool pg_ping ( resource connection)

pg_ping() ping database connection, try to reconnect if it is broken. It returns TRUE if connection is alive, otherwise FALSE.

Példa 1. pg_ping() example

<?php 
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
    echo "An error occured.\n";
    exit;
}

if (!pg_ping($conn))
    die("Connection is broken\n");
?>

See also pg_connection_status() and pg_connection_reset().

pg_Port

(PHP 3, PHP 4 )

pg_Port -- Melyik porton van a kapcsolat

Leírás

int pg_port ( int connection_id)

A pg_Port() függvény az adott PostgreSQL kapcsolat-azonosítójú összeköttetés portszámát adja meg.

pg_put_line

(PHP 4 >= 4.0.3)

pg_put_line -- Send a NULL-terminated string to PostgreSQL backend

Description

bool pg_put_line ( [resource connection, string data])

pg_put_line() sends a NULL-terminated string to the PostgreSQL backend server. This is useful for example for very high-speed inserting of data into a table, initiated by starting a PostgreSQL copy-operation. That final NULL-character is added automatically. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Megjegyzés: The application must explicitly send the two characters "\." on the last line to indicate to the backend that it has finished sending its data.

Példa 1. High-speed insertion of data into a table

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

See also pg_end_copy().

pg_query

(PHP 4 >= 4.2.0)

pg_query -- Execute a query

Description

resource pg_query ( resource connection, string query)

pg_query() returns a query result resource if query could be executed. It returns FALSE on failure or if connection is not a valid connection. Details about the error can be retrieved using the pg_last_error() function if connection is valid. pg_query() sends an SQL statement to the PostgreSQL database specified by the connection resource. The connection must be a valid connection that was returned by pg_connect() or pg_pconnect(). The return value of this function is an query result resource to be used to access the results from other PostgreSQL functions such as pg_fetch_array().

Megjegyzés: connection is an optional parameter for pg_query(). If connection is not set, default connection is used. Default connection is the last connection made by pg_connect() or pg_pconnect().

Although connection can be omitted, it is not recommended, since it could be a cause of hard to find bug in script.

Megjegyzés: 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.

See also pg_connect(), pg_pconnect(), pg_fetch_array(), pg_fetch_object(), pg_num_rows() and pg_affected_rows().

pg_result_error

(PHP 4 >= 4.2.0)

pg_result_error --  Get error message associated with result

Description

string pg_result_error ( resource result)

pg_result_error() returns error message associated with result resource. Therefore, user has better chance to get better error message than pg_last_error().

See also pg_query(), pg_send_query(), pg_get_result(), pg_last_error() and pg_last_notice()

pg_result_seek

(PHP 4 >= 4.3.0)

pg_result_seek -- Set internal row offset in result resource

Description

array pg_result_seek ( resource result, int offset)

pg_result_seek() set internal row offset in result resource. It returns FALSE, if there is error.

See also pg_fetch_row(), pg_fetch_assoc(), pg_fetch_array(), pg_fetch_object() and pg_fetch_result().

pg_result_status

(PHP 4 >= 4.2.0)

pg_result_status --  Get status of query result

Description

int pg_result_status ( resource result)

pg_result_status() returns status of result resource. Possible return values are PGSQL_EMPTY_QUERY, PGSQL_COMMAND_OK, PGSQL_TUPLES_OK, PGSQL_COPY_TO, PGSQL_COPY_FROM, PGSQL_BAD_RESPONSE, PGSQL_NONFATAL_ERROR and PGSQL_FATAL_ERROR.

See also pg_connection_status().

pg_select

(PHP 4 >= 4.3.0)

pg_select --  Select records.

Description

array pg_select ( resource connection, string table_name, array assoc_array [, int options])

pg_select() selects records specified by assoc_array which has field=>value. For successful query, it returns array contains all records and fields that match the condition specified by assoc_array. If options is specified, pg_convert() is applied to assoc_array with specified option.

Példa 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";
    }
?>

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

See also pg_convert()

pg_send_query

(PHP 4 >= 4.2.0)

pg_send_query --  Sends asynchronous query

Description

bool pg_send_query ( resource connection, string query)

bool pg_send_query ( string query)

pg_send_query() send asynchronous query to the connection. Unlike pg_query(), it can send multiple query to PostgreSQL and get the result one by one using pg_get_result(). Script execution is not blocked while query is executing. Use pg_connection_busy() to check connection is busy (i.e. query is executing). Query may be cancelled by calling pg_cancel_query().

Although user can send multiple query at once, user cannot send multiple query over busy connection. If query is sent while connection is busy, it waits until last query is finished and discards all result.

Példa 1. Asynchronous Queries

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

The above example would produce the following output:

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

See also pg_query(), pg_cancel_query(), pg_get_result() and pg_connection_busy().

pg_set_client_encoding

(PHP 3 CVS only, PHP 4 >= 4.0.3)

pg_set_client_encoding --  Set the client encoding

Description

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.

encoding is the client encoding and can be either : SQL_ASCII, EUC_JP, EUC_CN, EUC_KR, EUC_TW, UNICODE, MULE_INTERNAL, LATINX (X=1...9), KOI8, WIN, ALT, SJIS, BIG5, WIN1250. Available encoding depends on your PostgreSQL and libpq version. Refer to PostgreSQL manual for supported encodings for your PostgreSQL.

Megjegyzés: This function requires PHP-4.0.3 or higher and PostgreSQL-7.0 or higher. Supported encoding depends on PostgreSQL version. Refer to PostgreSQL manual for details.

The function used to be called pg_setclientencoding().

See also pg_client_encoding().

pg_trace

(PHP 4 >= 4.0.1)

pg_trace -- PostgreSQL szerver kapcsolatot követ nyomon

Leírás

bool pg_trace ( string filename [, string mode [, int connection]])

Engedélyezi a PostgreSQL felület kommunikációinak nyomkövetését egy fileba. Ahhoz, hogy megértsd az eredményeket, meg kell barátkoznod a PostgreSQL kommunikációs protokolljával. Ha nem ismeret a protokollt, hasznos lehet akkor is nyomon követni a szerverhez küldött kérések hibáit; például 'grep '^To backend' trace.log' paranccsal megnézni, hogy milyen kéréseket küldtek a PostgreSQL szervernek.

A filename és a mode paraméterek azonosak a fopen() függvényéhez (a mode alapértelmezése 'w'), connection határozza meg a nyomon követendő kapcsolatot; az utoljára megnyitot kapcsolat az alapértelmezett.

TRUE-val tér vissza, ha a filename paraméterben megadott filet meg lehet nyitni loggolásra, egyébként FALSE-szal tér vissza.

Lásd még a fopen() és a pg_untrace() függvényeket.

pg_tty

(PHP 3, PHP 4 )

pg_tty -- A tty nevét adja vissza

Leírás

string pg_tty ( int connection_id)

A pg_tty() függvény a tty nevét adja vissza, amelyre az adott azonosítójú kapcsolat szerver oldali nyomkövetésének kimenete kerül.

pg_unescape_bytea

(PHP 4 >= 4.3.0)

pg_unescape_bytea --  Unescape binary for bytea type

Description

string pg_unescape_bytea ( string data)

pg_unescape_bytea() unescapes string from bytea datatype. It returns unescaped string (binary).

Megjegyzés: When you SELECT bytea type, PostgreSQL returns octal byte value prefixed by \ (e.g. \032). Users are supposed to convert back to binary format by yourself.

This function requires PostgreSQL 7.2 or later. With PostgreSQL 7.2.0 and 7.2.1, bytea type must be casted 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 cast. Exception is when client and backend character encoding does not match, there may be multi-byte stream error. User must cast to bytea to avoid this error.

See also pg_escape_bytea() and pg_escape_string()

pg_untrace

(PHP 4 >= 4.0.1)

pg_untrace -- Abbahagyja az adott kapcsolat nyomkövetését

Leírás

bool pg_untrace ( [int connection])

A pg_trace() által elindított nyomkövetést szünteti meg. A connection paraméter határozza meg, hogy mely kapcsolat nyomkövetését kell abbahagyni. Az alapértelmezés az utoljára megnyitott kapcsolat.

Mindig TRUE-val tér vissza.

Lásd még a pg_trace() függvényt.

pg_update

(PHP 4 >= 4.3.0)

pg_update --  Update table.

Description

mixed pg_update ( resource connection, string table_name, array data, array condition [, int options])

pg_update() updates records that matches condition with data. If options is specified, pg_convert() is applied to data with specified options.

Példa 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";
    }
?>

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

See also pg_convert().

LXXXV. Process Control Functions

Bevezetés

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 webserver environment and unexpected results may happen if any Process Control functions are used within a webserver 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().

Megjegyzés: Ez a kiterjesztés nem működik Windows operációs rendszereken!


Követelmények

Az itt leírt függvények használatához semmilyen külső függvénykönyvtár megléte nem szükségeltetik.


Telepítés

Process Control support in PHP is not enabled by default. You have to compile the CGI or CLI version of PHP with --enable-pcntl configuration option when compiling PHP to enable Process Control support.

Megjegyzés: Currently, this module will not function on non-Unix platforms (Windows).


Futásidejű beállítások

Ez a kiterjesztés semmilyen konfigurációs beállításokat nem definiál a php.ini állományban.


Erőforrás típusok

Ez a kiterjesztés semmilyen erőforrás típust nem definiál.


Előre definiált állandók

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)


Példák

This example forks off a daemon process with a signal handler.

Példa 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()) {
    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
     }

}

?>

Lásd még

A look at the section about POSIX functions may be useful.

Tartalom
pcntl_exec --  Executes specified program in current process space
pcntl_fork -- Forks the currently running process
pcntl_signal -- Installs a signal handler
pcntl_waitpid -- Waits on or returns the status of a forked child
pcntl_wexitstatus --  Returns the return code of a terminated child
pcntl_wifexited --  Returns TRUE if status code represents a successful exit
pcntl_wifsignaled --  Returns TRUE if status code represents a termination due to a signal
pcntl_wifstopped --  Returns TRUE if 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

pcntl_exec

(PHP 4 >= 4.2.0)

pcntl_exec --  Executes specified program in current process space

Description

bool pcntl_exec ( string path [, array args [, array envs]])

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

pcntl_fork

(PHP 4 >= 4.1.0)

pcntl_fork -- Forks the currently running process

Description

int pcntl_fork ( void )

The pcntl_fork() function creates a child process that differs from the parent process only in it's PID and PPID. Please see your system's fork(2) man page for specific details as to how fork works on your system.

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.

Példa 1. pcntl_fork() example

<?php

$pid = pcntl_fork();
if ($pid == -1) {
     die("could not fork");
} else if ($pid) {
     // we are the parent
} else {
     // we are the child
}

?>

See also pcntl_waitpid() and pcntl_signal().

pcntl_signal

(PHP 4 >= 4.1.0)

pcntl_signal -- Installs a signal handler

Description

bool pcntl_signal ( int signo, callback handle [, bool restart_syscalls])

The pcntl_signal() function installs a new signal handler for the signal indicated by signo. The signal handler is set to handler which may be the name of a user created function, or either of the two global constants SIG_IGN or SIG_DFL. The optional restart_syscalls specifies whether system call restarting should be used when this signal arrives and defaults to TRUE.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Megjegyzés: The optional restart_syscalls parameter became available in PHP 4.3.0.

Megjegyzés: The ability to use an object method as a callback became available in PHP 4.3.0. 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.

Példa 1. pcntl_signal() example

<?php
// tick use required as of PHP 4.3.0
declare(ticks = 1);

// signal handler function
function sig_handler($signo) 
{

     switch ($signo) {
         case SIGTERM:
             // handle shutdown tasks
             exit;
             break;
         case SIGHUP:
             // handle restart tasks
             break;
         case SIGUSR1:
             echo "Caught SIGUSR1...\n";
             break;
         default:
             // handle all other signals
     }

}

echo "Installing signal handler...\n";

// setup signal handlers
pcntl_signal(SIGTERM, "sig_handler");
pcntl_signal(SIGHUP,  "sig_handler");
pcntl_signal(SIGUSR1, "sig_handler");

// or use an object, available as of PHP 4.3.0
// pcntl_signal(SIGUSR1, array($obj, "do_something");

echo"Generating signal SIGTERM to self...\n";

// send SIGUSR1 to current process id
posix_kill(posix_getpid(), SIGUSR1);

echo "Done\n"

?>

See also pcntl_fork() and pcntl_waitpid().

pcntl_waitpid

(PHP 4 >= 4.1.0)

pcntl_waitpid -- Waits on or returns the status of a forked child

Description

int pcntl_waitpid ( int pid, int &status, int options)

The pcntl_waitpid() function 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.

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

The value of pid can be one of the following:

Táblázat 1. 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.

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

The value of options is the value of zero or more of the following two global constants OR'ed together:

Táblázat 2. 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.

See also pcntl_fork(), pcntl_signal(), pcntl_wifexited(), pcntl_wifstopped(), pcntl_wifsignaled(), pcntl_wexitstatus(), pcntl_wtermsig() and pcntl_wstopsig().

pcntl_wexitstatus

(PHP 4 >= 4.1.0)

pcntl_wexitstatus --  Returns the return code of a terminated child

Description

int pcntl_wexitstatus ( int status)

Returns the return code of a terminated child. This function is only useful if pcntl_wifexited() returned TRUE.

The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().

See also pcntl_waitpid() and pcntl_wifexited().

pcntl_wifexited

(PHP 4 >= 4.1.0)

pcntl_wifexited --  Returns TRUE if status code represents a successful exit

Description

int pcntl_wifexited ( int status)

Returns TRUE if the child status code represents a successful exit.

The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().

See also pcntl_waitpid() and pcntl_wexitstatus().

pcntl_wifsignaled

(PHP 4 >= 4.1.0)

pcntl_wifsignaled --  Returns TRUE if status code represents a termination due to a signal

Description

int pcntl_wifsignaled ( int status)

Returns TRUE if the child process exited because of a signal which was not caught.

The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().

See also pcntl_waitpid() and pcntl_signal().

pcntl_wifstopped

(PHP 4 >= 4.1.0)

pcntl_wifstopped --  Returns TRUE if child process is currently stopped

Description

int pcntl_wifstopped ( int status)

Returns TRUE if 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.

The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().

See also pcntl_waitpid().

pcntl_wstopsig

(PHP 4 >= 4.1.0)

pcntl_wstopsig --  Returns the signal which caused the child to stop

Description

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.

The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().

See also pcntl_waitpid() and pcntl_wifstopped().

pcntl_wtermsig

(PHP 4 >= 4.1.0)

pcntl_wtermsig --  Returns the signal which caused the child to terminate

Description

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.

The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().

See also pcntl_waitpid(), pcntl_signal() and pcntl_wifsignaled().

LXXXVI. Programfuttató függvények

Ezek a függvények különböző külső program futtatására adnak lehetőséget, vagy segítik biztonságosabbá tenni ezeket a hívásokat. Érdemes megnézned a végrehajtó operátort is.

Tartalom
escapeshellarg -- Shell paraméterként átadandó karakterláncot állít elő
escapeshellcmd -- Shell metakaraktereket alakít át
exec -- Külső programot futtat
passthru --  Külső programot futtat, és a kimenetet feldolgozás nélküli jeleníti meg
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 --  lefuttat parancsértelmezőben egy parancsot és a teljes kimenetet visszaadja
system --  Külső programot futtat, és a kimenetet megjeleníti

escapeshellarg

(PHP 4 >= 4.0.3)

escapeshellarg -- Shell paraméterként átadandó karakterláncot állít elő

Leírás

string escapeshellarg ( string arg)

Az escapeshellarg() aposztrófok közé fogja az arg paraméterben átadott szöveget és megkettőzi a benne lévő aposztrófokat, így egy parancsértelmező függvények önálló paramétereként használható karaktersorozatot ad vissza. Ez a függvény használatos a felhasználótól érkező egyedi parancsértelmező függvények paramétereinek biztonságossá alakítására. Ezek a fügvények : az exec(), a system() és a végrehajtó operátor. Jellemző használata:

system("ls ".escapeshellarg($dir));

Lásd még: exec(), popen(), system() és a végrehajtó operátor!

escapeshellcmd

(PHP 3, PHP 4 )

escapeshellcmd -- Shell metakaraktereket alakít át

Leírás

string escapeshellcmd ( string command)

Az escapeshellcmd() escape-et alkalmaz minden speciális karakterre, ami nem kívánt parancsok futtatását okozná. Ez a függvény arra használható, hogy biztosítsd a felhasználótól érkező adat tisztaságát egy exec() vagy egy system() függényhívásnál, vagy egy végrehajtó operátorban használnád. Általános használati forma:

$e = escapeshellcmd($parancs);
system("echo $e"); // itt mindegy, hogy az $e tartalmaz-e szóközt
$f = escapeshellcmd($filenev);
system("touch \"/tmp/$f\"; ls -l \"/tmp/$f\""); // itt viszont nem, ezért van idézőjelben

Lásd még: escapeshellarg(), exec(), popen(), system() és a végrehajtó operátor!

exec

(PHP 3, PHP 4 )

exec -- Külső programot futtat

Leírás

string exec ( string command [, array array [, int return_var]])

Az exec() lefuttatja a command-ban megadott parancsot, amely így nem ír ki semmit, csak egyszerűen visszaadja a legutolsó sort, amit a parancs generált. A passthru() függvény használható arra, hogy a parancs eredménye minden adatfeldolgozás nélkül kiírása kerüljön.

Az array paraméter megadásával a program kimenetét a PHP soronként a megadott tömb végéhez fűzi. Ha az átadott tömb már tartalmaz néhány elemet, akkor az exec() a benne lévő adatok után fűzi a sorokat. Ha nincs szükség a régi elemekre, akkor az unset() függvénnyel lehet törölni az egész tömböt, az exec() meghívása előtt.

Az array paraméterrel együtt a return_var a futtatott parancs visszatérési állapotát tárolja el.

Figyelem

Ha felhasználótól származó adatot kell átadni ennek a függvénynek, akkor előtte használd az escapeshellcmd() függvényt, annak biztosítására, hogy nem tudnak a felhasználók tetszőleges parancsot futtatni.

Megjegyzés: Ezzel a függvénnyel elindított de háttérben futó program kimenetét mindenképpen fájlba vagy valamilyen más kimeneti csatornába kell átirányítani. Ellenkező esetben a PHP várakozni fog addig, amíg a program futása be nem fejeződik.

Lásd még: system(), passthru(), popen(), escapeshellcmd() és a végrehajtó operátor!

passthru

(PHP 3, PHP 4 )

passthru --  Külső programot futtat, és a kimenetet feldolgozás nélküli jeleníti meg

Leírás

void passthru ( string command [, int return_var])

A passthru() függvény hasonló az exec()-hez, ugyanis a command paraméterben megadott parancsot futtatja. A return_var paraméterben a parancs visszatérési állapota kerül. Ez a függvény használható az exec() vagy a system() helyett, ha a parancs kimenete bináris adat, amit közvetlenül a böngészőnek kell visszaküldeni. Tipikusan például a pbmplus eszközök futtatására használható, amelyek képesek közvetlenül kép visszaadására. A Content-type fejlécet image/gif-re állítva és a pbmplus programot meghívva, az visszaad egy képet, és így olyan PHP programot írhatók, amelyek közvetlenül képeket adnak vissza.

Figyelem

Ha felhasználótól származó adatot kell átadni ennek a függvénynek, akkor előtte használd az escapeshellcmd() függvényt, annak biztosítására, hogy nem tudnak a felhasználók tetszőleges parancsot futtatni.

Megjegyzés: Ezzel a függvénnyel elindított de háttérben futó program kimenetét mindenképpen fájlba vagy valamilyen más kimeneti csatornába kell átirányítani. Ellenkező esetben a PHP várakozni fog addig, amíg a program futása be nem fejeződik.

Lásd még: exec(), system(), popen(), escapeshellcmd() és a végrehajtó operátor!

proc_close

(PHP 4 >= 4.3.0)

proc_close --  Close a process opened by proc_open() and return the exit code of that process.

Description

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

proc_get_status

(PHP 5 CVS only)

proc_get_status --  Get information about a process opened by proc_open()

Description

array proc_get_status ( resource process)

proc_get_status() fetches data about a process opened using proc_open(). The collected information is returned in an array containing the following elements:

elementtypedescription
commandstringThe command string that was passed to proc_open()
pidintprocess id
runningbool TRUE if the process is still running, FALSE if it has terminated
signaledbool TRUE if the child process has been terminated by an uncaught signal. Always set to FALSE on Windows.
stoppedbool TRUE if the child process has been stopped by a signal. Always set to FALSE on Windows.
exitcodeint the exit code returned by the process (which is only meaningful if running is FALSE)
termsigint the number of the signal that caused the child process to terminate its execution (only meaningful if signaled is TRUE)
stopsigint the number of the signal that caused the child process to stop its execution (only meaningful if stopped is TRUE)

See also proc_open().

proc_nice

(PHP 5 CVS only)

proc_nice --  Change the priority of the current process

Description

bool proc_nice ( int priority)

proc_nice() changes the priority of the current process. If an error occurs, like the user lacks permission to change the priority, an error of level E_WARNING is generated and FALSE is returned. Otherwise, TRUE is returned.

Megjegyzés: proc_nice() will only exist if your system has 'nice' capabilities. 'nice' conforms to: SVr4, SVID EXT, AT&T, X/OPEN, BSD 4.3. This means that proc_nice() is not available on Windows.

proc_nice() is not related to proc_open() and its associated functions in any way.

proc_open

(PHP 4 >= 4.3.0)

proc_open --  Execute a command and open file pointers for input/output

Description

resource proc_open ( string cmd, array descriptorspec, array pipes)

proc_open() is similar to popen() but provides a much greater degree of control over the program execution. cmd is the command to be executed by the shell. descriptorspec is an indexed array where the key represents the descriptor number and the value represents how PHP will pass that descriptor to the child process. pipes will be set to an indexed array of file pointers that correspond to PHP's end of any pipes that are created. The return value is a resource representing the process; you should free it using proc_close() when you are finished with it.

<?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
);
$process = proc_open("php", $descriptorspec, $pipes);
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 echo \"Hello World!\"; ?>");
    fclose($pipes[0]);

    while (!feof($pipes[1])) {
        echo fgets($pipes[1], 1024);
    }
    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";
}
?>

The file descriptor numbers in descriptorspec 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.

Megjegyzés: 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.

Megjegyzés: If you only need a uni-directional (one-way) process pipe, use popen() instead, as it is much easier to use.

See also stream_select(), exec(), system(), passthru(), popen(), escapeshellcmd(), and the backtick operator.

proc_terminate

(PHP 5 CVS only)

proc_terminate --  kills a process opened by proc_open

Description

int proc_terminate ( resource process [, int signal])

Signals a process (created using proc_open()) that it should terminate. proc_terminate() returns immediately and does not wait for the process to terminate.

The optional signal 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.

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.

See also proc_open(), proc_close(), and proc_get_status().

shell_exec

(PHP 4 )

shell_exec --  lefuttat parancsértelmezőben egy parancsot és a teljes kimenetet visszaadja

Leírás

string shell_exec ( string cmd)

Ez a függvény azonos a végrehajtó operátorral.

system

(PHP 3, PHP 4 )

system --  Külső programot futtat, és a kimenetet megjeleníti

Leírás

string system ( string command [, int return_var])

A system() függvény olyan, mint C-beli társa, azaz a command paraméterben megadott parancsot futtaja, és kiírja a kimenetet. A return_var paraméterben a parancs visszatérési állapota kerülhet, ha szerepel.

Figyelem

Ha felhasználótól származó adatot kell átadni ennek a függvénynek, akkor előtte használd az escapeshellcmd() függvényt, annak biztosítására, hogy nem tudnak a felhasználók tetszőleges parancsot futtatni.

Megjegyzés: Ezzel a függvénnyel elindított de háttérben futó program kimenetét mindenképpen fájlba vagy valamilyen más kimeneti csatornába kell átirányítani. Ellenkező esetben a PHP várakozni fog addig, amíg a program futása be nem fejeződik.

A system() függvény automatikusan üríteni próbálja a szerver kimeneti pufferét minden kiadott sor után, ha a PHP szerver modulként fut.

Visszaadja a parancs kimenetének utolsó sorát siker esetén, vagy FALSE értéket ha hiba történik.

A passthru() függvény használható arra, hogy a parancs eredménye minden adatfeldolgozás nélkül kiírása kerüljön.

Lásd még: exec(), passthru(), popen(), escapeshellcmd() és a végrehajtó operátor!

LXXXVII. Printer functions

Bevezetés

These functions are only available under Windows 9.x, ME, NT4 and 2000. They have been added in PHP 4.0.4.


Telepítés

Add the line extension=php_printer.dll to your php.ini file.


Futásidejű beállítások

Az alábbi függvények viselkedése befolyásolható a php.ini segítségével.

Táblázat 1. Printer configuration options

NameDefaultChangeable
printer.default_printer""PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().

Tartalom
printer_abort -- Deletes the printer's spool file
printer_close -- Close an open printer connection
printer_create_brush -- Create a new brush
printer_create_dc -- Create a new device context
printer_create_font -- Create a new font
printer_create_pen -- Create a new pen
printer_delete_brush -- Delete a brush
printer_delete_dc -- Delete a device context
printer_delete_font -- Delete a font
printer_delete_pen -- Delete a pen
printer_draw_bmp -- Draw a bmp
printer_draw_chord -- Draw a chord
printer_draw_elipse -- Draw an ellipse
printer_draw_line -- Draw a line
printer_draw_pie -- Draw a pie
printer_draw_rectangle -- Draw a rectangle
printer_draw_roundrect -- Draw a rectangle with rounded corners
printer_draw_text -- Draw text
printer_end_doc -- Close document
printer_end_page -- Close active page
printer_get_option -- Retrieve printer configuration data
printer_list -- Return an array of printers attached to the server
printer_logical_fontheight -- Get logical font height
printer_open -- Open connection to a printer
printer_select_brush -- Select a brush
printer_select_font -- Select a font
printer_select_pen -- Select a pen
printer_set_option -- Configure the printer connection
printer_start_doc -- Start a new document
printer_start_page -- Start a new page
printer_write -- Write data to the printer

printer_abort

(no version information, might be only in CVS)

printer_abort -- Deletes the printer's spool file

Description

void printer_abort ( resource handle)

This function deletes the printers spool file.

handle must be a valid handle to a printer.

Példa 1. printer_abort() example

<?php
$handle = printer_open();
printer_abort($handle);
printer_close($handle);
?>

printer_close

(no version information, might be only in CVS)

printer_close -- Close an open printer connection

Description

void printer_close ( resource handle)

This function closes the printer connection. printer_close() also closes the active device context.

handle must be a valid handle to a printer.

Példa 1. printer_close() example

<?php
$handle = printer_open();
printer_close($handle);
?>

printer_create_brush

(no version information, might be only in CVS)

printer_create_brush -- Create a new brush

Description

mixed printer_create_brush ( int style, string color)

The function creates a new brush and returns a handle to it. A brush is used to fill shapes. For an example see printer_select_brush(). color must be a color in RGB hex format, i.e. "000000" for black, style must be one of the following constants:

  • PRINTER_BRUSH_SOLID: creates a brush with a solid color.

  • PRINTER_BRUSH_DIAGONAL: creates a brush with a 45-degree upward left-to-right hatch ( / ).

  • PRINTER_BRUSH_CROSS: creates a brush with a cross hatch ( + ).

  • PRINTER_BRUSH_DIAGCROSS: creates a brush with a 45 cross hatch ( x ).

  • PRINTER_BRUSH_FDIAGONAL: creates a brush with a 45-degree downward left-to-right hatch ( \ ).

  • PRINTER_BRUSH_HORIZONTAL: creates a brush with a horizontal hatch ( - ).

  • PRINTER_BRUSH_VERTICAL: creates a brush with a vertical hatch ( | ).

  • PRINTER_BRUSH_CUSTOM: creates a custom brush from an BMP file. The second parameter is used to specify the BMP instead of the RGB color code.

printer_create_dc

(no version information, might be only in CVS)

printer_create_dc -- Create a new device context

Description

void printer_create_dc ( resource handle)

The function creates a new device context. A device context is used to customize the graphic objects of the document. handle must be a valid handle to a printer.

Példa 1. printer_create_dc() example

<?php
$handle = printer_open();
printer_start_doc($handle);
printer_start_page($handle);

printer_create_dc($handle);
/* do some stuff with the dc */
printer_set_option($handle, PRINTER_TEXT_COLOR, "333333");
printer_draw_text($handle, 1, 1, "text");
printer_delete_dc($handle);

/* create another dc */
printer_create_dc($handle);
printer_set_option($handle, PRINTER_TEXT_COLOR, "000000");
printer_draw_text($handle, 1, 1, "text");
/* do some stuff with the dc */

printer_delete_dc($handle);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?>

printer_create_font

(no version information, might be only in CVS)

printer_create_font -- Create a new font

Description

mixed printer_create_font ( string face, int height, int width, int font_weight, bool italic, bool underline, bool strikeout, int orientaton)

The function creates a new font and returns a handle to it. A font is used to draw text. For an example see printer_select_font(). face must be a string specifying the font face. height specifies the font height, and width the font width. The font_weight specifies the font weight (400 is normal), and can be one of the following predefined constants.

  • PRINTER_FW_THIN: sets the font weight to thin (100).

  • PRINTER_FW_ULTRALIGHT: sets the font weight to ultra light (200).

  • PRINTER_FW_LIGHT: sets the font weight to light (300).

  • PRINTER_FW_NORMAL: sets the font weight to normal (400).

  • PRINTER_FW_MEDIUM: sets the font weight to medium (500).

  • PRINTER_FW_BOLD: sets the font weight to bold (700).

  • PRINTER_FW_ULTRABOLD: sets the font weight to ultra bold (800).

  • PRINTER_FW_HEAVY: sets the font weight to heavy (900).

italic can be TRUE or FALSE, and sets whether the font should be italic.

underline can be TRUE or FALSE, and sets whether the font should be underlined.

strikeout can be TRUE or FALSE, and sets whether the font should be stroked out.

orientation specifies a rotation. For an example see printer_select_font().

printer_create_pen

(no version information, might be only in CVS)

printer_create_pen -- Create a new pen

Description

mixed printer_create_pen ( int style, int width, string color)

The function creates a new pen and returns a handle to it. A pen is used to draw lines and curves. For an example see printer_select_pen(). color must be a color in RGB hex format, i.e. "000000" for black, width specifies the width of the pen whereas style must be one of the following constants:

  • PRINTER_PEN_SOLID: creates a solid pen.

  • PRINTER_PEN_DASH: creates a dashed pen.

  • PRINTER_PEN_DOT: creates a dotted pen.

  • PRINTER_PEN_DASHDOT: creates a pen with dashes and dots.

  • PRINTER_PEN_DASHDOTDOT: creates a pen with dashes and double dots.

  • PRINTER_PEN_INVISIBLE: creates an invisible pen.

printer_delete_brush

(no version information, might be only in CVS)

printer_delete_brush -- Delete a brush

Description

bool printer_delete_brush ( resource handle)

The function deletes the selected brush. For an example see printer_select_brush(). Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad. handle must be a valid handle to a brush.

printer_delete_dc

(no version information, might be only in CVS)

printer_delete_dc -- Delete a device context

Description

bool printer_delete_dc ( resource handle)

The function deletes the device context. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad. For an example see printer_create_dc(). handle must be a valid handle to a printer.

printer_delete_font

(no version information, might be only in CVS)

printer_delete_font -- Delete a font

Description

bool printer_delete_font ( resource handle)

The function deletes the selected font. For an example see printer_select_font(). Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad. handle must be a valid handle to a font.

printer_delete_pen

(no version information, might be only in CVS)

printer_delete_pen -- Delete a pen

Description

bool printer_delete_pen ( resource handle)

The function deletes the selected pen. For an example see printer_select_pen(). Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad. handle must be a valid handle to a pen.

printer_draw_bmp

(no version information, might be only in CVS)

printer_draw_bmp -- Draw a bmp

Description

void printer_draw_bmp ( resource handle, string filename, int x, int y)

The function simply draws an bmp the bitmap filename at position x, y. handle must be a valid handle to a printer.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Példa 1. printer_draw_bmp() example

<?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

printer_draw_bmp($handle, "c:\\image.bmp", 1, 1);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?>

printer_draw_chord

(no version information, might be only in CVS)

printer_draw_chord -- Draw a chord

Description

void printer_draw_chord ( resource handle, int rec_x, int rec_y, int rec_x1, int rec_y1, int rad_x, int rad_y, int rad_x1, int rad_y1)

The function simply draws an chord. handle must be a valid handle to a printer.

rec_x is the upper left x coordinate of the bounding rectangle.

rec_y is the upper left y coordinate of the bounding rectangle.

rec_x1 is the lower right x coordinate of the bounding rectangle.

rec_y1 is the lower right y coordinate of the bounding rectangle.

rad_x is x coordinate of the radial defining the beginning of the chord.

rad_y is y coordinate of the radial defining the beginning of the chord.

rad_x1 is x coordinate of the radial defining the end of the chord.

rad_y1 is y coordinate of the radial defining the end of the chord.

Példa 1. printer_draw_chord() example

<?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 2, "000000");
printer_select_pen($handle, $pen);

$brush = printer_create_brush(PRINTER_BRUSH_SOLID, "2222FF");
printer_select_brush($handle, $brush);

printer_draw_chord($handle, 1, 1, 500, 500, 1, 1, 500, 1);

printer_delete_brush($brush);
printer_delete_pen($pen);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);   
?>

printer_draw_elipse

(no version information, might be only in CVS)

printer_draw_elipse -- Draw an ellipse

Description

void printer_draw_elipse ( resource handle, int ul_x, int ul_y, int lr_x, int lr_y)

The function simply draws an ellipse. handle must be a valid handle to a printer.

ul_x is the upper left x coordinate of the ellipse.

ul_y is the upper left y coordinate of the ellipse.

lr_x is the lower right x coordinate of the ellipse.

lr_y is the lower right y coordinate of the ellipse.

Példa 1. printer_draw_elipse() example

<?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 2, "000000");
printer_select_pen($handle, $pen);

$brush = printer_create_brush(PRINTER_BRUSH_SOLID, "2222FF");
printer_select_brush($handle, $brush);

printer_draw_elipse($handle, 1, 1, 500, 500);

printer_delete_brush($brush);
printer_delete_pen($pen);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);     
?>

printer_draw_line

(no version information, might be only in CVS)

printer_draw_line -- Draw a line

Description

void printer_draw_line ( resource printer_handle, int from_x, int from_y, int to_x, int to_y)

The function simply draws a line from position from_x, from_y to position to_x, to_y using the selected pen. printer_handle must be a valid handle to a printer.

Példa 1. printer_draw_line() example

<?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 30, "000000");
printer_select_pen($handle, $pen);

printer_draw_line($handle, 1, 10, 1000, 10);
printer_draw_line($handle, 1, 60, 500, 60);

printer_delete_pen($pen);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?>

printer_draw_pie

(no version information, might be only in CVS)

printer_draw_pie -- Draw a pie

Description

void printer_draw_pie ( resource handle, int rec_x, int rec_y, int rec_x1, int rec_y1, int rad1_x, int rad1_y, int rad2_x, int rad2_y)

The function simply draws an pie. handle must be a valid handle to a printer.

rec_x is the upper left x coordinate of the bounding rectangle.

rec_y is the upper left y coordinate of the bounding rectangle.

rec_x1 is the lower right x coordinate of the bounding rectangle.

rec_y1 is the lower right y coordinate of the bounding rectangle.

rad1_x is x coordinate of the first radial's ending.

rad1_y is y coordinate of the first radial's ending.

rad2_x is x coordinate of the second radial's ending.

rad2_y is y coordinate of the second radial's ending.

Példa 1. printer_draw_pie() example

<?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 2, "000000");
printer_select_pen($handle, $pen);

$brush = printer_create_brush(PRINTER_BRUSH_SOLID, "2222FF");
printer_select_brush($handle, $brush);

printer_draw_pie($handle, 1, 1, 500, 500, 1, 1, 500, 1);

printer_delete_brush($brush);
printer_delete_pen($pen);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle); 
?>

printer_draw_rectangle

(no version information, might be only in CVS)

printer_draw_rectangle -- Draw a rectangle

Description

void printer_draw_rectangle ( resource handle, int ul_x, int ul_y, int lr_x, int lr_y)

The function simply draws a rectangle.

handle must be a valid handle to a printer.

ul_x is the upper left x coordinate of the rectangle.

ul_y is the upper left y coordinate of the rectangle.

lr_x is the lower right x coordinate of the rectangle.

lr_y is the lower right y coordinate of the rectangle.

Példa 1. printer_draw_rectangle() example

<?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 2, "000000");
printer_select_pen($handle, $pen);

$brush = printer_create_brush(PRINTER_BRUSH_SOLID, "2222FF");
printer_select_brush($handle, $brush);

printer_draw_rectangle($handle, 1, 1, 500, 500);

printer_delete_brush($brush);
printer_delete_pen($pen);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?>

printer_draw_roundrect

(no version information, might be only in CVS)

printer_draw_roundrect -- Draw a rectangle with rounded corners

Description

void printer_draw_roundrect ( resource handle, int ul_x, int ul_y, int lr_x, int lr_y, int width, int height)

The function simply draws a rectangle with rounded corners.

handle must be a valid handle to a printer.

ul_x is the upper left x coordinate of the rectangle.

ul_y is the upper left y coordinate of the rectangle.

lr_x is the lower right x coordinate of the rectangle.

lr_y is the lower right y coordinate of the rectangle.

width is the width of the ellipse.

height is the height of the ellipse.

Példa 1. printer_draw_roundrect() example

<?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 2, "000000");
printer_select_pen($handle, $pen);

$brush = printer_create_brush(PRINTER_BRUSH_SOLID, "2222FF");
printer_select_brush($handle, $brush);

printer_draw_roundrect($handle, 1, 1, 500, 500, 200, 200);

printer_delete_brush($brush);
printer_delete_pen($pen);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?>

printer_draw_text

(no version information, might be only in CVS)

printer_draw_text -- Draw text

Description

void printer_draw_text ( resource printer_handle, string text, int x, int y)

The function simply draws text at position x, y using the selected font. printer_handle must be a valid handle to a printer.

Példa 1. printer_draw_text() example

<?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$font = printer_create_font("Arial", 72, 48, 400, false, false, false, 0);
printer_select_font($handle, $font);
printer_draw_text($handle, "test", 10, 10);
printer_delete_font($font);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?>

printer_end_doc

(no version information, might be only in CVS)

printer_end_doc -- Close document

Description

bool printer_end_doc ( resource handle)

Closes a new document in the printer spooler. The document is now ready for printing. For an example see printer_start_doc(). handle must be a valid handle to a printer.

printer_end_page

(no version information, might be only in CVS)

printer_end_page -- Close active page

Description

bool printer_end_page ( resource handle)

The function closes the active page in the active document. For an example see printer_start_doc(). handle must be a valid handle to a printer.

printer_get_option

(no version information, might be only in CVS)

printer_get_option -- Retrieve printer configuration data

Description

mixed printer_get_option ( resource handle, string option)

The function retrieves the configuration setting of option. handle must be a valid handle to a printer. Take a look at printer_set_option() for the settings that can be retrieved, additionally the following settings can be retrieved:

  • PRINTER_DEVICENAME returns the devicename of the printer.

  • PRINTER_DRIVERVERSION returns the printer driver version.

Példa 1. printer_get_option() example

<?php
$handle = printer_open();
echo printer_get_option($handle, PRINTER_DRIVERVERSION);
printer_close($handle);
?>

printer_list

(no version information, might be only in CVS)

printer_list -- Return an array of printers attached to the server

Description

array printer_list ( int enumtype [, string name [, int level]])

The function enumerates available printers and their capabilities. level sets the level of information request. Can be 1,2,4 or 5. enumtype must be one of the following predefined constants:

  • PRINTER_ENUM_LOCAL: enumerates the locally installed printers.

  • PRINTER_ENUM_NAME: enumerates the printer of name, can be a server, domain or print provider.

  • PRINTER_ENUM_SHARED: this parameter can't be used alone, it has to be OR'ed with other parameters, i.e. PRINTER_ENUM_LOCAL to detect the locally shared printers.

  • PRINTER_ENUM_DEFAULT: (Win9.x only) enumerates the default printer.

  • PRINTER_ENUM_CONNECTIONS: (WinNT/2000 only) enumerates the printers to which the user has made connections.

  • PRINTER_ENUM_NETWORK: (WinNT/2000 only) enumerates network printers in the computer's domain. Only valid if level is 1.

  • PRINTER_ENUM_REMOTE: (WinNT/2000 only) enumerates network printers and print servers in the computer's domain. Only valid if level is 1.

Példa 1. printer_list() example

<?php
/* detect locally shared printer */
var_dump(printer_list(PRINTER_ENUM_LOCAL | PRINTER_ENUM_SHARED));
?>

printer_logical_fontheight

(no version information, might be only in CVS)

printer_logical_fontheight -- Get logical font height

Description

int printer_logical_fontheight ( resource handle, int height)

The function calculates the logical font height of height. handle must be a valid handle to a printer.

Példa 1. printer_logical_fontheight() example

<?php
$handle = printer_open();
echo printer_logical_fontheight($handle, 72);
printer_close($handle);
?>

printer_open

(no version information, might be only in CVS)

printer_open -- Open connection to a printer

Description

mixed printer_open ( [string devicename])

This function tries to open a connection to the printer devicename, and returns a handle on success or FALSE on failure.

If no parameter was given it tries to open a connection to the default printer (if not specified in php.ini as printer.default_printer, PHP tries to detect it).

printer_open() also starts a device context.

Példa 1. printer_open() example

<?php
$handle = printer_open("HP Deskjet 930c");
$handle = printer_open();
?>

printer_select_brush

(no version information, might be only in CVS)

printer_select_brush -- Select a brush

Description

void printer_select_brush ( resource printer_handle, resource brush_handle)

The function selects a brush as the active drawing object of the actual device context. A brush is used to fill shapes. If you draw an rectangle the brush is used to draw the shapes, while the pen is used to draw the border. If you haven't selected a brush before drawing shapes, the shape won't be filled. printer_handle must be a valid handle to a printer. brush_handle must be a valid handle to a brush.

Példa 1. printer_select_brush() example

<?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 2, "000000");
printer_select_pen($handle, $pen);
$brush = printer_create_brush(PRINTER_BRUSH_CUSTOM, "c:\\brush.bmp");
printer_select_brush($handle, $brush);

printer_draw_rectangle($handle, 1, 1, 500, 500);

printer_delete_brush($brush);

$brush = printer_create_brush(PRINTER_BRUSH_SOLID, "000000");
printer_select_brush($handle, $brush);
printer_draw_rectangle($handle, 1, 501, 500, 1001);
printer_delete_brush($brush);

printer_delete_pen($pen);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?>

printer_select_font

(no version information, might be only in CVS)

printer_select_font -- Select a font

Description

void printer_select_font ( resource printer_handle, resource font_handle)

The function selects a font to draw text. printer_handle must be a valid handle to a printer. font_handle must be a valid handle to a font.

Példa 1. printer_select_font() example

<?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$font = printer_create_font("Arial", 148, 76, PRINTER_FW_MEDIUM, false, false, false, -50);
printer_select_font($handle, $font);
printer_draw_text($handle, "PHP is simply cool", 40, 40);
printer_delete_font($font);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?>

printer_select_pen

(no version information, might be only in CVS)

printer_select_pen -- Select a pen

Description

void printer_select_pen ( resource printer_handle, resource pen_handle)

The function selects a pen as the active drawing object of the actual device context. A pen is used to draw lines and curves. I.e. if you draw a single line the pen is used. If you draw an rectangle the pen is used to draw the borders, while the brush is used to fill the shape. If you haven't selected a pen before drawing shapes, the shape won't be outlined. printer_handle must be a valid handle to a printer. pen_handle must be a valid handle to a pen.

Példa 1. printer_select_pen() example

<?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 30, "2222FF");
printer_select_pen($handle, $pen);

printer_draw_line($handle, 1, 60, 500, 60);

printer_delete_pen($pen);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?>

printer_set_option

(no version information, might be only in CVS)

printer_set_option -- Configure the printer connection

Description

bool printer_set_option ( resource handle, int option, mixed value)

The function sets the following options for the current connection. handle must be a valid handle to a printer. For option can be one of the following constants:

  • PRINTER_COPIES: sets how many copies should be printed, value must be an integer.

  • PRINTER_MODE: specifies the type of data (text, raw or emf), value must be a string.

  • PRINTER_TITLE: specifies the name of the document, value must be a string.

  • PRINTER_ORIENTATION: specifies the orientation of the paper, value can be either PRINTER_ORIENTATION_PORTRAIT or PRINTER_ORIENTATION_LANDSCAPE

  • PRINTER_RESOLUTION_Y: specifies the y-resolution in DPI, value must be an integer.

  • PRINTER_RESOLUTION_X: specifies the x-resolution in DPI, value must be an integer.

  • PRINTER_PAPER_FORMAT: specifies the a predefined paper format, set value to PRINTER_FORMAT_CUSTOM if you want to specify a custom format with PRINTER_PAPER_WIDTH and PRINTER_PAPER_LENGTH. value can be one of the following constants.

    • PRINTER_FORMAT_CUSTOM: let's you specify a custom paper format.

    • PRINTER_FORMAT_LETTER: specifies standard letter format (8 1/2- by 11-inches).

    • PRINTER_FORMAT_LETTER: specifies standard legal format (8 1/2- by 14-inches).

    • PRINTER_FORMAT_A3: specifies standard A3 format (297- by 420-millimeters).

    • PRINTER_FORMAT_A4: specifies standard A4 format (210- by 297-millimeters).

    • PRINTER_FORMAT_A5: specifies standard A5 format (148- by 210-millimeters).

    • PRINTER_FORMAT_B4: specifies standard B4 format (250- by 354-millimeters).

    • PRINTER_FORMAT_B5: specifies standard B5 format (182- by 257-millimeter).

    • PRINTER_FORMAT_FOLIO: specifies standard FOLIO format (8 1/2- by 13-inch).

  • PRINTER_PAPER_LENGTH: if PRINTER_PAPER_FORMAT is set to PRINTER_FORMAT_CUSTOM, PRINTER_PAPER_LENGTH specifies a custom paper length in mm, value must be an integer.

  • PRINTER_PAPER_WIDTH: if PRINTER_PAPER_FORMAT is set to PRINTER_FORMAT_CUSTOM, PRINTER_PAPER_WIDTH specifies a custom paper width in mm, value must be an integer.

  • PRINTER_SCALE: specifies the factor by which the printed output is to be scaled. the page size is scaled from the physical page size by a factor of scale/100. for example if you set the scale to 50, the output would be half of it's original size. value must be an integer.

  • PRINTER_BACKGROUND_COLOR: specifies the background color for the actual device context, value must be a string containing the rgb information in hex format i.e. "005533".

  • PRINTER_TEXT_COLOR: specifies the text color for the actual device context, value must be a string containing the rgb information in hex format i.e. "005533".

  • PRINTER_TEXT_ALIGN: specifies the text alignment for the actual device context, value can be combined through OR'ing the following constants:

    • PRINTER_TA_BASELINE: text will be aligned at the base line.

    • PRINTER_TA_BOTTOM: text will be aligned at the bottom.

    • PRINTER_TA_TOP: text will be aligned at the top.

    • PRINTER_TA_CENTER: text will be aligned at the center.

    • PRINTER_TA_LEFT: text will be aligned at the left.

    • PRINTER_TA_RIGHT: text will be aligned at the right.

Példa 1. printer_set_option() example

<?php
$handle = printer_open();
printer_set_option($handle, PRINTER_SCALE, 75);
printer_set_option($handle, PRINTER_TEXT_ALIGN, PRINTER_TA_LEFT);
printer_close($handle);
?>

printer_start_doc

(no version information, might be only in CVS)

printer_start_doc -- Start a new document

Description

bool printer_start_doc ( resource handle [, string document])

The function creates a new document in the printer spooler. A document can contain multiple pages, it's used to schedule the print job in the spooler. handle must be a valid handle to a printer. The optional parameter document can be used to set an alternative document name.

Példa 1. printer_start_doc() example

<?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?>

printer_start_page

(no version information, might be only in CVS)

printer_start_page -- Start a new page

Description

bool printer_start_page ( resource handle)

The function creates a new page in the active document. For an example see printer_start_doc(). handle must be a valid handle to a printer.

printer_write

(no version information, might be only in CVS)

printer_write -- Write data to the printer

Description

bool printer_write ( resource handle, string content)

Writes content directly to the printer. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

handle must be a valid handle to a printer.

Példa 1. printer_write() example

<?php
$handle = printer_open();
printer_write($handle, "Text to print");
printer_close($handle);
?>

LXXXVIII. Pspell Functions

Bevezetés

These functions allow you to check the spelling of a word and offer suggestions.

Megjegyzés: Ez a kiterjesztés nem működik Windows operációs rendszereken!


Követelmények

To compile PHP with pspell support, you need the aspell library, available from http://aspell.sourceforge.net/.


Telepítés

If you have the libraries needed add the --with-pspell[=dir] option when compiling PHP.


Futásidejű beállítások

Ez a kiterjesztés semmilyen konfigurációs beállításokat nem definiál a php.ini állományban.


Erőforrás típusok

Ez a kiterjesztés semmilyen erőforrás típust nem definiál.


Előre definiált állandók

Az itt listázott állandókat ez a kiterjesztés definiálja, és csak akkor elérhetőek, ha az adott kiterjesztés be van fordítva a PHP-be, vagy dinamikusan betöltött.

PSPELL_FAST (integer)

PSPELL_NORMAL (integer)

PSPELL_BAD_SPELLERS (integer)

PSPELL_RUN_TOGETHER (integer)

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

pspell_add_to_personal

(PHP 4 >= 4.0.2)

pspell_add_to_personal -- Add the word to a personal wordlist

Description

int 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(). Please, note that this function will not work unless you have pspell .11.2 and aspell .32.5 or later.

Példa 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);
?>

pspell_add_to_session

(PHP 4 >= 4.0.2)

pspell_add_to_session -- Add the word to the wordlist in the current session

Description

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

pspell_check

(PHP 4 >= 4.0.2)

pspell_check -- Check a word

Description

bool pspell_check ( int dictionary_link, string word)

pspell_check() checks the spelling of a word and returns TRUE if the spelling is correct, FALSE if not.

Példa 1. pspell_check()

<?php
$pspell_link = pspell_new("en");

if (pspell_check($pspell_link, "testt")) {
    echo "This is a valid spelling";
} else {
    echo "Sorry, wrong spelling";
}
?>

pspell_clear_session

(PHP 4 >= 4.0.2)

pspell_clear_session -- Clear the current session

Description

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

Példa 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_clear_session($pspell_link);
pspell_save_wordlist($pspell_link);    //"Vlad" will not be saved
?>

pspell_config_create

(PHP 4 >= 4.0.2)

pspell_config_create -- Create a config used to open a dictionary

Description

int pspell_config_create ( string language [, string spelling [, string jargon [, string encoding]]])

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.

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.

The spelling parameter is the requested spelling for languages with more than one spelling such as English. Known values are 'american', 'british', and 'canadian'.

The jargon parameter contains extra information to distinguish two different words lists that have the same language and spelling parameters.

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.

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)

For more information and examples, check out inline manual pspell website:http://aspell.net/.

Példa 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_config_ignore

(PHP 4 >= 4.0.2)

pspell_config_ignore -- Ignore words less than N characters long

Description

int 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 spellchecker. Words less then n characters will be skipped.

Példa 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_mode

(PHP 4 >= 4.0.2)

pspell_config_mode -- Change the mode number of suggestions returned

Description

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

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)

Példa 1. pspell_config_mode()

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

(PHP 4 >= 4.0.2)

pspell_config_personal -- Set a file that contains personal wordlist

Description

int pspell_config_personal ( int dictionary_link, string file)

pspell_config_personal() should be used on a config before calling pspell_new_config(). The personal wordlist will be loaded and used in addition to the standard one after you call pspell_new_config(). If the file does not exist, it will be created. The file is also the file where pspell_save_wordlist() will save personal wordlist to. The file should be writable by whoever PHP runs as (e.g. nobody). Please, note that this function will not work unless you have pspell .11.2 and aspell .32.5 or later.

Példa 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");
?>

pspell_config_repl

(PHP 4 >= 4.0.2)

pspell_config_repl -- Set a file that contains replacement pairs

Description

int pspell_config_repl ( int dictionary_link, string file)

pspell_config_repl() should be used on a config before calling pspell_new_config(). 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. The file should be writable by whoever PHP runs as (e.g. nobody). Please, note that this function will not work unless you have pspell .11.2 and aspell .32.5 or later.

Példa 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");
?>

pspell_config_runtogether

(PHP 4 >= 4.0.2)

pspell_config_runtogether -- Consider run-together words as valid compounds

Description

int pspell_config_runtogether ( int dictionary_link, bool flag)

pspell_config_runtogether() should be used on a config before calling pspell_new_config(). 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.

Példa 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_save_repl

(PHP 4 >= 4.0.2)

pspell_config_save_repl -- Determine whether to save a replacement pairs list along with the wordlist

Description

int pspell_config_save_repl ( int dictionary_link, bool flag)

pspell_config_save_repl() should be used on a config before calling pspell_new_config(). It 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. Please, note that this function will not work unless you have pspell .11.2 and aspell .32.5 or later.

pspell_new_config

(PHP 4 >= 4.0.2)

pspell_new_config -- Load a new dictionary with settings based on a given config

Description

int pspell_new_config ( int config)

pspell_new_config() opens up a new dictionary with settings specified in a config, created with 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().

The config parameter is the one returned by pspell_config_create() when the config was created.

Példa 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_new_personal

(PHP 4 >= 4.0.2)

pspell_new_personal -- Load a new dictionary with personal wordlist

Description

int pspell_new_personal ( string personal, string language [, string spelling [, string jargon [, string encoding [, int mode]]]])

pspell_new_personal() opens up a new dictionary with a personal wordlist and returns the dictionary link identifier for use in other pspell functions. 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().

The personal parameter specifies 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.

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.

The spelling parameter is the requested spelling for languages with more than one spelling such as English. Known values are 'american', 'british', and 'canadian'.

The jargon parameter contains extra information to distinguish two different words lists that have the same language and spelling parameters.

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.

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.

For more information and examples, check out inline manual pspell website:http://aspell.net/.

Példa 1. pspell_new_personal()

<?php
$pspell_link = pspell_new_personal ("/var/dictionaries/custom.pws", 
        "en", "", "", "", PSPELL_FAST|PSPELL_RUN_TOGETHER);
?>

pspell_new

(PHP 4 >= 4.0.2)

pspell_new -- Load a new dictionary

Description

int pspell_new ( string language [, string spelling [, string jargon [, string encoding [, int mode]]]])

pspell_new() opens up a new dictionary and returns the dictionary link identifier for use in other pspell functions.

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.

The spelling parameter is the requested spelling for languages with more than one spelling such as English. Known values are 'american', 'british', and 'canadian'.

The jargon parameter contains extra information to distinguish two different words lists that have the same language and spelling parameters.

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.

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.

For more information and examples, check out inline manual pspell website:http://aspell.net/.

Példa 1. pspell_new()

<?php
$pspell_link = pspell_new("en", "", "", "", 
                           (PSPELL_FAST|PSPELL_RUN_TOGETHER));
?>

pspell_save_wordlist

(PHP 4 >= 4.0.2)

pspell_save_wordlist -- Save the personal wordlist to a file

Description

int pspell_save_wordlist ( int dictionary_link)

pspell_save_wordlist() saves the personal wordlist from the current session. The dictionary has to be open with pspell_new_personal(), and the location of files to be saved specified with pspell_config_personal() and (optionally) pspell_config_repl(). Please, note that this function will not work unless you have pspell .11.2 and aspell .32.5 or later.

Példa 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);
?>

pspell_store_replacement

(PHP 4 >= 4.0.2)

pspell_store_replacement -- Store a replacement pair for a word

Description

int 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. Please, note that this function will not work unless you have pspell .11.2 and aspell .32.5 or later.

Példa 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);
?>

pspell_suggest

(PHP 4 >= 4.0.2)

pspell_suggest -- Suggest spellings of a word

Description

array pspell_suggest ( int dictionary_link, string word)

pspell_suggest() returns an array of possible spellings for the given word.

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

LXXXIX. GNU Readline

A readline() függvények a GNU Readline könyvtár használatát teszik lehetővé PHP-ből. Ezek a függvények egy szerkeszthető parancssort nyújtanak. Például ilyen a Bash, ami a kurzormozgató gombok használatával lehetőséget ad karakterek beszúrására, és a korábban kiadott parancsok visszakérésére. Ezen könyvtár interaktív természetéből fakadóan kis hasznnal bír Web alkalmazások tervezésekor, de hasznos lehet parancssorból futó programok írásakor.

A GNU Readline projekt honlapja a http://cnswww.cns.cwru.edu/~chet/readline/rltop.html címen található. A honlapot Chet Ramey tartja fent, aki a Bash szerzője.

Tartalom
readline_add_history -- Egy sort ad a 'history'-hoz
readline_clear_history -- Törli a 'history'-t
readline_completion_function -- Regisztrál egy kiegészítést végző függvényt
readline_info -- Lekér/beállít egy belső readline változót
readline_list_history -- A 'history' listázása
readline_read_history -- Beolvassa a 'history'-t
readline_write_history -- Kimenti a 'history'-t
readline -- Beolvas egy sort

readline_add_history

(PHP 4 )

readline_add_history -- Egy sort ad a 'history'-hoz

Leírás

void readline_add_history ( string line)

Ez a függvény egy sort ad a parancssor 'history'-hoz.

readline_clear_history

(PHP 4 )

readline_clear_history -- Törli a 'history'-t

Leírás

boolean readline_clear_history ( void )

Ez a függvény törli a teljes 'history'-t.

readline_completion_function

(PHP 4 )

readline_completion_function -- Regisztrál egy kiegészítést végző függvényt

Leírás

boolean readline_completion_function ( string line)

Ez a függvény regisztrál egy kiegészítést végző függvényt. Egy létező függvény nevét kell megadnod, ami egy részparancsot vár és a lehetséges kiegészítések tömbjét adja vissza. Ez az a funkció, amit a tab billenytű leütésével kapsz ha Bash-t használsz.

readline_info

(PHP 4 )

readline_info -- Lekér/beállít egy belső readline változót

Leírás

mixed readline_info ( [string varname [, string newvalue]])

Ha paraméter nélkül hívod, visszaadja az összes readline beállítás tömbjét. Az elemek a következő indexeket kapják: done, end, erase_empty_line, library_version, line_buffer, mark, pending_input, point, prompt, readline_name, és terminal_name.

Ha egy paramétert adsz át, a megadott beállítás értékét adja vissza. Ha két paramétert adsz át, a beállítás a megadott értékre változik.

readline_list_history

(PHP 4 )

readline_list_history -- A 'history' listázása

Leírás

array readline_list_history ( void )

Ez a függvény a teljes 'history' tömbjével tér vissza. Az elemek NULLától kezdve pozitív egész számok.

readline_read_history

(PHP 4 )

readline_read_history -- Beolvassa a 'history'-t

Leírás

boolean readline_read_history ( string filename)

Beolvassa a 'history'-t egy fájlból.

readline_write_history

(PHP 4 )

readline_write_history -- Kimenti a 'history'-t

Leírás

boolean readline_write_history ( string filename)

Kimenti a 'history'-t egy fájlba.

readline

(PHP 4 )

readline -- Beolvas egy sort

Leírás

string readline ( [string prompt])

Ez a függvény egy a felhasználtól érkező stringet ad vissza. Megadhatsz egy stringet, ami prompt-ként megjelenik a felhasználónak. A visszaadott sor végéről a soremelést a függvény törli. Ezt magadnak kell behelyezned a 'history' listába a readline_add_history() függvénnyel.

Példa 1. readline() példa

// Három parancs bekérése a felhasználótól
for ($i=0; $i < 3; $i++) {
        $parancs = readline ("Parancs: ");
        readline_add_history ($parancs);
}

// A 'history' kilistázása
print_r (readline_list_history());

// Változók listázása
print_r (readline_info());

XC. GNU Recode függvények

Ez a modul egy felületet biztosít a GNU Recode könyvtár 3.5-ös verziójához. Ahhoz, hogy használhasd az itt bemutatott függvényeket, a PHP-t a --with-recode paraméterrel kell fordítanod. Ahhoz, hogy ezt megtehesd a rendszereden rendelkezésre kell, hogy álljon a GNU Recode 3.5 vagy újabb verzió.

A GNU Recode könyvtár fájlokat alakít át különböző fájl és felületi kódolások figyelembevételével. Amikor ez nem végezhető el tökéletesen, kitüörölheti a problémás karaktereket, vagy közelítéseket alkalmazhat. A könyvtár felismer illetve képes előállítani 150 különböző karakterkódolást, és képes majdnem minden két kódolás között átalakítást végezni. A legtöbb Most RFC 1345 karakterkészlet támogatott.

Tartalom
recode_file --  Fájlból fájlba kódol egy recode kérésnek megfelelően
recode_string -- Recode-ol egy stringet egy recode kéréssnek meggelelően
recode -- Recode-ol egy stringet egy recode kéréssnek meggelelően

recode_file

(PHP 3>= 3.0.13, PHP 4 )

recode_file --  Fájlból fájlba kódol egy recode kérésnek megfelelően

Leírás

boolean recode_file ( string request, resource input, resource output)

Recode-olja az input fájl azonosítóval megadott fájlt az output fájl azonosító által megadott fájlba a request recode kérésnek megfelelően. Ha sikertelen a művelet, FALSE-al tér vissza, egyébként TRUE-val.

Egy a függvény még nem kezeli azokat a fájl hivatkozásokat, amik távoli fájlokra vonatkoznak (URLekre). Mindkét fájl azonosító helyi fájlra kell, hogy mutasson.

Példa 1. Alapvető recode_file() példa

$bemenet = fopen ('bemenet.txt', 'r');
$kimenet = fopen ('kimenet.txt', 'w');
recode_file ("us..flat", $bemenet, $kimenet);

recode_string

(PHP 3>= 3.0.13, PHP 4 )

recode_string -- Recode-ol egy stringet egy recode kéréssnek meggelelően

Leírás

string recode_string ( string request, string string)

A string stringet recode-olja a request kérésnek megfelelően. A recode-olt string-el tér vissza vagy FALSE értékkel, ha képtelen végrehajtani a kérést.

Egy egyszerű recode kérés lehet a "lat1..iso646-de" string. Lásd még a GNU Recode dokumentációt további részletekért a recode kéréseket illetően.

Példa 1. Alapvető recode_string() példa:

print recode_string ("us..flat", "A kovetkezo betu nem az angol abc resze: &aacute;");

recode

(PHP 4 )

recode -- Recode-ol egy stringet egy recode kéréssnek meggelelően

Leírás

string recode_string ( string request, string string)

Megjegyzés: Ez a függvény egy alias a recode_string() függvényre. A PHP 4-es verzióban került a nyelvbe.

XCI. Reguláris kifejezések függvényei (Perl kompatibilis)

Bevezetés

Ezekben a függvényekben használatos minták szintaktikája nagyon hasonlít a PERL-ben megismerthez. A kifejezéseket határolójelek közé kell rakni, például perjelek / közé. Az alfanumerikus karakterektől és a visszaperjeltől (\) eltekintve bármi használható határolójelként. Ha a határolójel magában a kifejezésben is szerepel, akkor egy visszaperjelet (\) kell eléírni. A PHP 4.0.4-s verziójától kezdve lehetőség van a (), {}, [], és <> párban álló határolók használatára, ahogy Perl-ben is.

A lezáró határolójelet különféle módosítók követhetik, amelyek a mintailleszkedést befolyásolják. Bővebben: Minta módosítók fejezet.

PHP a kiterjesztett POSIX reguláris kifejezéseket is támogatja.


Követelmények

A reguláris kifejezések támogatását a PCRE könyvtár biztosítja. Ez nyílt forráskódú szoftver, amit Philip Hazel írt, és a szerzői jogok az angliai Cambridge Egyetem tulajdona. A csomag hozzáférhető a ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/ címen.


Telepítés

PHP 4.2.0 -től kezdve ezek függvények alapértelmezésben telepítve lesznek. Régebbi verziók esetén a PHP-t a --with-pcre-regex[=DIR] opcióval kellett fordítani. A függvényeket le lehet tiltani fordítás idején a --without-pcre-regex opció megadásával.


Futásidejű beállítások

Ez a kiterjesztés semmilyen konfigurációs beállításokat nem definiál a php.ini állományban.


Erőforrás típusok

Ez a kiterjesztés semmilyen erőforrás típust nem definiál.


Előre definiált állandók

Az itt listázott állandókat ez a kiterjesztés definiálja, és csak akkor elérhetőek, ha az adott kiterjesztés be van fordítva a PHP-be, vagy dinamikusan betöltött.

Táblázat 1. PREG állandók

állandóleírás
PREG_PATTERN_ORDER Azt eredményezi, hogy a $matches[0] olyan tömb lesz, ahol az összes a teljes mintára illeszkedő szövegrész lesz egymás után, a $matches[1] tömbben pedig azok a szövegrészek, amelyek első "gyűjtő" részmintára illeszkednek, és így tovább. Ezt a preg_match_all() függvény paramétereként lehet használni.
PREG_SET_ORDER Azt eredményezi, hogy $matches[0]-ben az első illesztés eredményeit, a $matches[1] a másodikét fogja tartalmazni, és így tovább. Ezt a preg_match_all() függvény paramétereként lehet használni.
PREG_OFFSET_CAPTURE Lásd a PREG_SPLIT_OFFSET_CAPTURE állandót! Ez a PHP 4.3.0 verziójától használható.
PREG_SPLIT_NO_EMPTY Ennek hatására csak a nem üres elemeket adja vissza a preg_split() függvény eredményül.
PREG_SPLIT_DELIM_CAPTURE Ekkor a kerekzárójelek közé fogott ("gyűjtő") részmintára illeszkedő szövegrészeket is visszadja a preg_split() függvény. Ez a jelző a PHP 4.0.5 verziójától használható.
PREG_SPLIT_OFFSET_CAPTURE Minden egyezéshez az egyezés kezdőpozicióját is visszaadja az eredményben. Ez maga után vonja, hogy a visszaadott tömb minden eleme olyan tömb lesz, amelynek a 0. indexe az illeszkedő szöveget tartalmazza, míg az 1. indexen levő elem ennek a subject-en belüli kezdőpozicióját. Ez a jelzőbit PHP 4.3.0 verziójától használható.

Példák

Példa 1. Példák érvényes mintákra

  • /<\/\w+>/

  • |(\d{3})-\d+|Sm

  • /^(?i)php[34]/

  • {^\s+(\s+)?$}

Példa 2. Példák helytelen mintákra

  • /href='(.*)' - hiányzó lezáró határolókarakter

  • /\w+\s*\w+/J - ismeretlen módosító 'J'

  • 1-\d3-\d3-\d4| - hiányzó kezdő határolókarakter

Tartalom
Minta módosítók -- A lehetséges, PCRE reguláris kifejezések kiértékelését befolyásoló módosítók felsorolása
Regurális kifejezések szintaxisa -- PCRE regurális kifejezések nyelvtanának leírása
preg_grep --  Visszaadja azokat a tömbelemeket, amelyek illeszkednek a mintára
preg_match_all -- Reguláris kifejezés teljeskörű illesztését végzi
preg_match -- Reguláris kifejezést illeszt a megadott szövegre
preg_quote -- Reguláris kifejezés metakaraktereit literálissá változtatja
preg_replace_callback -- Reguláris kifejezés alapján keres és a megadott függvényt meghívva végzi a cserét
preg_replace -- Reguláris kifejezés alapján keres és cserél
preg_split -- Sztringet darabol fel reguláris kifejezésre illeszkedő részei mentén

Minta módosítók

Minta módosítók -- A lehetséges, PCRE reguláris kifejezések kiértékelését befolyásoló módosítók felsorolása

Leírás

Itt látható a pillanatnyilag használható PCRE módosítók listája. A zárójelekben közölt nevek a módosítók PCRE-ben használt belső nevei.

i (PCRE_CASELESS)

Ha ez a módosító be van kapcsolva, akkor a minta a nagy- és kisbetűk különbözőségére érzéketlen, a mintában előforduló betűk mind a kis- mind a nagybetűkre illeszkednek.

m (PCRE_MULTILINE)

Alapértelmezés szerint PCRE úgy tekinti a tárgyszöveget, mintha az egyetlen sorból állna (mégha történetesen tartalmaz is néhány újsor karaktert). A "sor eleje" metakarakter (^) csakis a tárgyszöveg elejére, míg a "sor vége" metakarakter ($) csakis a szöveg végére vagy a lezáró újsor-karakterre engedi illeszteni a mintát - kivéve ha D módosító be van kapcsolva. Ez ugyanúgy működik, mint Perl-ben.

Amikor ez a módosító be van kapcsolva, akkor "sor eleje" illetve "sor vége" szerkezetek közvetlenül a következő illetve közvetlenül a megelőző újsor karakterekre, és a szöveg legelejére illetve legvégére illeszkednek. Ez egyenértékű Perl /m módosítójával. Ha nincs a tárgyszövegben "\n" karakter vagy a mintában nincs ^ illetve $, akkor ennek a módosítónak nincs hatása.

s (PCRE_DOTALL)

Ha ez a módosító be van kapcsolva, a mintában előforduló . metakarakter minden karakterre - beleértve az újsor karaktert is - illeszkedik, míg enélkül az újsor karakterre nem illeszkedne. Ez egyenértékű a Perl /s módosítójával. A tagadó karakterosztályok (mint például [^a]) mindig illeszkednek az újsor karakterre függetlenül ennek a módósítónak a beállításától.

x (PCRE_EXTENDED)

Ha ez a módosító be van kapcsolva, akkor a mintában szereplő térközök - kivéve visszaperjelet elétéve vagy a karakterosztályokon belülieket - nem lesznek részei a mintának, valamint minden karakter, amely karakterosztályon kívüli literális # és a rákövetkező újsorkarakter közé esik, figyelmen kívül hagy a PCRE. Ez egyenértékű a Perl /x módosítójával, ami lehetővé teszi megjegyzések elhelyezését a bonyolultabb mintákban. Megjegyzendő, hogy ez csak bizonyos poziciókra vonatkozik, térközkarakterek soha nem szerepelhetnek speciális karaktersorozatokban, mint például (?( -ban, ami egy feltételes részminta kezdetét jelöli.

e

Ha ez a módosító be van kapcsolva, akkor preg_replace () függvény a helyettesítési paraméterként kapott sztringet - a hivatkozások feloldása után - PHP kódként értelmezi, és ennek a kódnak az eredményét helyettesíti be a keresett szöveg helyére.

Csak a preg_replace() használja ezt a módosítót, a többi PCRE függvény figyelmen kívül hagyja.

Megjegyzés: Ez a módosító PHP3-ban nem használható.

A (PCRE_ANCHORED)

Ha ez a módosító be van kapcsolva, akkor a keresett mintát "lerögzíti", ami annyit jelent, hogy a minta illesztése korlátozva van a tárgyszöveg elejére. Ezt a hatást elérhetjük ha magát a mintát megfelelően alakítjuk ki, miként Perl-ben ennek ez az egyetlen módja.

D (PCRE_DOLLAR_ENDONLY)

Ha ez a módosító be van kapcsolva, akkor dollár metakarakter ($) a mintán belül csak a tárgyszöveg végére illeszkedik. Enélkül a módosító nélkül a $ a legutolsó újsorkarakter előtti pozicióra is illeszkedik, de semmilyen más poziciójú újsorkarakter előtt nem. Ezt a módosítót figyelmen kívül hagyja a PCRE, ha a m be van kapcsolva. Nincs megfelelője Perl-ben.

S

Ha egy mintát többször használunk, akkor érdemes több időt hagyni a kiértékelésére, hogy az illesztésre fordított idő lerövidülhessen. Ennek a módosítónak a bekapcsolásával ezt biztosítjuk. Jelenleg, csak olyan nem "rögzített" minták esetén hasznos, amelyek nem egy egyszerű, rögzített karakterrel kezdődnek.

U (PCRE_UNGREEDY)

Ez a módosító megfordítja a kvantorok (sokszorozók) mohóságát, azaz alapértelmezés szerint nem lesznek mohók, csak ha egy ? követi azokat. Ez nem Perl-kompatibilis. A mintában is beállítható (?U) sorozat megadásával.

X (PCRE_EXTRA)

Ez a módosító PCRE további lehetőségeit teszi elérhetővé, amelyek nem Perl-kompatibilisak. Valamennyi visszaperjel a mintában, amit olyan karakter követ, aminek nincs speciális jelentése, hibát okoz, és ilyenformán lefoglalja ezeket a karakterkombinációkat a jövőbeni kiterjesztések előtt. Alapértelmezés szerint az ilyen különleges jelentés nélküli karakter előtt álló visszaperjelet a Perl betű szerint veszi. Jelenleg nincs más jellegzetesség, amit ez a módosító befolyásolna.

u (PCRE_UTF8)

Ez a módosító is PCRE olyan további lehetőségét teszi elérhetővé, ami nem Perl-kompatibilis. A mintát UTF-8 kódolású szövegnek tekinti. Ez a módosító PHP 4.1.0-től kezdve érhető el.

Regurális kifejezések szintaxisa

Regurális kifejezések szintaxisa -- PCRE regurális kifejezések nyelvtanának leírása

Leírás

A PCRE könyvtár függvények sorát tartalmazza, amelyek reguláris kifejezések mintaillesztését végzik el ugyanazt a szintaxist és szemantikát használva - néhány eltérést nem számítva -, mint a Perl 5. (lásd alább). A jelenlegi megvalósítás Perl 5.005-höz hasonló.

Perl-től való eltérések

Különbségek Perl 5.005-höz képest:

  1. 1. Alapértelmezés szerint térköznek tekintendő minden olyan karakter, amit a C könyvtár isspace() függvénye felismer, bár lehetőség van arra, hogy PCRE-t eltérő karakterkódtáblázattal fordítsuk le. Az isspace() rendszerint a szóköz, lapdobás, "kocsi-vissza", újsor és vízszintes illetve függőleges tabulátorokat tekinti térköznek. Perl 5-ben ez utóbbi már nem szerepel a listában. A \v szekvencia nagyon sokáig benne volt a Perl dokumentációjában, valójában soha nem ismerte fel mintaillesztés közben. Legalább az 5.002 verzióig ezt a karaktert is térköznek tekintették, de a 5.004 és 5.005 verziókban már nem illeszkedik a \s-re.

  2. 2. PCRE nem engedi meg az előretekintő tesztekben (lookahead assertion) a kvantorok (sokszorozók) használatát. Perl-ben ez megengedett, de nem a várt eredményt adja. Például (?!a){3}, nem azt jelenti, hogy teszteli, vajon a következő három karakter nem "a", hanem azt, hogy háromszor "jelenti", ha a következő karakter nem "a".

  3. Tagadó előretekintő tesztekben (negated lookahead assertion) szereplő "begyűjtő" részminták (capturing subpatterns) számon vannak tartva, de a hozzájuk tartozó numerikus változók soha nem kerülnek feltöltésre. Perl feltölti ezeket a numerikus változókat valamilyen, a sikertelen teszt előtti mintára illeszkedő részt követő karakterekkel, de csak akkor, ha a tagadó előretekintő tesztnek csak egy ága volt.

  4. A bináris nullkarakter használata megengedett a tárgyszövegben, de a mintában nem, mert a mintául szolgáló sztring nullvégű C sztringként adódik át. A "\\x00" vezérlőszekvencia használható a mintában bináris nullkarakter megjelenítésére.

  5. Nem támogatja az alábbi Perl vezérlőszekvenciákat: \l, \u, \L, \U, \E, \Q. Valójában ezek a funkciók a Perl sztringkezelő részében vannak megvalósítva, és nem tartoznak annak mintaillesztő motorjához.

  6. A Perl \G tesztjét nem támogatja, mivel nem fontos az egyszeres minta illesztésekben.

  7. Magától érthetődően PCRE nem támogatja a (?{kód}) szerkezetet.

  8. A kézikönyv írása során néhány furcsaság még van a Perl 5.002_2-ben a begyűjtött sztringek feltöltésével kapcsolatban, ha a mintarészek ismétlődhetnek. Például, "aba"-ra illesztve a /^(a(b)?)+$/ mintát $2 numerikus változó értéke "b" lesz, míg a "aabbaa"-ra illesztve /^(aa(bb)?)+$/ -t $2 üres marad. Mindamellett /^(aa(b(b))?)+$/ -ra módosítva a mintát $2 és $3 is beállításra kerül. Perl 5.004-ben $2 mindkét esetben beállításra kerül, mint ahogy ez a PCRE-re is igaz. Ha a jövőben a Perl-ben ezt egységesíteni fogják, akkor PCRE követni fogja ezt.

  9. Másik mindeddig megoldatlan eltérés, hogy pl. /^(a)?(?(1)a|b)+$/ minta Perl 5.002_2-ben illeszkedik a "a"-ra, míg PCRE-ben nem. Ráadásul mind Perl-ben mind PCRE-ben /^(a)?a/ minta "a"-ra illesztése során a $1 változó üresen marad.

  10. PCRE néhény bővítést is nyújt a Perl reguláris kifejezéseinek lehetőségeihez:

    1. Jóllehet a hátratekintő tesztek csak rögzített hosszúságú sztringekre illeszkedhetnek, az alternatív ágak mindegyikében különböző hosszúságú sztringre illeszkedő minta adható meg. Perl 5.005-ben minden ágban ugyanakkorának kell lennie ennek a hossznak.

    2. Ha a PCRE_DOLLAR_ENDONLY be van kapcsolva, és a PCRE_MULTILINE nincs bekapcsolva, akkor $ metakarakter csakis a sztring legvégére illeszkedik.

    3. Ha PCRE_EXTRA be van kapcsolva, akkor bármilyen külön jelentéssel nem bíró karakter előtti visszaperjel hibának minősül.

    4. Ha PCRE_UNGREEDY be van kapcsolva, akkor a kvantorok (sokszorozók) mohóságát fordítva értelmezi, azaz, alapértelmezés szerint nem mohók, csak ha egy kérdőjel ? áll utánuk.

A reguláris kifejezések részletei

Bevezetés

Az alábbiakban a PCRE által megvalósított reguláris kifejezések szintaktikáját és szemantikáját adjuk meg. A reguláris kifejezések leírása a Perl dokumentációnak része is, és néhány könyv is foglalkozik vele, némelyik rengeteg példával. Jeffrey Friedl "Mastering Regular Expression" c. könyve, amely az O'Reilly gondozásában jelent meg (ISBN 1-56592-257-3) igen nagy mélységben tárgyalja a reguláris kifejezéseket. Az itteni leírást referenciának szánjuk.

A reguláris kifejezés maga egy minta, amit a tárgyszövegre kell illeszteni balról jobbra. A karakterek többsége maga helyett áll a mintában, azaz csak saját magára illeszkedik a tárgyszövegben. Egy egyszerű példán bemutatva: az a gyors vörös róka minta a tárgyszöveg azon részére illeszkedik, ami megegyezik vele (azaz ahol az a gyors vörös róka előfordul).

Metakarakterek

A reguláris kifejezések ereje abban rejlik, hogy lehetőségünk van vagylagosságot (alternatívákat) és ismétléseket megadni a mintában. Ezeket a metakarakterek használatával lehet megadni, amelyek nem saját maguk helyett állnak a mintában, hanem speciális jelentéssel bírnak.

Két különböző típusú metakarakter létezik: az egyik bárhol előfordulhat a mintában, kivéve szögeletes zárójelek [] között, és a másik, ami csak szögeletes zárójelek között azonosítható metakarakterként. A szögletes zárójeleken kívüli metakarakterek:

\

több karakterből álló vezérlőszekvencia kezdetét jelzi

^

tárgyszöveg elejét (vagy sor elejét többsoros módban) jelenti

$

tárgyszöveg végét (vagy sor végét többsoros módban) jelenti

.

bármilyen karakterre illeszkedik, kivéve az újsor karaktert (alapértelmezés szerint)

[

karakterosztály definició kezdetét jelzi

]

karakterosztály definició végét jelzi

|

elágazás kezdetét jelzi

(

részminta kezdetét jelzi

)

részminta végét jelzi

?

opcionálitást jelez (0 vagy 1 előfordulást engedélyez), vagy kibővíti az előtte álló ( jelentését, és a kvantorok (sokszorozók) mohóságát befolyásolja

*

"0 vagy több" kvantor (sokszorozó)

+

"1 vagy több" kvantor (sokszorozó)

{

"min/max" kvantor (sokszorozó) kezdetét jelzi

}

"min/max" kvantor (sokszorozó) végét jelzi

A minta szögletes zárójelek [] közötti részét karakterosztálynak hívjuk. A karakterosztályokban engedélyezett metakarakterek a következők:

\

több karakterből álló vezérlőszekvencia kezdetét jelzi

^

negálja az osztályt, kizáró / tagadó osztályt definiál, de csak ha ez az első karakter az osztályon belül

-

karaktertartományt jelez

]

lezárja a karakterosztályt

A következő fejezetek a metakarakterek használatát írják le.

visszaperjel \

A visszaperjel \ karakternek számos alkalmazása van. Először is, ha nem alfanumerikus karakter követi, akkor annak bármilyen különleges jelentését (metakarakterek) figyelmen kívül hagyja, és azt mint maga helyett álló karaktert értelmezi. Ebben a minőségében mind karakterosztályon belül mind kívül használható.

Például, ha "*" karaktert kell illeszteni, akkor "\*"-t kell írni a mintában. Akármikor használható ez a szerkezet, akár a következő karakter egyébként metakarakterként lenne értelmezve, akár nem. (Egy kivétel van lásd a ] karakternél - a fordító.) Ezért biztos módszer előírni azt, hogy minden nem alfanumerikus karakter maga helyett álljon, úgy, hogy visszaperjelet (\) írunk elé. Különben ha a visszaperjelre szeretnénk illeszteni, akkor "\\"-t kell írni.

Ha a minta PCRE_EXTENDED módosítóval van megadva, akkor minden olyan térközkaraktert figyelmen kívül hagy, amely karakterosztályon kívül vagy karakterosztályon kívüli "#" és azt követő újsor-karakter között szerepel. Visszaperjellel bevezetett térköz- vagy "#" karakterek a minta részét képezik.

A visszaperjel másik alkalmazása a nem nyomtatható karakterek kódolását teszi láthatóvá a mintában. Nincs megszorítás a nem nyomtatható karakterek megjelenésére, kivéve a mintát lezáró nullkaraktert. Ha a minta szövegszerkesztés folyományaként áll elő, akkor általában könnyebb valamelyik alábbi vezérlőszekvenciát használni, mint az általuk reprezentált karakter bináris alakját:

\a

csengő karakter (hexadecimálisan 07)

\cx

"control-x", ahol x bármilyen karakter lehet

\e

"escape" (hexadecimálisan 1B)

\f

lapdobás (hexadecimálisan 0C)

\n

újsor (hexadecimálisan 0A)

\r

kocsivissza (hexadecimálisan 0D)

\t

tabulátor (hexadecimálisan 09)

\xhh

hh hexadecimális kódú karakter

\ddd

ddd oktális kódú karakter, vagy "hivatkozás"

A "\cx" feloldása precízen megfogalmazva a következő: ha "x" kisbetű, akkor nagybetűvé konvertálódik. Ezután a karakter 6. bitjét (hexadecimálisan 40) invertálja. Ilyenformán "\cz"-ból hexadecimális 1A lesz, de "\c{"-ból hexadecimális 3B lesz, míg "\c;"-ból hexadecimális 7B.

A "\x" után két hexadecimális számjegy kerül beolvasásra (a betűk lehetnek kis és nagybetűk is).

A "\0" után két további oktális számjegy kerül beolvasásra. Minden esetben - még ha kevesebb, mint két számjegy került is megadásra - a meglevő számjegyek lesznek felhasználva. Ekképpen "\0\x\07" egy olyan sorozatot definiál, ahol két bináris nullkaraktert követ egy csengőkarakter. Bizonyosodj meg affelől, hogy mindig van két számjegy a kezdő 0 után, ha a következő karakter oktális számjegy!

A nem 0-val folytatódó visszaperjel kezelése bonyolult. Karakterosztályon kívül PCRE ezt és a soron következő számjegyeket tízes számrendszerbeli számként értelmezi. Ha szám 10-nél kisebb vagy legalább ezzel a számmal egyező "gyűjtő" nyitó zárójel előzi meg a kifejezésben, akkor az egész sorozatot hivatkozásként értelmezi. Később a zárójelezett részminták fejezetében részletesen tárgyaljuk, hogyan használható is ez.

Karakterosztályon belül vagy ha a tízes számrendszerbeli szám 9-nél nagyobb, és nincs ennyi számú "gyűjtő" részminta, akkor PCRE újraolvassa a visszaperjelet követő három oktális karaktert, és egy bájtra váltja a 8 legkisebb helyiértékű bitet. Bármely rákövetkező számjegy maga helyett áll, magára illeszkedik.

\040

egy másik módja a szóköz megadásának

\40

ugyanaz mint előbb, ha biztosított, hogy 40-nél kevesebb "gyűjtő" részminta van előtte

\7

mindig hivatkozásként értelmezi

\11

hivatkozás is lehet, vagy a tabulátort írhatjuk így

\011

mindig tabulátort jelent

\0113

tabulátor és utána egy "3"

\113

113-as oktális kódú karakter ("K"), mivel hivatkozások száma nem lehet több, mint 99

\377

egy olyan bájt, ami teljes egészében 1 értékű biteket tartalmaz

\81

akár hivatkozás is lehet, vagy egy bináris nullkarakter és utána két karakter egy "8" és egy "1"

Figyelj arra, hogy 100-nál nagyobb oktális értékek elé nem szabad bevezető 0-t írni, mert mindig csak három oktális kerül beolvasásra.

Minden sorozat, ami egy egyszerű bájtot határoz meg, karakterosztályon belül és kívül is használható. Ráadásul karakterosztályokon belül a "\b" szekvencia "visszatörlés" karakterként (backspace) (hexadecimálisan 08) jelent. Ennek karakterosztályokon kívül más jelentése van (lásd alább).

A visszaperjel harmadik alkalmazási módja általános karakterfajták megadása:

\d

bármilyen tízes számrendszerbeli számjegy (decimális)

\D

bármilyen karakter, ami nem tízes számrendszerbeli számjegy

\s

bármilyen térközkarakter

\S

bármilyen nem térközkarakter

\w

bármilyen "szóépítő" karakter

\W

bármilyen nem "szóépítő" karakter

Mindegyik szekvenciapár két diszjunkt (egymással nem átfedő) részre osztja a karakterek teljes halmazát. Minden karakter csakis a párok egyik felébe tartozik.

"Szóépítő" karakter minden betű vagy számjegy vagy aláhúzás, azaz minden olyan karakter, amit egy Perl-típusú "szónak" része lehet. A betűk és számjegyek értelmezése a PCRE karaktertáblázataitól függ, amelyek változhatnak ha nyelvi beállítástól függően. Például, "fr" (vagy "hu" - a fordító) nyelvi beálllítás esetén 128-nál magasabb kódú karakterek használatosak az ékezetes betűkhöz, amelyekre illeszkedik a \w.

Ezek a karakterfajták mind karekterosztályokon belül és kívül is alkalmazhatók. Mindegyik csak egy, a neki megfelelő karakterre illeszkedik. Ha az aktuális illeszkedési pont a tárgyszöveg vége, akkor mindegyik sikertelen lesz, mert egyáltalán nincs karakter, amire illeszteni lehetne.

A visszaperjelet végül de nem utolsósorban néhány egyszerű teszt megadására használhatjuk. A tesztek (assertion) olyan feltételek, amelyeknek az illesztés adott pontján kell teljesülnie anélkül, hogy a tárgyszöbegből karaktereket használnának el - és így karaktereket vennének el az illesztéstől. Később megadjuk, hogy hogyan használhatók a részminták összetettebb tesztek megadásához. A "visszaperjeles" tesztek:

\b

szóhatár

\B

nem szóhatár

\A

tárgyszöveg kezdete (függetlenül többsoros üzemmódtól)

\Z

tárgyszöveg vége vagy újsor karakter a végén (függetlenül többsoros üzemmódtól)

\z

tárgyszöveg vége (függetlenül többsoros üzemmódtól)

Ezek a tesztek karakterosztályokban nem használhatók. (Figyeld meg, hogy "\b"-nek eltérő jelentése van karakteroszályokon belül, nevezetesen itt a "visszatörlés" karakter helyett áll.)

A szóhatár a tárgyszöveg azon poziciója, ahol az aktuális és az azt megelőző karakterek fajtája \w illetve \W vagy fordítva (az egyik \w-re illeszkedik, míg a másik \W-re), vagy a tárgyszöveg eleje illetve vége, ha az első illetve utolsó karakter a \w-re illeszkedik.

A \A, \Z és \z tesztek különböznek a hagyományos kalap(os ékezet) "^" és dollárjel "$" szimbólumoktól, mert az előbbiek minden esetben csakis a tárgyszöveg legelejére illetve legvégére illeszkednek. Nem befolyásolja a viselkedésüket sem PCRE_NOTBOL sem PCRE_NOTEOL módosító. A \Z és \z közti különbség annyi, hogy a \z csak a tárgyszöveg végére illeszkedik, míg \Z az esetlegesen a tárgyszöveg végén lévő újsor karakter előtt is.

kalap(os ékezet) ^ és dollárjel $


     Karakterosztályokon   kívül  az  alapértelmezett  illesztési
     üzemmódban a kalap(os ékezet) egy olyan tesztet jelent,amely
     csak akkor és csak is akkor igaz (TRUE), ha  a pillanatnyi
     illesztési pont  a tárgyszöveg kezdete.  Karakterosztályokon
     belül teljesen más jelentése van (lásd alább).

     A kalapnak akkor nem szükséges  a minta legelején állnia, ha
     több  választási  lehetőség  is  fennáll (lásd:  retesz pipa
     csővezeték |), de minden választható ágban a legelsőnek kell
     lennie, ha azt akarod, hogy a minta valaha is illeszkedjen.
     Ha mindegyik  lehetséges ág  "kalappal" kezdődik,  azaz ha a
     minta  mindenesetben  csak  a  tárgyszöveg  elejétől  kezdve
     illeszkedhet, akkor "(le)rögzített" mintáról beszélünk.
     (Más módja is van, hogy egy mintát "rögzíts".)

     A dollárjel olyan tesztet jelent, amely csak akkor és csakis
     akkor  igaz (TRUE),  ha  a pillanatnyi  illesztési pont  a
     tárgyszöveg vége vagy egy újsor karakter előtti pozició - az
     alapértelmezés szerint. A dollárjelnek akkor nem szükséges a
     minta legvégén állnia, ha több választási lehetőség is fennáll
     (lásd: retesz pipa csővezeték |),de minden választható ágban
     - ahol szerepel - a legutolsónak kell lennie. A dollárjelnek
     nincs külön jelentése karakterosztályokon belül.

     A dollárjel  jelentése  megváltozik  és  csak  a tárgyszöveg
     végére illeszkedik, ha a PCRE_DOLLAR_ENDONLY módosító be van
     kapcsolva  a  minta fordításakor / kiértékelésekor  vagy  az
     illesztés pillanatában. Ez nem érinti a \Z tesztet.

     A kalap(os ékezet) és a dollárjel jelentését  megváltoztatja
     PCRE_MULTILINE módosító bekapcsolása. Ebben az esetben a
     közbenső "\n" újsorkarakterek közvetlen előtti illetve utáni
     pozicióira  is  illeszkednek  a  tárgyszöveg  eleji  és végi
     pozición felül. Például, így a /^abc$/ minta többsoros
     üzemmódban  illeszkedik a  "def\nabc" szövegre, de egyébként
     nem. Következésképpen az egysoros üzemmódban  "rögzítettnek"
     tekintett  minták,  nem  "rögzítettek" többsoros üzemmódban,
     mert ekkor  "^"-kal  kezdődő  vagylagos ágak nem tekinthetők
     "rögzítettnek". A PCRE_DOLLAR_ENDONLY módosítót figyelmen kívül hagyja, ha a
     PCRE_MULTILINE, módosító be van kapcsolva.

     Figyelj  arra,  hogy  a  \A, \Z  és  \z  szekvenciák mindkét
     üzemmódban használhatók a tárgyszöveg elejére illetve végére
     illesztésben, és ha minden  vagylagos ág  \A -val  kezdődik,
     akkor a minta mindig "rögzített" lesz akármi is a
     PCRE_MULTILINE módosító állapota.
     

pont .


      Karakterosztályokon  kívül  a  pont  bármelyik  karakterre
     illeszkedik  beleértve minden  nem nyomtatható karaktert is,
     kivéve az újsort - alapértelmezés szerint. Ha a PCRE_DOTALL
     be van kapcsolva, akkor az újsor karakterre  is illeszkedik.
     A pont kezelése  teljesen független  a kalap(os ékezet) ^ és
     a dollárjel $ kezelésétől, az egyetlen közös hármukban, hogy
     mindegyiknek köze van az újsor karakterhez. A pontnak  nincs
     speciális jelentése karakterosztályokon belül.
     

Szögeletes zárójel []


     A nyitó szögeletes zárójel egy karakterosztály kezdetét, míg
     a záró párja annak  végét jelzi.  A bezáró zárójel önmagában
     nem hordoz  speciális  jelentést. Ha egy ] karaktert  kell a
     karakterosztályon belül megadni, akkor  annak  vagy  legelöl
     kell állnia - az esetleges kalap(os ékezet) után -, vagy egy
     visszaperjelet kell eléírni.

     A karakterosztályok  csak a tárgyszöveg egyetlen karakterére
     illeszkednek.  Ha a karakterosztály legelső karaktere  nem a
     kalap(os ékezet) ^,akkor ez csak a karakterosztályba tartozó
     karakterek valamelyikére illeszkedik,  ha a legelső karakter
     kalap(os ékezet) ^ ,  akkor  pedig  csak azokra, amelyek nem
     elemei  az osztálynak. (Ez utóbbit hívjuk tagadó vagy kizáró
     karakterosztálynak - a fordító.)  Ha a kalap(os ékezet)  ^
     karaktert kell megadni egy karakterosztály elemeként,  akkor
     az nem lehet a legelső pozicióban, vagy visszaperjelet  kell
     eléírni.

     Az [aeiou] karakterosztály  például  minden kisbetűs  ékezet
     nélküli  magánhangzóra illeszkedik,  míg  az  [^aeiou]  pont
     ezekre nem. A kalap(os ékezet) kényelmes jelölési forma olyan
     karakterosztályok  megadására,  ahol  a  kizárandó  elemeket
     könnyebb felsorolni. Ez nem teszt,  ez karaktereket  használ
     el a tárgyszövegből, ezért a tárgyszöveg végén  az illesztés
     sikertelen lesz.

     Amikor a kis- és nagybetűk különbözősége nem számít, akkor a
     betűk  a  kis- és nagybetűs  alakjukat is  képviselik, tehát
     ilyen esetben például  [aeiou]  illeszkedik az "A"-ra  és az
     "a"-ra is, és az [^aeiou] nem  illeszkedik a "A"-ra, csak ha
     a kis- és nagybetű különbözősége számít.

     Karakterosztályokban  az újsort  soha nem kezelik különleges
     módon, bármi is a PCRE_DOTALL és a PCRE_MULTILINE módosító
     értéke. A kizáró karakterosztályok - mint pl.: [^a] -  pedig
     mindig illeszkednek az újsor karakterre.

     Az "-" elválasztójellel karaktertartományokat  lehet megadni
     a karakterosztályon belül.  A [d-m], például, a d és m közti
     bármelyik karakterre illeszkedik - d-t és m-et is beleértve.
     Ha az elválasztójelet kell a karakterosztályon belül megadni,
     akkor  vagy  egy  visszaperjelet  kell  eléírni,  vagy olyan
     pozicióban kell megadni, ahol  nem lehet  tartományképzőként
     értelmezni, jellemzően a  karakterosztály első  vagy  utolsó
     tagjaként.

     A "]" karaktert ebben a  literális formában  nem  lehet  egy
     tartomány záró tagjaként használni.  A [W-]46] minta például
     azt  jelenti,  hogy  a  "W" és "-"  karakterek  valamelyikét
     kövesse  a  "46]"  sztring,  ezért  a  "W46]"  vagy a "-46]"
     illeszkedik a mintára. Ha  azonban visszaperjelet írunk elé,
     akkor a visszaperjel lesz a tartomány felső határa, és ekkor
     "[W-\]46]" mintát egy egyszerű  osztályként értelmezi,  amit
     három különálló karakter követ.  Oktális  vagy hexadecimális
     ábrázolásban  lehet megadni a  "]"-t mint  tartományt lezáró
     karaktert.

     A tartományok  meghatározásakor  az  ASCII  karaktertáblázat
     karakterkódjai számítanak. A karakterek helyett  a numerikus
     kódjaik  is  használhatók,  például [\000-\037].  Ha kis- és
     nagybetűkre nem érzékeny az illesztés és a tartomány betűket
     is  felölel,  akkor  azok  mind  a  kis-  mind  a  nagybetűs
     alakjuknak  megfelelő  karaktereket egyaránt  helyettesítik,
     például a [W-c] ugyanaz, mint a  [][\^_`wxyzabc] , és  ha  a
     "fr" nyelvi beállítást használjuk, akkor a [\xc8-\xcb] minta
     illeszkedik minden ékezetes e illetve E karakterre.
     (franciában van pár ilyen :)

     A karakterosztályokhoz karakterfajtákat - \d, \D, \s, \S, \w
     és \W -t -  is  hozzáadhatunk,  és  így  a  fajtába  tartozó
     karaterekkel  bővíthejük.  A  [\dABCDEF] - például -  minden
     hexadecimális számjegyre illeszkedik . A  kalap(os ékezet)-t
     a nagybetűs (tagadó) fajtákkal együtt használva  kényelmesen
     megadható a kisbetűs párjuknál korlátozotabb halmaz.A [^\W_]
     karakterosztály minden betűre és számjegyre illeszkedik,  de
     az aláhúzásra nem (ami ugyancsak eleme a \w-nek).

     A  \,  -, a kezdő ^  és a záró ] karakterektől eltekintve  a
     nem alfanumerikus karaktereknek nincs  különleges jelentésük
     a karakterosztályokon belül, de nem okoz gondot,  ha esetleg
     visszperjel előzi meg ezeket.
     

Retesz, pipa, csővezeték |


     A  "|"  karakterrel  vagylagos - alternatív - mintákat lehet
     megadni, pontosabban azokat választja el egymástól.  Például

       gyula|sacika

     minta illeszkedik a "gyula" és a "sacika" szövegre is.
     Bármennyi  vagylagos mintát fel lehet sorolni, köztük az üres
     mintát is, ami az üres sztringre illeszkedik. Az illesztés  a
     mintákat balról jobbra,  egymás után  sorjában veszi,  és  a
     legelső sikeresen illesztett lesz használva.  A részmintákban
     használt vagylagos ágak esetében a "sikeresen" azt jelenti, a
     minta fennmaradó részét is sikerül illeszteni.
     

Módosítók mintán belüli beállításai


     A PCRE_CASELESS , PCRE_MULTILINE , PCRE_DOTALL és
     PCRE_EXTENDED módosítókat a minta belsejében is  átállíthatjuk
     "(?" és ")" közé írt Perl-beli betűjelzéseikkel. Ezek a betűk:

       i = PCRE_CASELESS
       m = PCRE_MULTILINE
       s = PCRE_DOTALL
       x = PCRE_EXTENDED

     A "(?im)" bekapcsolja a többsoros és a "kis-nagybetű mindegy"
     üzemmódot. Kikapcsolni az egyes beállításokat az  eléjük írt
     kötőjellel lehet. Ezenkívül a módosítók együttes állítása is
     megengedett, például a (?im-sx) bekapcsolja a PCRE_CASELESS-t
     és a PCRE_MULTILINE-t  valamint kikapcsolja PCRE_DOTALL-t
     és PCRE_EXTENDED-t. Ha egy betűjelzés a kötőjel mindkét oldalán
     szerepel, akkor a módosító ki lesz kapcsolva.

     Ezeknek a beállításoknak  az érvényességi köre  attól  függ,
     hogy  a mintán belül  hol fordulnak elő.  Minden  részmintán
     kívüli beállítás olyan,  mintha  az illesztés kezdetén  lett
     volna megadva, ezért a következő minták tökéletesen ugyanúgy
     működnek:

       (?i)abc
       a(?i)bc
       ab(?i)c
       abc(?i)

     , ami ugyanaz, mintha az "abc" mintát PCRE_CASELESS módosítóval
     adtuk volna meg. Másszóval a legfelső szintű beálllítások az
     egész mintára érvényesek, hacsak egy részmintában  felül nem
     bírálod azokat. Ha a módosítónak több beállítása is szerepel
     a legfelső szinten, akkor a  jobbról legutolsó fog  érvényre
     jutni.

     Ha részmintán  belül történik  módosítóváltoztatás,  akkor a
     hatás különböző (Perl 5.005 viselkedésbeli változása).
     A  részmintán  belüli  módosító-állítás   csak  a  részminta
     hátramaradó részét érinti, ezért

       (a(?i)b)c

     minta csak az "abc" és "aBc" szövegekre illeszkedik feltéve,
     hogy PCRE_CASELESS módosítót nem adtuk meg. Ez azt
     jelenti, hogy  a minta különböző  helyein a módosítók más és
     más értékeit lehet beállítani.  Bármilyen  változtatás  egy
     vagylagos (választható) ágban a következő ágakra is hatással
     van ugyanabban a részmintában, például

       (a(?i)b|c)

     minta  illeszkedik az "ab", "aB", "c" és "C" szövegekre  még
     akkor is, ha "C"-re illeszkedve az nem is az első ágra esett
     a választás, ahol a módosító  be lett állítva. Ennek  az  az
     oka,  hogy  a  módosító  beállítások hatásai már a kifejezés
     fordításakor / kiértékelésekor rögzülnek, máskülönben  néha
     nagyon furcsa viselkedést tapasztalhatnánk.

     A PCRE-specifikus PCRE_UNGREEDY és PCRE_EXTRA módosítókat
     a Perl-kompatibilisekhez hasonló módon állíthatók, az U és X
     karakterek használatával.A (?X) beállítás különleges, mert -
     még a legfelső szinten is - mindig hamarabb kell szerepelnie
     a mintában,  mint a további kapcsolóknak.  Legjobb  a  minta
     legelejére rakni.
     

Részminták


     A  részminták  egymásba  ágyazhatók, és  kerek zárójel fogja
     közre őket. A minta egy darabját részmintaként szerepeltetni
     két dolgot jelent:

     1. Elágazási lehetőségek helyét jelöli ki (csoportosítás):

       szél(toló|kakas|)

     minta  illeszkedik  a  "szél",  "széltoló" vagy  "szélkakas"
     szavak egyikére. Zárójel nélkül a "széltoló"-ra, a "kakas"-ra
     vagy az üres sztringre illeszkedne.

     2.  A részmintát  "gyűjtő" részmintává  változtatja.  Ha  a
     teljes mintát sikerült illeszteni, akkor a tárgyszöveg  azon
     részei,  amelyek   a  "gyűjtő"  részmintákra   illeszkedtek,
     a pcre_exec() függvény ovector paraméterében a hívó
     függvénynek  lesznek  átadva.
     A kerek nyitó zárójelek számozása balról jobbra 1-től kezdve
     történik, és "gyűjtő" részminták (sor)számát adják.

     Például, ha az "a vörös király" szöveget illesztjük

       a ((vörös|sápadt) (király|királynő))

     mintára, akkor a megtalált / begyűjtött szövegrészek :
     1. "vörös király", 2. "vörös" és 3. "király".

     Az a tény,  hogy a kerek zárójelnek  kettős szerepe van, nem
     minden esetben hasznos.  Sokszor előfordulhat, hogy  csak  a
     csoportosító funkcióra van szükségünk "begyűjtés"  nélkül.
     Erre szolgál a nyitó zárójel után irható "?:" karaktersorozat
     , mert  ekkor  a részminta  nem  gyűjti  be / tárolja  el  a
     ráilleszkedő szövegrészt, és  nem is számít bele a következő
     "gyűjtő" részminták sorszámozásába. Az előző példánál maradva
     "a sápadt királynő"

       a ((?:vörös|sápadt) (király|királynő))

     mintára  illesztve  a megtalált /  begyűjtött  részminták :
     1. "sápadt királynő" és a 2. "királynő".
     A "gyűjtő" részminták száma legfeljebb 99 lehet,és az összes
     részminta "gyűjtő" és "nem-gyűjtő" együtt legfeljebb 200.

     Ha egy nem-gyűjtő részminta elején módosítókat kell állítani,
     akkor kényelmes rövidítésként használható, hogy  a módosítók
     betűjelei  a "?"  és a ":"  közé írhatók.  Ebből  adódóan az
     alábbi két minta

       (?i:szombat|szerda)
       (?:(?i)szombat|szerda)

     pontosan ugyanazokra a sztringekre illeszkedik.
     Mivel  a vagylagos / választható  ágak  próbálgatása  balról
     jobbra  történik,  és  a  módosító  hatása  addig él, amíg a
     részminta le nem zárul, az egyik ágban  beállított  módosító
     hatással  van  a következő ágra  is,  ezért  a fenti  minta
     illeszkedik a "SZERDA" és "Szombat" szavakra is.
     

ISMÉTLÉSEK


     Az ismétléseket kvantorokkal (sokszorozókkal) lehet megadni
     a következő poziciók után:

       egyszerű karakter (esetleg visszaperjellel bevezetve),
       . metakarakter,
       karakterosztály,
       hivatkozás (ld. következő szakasz) vagy
       zárójeles részminta (nem teszt)

     után.

     Az  általános  ismétlő  kvantor  (sokszorozó)  -   kapcsos
     zárójelben vesszővel elválasztva - írja elő azt minimális és
     maximális előfordulási számot, ahányszor a mintát illeszteni
     kell illetve lehet. Ezeknek 65536-nél kisebbnek kell lenniük,
     és az első legfeljebb annyi lehet, mint a második. Például a

       z{2,4}

     minta illeszkedik a "zz", "zzz" vagy "zzzz" szövegekre.
     Az egymagában álló  záró kapcsos zárójel  nem bír  speciális
     jelentéssel. Ha a második számot  nem adjuk meg, de a vessző
     szerepel, akkor az illesztésnek nincs felső határa,  de ha a
     vesszőt is elhagyjuk, akkor a kvantor (sokszorozó)  pontosan
     a megadott számú illesztést engedi csak. Ekképpen:

       [aáeéiíoóöőuúüű]{3,}

     legalább 3 egymást követő magánhangzóra illeszkedik, de akár
     többre is, míg a

       \d{8}

     csakis 8 darab számjegyre. Ha  a nyitó kapcsos zárójel olyan
     helyen szerepel,  ahol kvantor nem szerepelhet,  akkor  betű
     szerint lesz figyelembe véve, maga helyett áll a mintában. A
     {,6} például nem kvantor (sokszorozó), hanem egy négy
     karakteres minta betű szerint értelmezve.

     A  {0} kvantor  (sokszorozó)  megengedett,  és hatása olyan,
     mintha  az  előtte álló mintaelem és maga a kvantor  nem  is
     szerepelne.

     Kényelmi és  történelmi okokból  három,  gyakori  kvantornak
     létezik rövidítése is:

       *    egyenlő a {0,} - val
       +    egyenlő a {1,} - val
       ?    egyenlő a {0,1} - val

     Végtelen  ciklusokat is lehet  definiálni úgy, ha egy  olyan
     részmintát  sokszorozzunk  felsőhatár  nélkül, amelynek  nem
     muszáj illeszkednie egyetlen karakterre sem, például:

       (a?)*

     Perl és PCRE korábbi verziói hibát jeleztek az ilyen  minták
     kiértékelésekor / fordításakor. Azonban vannak esetek,amikor
     ezek a minták is hasznosak lehetnek, ezért ezeket a mintákat
     most  már  elfogadják, de  ha  a részminták  ismételten  nem
     illeszkednek   egy  karakterre   sem,  a  ciklust erőszakkal
     megszakítják.

     Alapértelmezés szerint  a kvantorok (sokszorozók)  "mohók" ,
     azaz  amennyi karakterre  csak illeszteni tudnak,  azt  mind
     elhasználják a tárgyszövegből a felső határ figyelembe vétele
     mellett  és anélkül, hogy  a minta többi része  sikertelenül
     illeszkedne.
     A klasszikus példa, ahol ez problémát okoz,  a C forráskódok
     megjegyzéseire illeszkedő kifejezés. Ezek a megjegyzések nem
     egymásba ágyazhatók, /* és */ közé írt tetszőleges szövegek,
     amelyekben szerepelhet a * és / jel is (nem egymás mellett).

       /\*.*\*/

     mintát a

       /* első megjegyzés */  c_code();  /* második megjegyzés */

     C forrásrészletre illesztve kudarcot vallunk -  köszönhetően
     a .* elem mohóságának. (Az illesztés sikeres, csak nem  arra
     való, amire szerettük volna - a fordító).

     Ha azonban a kvantort (sokszorozót) kérdőjel ? követi, akkor
     ez megszünteti annak mohóságát, és csak a lehető legkevesebb
     illesztést engedi, ezért a

       /\*.*?\*/

     minta az, ami C forráskódú megjegyzésekre való.  A különböző
     kvantorok (sokszorozók)  jelentése  egyébként  nem  változik
     ettől,  csak az előnyben részesített  illeszkedési számuk. A
     kérdőjelnek  ez a szerepe nem összetévesztendő  a feltételes
     kvantorral (sokszorozóval), mert  a kérdőjelet kétféleképpen
     és néha megkettőzve használjuk, például:

       \d??\d

     egy számjegyre illeszkedik leginkább, és csak akkor kettőre,
     ha a minta maradék része másképp nem illeszkedne.

     Ha a PCRE_UNGREEDY módosító be van kapcsolva, akkor
     a kvantorok (sokszorozók)  alapértelmezés szerint  nem mohók
     (szerények :), csak ha egykérdőjel követi őket. Másszóval, a
     kérdőjel  átállítja  a  kvantorok   alapértelmezés  szerinti
     viselkedését.

     Amikor  egy  zárójelezett  részminta  egynél  többször  vagy
     legfeljebb  meghatározott  számban   ismétlődhet,  akkor   a
     kiértékelt minta  több   memóriát  foglal  el a minimális és
     maximális előfordulással arányosan.

     Ha a minta .* -val vagy .{0,} -val kezdődik és a PCRE_DOTALL
     módosító (Perl-beli /s-nek megfelelője) be van kapcsolva, és
     így a . illeszkedik  az  újsor karakterre is,  akkor a minta
     hallgatólagosan  "rögzített" lesz, mert bármi is  következik
     utána, az a tárgyszöveg minden  karakterpoziciójára "rá lesz
     próbálva", így  nincs az  elsőn kívül  más  karakterpozició,
     ahonnan az egész illesztés újrakezdődhetne.  PCRE  az  ilyen
     mintákat  úgy tekinti,  mintha \A-val kezdődne.  Azokban  az
     esetekben,  amikor tudjuk,  hogy a tárgyszöveg nem tartalmaz
     újsorkaraktereket  és  a minta  .* -gal  kezdődik,  érdemes
     beállítani a PCRE_DOTALL módosítót vagy ^ -t használni
     a  "rögzítés"  eléréséhez,  hogy  ezt  az  optimalizálást
     kieszközöljük.

     Ha a "(be)gyűjtő" részminta  az  illesztés  során ismételten
     felhasználásra kerül, akkor a begyűjtött / megtalált szöveg-
     rész az utolsó ismétlésben illeszkedő rész lesz. Például a

       (csori[keat]{3}\s*)+

     minta  a "csorikea csoriaet"  történő  illesztése  után  a
     begyűjtött / megtalált szövegrész "csoriaet" lesz. Egymásba
     ágyazott részminták esetén a begyűjtött érték lehet, hogy az
     előző lépésben lett beállítva, például:

       /(a|(b))+/

     illesztve a "aba" -ra a második begyűjtött szövegrész a "b".
     

HIVATKOZÁSOK


     Karakterosztályon kívül visszaperjelet követő számjegy(ek) a
     mintában  korábban előforduló  "gyűjtő"  részmintára történő
     hivatkozásnak minősül(nek), ha a számnak megfelelő "gyűjtő"
     részminta nyitó kerek-zárójele ( előfordult már a mintában.

     Ha azonban ez a  tízes számrendszerbeli  szám 10-nél kisebb,
     akkor mindig hivatkozásnak minősül, s csak akkor okoz hibát,
     ha nincs ennyi "gyűjtő" részminta megnyitva az egész mintán
     belül.  Magyarán  a  10-nél  kisebb  sorszámú   kerek  nyitó
     zárójeleknek nem kell  a hivatkozás előtt,  a mintában ettől
     balra állniuk. Olvasd el a  "visszaperjel \" szakaszt,  ahol
     részletesen olvashatsz arról,  hogy miképpen kezeli a PCRE a
     visszaperjel után álló számjegyeket.

     A hivatkozások  az általuk megcímzett  "gyűjtő" részmintákra
     ténylegesen illeszkedő szövegrészeket testesítik meg, és nem
     azokat, amelyre  illeszkedhettek  volna  egyébként. Mindjárt
     megvilágítjuk egy példán keresztül:

       (ért|kegy) és \1elem

     illeszkedik a "kegy és kegyelem"-re és  "ért és értelem"-re,
     de nem illeszkedik az "ért és kegyelem"-re.
     Ha a kis- és nagybetűk különbsége érvényben van a hivatkozás
     pillanatában, akkor számít a betűalakok különbsége. Például

       ((?i)rah)\s+\1

     minta illeszkedik a "rah rah" és "RAH  RAH" szövegekre, de a
     "RAH rah" -ra  még   akkor  sem,  ha   az  eredeti  "gyűjtő"
     részmintában a kis- és nagybetűk  különbsége nem számított.

     Egy részmintára több hivatkozás is utalhat.  Ha a  részminta
     ténylegesen nem lett felhasználva az illesztés során,  akkor
     bármilyen hivatkozás rá hibát jelent. Például

       (a|(bc))\2

     minta mindig hibázik,  ha az illesztés "a"-val kezdődött  és
     nem "bc"-vel.Mivel legfeljebb 99 hivatkozás lehet egy mintán
     belül, minden visszaperjel után álló számjegy egy lehetséges
     hivatkozás  részét   képezheti.  Ha  a  mintát   számjeggyel
     kellene  folytatni,  akkor  a  hivatkozás  végét  valamilyen
     elválasztókarakterrel kell jelezni. Ha PCRE_EXTENDED módosító
     be van kapcsolva, akkor ez  bármilyen térközkarakter  lehet,
     egyébként egy üres megjegyzés is megfelel.

     Azok a hivatkozások, amelyek magára a hivatkozást tartalmazó
     részmintára utalnak,a részminta első illesztésekor hibáznak,
     ezért például (a\1) soha nem illeszkedik semmire. Azonban az
     ilyen hivatkozások is értelmet nyerhetnek, például az alábbi
     minta

       (a|b\1)+

     illeszkedik  a csupa "a"-ból álló  és az "aba",  "ababaa"  s
     ehhez  hasonló  sorozatokra.  A részminta  illesztés  minden
     iterációjában  a  hivatkozás  az előző iterációnak megfelelő
     karaktersorozatra utal.  Azért, hogy ez működjön, a mintának
     olyannak kell lennie,  hogy  az első lépésben nem kelljen  a
     hivatkozásnak illeszkednie.Ez vagylagos ágak vagy elhagyható
     - minimálisan 0 ismétlést előíró -  kvantor  (sokszorozó)
     használatával megoldható.
     

TESZTEK - FELTÉTELEK


     Angolul  "assertion"-nek nevezett  szerkezet  olyan  tesztet
     vagy feltételt jelent, ami a pillanatnyi  illesztési pozició
     előtti vagy utáni  karakterekre  vonatkozik,  de ténylegesen
     nem használ el  karaktereket  a tárgyszövegből  az illesztés
     elől, csak ellenőrzi  egy feltétel fennállását.  Az egyszerű
     teszteket - \b, \B,  \A,  \Z,  \z, ^ és $ - már tárgyaltuk.
     Az ennél bonyolultabbakat részmintaként kell megadni.Kétféle
     teszt van:  az előretekintő,  ami  a pillanatnyi  illesztési
     pozició utáni karaktereket vizsgálja, és a hátratekintő, ami
     az az előttieket.

     A  teszt  részmintája  a szokásos módon  illeszkedik,  attól
     eltekintve,  hogy  a  pillanatnyi  illesztési  poziciót  nem
     változtatja meg. Az előretekintő  tesztek "(?=" vagy  tagadó
     feltétel esetén "(?!" sorozattal kezdődnek, például

       \w+(?=;)

     illeszkedik minden szóra, amelyet pontosvessző követ, de a
     pontosvessző nem szerepel az illeszkedésben, és az

       ize(?!bigyo)

     illeszkedik a "ize" minden olyan előfordulására, amit nem  a
     "bigyo" követ. Nyilvánvaló, hogy egy hasonló minta

       (?!ize)bigyo

     nem azokat a "bigyo"-kat találja meg, amelyek előtt nem "ize"
     van; hanem  minden "bigyo"-t megtalál,  mert a (?!ize) teszt
     mindig igaz, hiszen az utána jövő három karakter tényleg nem
     "ize", hanem  "big"  (tesztként  nem változik  a pillanatnyi
     illesztési pozició - a fordító). Ahhoz, hogy a kívánt hatást
     érjük el a hátratekintő tesztre van szükségünk.

     A hátratekintő tesztek (?<=  vagy tagadó  feltétel esetén
     a (?<! sorozattal kezdődnek, például

       (?<!ize)bigyo

     azokat a "bigyo"-kat találja meg, amelyek előtt nincs "ize".
     A hátratekintő tesztek csak rögzített hosszúságúak lehetnek.
     Ha  azonban  több  alternatívát  adunk meg  a teszten belül,
     a különböző ágaknak lehet eltérő a hossza, ilyenformán a

       (?<=tulok|szamár)

     megengedett, ellentétben a

       (?<!kutyus(ok)?|macsk(ák)?)

     mintával, amely kiértékelés / fordítás során hibát okoz.
     Az  eltérő  hosszúságú  ágtesztek   a  hátratekintő  tesztek
     legfelső  szintjén  megengedettek.  Ez  PCRE bővítés  a Perl
     5.005-höz képest,ahol minden ágtesztnek azonos hosszúságúnak
     kell lennie. A

       (?<=ab(c|de))

     mintához hasonlók nem megengedettek, mert a legfelső szinten
     levő  egyetlen  ág  két  különböző  hosszúságú  szövegre  is
     illeszkedhet,  de átírható,  hogy  a  vagylagosságot a felső
     szintre emeljük:

       (?<=abc|abde)

     A  hátratekintő  tesztek  megvalósítása  a következő: minden
     ágra  a pillanatnyi  illesztési pozició  átmenetileg hátrébb
     kerül az ágtesztnek  megfelelő számú karakterrel  és  ezután
     illeszteni próbál. Ha nincs elég karakter  a visszalépéshez,
     az  illesztés  sikertelen lesz.  A hátratekintő tesztek  az
     egyszeri részmintákkal együtt  különösen hasznosak  lehetnek
     a szöveg végi illeszkedéseknél,  az "Egyszeri részminták" c.
     szakasz végén található erre példa.

     Számos különböző fajtájú teszt állhat egymás után, például:

       (?<=\d{3})(?<!999)ize

     minta azokra az "ize"-kre illeszkedik, ami előtt  3 számjegy
     áll, amely nem  a "999".  Figyelj  arra, hogy  minden  teszt
     egymástól  függetlenül, ugyanabban  az illesztési  pozicóban
     kerül kiértékelésre. Először  azt ellenőrzi, hogy a megelőző
     három  karakter  számjegy-e  és utána  azt, hogy  ezek nem a
     "999"-t adják.Ez a minta nem azokra az "ize"-kre illeszkedik,
     amelyek  előtt  hat  karakter áll:  három számjegy  és másik
     három,  ami  nem  a  "999", példaképpen nem  illeszkedik  a
     "123abcize" szövegre. Az a minta, ami ezt tudja a következő:

       (?<=\d{3}...)(?<!999)ize

     Ebben az esetben az első teszt a megelőző hat karaktert nézi,
     és  azt vizsgálja, hogy az  első három  számjegy-e, ezután a
     második feltétel a maradék három  karaktert nézi, hogy  azok
     nem a "999" sorozat. A tesztek egymásba ágyazhatók bármilyen
     komibinációban. Például a

       (?<=(?<!ize)bigyo)figyula

     arra a "figyula"-ra illeszkedik,  amit egy "bigyo" előz meg,
     ami előtt nem áll "ize". Miközben

       (?<=\d{3}(?!999)...)ize

     egy  másik minta  az  olyan  "ize"-kre, amelyek  előtt három
     számjegy s ezután három olyan karakter áll, amely nem "999".

     A teszt-minták nem "gyűjtő" részminták, és nem ismételhetők,
     hiszen  nincs  sok  értelme  ugyanazt  többször   tesztelni.
     Ha  bármilyen  teszt  "gyűjtő"  részmintát  tartalmaz, akkor
     ezek a részminták is beleszámítanak a "gyűjtő" részminták
     számozásába, azonban csak pozitív tesztekre lesz végrehajtva
     a  megtalált  szövegrész  "begyűjtése", mert  tagadó tesztek
     esetén ennek nincs értelme.

     A  tesztek   beleszámítanak  a  zárójelezett  részmintákra
     vonatkozó 200-as felső korlátba.
     

Egyszeri részminták


     A mind a maximalizáló (mohó)  mind a minimalizáló (szerény)
     ismétlés  esetén  a további részek  sikertelen illesztése a
     általában az ismételt elem újbóli kiértékelését eredményezi,
     hogy eltérő ismétlésszámmal a minta maradéka illeszkedik-e.
     Néhány esetben  hasznos ezt megelőzni  akár a mintaillesztés
     viselkedésének megváltoztatásával,  vagy hagyni,  hogy  az
     illesztés hamarabb  elbukjon - mint egyébként -, ha  a minta
     készítője tudja, hogy nincs értelme folytatni.

     Nézzük a következő példát, ahol a \d+ize mintát a

       123456bigyo

     szövegre illesztjük.
     Miután 6 számjeggyel végzett,az illesztés elbukik az "ize"-n.
     Ekkor a szokásos lépés, hogy megpróbálja újból 5 majd 4  és
     - és így tovább sorjában - eggyel kevesebb számjegyet illeszteni
     a "\d+"-re , amíg   végül   minden  lehetőséget  kimerítve
     az illesztés elbukik. Az egyszeri részminták azt a lehetőséget
     biztosítják  nekünk,  hogy  ha  egyszer  a minta egy darabja
     illeszkedett, akkor az  ne legyen újra és újra kiértékelve a
     fenti módon, hanem az illesztés fejeződjön be azonnal, ha az
     "ize"-t nem tudja illeszteni mar az első alkalommal. Ennek a
     jelölésére egy speciális zárójelezés szolgál (?>)

       (?>\d+)bigyo

     Ez  a zárójelféle  lezárja  a közrefogott  részmintát, ha az
     egyszer már illeszkedett,és az illesztés későbbi  sikertelen
     szakaszában megakadályozza, hogy  az illesztés  visszalépjen
     ebbe  a részbe.  Emellett  azonban  az előző  elemekre  a
     visszalépegetés a szokásos módon történik.


     Másfajta leírása, hogy ez a fajta részminta úgy illeszkedik
     a szövegre, mint ahogy egy, a pillanatnyi illesztési ponthoz
     rögzített, de az eredetivel teljesen megegyező, önálló minta
     lenne.

     Az  egyszeri  részminták  nem "gyűjtő"  részminták. Egyszerű
     esetekben egy  maximalizált  ismétlésnek  tekinthető,  amely
     minden lehetőt elnyel -  ahogy a  fenti  példában.  Miközben
     tehát  a \d+  és a \d+?  is annyi karaktert készül elnyelni,
     hogy a minta maradék része  is illeszkedni  tudjon,  addig a
     (?>\d+) csakis a teljes  számjegy  sorozatra illeszkedik.

     Ez a szerkezet egymásba ágyazható, és természetesen
     tartalmazhat tetszőlegesen bonyolult részmintákat is.

     Az egyszeri részminták  a  hátratekintő  tesztekkel közösen
     hatékony a szöveg végére illeszkedő mintát képesek megadni.
     Nézzük a következő mintát

       abcd$

     egy hosszú, nem illeszkedő szövegre alkalmazva. Mivel az
     illesztés balról jobbra történik,  PCRE a tárgyszöveg minden
     "a" betűjét  végignézi,  és  megvizsgálja,  hogy  onnantól a
     minta többi része illeszkedik-e. Ha a mintát így adjuk meg:

       ^.*abcd$

     akkor a kezdő .*  először a teljes  szövegre illeszkedik, de
     mikor  a minta  maradéka  elbukik -  hiszen  nem  következik
     semmilyen  "a" betű -,  az  algoritmus  visszalép,  hogy  az
     utolsó  karakter  kivételével  mindent  elnyeljen,  majd  az
     utolsó  két  karakter kivételével, stb.  Az "a"  megkeresése
     mégegyszer lefedi az egész szöveget - most jobbról balról -,
     ez sem jobb. Ha azonban a mintát az alábbi alakra hozzuk

       ^(?>.*)(?<=abcd)

     az eljárás nem tud  visszalépni  .*  elemre, csak  az  egész
     szövegre   tud   illeszkedni  a  minta. A  soron  következő
     hátratekintő teszt pedig az utolsó négy karaktert ellenőrzi.
     Ha a teszt sikertelen, akkor  az illesztés  nyomban elbukik.
     Hosszú szövegek esetén ez a megközelítés jelentős - mérhető
     - különbséget jelent a feldolgozási időben.

     A  korlátlan  ismétlésű  részmintákat  tartalmazó mintákban,
     amelyek  maguk  is   korlátlan  számban  ismétlődhetnek,  az
     egyszeri részmintával  akadályozható meg  egyedül  az,  hogy
     néhány sikertelen illesztés valóban hosszú ideig tartson. A

       (\D+|<\d+>)*[!?]

     minta  azokra  a szövegekre  illeszkedik, amelyek  korlátlan
     számú nem számjegy karakterek vagy <> közé írt számjegyek
     sorozatából és egy !-ből vagy ?-ből állnak.  Ha illeszkedik,
     az gyorsan kiderül. Ám ha az

       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

     szövegre  próbáljuk illeszteni, akkor sok időt vesz igénybe,
     mire "értesülünk a kudarcról". Ez azért van, mert a szöveget
     nagyon sokféleképpen lehet feldarabolni  két ismétlés között
     és mindet  végig  kell próbálni. (A példában azért szerepelt
     [!?] a minta végén egy egyszerű karakter helyett, mert  Perl
     és PCRE is rendelkezik egy beépített optimalizálással, amely
     lehetővé   teszi   a  sikertelenség  korai   jelzését,  mert
     megjegyzik  az  utolsó  illesztendő   karaktert   és   korán
     jeleznek, ha az nincs benne a tárgyszövegben.)
     Ha a mintát a következőképp módosítjuk:

       ((?>\D+)|<\d+>)*[!?]

     akkor a nem számjegyekből álló sorozatot nem lehet széttörni
     és hamar kiderül, hogy az illesztés nem sikerült.
     

Feltételes részminták


     Lehetőség van arra, hogy egy teszt (assertion)  eredményétől
     vagy  egy  előző "gyűjtő" részminta  illeszkedésétől függően
     más-más részmintával folytatódjon az illesztés. A feltételes
     részminták két alakja:

       (?(feltétel)igen-minta)
       (?(feltétel)igen-minta|nem-minta)

     Ha  a  feltétel  teljesül, az  "igen-minta" lesz  illesztve,
     egyébként a "nem-minta", ha  megadtunk ilyet. Ha  2-nél több
     választható  részmintát  adtunk meg, akkor  az a  kiértkelés
     - fordítás során hibát okoz.

     Kétfajta feltételt lehet megadni.Ha a kerek zárójelek között
     csak  számjegyek  szerepelnek,  akkor ezt egy hivatkozásként
     értelmezve  a  feltétel  abban  az  esetben  teljesül, ha  a
     hivatkozott  "gyűjtő" részminta előzőleg  már illeszkedett a
     szöveg valamely részére. Nézzük a következő mintát, amelyben
     a térközök  nem számítanak,  csak  az  olvashatóságot  és  a
     könnyebb  tárgyalást  szolgálják.   (Feltételezzük,  hogy  a
     PCRE_EXTENDED be van kapcsolva):

       ( \( )?    [^()]+    (?(1) \) )

     A minta  első része  egy  nem kötelező kerek nyitó zárójelre
     illeszkedik,  és ha  ez a karakter  szerepel, akkor  az első
     begyűjtött - megtalált  szövegrész  (\1  vagy  $1  numerikus
     változó) ezt fogja  tartlamazni. A minta második része a nem
     kerek zárójelekre  illeszkedik. A harmadik részben található
     a  feltételes  részminta,  ami azt teszteli,  hogy  az  első
     részben a  nyitózárójel  illeszkedett-e  vagy  sem. Ha igen,
     azaz ha a tárgyszöveg  nyitó zárójellel kezdődött,  akkor az
     "igen-részminta" érvényre jut, és a bezáró kerek zárójel már
     kötelező lesz, egyébként - mivel nincs megadva "nem-minta" -
     semminek  nem  kell illeszkednie.  Magyarán  ez a minta  az
     elhagyható zárójelek közé fogott zárójeleket nem tartalmazó
     karaktersorozatra illeszkedik.

     Ha a feltételrészben nem csak számjegyek vannak, akkor annak
     kötelezően  egy tesztnek (assertion) kell lennie.  Ez  lehet
     akár előre- vagy hátratekintő,  állító  vagy  tagadó felétel
     is.  Tekintsünk  most egy,  két  választható  mintából  álló
     példát, ahol a térközök szintén nem számítanak:

       (?(?=[^a-z]*[a-z])
       \d{2}-[a-z]{3}-\d{2}  |  \d{2}-\d{2}-\d{2} )

       (Az első sorban a tesztfeltétel,
        a másodikban a két választható minta.)
     A feltétel olyan előretekintő teszt, ami azt vizsgálja, hogy
     egy betű előtt elhagyható, nem betűkből álló karaktersorozat
     áll, azaz legalább egy betű jelenlétét vizsgálja.  Ha  ez  a
     betű  jelen van  a szövegben,  akkor  a tárgyszöveg  az első
     mintára illeszkedik, egyébként a másodikra. Ez a minta vagy a
     "dd-aaa-dd"  vagy a "dd-dd-dd"  alakú szövegekre illeszkedik,
     ahol  "aaa"  három betűt, "dd" pedig két számjegyet jelez.
     

Megjegyzések


     A (?# karartersorozat  megjegyzések kezdetét  jelzi a mintán
     belül, amely  a  következő  bezáró  kerek zárójelig tart.  A
     megjegyzéseket  nem lehet  egymásba  ágyazni,  és  a  bennük
     előforduló karakterek nem  játszanak  semmilyen  szerepet  a
     mintaillesztés során.

     Ha a PCRE_EXTENDED  módosító be van kapcsolva, akkor
     karakterosztályon  kívüli  visszaperjel  nélküli  # karakter
     "egy soros" megjegyzést vezet be, amely a legközelebbi újsor
     karakterig tart.
     

Rekurzív (önhivatkozó) minták



     Nézzük   az   egymásba   ágyazható  zárójeles  kifejezésekre
     illeszkedő minta problémáját.  Rekurzió használata  nélkül a
     legtöbb,  amit  tehetünk,  hogy   rögzített  számú  egymásba
     ágyazhatóságot kezelő mintát használunk.  Nem  megoldható  a
     tetszőleges mélységű egymásbaágyazhatóság.
     Perl  5.6  kísérleti  jelleggel  biztosítja  a lehetőséget a
     reguláris kifejezések rekurzív bejárására (több más mellett).
     A különleges (?R) elem jelenti a meghatározott önhivatkozási
     pontot.
     A PCRE   minta,  amely   megoldja  a  zárójelezett  szövegek
     problémáját (feltéve, hogy a PCRE_EXTENDED módosító be
     van kapcsolva,  tehát  a  térközök  nem részei a mintának) a
     következő:

       \( ( (?>[^()]+) | (?R) )* \)

     Először  egy nyitó zárójelre illeszkedik, ezután tetszőleges
     hosszúságú  karakterresorozatra,  amely  vagy nem  tartalmaz
     zárójeleket, vagy rekurzívan az egész mintára illeszkedik (a
     zárójelezett szövegekre). Végül a bezáró zárójel következik.

     Ez a  sajátságos minta  korlátlan  számú, egymásba  ágyazott
     ismétlést  takar,  ezért  a  zárójel  nélküli   szövegrészre
     illesztésnél az egyszeri részminta használata nagyon fontos,
     kiváltképp ha  nem illeszkedő tárgyszövegre alkalmazzuk.  Ha
     például a

       (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()

     szövegre próbáljuk a mintát, akkor nagyon hamar megkapjuk az
     eredményt.  Ha nem használnánk az egyszeri részmintát, akkor
     az illesztés nagyon sokáig tartana, mert  rengeteg különböző
     módon lehet a tárgyszöveget felszeletelni a * és + kvantorok
     (sokszorozók)  között,  és  minden   lehetőséget   ki   kell
     próbálni, mire  az  illesztést  végleg  sikertelennek  lehet
     minősíteni.

     A "gyűjtő" részminták által  begyűjtött szövegek a  rekurzió
     során a legutoljára illesztett szövegrészek.A fenti mintát a

       (ab(cd)ef)

     szövegre  alkalmazva a "begyűjtött" / megtalált rész az "ef"
     lesz, amely a felső szinten  az  utolsó  felvett  érték.  Ha
     további zárójeleket helyezünk  el a mintában  ekképpen:

       \( ( ( (?>[^()]+) | (?R) )* ) \)
          ^                        ^
          ^                        ^
     , akkor a  "ab(cd)ef"  szöveg lesz legkülső "gyűjtő" zárójel
     értéke. Ha 15-nél  több  "gyűjtő"  zárójel  van  a mintában,
     akkor PCRE tartalék memóriát foglal le, hogy az adatokat itt
     tárolja a rekurzió alatt (pcre_malloc-kal foglalja le,  és a
     pcre_free-vel  szabadítja  fel  azután.) Ha  nem lehet  több
     memóriához  hozzájutni,  akkor  csak  az  első  15  "gyűjtő"
     zárójelnek  menti el az adatait,  minthogy lehetetlen "nincs
     elég memória" hibaüzenetet kiadni a rekurzión belül.
     

Teljesítmény


     Bizonyos  minták sokkal  hatékonyabbak,  mint mások, például
     [aáeéiíoóöőuúüű] karakterosztály hatékonyabb,  mint ugyanezt
     választható mintákkal (a|á|e|é|i|í|o|ó|ö|ő|u|ú|ü|ű) megoldani.
     Általában a legegyszerűbb szerkezet, amely a kívánt viselkedést
     biztosítja rendszerint a leghatékonyabb. Jeffrey Friedl könyve
     rengeteg példát tartalmaz, hogyan kell reguláris kifejezéseket
     optimalizálni a hatékony végrehajtáshoz.

     Ha  a minta .* -gal  kezdődik, és a PCRE_DOTALL módosító
     be  van  kapcsolva,  akkor  PCRE  a  mintát  hallagtólagosan
     "rögzíti", mivel az csak a tárgyszöveg elejére illeszkedhet.
     Ha  ez  a módosító  nincs beállítva,  akkor  nem élhet ilyen
     optimalizálással, mivel a . metakarakter  nem illeszkedik az
     újsorkarakterre,  ezért  előfordulhat, hogy  a mintát minden
     egyes újsortól illeszteni kell, nem csak a szöveg elejére. A

       (.*) második

     minta úgy illeszkedik az "első\nés második" szövegre (ahol a
     \n  az újsort testesíti  meg),  hogy  az  első  "begyűjtött"
     szövegrész az "és" lesz. Ehhez a PCRE-nek  minden újsor után
     újból meg kell próbálni az illesztést.

     Ha  az  ilyesfajta  mintákat  olyan  szövegekre  alkalmazod,
     amelyekben nincsenek sortörések (újsorkarakterek),  akkor  a
     legjobb teljesítmény a PCRE_DOTALL módosító beállításával
     vagy a "rögzítés"  egyértelmű  megadásával  lehetséges: ^.*.
     Ez  megkíméli a PCRE-t,  hogy  végignézze  a  tárgyszöveget
     újsorkaraktert keresve, ahonnan az illesztést újrakezdheti.

     Vigyázz  azokkal  a  mintákkal,  amelyek  egymásba  ágyazott
     határozatlan számú ismétlést tartalmaznak. Ezek a minták sok
     időt vesznek el, ha nem illeszkedő szövegre  kell alkalmazni
     őket. Nézzük a

       (a+)*

     mintát! Ez 33 féleképpen illeszkedik  az "aaaa" szövegre, és
     ez a szám rohamosan növekszik, ahogy a szöveg egyre hosszabb
     lesz. (A * illeszkedhet 0-szor, 1-szer, 2-szer, 3-szor  vagy
     4-szer, és - 0-t kivéve - minden esetben a  +  is  különböző
     számúszor.)  Amikor  a  minta  fennmaradó része  ilyen és az
     illesztés   egésze  sikertelenül  érne   vége,  PCRE  elvben
     végigpróbálja az összes lehetőséget, ami rendkívül  sok időt
     vehet igénybe.

     Néhány egyszerűbb minta  esetén optimalizálás történik, mint
     például

       (a+)*b

     , ahol literális  (önmagára illeszkedő)  karakter  követi  a
     vizsgált részt. Mielőtt  a  hagyományos  illesztési  eljárás
     elkezdődik,  PCRE  megvizsgálja,  hogy  előfordul-e később a
     mintában  "b",  és  ha  nem,  akkor  azonnal  sikertelennek
     minősíti az illesztést.  Amikor azonban nem literális követi
     a mintarészt,  akkor  ez  az optimalizáció  nem használható.
     A különbséget megvizsgálhatod a

       (a+)*\d

     minta   viselkedésével  összehasonlítva.  Az  előbbi  szinte
     azonnal véget ér, ha csupa "a"-ból álló sorozatra illesztik,
     míg  az  utóbbi   kipróbálása   jelentős  időt  vesz  el  20
     karakternél hosszabb tárgyszövegekre.
     

preg_grep

(PHP 4 )

preg_grep --  Visszaadja azokat a tömbelemeket, amelyek illeszkednek a mintára

Leírás

array preg_grep ( string pattern, array input)

A preg_grep() függvény egy olyan tömbbel tér vissza, amelyben az input tömb azon elemei szerepelnek, amelyek a pattern mintára illeszkedtek.

PHP 4.0.4-től kezdve a preg_grep() függvény eredményeként visszaadott tömb az input indexeit használja. Ha ez nem előnyös, akkor az array_values() függvénnyel lehet a preg_grep() által visszaadott tömböt újraindexelni.

Példa 1. preg_grep() példa

// visszad minden olyan $tomb-beli elemet, ami lebegőpontos számot tartalmaz
$lebegopontos_tomb = preg_grep ("/^(\d+)?\.\d+$/", $tomb);

preg_match_all

(PHP 3>= 3.0.9, PHP 4 )

preg_match_all -- Reguláris kifejezés teljeskörű illesztését végzi

Leírás

int preg_match_all ( string pattern, string subject, array matches [, int flags])

A subject szövegben megkeresi az összes, a pattern mintára illeszkedő részt, és a matches tömbbe menti azokat az order paraméterben meghatározott sorrendben.

Amint az első illeszkedés megtalálta, a soron következő illesztést az utolsó illeszkedés végétől folytatja.

A flag paraméter az alábbi értékek kombinációja lehet (bár értelmetlen a PREG_PATTERN_ORDER-t és a PREG_SET_ORDER-t együtt használni):

PREG_PATTERN_ORDER

Azt eredményezi, hogy a $matches[0] olyan tömb lesz, ahol az összes a teljes mintára illeszkedő szövegrész lesz egymás után, a $matches[1] tömbben pedig azok a szövegrészek, amelyek első "gyűjtő" részmintára illeszkednek, és így tovább.

preg_match_all ("|<[^>]+>(.*)</[^>]+>|U",
    "<b>példa: </b><div align=left>ez itt a teszt szöveg</div>",
    $out, PREG_PATTERN_ORDER);
print $out[0][0].", ".$out[0][1]."\n";
print $out[1][0].", ".$out[1][1]."\n"

Ez a példa az alábbi eredményt adja:
<b>példa: </b>, <div align=left>ez itt a teszt szöveg</div>
példa: , ez itt a teszt szöveg

Tehát, az $out[0] egy tömb az összes, teljes mintára illeszkedő szöveggel, és $out[1] egy tömb az összes HTML-elem közti szöveggel.

PREG_SET_ORDER

Azt eredményezi, hogy $matches[0]-ben az első illesztés eredményeit, a $matches[1] a másodikét fogja tartalmazni, és így tovább.

preg_match_all ("|<[^>]+>(.*)</[^>]+>|U",
    "<b>példa: </b><div align=left>ez itt a teszt szöveg</div>",
    $out, PREG_SET_ORDER);
print $out[0][0].", ".$out[0][1]."\n";
print $out[1][0].", ".$out[1][1]."\n"

Ez a példa az alábbi eredményt adja:
<b>példa: </b>, példa:
<div align=left>ez itt a teszt szöveg</div>, ez itt a teszt szöveg

Ebben az esetben $matches[0] az első illesztés során megtalált szövegrészeket tartalmazza, a $matches[0][0]-ban a teljes mintára illeszkedő szöveggel, $matches[0][1]-ban az első "gyűjtő" részmintára illeszkedő résszel, és így tovább. Ehhez hasonlóan $matches[1] a második illesztés során megtalált szövegeket tartalmazza, stb.

PREG_OFFSET_CAPTURE

Minden egyezéshez az egyezés kezdőpozícióját is visszaadja az eredményben. Ez maga után vonja, hogy a visszaadott tömb minden eleme olyan tömb lesz, amelynek a 0. indexe az illeszkedő szöveget tartalmazza, míg az 1. indexen levő elem ennek a subject-en belüli kezdőpozicióját. Ez a jelzőbit PHP 4.3.0 verziójától használható.

Ha nincs megadva a flag paraméter, akkor az alapértelmezés a PREG_PATTERN_ORDER.

Ez a függvény az összes illeszkedés számával tér vissza (ami lehet akár 0 (!) is sikertelen illesztés esetén), vagy FALSE-szal hiba esetén.

Példa 1. Az összes telefonszám kigyűjtése egy adott szövegből.

preg_match_all ("/\(?  (\d{3})?  \)?  (?(1)  [\-\s] ) \d{3}-\d{4}/x",
                "Hívd a 555-1212 vagy 1-800-555-1212 számot", $phones);

Példa 2. HTML elemek keresése (mohón)

// A \\2 példa a "gyűjtő" részmintára történő hivatkozásra. Ez mondja meg
// PCRE-nek, hogy a másodikként megadott kerek zárójelre - ami ebben az
// esetben ([\w]+) - illesztett szövegnek kell szerepelnie a hivatkozás
// helyén is. A plusz visszaperjelre azért van szükség, mert a minta
// macskakörmök ("") közé van fogva.
$html = "<b>félkövér szöveg</b><a href=howdy.html>kattints ide</a>

preg_match_all ("/(<([\w]+)[^<]*>)(.*)(<\/\\2>)/", $html,
$matches);

for ($i=0; $i < count($matches[0]); $i++) {
echo "passzolt: ".$matches[0][$i]."\n";
echo "1. rész: ".$matches[1][$i]."\n";
echo "2. rész: ".$matches[3][$i]."\n";
echo "3. rész: ".$matches[4][$i]."\n\n";
}
A példa ezt eredményezi:
passzolt: <b>félkövér szöveg</b>
1. rész: <b>
2. rész: félkövér szöveg
3. rész: </b>

passzolt: <a href=howdy.html>kattints ide</a>
1. rész: <a href=howdy.html>
2. rész: kattints ide
3. rész: </a>

Lásd még: preg_match(), preg_replace(), és preg_split()!

preg_match

(PHP 3>= 3.0.9, PHP 4 )

preg_match -- Reguláris kifejezést illeszt a megadott szövegre

Leírás

int preg_match ( string pattern, string subject [, array matches [, int flags]])

A subject szövegben egyezést keres a pattern mintában megadott reguláris kifejezéssel.

A matches paraméterrel meghívva a keresés végeredményét ebbe a tömbbe tárolja el a függvény. A $matches[0] tartalmazza azt a szövegrészt, ami a teljes mintára illeszkedett, és a további elemek ($matches[1] és így tovább) azokat, amelyek a tömbindex szerinti "gyűjtő" részmintákra illeszkedtek.

A flags paraméter az alábbi értékeket veheti fel::

PREG_OFFSET_CAPTURE

Minden egyezéshez az egyezés kezdőpozicióját is visszaadja az eredményben. Ez maga után vonja, hogy a visszaadott tömb minden eleme olyan tömb lesz, amelynek a 0. indexe az illeszkedő szöveget tartalmazza, míg az 1. indexen levő elem ennek a subject-en belüli kezdőpozicióját. Ez a jelzőbit PHP 4.3.0 verziójától használható.

A preg_match() a pattern talált egyezések számával tér vissza, azaz 0-val, ha nem volt egyezés, vagy 1-gyel, mert a preg_match() az első egyezés után megáll. A preg_match_all() függvény ellenben a subject végéig folytatja a keresést és az illesztést. A preg_match() FALSE-t ad vissza hiba esetén.

Példa 1. A "php" sztring keresése

// az "i" a minta határolójele után azt jelzi,
// hogy a kis- és nagybetűkre közömbös a keresés.
if (preg_match ("/php/i", "PHP a web-scripting nyelvek egyike.")) {
    print "A minta passzol.";
} else {
    print "A minta nem passzol.";
}

Példa 2. A "web" szó keresése

// a mintában a \b szóhatárt jelöl, ezért csak a különálló
// "web" szavakra fog illeszkedni, és szórészletekre
// úgymint "webbing" vagy "cobweb" pedig nem.
if (preg_match ("/\bweb\b/i", "PHP a web scripting nyelvek egyike."))
{
    print "A minta passzol.";
} else {
    print "A match nem passzol.";
}
if (preg_match ("/\bweb\b/i", "PHP a website scripting nyelvek egyike.")) {
    print "A minta passzol.";
} else {
    print "A match nem passzol.";
}

Példa 3. domain-név kinyerése URL-ből

// gazdagép neve az URL-ből
preg_match("/^(http:\/\/)?([^\/]+)/i",
"http://www.php.net/index.html", $matches);
$host = $matches[2];
// a gazdagépnév utolsó két része
preg_match("/[^\.\/]+\.[^\.\/]+$/",$host,$matches);
echo "A domain név : ".$matches[0]."\n";
Ez a példa a következőt eredményezi:
A domain név : php.net

Lásd még: preg_match_all(), preg_replace() és preg_split()!

preg_quote

(PHP 3>= 3.0.9, PHP 4 )

preg_quote -- Reguláris kifejezés metakaraktereit literálissá változtatja

Leírás

string preg_quote ( string str [, string delimiter])

A preg_quote() függvény az str paraméterben kapott szövegben minden olyan karakter elé egy visszaperjelet helyez el, amely egy reguláris kifejezésben speciális jelentéssel bírhat. Ez akkor hasznos, ha olyan futási idő alatt összeállított sztringet kell egy mintában felhasználni, amelyben előfordulhatnak speciális jelentéssel bíró reguláris karakterek.

Ha a nem kötelező delimiter-t is megadod, akkor ez a karakter is visszaperjellel lesz bevezetve. Ez pedig azért hasznos, mert PCRE által megkövetelt határolójeleket is le lehet kezelni így. A / a leggyakrabban használt határolójel.

A reguláris kifejezésekben előforduló speciális karakterek:
. \ + * ? [ ^ ] $ ( ) { } = ! < > | :

Példa 1.

$kulcsszavak = "$40 egy g3/400-ért";
$kulcsszavak = preg_quote ($keywords, "/");
echo $kulcsszavak; // \$40 egy g3\/400-ért adja vissza

Példa 2. Adott szöveg dőlt betűssé alakítása HTML-ben

// Ebben a példában preg_quote($szo)-t használjuk arra, hogy
// a csillagokat megfosszuk a reguláris kifejezésekben használt
// speciális jelentésüktől.

$szoveg = "Ezt a könyvet *nagyon* nehéz megtalálni.";
$szo    = "*nagyon*";
$szoveg = preg_replace ("/".preg_quote($szo)."/",
                          "<i>".$szo."</i>;",
                          $szoveg);

preg_replace_callback

(PHP 4 >= 4.0.5)

preg_replace_callback -- Reguláris kifejezés alapján keres és a megadott függvényt meghívva végzi a cserét

Leírás

mixed preg_replace_callback ( mixed pattern, mixed callback, mixed subject [, int limit])

Ennek a függvénynek a működése szinte azonos a preg_replace() függvényével azt leszámítva, hogy replacement paraméterként egy callback függvényt kell megadni, amely minden sikeres illesztésnél meghívásra kerül. Az illeszkedő szövegeket egy tömbben adja át a PHP a 'meghívott' függvénynek, és annak a helyettesítési szöveggel kell visszatérnie. Ez a függvény a PHP 4.0.5-től elérhető.

Lásd még: preg_replace()!

preg_replace

(PHP 3>= 3.0.9, PHP 4 )

preg_replace -- Reguláris kifejezés alapján keres és cserél

Leírás

mixed preg_replace ( mixed pattern, mixed replacement, mixed subject [, int limit])

A subject-ben megadott szövegben keres a pattern paraméterben megadott mintára illeszkedő részeket és azokat lecseréli a replacement-ben megadott kifejezésre. Ha a limit is szerepel, akkor csak az első limit számú illeszkedő részt cseréli le. Ha limit hiányzik vagy értéke -1, akkor minden illeszkedő részt cserél.

A replacement-ben hivatkozásokat is el lehet helyezni \\n vagy - PHP 4.0.4-től kezdve - $n alakban. (Ez utóbbit részesítsd előnyben.) Minden ilyen hivatkozás az n. zárójelezett részminta által megtalált szöveggel lesz helyettesítve. Az n értéke 0-tól 99-ig terjedhet, ahol is a \\0 vagy $0 hivatkozás a teljes mintára illeszkedő szöveget jelenti. A kerek nyitó zárójelek 1-től kezdve balról jobbra vannak számozva és az általuk bevezetett "gyűjtő" részminták sorszámát adják.

Ha volt egyezés, akkor az új subject-tel tér vissza a függvény, egyébként a változatlanul hagyott, eredeti subject-tel.

A limit-től eltekintve minden, preg_replace()-nek átadott paraméter lehet tömb is.

Ha subject tömb típusú, akkor a keresés és a helyettesítés a tömb minden elemén végrehajtódik, és a visszatérési érték is tömb lesz.

Ha a pattern és replacement paraméterek tömb típusúak, akkor a preg_replace() veszi a tömbök elemeit és mindegyikkel páronként elvégzi a keresést és a helyettesítést a subject szövegen. Ha a replacement tömbnek a pattern tömbnél a kevesebb eleme van, akkor a pár nélküli mintákat üres sztringgel fogja helyettesíteni. Ha a pattern tömb és replacement sztring típusú, akkor ezt a helyettesítési szöveget használja minden pattern-beli mintához. A fordított esetnek nem lenne sok értelme.

Az /e módosító hatására a preg_replace() a replacement paramétert PHP kódként értelmezi, miután a hivatkozások behelyettesítését elvégezte. Jó tanácsként: érdemes megbizonyosodni arról, hogy replacement érvényes PHP kódot tartalmaz (sztringben megadva), másképp a PHP szintaktikai hibát (Parse Error) fog jelezni abban a sorban, ahol a preg_replace() függvényt meghívtad.

Példa 1. Néhány érték cseréje

$mintak = array ("/(19|20)(\d{2})-(\d{1,2})-(\d{1,2})/",
                   "/^\s*{(\w+)}\s*=/");
$csere  = array ("\\3/\\4/\\1\\2", "$\\1 =");
print preg_replace ($mintak, $csere, "{kezdoDatum} = 1999-5-27");
Ennek a példának a végeredménye:
$kezdoDatum = 5/27/1999

Példa 2. Az /e módosítót használata:

preg_replace ("/(<\/?)(\w+)([^>]*>)/e",
              "'\\1'.strtoupper('\\2').'\\3'",
              $html_body);

Ez az összes HTML elemet nagybetűsre cseréli a bemeneti szövegben.

Példa 3. HTML-ből sima szöveggé konvertálás

// A $dokumentum HTML formátumú.
// Minden HTML elemet, javascript szakaszt és térközt eltávolít a
// dokumentumból. Ezenkívül néhány megszokott HTML entitást is a
// sima, karakteres megfelelőikre konvertál.

$mit = array ("'<script[^<]*?>.*?</script>'si", // javascript eltüntetése
              "'<[\/\!]*?[^<>]*?>'si",  // HTML elemek eltüntetése
              "'([\r\n])[\s]+'",  // térközök
              "'&(quot|#34);'i",  // HTML entitások
              "'&(amp|#38);'i",
              "'&(lt|#60);'i",
              "'&(gt|#62);'i",
              "'&(nbsp|#160);'i",
              "'&(iexcl|#161);'i",
              "'&(cent|#162);'i",
              "'&(pound|#163);'i",
              "'&(copy|#169);'i",
              "'&#(\d+);'e");  // PHP kódként értelmezze

$mire = array ("",
               "",
               "\\1",
               "\"",
               "&",
               "<",
               ">",
               " ",
               chr(161),
               chr(162),
               chr(163),
               chr(169),
               "chr(\\1)");

$szoveg = preg_replace ($mit, $mire, $dokumentum);

Megjegyzés: A limit paraméter a PHP 4.0.1pl2 után került a nyelvbe.

Lásd még: preg_match(), preg_match_all() és preg_split()!

preg_split

(PHP 3>= 3.0.9, PHP 4 )

preg_split -- Sztringet darabol fel reguláris kifejezésre illeszkedő részei mentén

Leírás

array preg_split ( string pattern, string subject [, int limit [, int flags]])

Megjegyzés: A flags paraméterrel a PHP 4 Beta 3-ban lett kiegészítve.

Ez a függvény a pattern minta illesztésének határai mentén darabolja fel a subject szöveget, és a szövegdarabokat tömbbe összefogva adja vissza.

Ha a limit meg van adva, akkor csak limit számú elemmel tér vissza. A limit értéke lehet -1 (jelentése: nincs korlát), és ez akkor hasznos, ha a flags paramétert egy konkrét korlát megadása nélkül kell beállítani.

A flags a következő jelzőknek bármilyen kombinációja lehet a ( bitszintű | operátorral):

PREG_SPLIT_NO_EMPTY

Ekkor csak a nem üres szövegrészeket adja vissza a preg_split().

PREG_SPLIT_DELIM_CAPTURE

Ekkor a kerekzárójelek közé fogott ("gyűjtő") részmintára illeszkedő szövegrészeket is visszadja a függvény. Ez a jelző 4.0.5 verziótól használható.

PREG_SPLIT_OFFSET_CAPTURE

Minden egyezéshez az egyezés kezdőpozicióját is visszaadja az eredményben. Ez maga után vonja, hogy a visszaadott tömb minden eleme olyan tömb lesz, amelynek a 0. indexe az illeszkedő szöveget tartalmazza, míg az 1. indexen levő elem ennek a subject-en belüli kezdőpozicióját. Ez a jelzőbit PHP 4.3.0 verziójától használható.

Példa 1. preg_split() példa : a keresett szöveg kucslszavait adja vissza.

// Feldarabolja a kifejezést vesszők és térközkarakterek mentén,
// amelyek a következők " ", \r, \t, \n és \f .
$kulcsszavak = preg_split ("/[\s,]+/", "hypertext language, programming");

Példa 2. Sztring karakterekre darabolása

$sztring = 'karakterfűzér';
$karakterek = preg_split('//', $sztring, -1, PREG_SPLIT_NO_EMPTY);
print_r($karakterek);

Példa 3. Az illeszkedések és a pozicióik a szöveg feldarabolása után

$sztring = 'hypertext language programming';
$szavak  = preg_split('/ /', $sztring, -1, PREG_SPLIT_OFFSET_CAPTURE);
print_r($szavak);

will yield

Array
(
    [0] => Array
        (
            [0] => hypertext
            [1] => 0
        )

    [1] => Array
        (
            [0] => language
            [1] => 10
        )

    [2] => Array
        (
            [0] => programming
            [1] => 19
        )
)

Lásd még: spliti(), split(), implode(), preg_match(), preg_match_all() és preg_replace()!

XCII. qtdom functions

Figyelem

Ez a kiterjesztés KÍSÉRLETI JELLEGGEL MŰKÖDIK. Ez azt jelenti, hogy minden itt dokumentált működés, beleértve a függvények nevét, működését vagy bármi más, amit a kiterjesztés kapcsán leírtunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a kiterjesztést csak a saját felelősségedre használd!

Megjegyzés: Ez a kiterjesztés nem működik Windows operációs rendszereken!


Követelmények

You need the Qt-library >=2.2.0


Telepítés

Configure PHP --with-qtdom to use these functions.

Tartalom
qdom_error -- Returns the error string from the last QDOM operation or FALSE if no errors occurred
qdom_tree -- Creates a tree of an XML string

qdom_error

(PHP 4 >= 4.0.5)

qdom_error -- Returns the error string from the last QDOM operation or FALSE if no errors occurred

Description

string qdom_error ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

qdom_tree

(PHP 4 >= 4.0.4)

qdom_tree -- Creates a tree of an XML string

Description

object qdom_tree ( string )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

XCIII. Regular Expression Functions (POSIX Extended)

Bevezetés

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

Figyelem

These regular expression functions are not binary-safe. The PCRE functions are.

Regular expressions are used for complex string manipulation in PHP. The functions that support regular expressions are:

These functions all take a regular expression string as their first argument. 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.


Követelmények

Az itt leírt függvények használatához semmilyen külső függvénykönyvtár megléte nem szükségeltetik.


Telepítés

Figyelem

Do not change the TYPE unless you know what you are doing.

To enable regexp support configure PHP --with-regex[=TYPE]. TYPE can be one of system, apache, php. The default is to use php.

A PHP Windowsos változata beépített támogatással rendelkezik eme kiterjesztéshez. nincs szükség semmilyen kiterjesztés betöltésére, hogy az itt felsorolt függvnyeket használhasd.


Futásidejű beállítások

Ez a kiterjesztés semmilyen konfigurációs beállításokat nem definiál a php.ini állományban.


Erőforrás típusok

Ez a kiterjesztés semmilyen erőforrás típust nem definiál.


Előre definiált állandók

Ez a kiterjesztés semmilyen konstans értéket nem definiál.


Példák

Példa 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)", $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);
?>


Lásd még

For regular expressions in Perl-compatible syntax have a look at the PCRE functions. The simpler shell style wildcard pattern matching is provided by fnmatch().

Tartalom
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

ereg_replace

(PHP 3, PHP 4 )

ereg_replace -- Replace regular expression

Description

string ereg_replace ( string pattern, string replacement, string string)

This function scans string for matches to pattern, then replaces the matched text with replacement.

The modified string is returned. (Which may mean that the original string is returned if there are no matches to be replaced.)

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.

If no matches are found in string, then string will be returned unchanged.

For example, the following code snippet prints "This was a test" three times:

Példa 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:

Példa 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.' */
?>

Példa 3. Replace URLs with links

<?php
$text = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]",
                     "<a href=\"\\0\">\\0</a>", $text);
?>

Tipp: preg_replace(), which uses a Perl-compatible regular expression syntax, is often a faster alternative to ereg_replace().

See also ereg(), eregi(), eregi_replace(), str_replace(), and preg_match().

ereg

(PHP 3, PHP 4 )

ereg -- Regular expression match

Description

bool ereg ( string pattern, string string [, array regs])

Megjegyzés: preg_match(), which uses a Perl-compatible regular expression syntax, is often a faster alternative to ereg().

Searches a string for matches to the regular expression given in pattern in a case-sensitive way.

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.

Megjegyzés: 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().

Returns TRUE if a match for pattern was found in string, or FALSE if no matches were found or an error occurred.

The following code snippet takes a date in ISO format (YYYY-MM-DD) and prints it in DD.MM.YYYY format:

Példa 1. ereg() example

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

See also eregi(), ereg_replace(), eregi_replace(), preg_match(), strpos(), and strstr().

eregi_replace

(PHP 3, PHP 4 )

eregi_replace -- replace regular expression case insensitive

Description

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.

See also ereg(), eregi(), and ereg_replace().

eregi

(PHP 3, PHP 4 )

eregi -- case insensitive regular expression match

Description

bool eregi ( string pattern, string string [, array regs])

This function is identical to ereg() except that this ignores case distinction when matching alphabetic characters.

Példa 1. eregi() example

<?php
if (eregi("z", $string)) {
    echo "'$string' contains a 'z' or 'Z'!";
}
?>

See also ereg(), ereg_replace(), eregi_replace(), stripos(), and stristr().

split

(PHP 3, PHP 4 )

split -- split string into array by regular expression

Description

array split ( string pattern, string string [, int limit])

Tipp: preg_split(), which uses a Perl-compatible regular expression syntax, is often a faster alternative to split(). If you don't require the power of regular expressions, it is faster to use explode(), which doesn't incur the overhead of the regular expression engine.

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 limit is set, the returned array will contain a maximum of limit elements with the last element containing the whole rest of string. If an error occurs, split() returns FALSE.

To split off the first four fields from a line from /etc/passwd:

Példa 1. split() example

<?php
list($user, $pass, $uid, $gid, $extra) =
    split(":", $passwd_line, 5);
?>

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.

To parse a date which may be delimited with slashes, dots, or hyphens:

Példa 2. split() example

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

For users looking for a way to emulate Perl's @chars = split('', $str) behaviour, please see the examples for preg_split().

Please note that pattern is a 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.

See also: preg_split(), spliti(), explode(), implode(), chunk_split(), and wordwrap().

spliti

(PHP 4 >= 4.0.1)

spliti --  Split string into array by regular expression case insensitive

Description

array spliti ( string pattern, string string [, int limit])

This function is identical to split() except that this ignores case distinction when matching alphabetic characters.

See also preg_spliti(), split(), explode(), and implode().

sql_regcase

(PHP 3, PHP 4 )

sql_regcase --  Make regular expression for case insensitive match

Description

string sql_regcase ( string string)

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.

Példa 1. sql_regcase() example

<?php
echo sql_regcase("Foo - bar.");
?>

prints:

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

XCIV. Semaphore, Shared Memory and IPC Functions

Bevezetés

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.

Táblázat 1. Limits of Shared Memory by the Unix OS

SHMMAXmax size of shared memory, normally 131072 bytes
SHMMINminimum 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.

Megjegyzés: Ez a kiterjesztés nem működik Windows operációs rendszereken!


Követelmények

Az itt leírt függvények használatához semmilyen külső függvénykönyvtár megléte nem szükségeltetik.


Telepítés

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.


Futásidejű beállítások

Az alábbi függvények viselkedése befolyásolható a php.ini segítségével.

Táblázat 2. Semaphore Configuration Options

NameDefaultChangeable
sysvmsg.value"42"PHP_INI_ALL
sysvmsg.string"foobar"PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().


Erőforrás típusok


Előre definiált állandók

Ez a kiterjesztés semmilyen konstans értéket nem definiál.

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

ftok

(PHP 4 >= 4.2.0)

ftok --  Convert a pathname and a project identifier to a System V IPC key

Description

int ftok ( string pathname, string proj)

The function converts the pathname of an existing accessible file and a project identifier (proj) into a integer for use with for example shmop_open() and other System V IPC keys. The proj parameter should be a one character string.

On success the return value will be the created key value, otherwise -1 is returned.

See also shmop_open() and sem_get().

msg_get_queue

(PHP 4 >= 4.3.0)

msg_get_queue --  Create or attach to a message queue

Description

int msg_get_queue ( int key [, int perms])

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 (default: 0666). 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. If the message queue already exists, the perms will be ignored.

See also: msg_remove_queue(), msg_receive(), msg_send(), msg_stat_queue() and msg_set_queue().

msg_receive

(PHP 4 >= 4.3.0)

msg_receive --  Receive a message from a message queue

Description

bool msg_receive ( int queue, int desiredmsgtype, int msgtype, int maxsize, mixed message [, bool unserialize [, int flags [, int errorcode]]])

msg_receive() will receive the first message from the specified queue of the type specified by desiredmsgtype. The type of the message that was received will be stored in msgtype. 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). The received message will be stored in message, unless there were errors receiving the message, in which case the optional errorcode will be set to the value of the system errno variable to help you identify the cause.

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.

unserialize defaults to TRUE; if it is 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.

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

Táblázat 1. Flag values for msg_receive

MSG_IPC_NOWAITIf there are no messages of the desiredmsgtype, return immediately and do not wait. The function will fail and return an integer value corresponding to ENOMSG.
MSG_EXCEPTUsing 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.

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.

msg_receive() returns TRUE on success or FALSE on failure. If the function fails, the optional errorcode will be set to the value of the system errno variable.

See also: msg_remove_queue(), msg_send(), msg_stat_queue() and msg_set_queue().

msg_remove_queue

(PHP 4 >= 4.3.0)

msg_remove_queue --  Destroy a message queue

Description

bool msg_remove_queue ( int 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.

See also: msg_remove_queue(), msg_receive(), msg_stat_queue() and msg_set_queue().

msg_send

(PHP 4 >= 4.3.0)

msg_send --  Send a message to a message queue

Description

bool msg_send ( int queue, int msgtype, mixed message [, bool serialize [, bool blocking [, int errorcode]]])

msg_send() sends a message of type msgtype (which MUST be greater than 0) to a the message queue specified by queue.

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 EAGAIN, indicating that you should try to send your message again a little later on.

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.

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.

See also: msg_remove_queue(), msg_receive(), msg_stat_queue() and msg_set_queue().

msg_set_queue

(PHP 4 >= 4.3.0)

msg_set_queue --  Set information in the message queue data structure

Description

bool msg_set_queue ( int 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. You specify the values you require by setting the value of the keys that you require in the data array.

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.

See also: msg_remove_queue(), msg_receive(), msg_stat_queue() and msg_set_queue().

msg_stat_queue

(PHP 4 >= 4.3.0)

msg_stat_queue --  Returns information from the message queue data structure

Description

array msg_stat_queue ( int 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.

The return value is an array whose keys and values have the following meanings:

Táblázat 1. 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 number of bytes of space currently available in the queue to hold sent messages until they are received.
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.

See also: msg_remove_queue(), msg_receive(), msg_stat_queue() and msg_set_queue().

sem_acquire

(PHP 3>= 3.0.6, PHP 4 )

sem_acquire -- Acquire a semaphore

Description

bool sem_acquire ( int sem_identifier)

sem_acquire() blocks (if necessary) until the semaphore can be acquired. A process attempting to acquire a semaphore which it has already acquired will block forever if acquiring the semaphore would cause its max_acquire value to be exceeded.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

After processing a request, any semaphores acquired by the process but not explicitly released will be released automatically and a warning will be generated.

See also: sem_get() and sem_release().

sem_get

(PHP 3>= 3.0.6, PHP 4 )

sem_get -- Get a semaphore id

Description

int sem_get ( int key [, int max_acquire [, int perm]])

sem_get() returns an id that can be used to access the System V semaphore with the given key. The semaphore is created if necessary using the permission bits specified in perm (defaults to 0666). The number of processes that can acquire the semaphore simultaneously is set to max_acquire (defaults to 1). Actually this value is set only if the process finds it is the only process currently attached to the semaphore.

Returns: A positive semaphore identifier on success, or FALSE on error.

A second call to sem_get() for the same key will return a different semaphore identifier, but both identifiers access the same underlying semaphore.

See also sem_acquire(), sem_release(), and ftok().

Megjegyzés: This function does not work on Windows systems.

sem_release

(PHP 3>= 3.0.6, PHP 4 )

sem_release -- Release a semaphore

Description

bool sem_release ( int sem_identifier)

sem_release() releases the semaphore if it is currently acquired by the calling process, otherwise a warning is generated.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

After releasing the semaphore, sem_acquire() may be called to re-acquire it.

See also sem_get() and sem_acquire().

Megjegyzés: This function does not work on Windows systems.

sem_remove

(PHP 4 >= 4.1.0)

sem_remove -- Remove a semaphore

Description

bool sem_remove ( int sem_identifier)

sem_remove() removes the semaphore sem_identifier if it has been created by sem_get(), otherwise generates a warning.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

After removing the semaphore, it is no more accessible.

See also: sem_get(), sem_release() and sem_acquire().

Megjegyzés: This function does not work on Windows systems. It was added on PHP 4.1.0.

shm_attach

(PHP 3>= 3.0.6, PHP 4 )

shm_attach -- Creates or open a shared memory segment

Description

int shm_attach ( int key [, int memsize [, int perm]])

shm_attach() returns an id that 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 (default: sysvshm.init_mem in the php.ini, otherwise 10000 bytes) and the optional perm-bits perm (default: 0666).

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.

See also: ftok().

Megjegyzés: This function does not work on Windows systems.

shm_detach

(PHP 3>= 3.0.6, PHP 4 )

shm_detach -- Disconnects from shared memory segment

Description

bool shm_detach ( int 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.

shm_detach() always returns TRUE.

shm_get_var

(PHP 3>= 3.0.6, PHP 4 )

shm_get_var -- Returns a variable from shared memory

Description

mixed shm_get_var ( int id, int variable_key)

shm_get_var() returns the variable with a given variable_key. The variable is still present in the shared memory.

Megjegyzés: This function does not work on Windows systems.

shm_put_var

(PHP 3>= 3.0.6, PHP 4 )

shm_put_var -- Inserts or updates a variable in shared memory

Description

int shm_put_var ( int shm_identifier, int variable_key, mixed variable)

Inserts or updates a variable with a given variable_key. All variable-types are supported.

Megjegyzés: This function does not work on Windows systems.

shm_remove_var

(PHP 3>= 3.0.6, PHP 4 )

shm_remove_var -- Removes a variable from shared memory

Description

int shm_remove_var ( int id, int variable_key)

Removes a variable with a given variable_key and frees the occupied memory.

Megjegyzés: This function does not work on Windows systems.

shm_remove

(PHP 3>= 3.0.6, PHP 4 )

shm_remove -- Removes shared memory from Unix systems

Description

int shm_remove ( int shm_identifier)

Removes shared memory from Unix systems. All data will be destroyed.

Megjegyzés: This function does not work on Windows systems.

XCV. SESAM database functions

Bevezetés

SESAM/SQL-Server is a mainframe database system, developed by Fujitsu Siemens Computers, Germany. It runs on high-end mainframe servers using the operating system BS2000/OSD.

In numerous productive BS2000 installations, SESAM/SQL-Server has proven

  • the ease of use of Java-, Web- and client/server connectivity,

  • the capability to work with an availability of more than 99.99%,

  • the ability to manage tens and even hundreds of thousands of users.

There is a PHP3 SESAM interface available which allows database operations via PHP-scripts.

Megjegyzés: Access to SESAM is only available with the latest CVS-Version of PHP3. PHP 4 does not support the SESAM database.


Futásidejű beállítások

Az alábbi függvények viselkedése befolyásolható a php.ini segítségével.

sesam_oml string

Name of BS2000 PLAM library containing the loadable SESAM driver modules. Required for using SESAM functions. The BS2000 PLAM library must be set ACCESS=READ,SHARE=YES because it must be readable by the apache server's user id.

sesam_configfile string

Name of SESAM application configuration file. Required for using SESAM functions. The BS2000 file must be readable by the apache server's user id.

The application configuration file will usually contain a configuration like (see SESAM reference manual):

CNF=B
NAM=K
NOTYPE

sesam_messagecatalog string

Name of SESAM message catalog file. In most cases, this directive is not necessary. Only if the SESAM message file is not installed in the system's BS2000 message file table, it can be set with this directive.

The message catalog must be set ACCESS=READ,SHARE=YES because it must be readable by the apache server's user id.


Configuration notes

There is no standalone support for the PHP SESAM interface, it works only as an integrated Apache module. In the Apache PHP module, this SESAM interface is configured using Apache directives.

Táblázat 1. SESAM Configuration directives

DirectiveMeaning
php3_sesam_oml Name of BS2000 PLAM library containing the loadable SESAM driver modules. Required for using SESAM functions.

Example:

php3_sesam_oml $.SYSLNK.SESAM-SQL.030

php3_sesam_configfile Name of SESAM application configuration file. Required for using SESAM functions.

Example:

php3_sesam_configfile $SESAM.SESAM.CONF.AW

It will usually contain a configuration like (see SESAM reference manual):

CNF=B
NAM=K
NOTYPE

php3_sesam_messagecatalog Name of SESAM message catalog file. In most cases, this directive is not necessary. Only if the SESAM message file is not installed in the system's BS2000 message file table, it can be set with this directive.

Example:

php3_sesam_messagecatalog $.SYSMES.SESAM-SQL.030

In addition to the configuration of the PHP/SESAM interface, you have to configure the SESAM-Database server itself on your mainframe as usual. That means:

  • starting the SESAM database handler (DBH), and

  • connecting the databases with the SESAM database handler

To get a connection between a PHP script and the database handler, the CNF and NAM parameters of the selected SESAM configuration file must match the id of the started database handler.

In case of distributed databases you have to start a SESAM/SQL-DCN agent with the distribution table including the host and database names.

The communication between PHP (running in the POSIX subsystem) and the database handler (running outside the POSIX subsystem) is realized by a special driver module called SQLSCI and SESAM connection modules using common memory. Because of the common memory access, and because PHP is a static part of the web server, database accesses are very fast, as they do not require remote accesses via ODBC, JDBC or UTM.

Only a small stub loader (SESMOD) is linked with PHP, and the SESAM connection modules are pulled in from SESAM's OML PLAM library. In the configuration, you must tell PHP the name of this PLAM library, and the file link to use for the SESAM configuration file (As of SESAM V3.0, SQLSCI is available in the SESAM Tool Library, which is part of the standard distribution).

Because the SQL command quoting for single quotes uses duplicated single quotes (as opposed to a single quote preceded by a backslash, used in some other databases), it is advisable to set the PHP configuration directives php3_magic_quotes_gpc and php3_magic_quotes_sybase to On for all PHP scripts using the SESAM interface.


Runtime considerations

Because of limitations of the BS2000 process model, the driver can be loaded only after the Apache server has forked off its server child processes. This will slightly slow down the initial SESAM request of each child, but subsequent accesses will respond at full speed.

When explicitly defining a Message Catalog for SESAM, that catalog will be loaded each time the driver is loaded (i.e., at the initial SESAM request). The BS2000 operating system prints a message after successful load of the message catalog, which will be sent to Apache's error_log file. BS2000 currently does not allow suppression of this message, it will slowly fill up the log.

Make sure that the SESAM OML PLAM library and SESAM configuration file are readable by the user id running the web server. Otherwise, the server will be unable to load the driver, and will not allow to call any SESAM functions. Also, access to the database must be granted to the user id under which the Apache server is running. Otherwise, connections to the SESAM database handler will fail.


Cursor Types

The result cursors which are allocated for SQL "select type" queries can be either "sequential" or "scrollable". Because of the larger memory overhead needed by "scrollable" cursors, the default is "sequential".

When using "scrollable" cursors, the cursor can be freely positioned on the result set. For each "scrollable" query, there are global default values for the scrolling type (initialized to: SESAM_SEEK_NEXT) and the scrolling offset which can either be set once by sesam_seek_row() or each time when fetching a row using sesam_fetch_row(). When fetching a row using a "scrollable" cursor, the following post-processing is done for the global default values for the scrolling type and scrolling offset:

Táblázat 2. Scrolled Cursor Post-Processing

Scroll TypeAction
SESAM_SEEK_NEXTnone
SESAM_SEEK_PRIORnone
SESAM_SEEK_FIRST set scroll type to SESAM_SEEK_NEXT
SESAM_SEEK_LAST set scroll type to SESAM_SEEK_PRIOR
SESAM_SEEK_ABSOLUTEAuto-Increment internal offset value
SESAM_SEEK_RELATIVEnone. (maintain global default offset value, which allows for, e.g., fetching each 10th row backwards)


Porting note

Because in the PHP world it is natural to start indexes at zero (rather than 1), some adaptions have been made to the SESAM interface: whenever an indexed array is starting with index 1 in the native SESAM interface, the PHP interface uses index 0 as a starting point. E.g., when retrieving columns with sesam_fetch_row(), the first column has the index 0, and the subsequent columns have indexes up to (but not including) the column count ($array["count"]). When porting SESAM applications from other high level languages to PHP, be aware of this changed interface. Where appropriate, the description of the respective PHP sesam functions include a note that the index is zero based.


Security concerns

When allowing access to the SESAM databases, the web server user should only have as little privileges as possible. For most databases, only read access privilege should be granted. Depending on your usage scenario, add more access rights as you see fit. Never allow full control to any database for any user from the 'net! Restrict access to PHP scripts which must administer the database by using password control and/or SSL security.


Migration from other SQL databases

No two SQL dialects are ever 100% compatible. When porting SQL applications from other database interfaces to SESAM, some adaption may be required. The following typical differences should be noted:

  • Vendor specific data types

    Some vendor specific data types may have to be replaced by standard SQL data types (e.g., TEXT could be replaced by VARCHAR(max. size)).

  • Keywords as SQL identifiers

    In SESAM (as in standard SQL), such identifiers must be enclosed in double quotes (or renamed).

  • Display length in data types

    SESAM data types have a precision, not a display length. Instead of int(4) (intended use: integers up to '9999'), SESAM requires simply int for an implied size of 31 bits. Also, the only datetime data types available in SESAM are: DATE, TIME(3) and TIMESTAMP(3).

  • SQL types with vendor-specific unsigned, zerofill, or auto_increment attributes

    Unsigned and zerofill are not supported. Auto_increment is automatic (use "INSERT ... VALUES(*, ...)" instead of "... VALUES(0, ...)" to take advantage of SESAM-implied auto-increment.

  • int ... DEFAULT '0000'

    Numeric variables must not be initialized with string constants. Use DEFAULT 0 instead. To initialize variables of the datetime SQL data types, the initialization string must be prefixed with the respective type keyword, as in: CREATE TABLE exmpl ( xtime timestamp(3) DEFAULT TIMESTAMP '1970-01-01 00:00:00.000' NOT NULL );

  • $count = xxxx_num_rows();

    Some databases promise to guess/estimate the number of the rows in a query result, even though the returned value is grossly incorrect. SESAM does not know the number of rows in a query result before actually fetching them. If you REALLY need the count, try SELECT COUNT(...) WHERE ..., it will tell you the number of hits. A second query will (hopefully) return the results.

  • DROP TABLE thename;

    In SESAM, in the DROP TABLE command, the table name must be either followed by the keyword RESTRICT or CASCADE. When specifying RESTRICT, an error is returned if there are dependent objects (e.g., VIEWs), while with CASCADE, dependent objects will be deleted along with the specified table.


Notes on the use of various SQL types

SESAM does not currently support the BLOB type. A future version of SESAM will have support for BLOB.

At the PHP interface, the following type conversions are automatically applied when retrieving SQL fields:

Táblázat 3. SQL to PHP Type Conversions

SQL TypePHP Type
SMALLINT, INTEGERinteger
NUMERIC, DECIMAL, FLOAT, REAL, DOUBLEfloat
DATE, TIME, TIMESTAMPstring
VARCHAR, CHARACTERstring
When retrieving a complete row, the result is returned as an array. Empty fields are not filled in, so you will have to check for the existence of the individual fields yourself (use isset() or empty() to test for empty fields). That allows more user control over the appearance of empty fields (than in the case of an empty string as the representation of an empty field).


Support of SESAM's "multiple fields" feature

The special "multiple fields" feature of SESAM allows a column to consist of an array of fields. Such a "multiple field" column can be created like this:

Példa 1. Creating a "multiple field" column

CREATE TABLE multi_field_test (
    pkey CHAR(20) PRIMARY KEY,
    multi(3) CHAR(12)
)
and can be filled in using:

Példa 2. Filling a "multiple field" column

INSERT INTO multi_field_test (pkey, multi(2..3) )
    VALUES ('Second', <'first_val', 'second_val'>)
Note that (like in this case) leading empty sub-fields are ignored, and the filled-in values are collapsed, so that in the above example the result will appear as multi(1..2) instead of multi(2..3).

When retrieving a result row, "multiple columns" are accessed like "inlined" additional columns. In the example above, "pkey" will have the index 0, and the three "multi(1..3)" columns will be accessible as indices 1 through 3.


Lásd még

For specific SESAM details, please refer to the SESAM/SQL-Server documentation (english) or the SESAM/SQL-Server documentation (german), both available online, or use the respective manuals.

Tartalom
sesam_affected_rows --  Get number of rows affected by an immediate query
sesam_commit --  Commit pending updates to the SESAM database
sesam_connect -- Open SESAM database connection
sesam_diagnostic --  Return status information for last SESAM call
sesam_disconnect -- Detach from SESAM connection
sesam_errormsg -- Returns error message of last SESAM call
sesam_execimm -- Execute an "immediate" SQL-statement
sesam_fetch_array -- Fetch one row as an associative array
sesam_fetch_result -- Return all or part of a query result
sesam_fetch_row -- Fetch one row as an array
sesam_field_array --  Return meta information about individual columns in a result
sesam_field_name --  Return one column name of the result set
sesam_free_result -- Releases resources for the query
sesam_num_fields --  Return the number of fields/columns in a result set
sesam_query -- Perform a SESAM SQL query and prepare the result
sesam_rollback --  Discard any pending updates to the SESAM database
sesam_seek_row --  Set scrollable cursor mode for subsequent fetches
sesam_settransaction -- Set SESAM transaction parameters

sesam_affected_rows

(PHP 3 CVS only)

sesam_affected_rows --  Get number of rows affected by an immediate query

Description

int sesam_affected_rows ( string result_id)

result_id is a valid result id returned by sesam_query().

Returns the number of rows affected by a query associated with result_id.

The sesam_affected_rows() function can only return useful values when used in combination with "immediate" SQL statements (updating operations like INSERT, UPDATE and DELETE) because SESAM does not deliver any "affected rows" information for "select type" queries. The number returned is the number of affected rows.

Példa 1. sesam_affected_rows() example

<?php
$result = sesam_execimm("DELETE FROM PHONE WHERE LASTNAME = '" . strtoupper($name) . "'");
if (!$result) {
    /* ... error ... */
}
echo sesam_affected_rows($result).
    " entries with last name " . $name . " deleted.\n";
?>

See also sesam_query() and sesam_execimm().

sesam_commit

(PHP 3 CVS only)

sesam_commit --  Commit pending updates to the SESAM database

Description

bool sesam_commit ( void )

Returns: TRUE on success, FALSE on errors

sesam_commit() commits any pending updates to the database.

Note that there is no "auto-commit" feature as in other databases, as it could lead to accidental data loss. Uncommitted data at the end of the current script (or when calling sesam_disconnect()) will be discarded by an implied sesam_rollback() call.

See also: sesam_rollback().

Példa 1. Committing an update to the SESAM database

<?php
if (sesam_connect ("mycatalog", "myschema", "otto")) {
    if (!sesam_execimm ("INSERT INTO mytable VALUES (*, 'Small Test', <0, 8, 15>)"))
        die("insert failed");
    if (!sesam_commit())
        die("commit failed");
}
?>

sesam_connect

(PHP 3 CVS only)

sesam_connect -- Open SESAM database connection

Description

bool sesam_connect ( string catalog, string schema, string user)

Returns TRUE if a connection to the SESAM database was made, or FALSE on error.

sesam_connect() establishes a connection to an SESAM database handler task. The connection is always "persistent" in the sense that only the very first invocation will actually load the driver from the configured SESAM OML PLAM library. Subsequent calls will reuse the driver and will immediately use the given catalog, schema, and user.

When creating a database, the "catalog" name is specified in the SESAM configuration directive //ADD-SQL-DATABASE-CATALOG-LIST ENTRY-1 = *CATALOG(CATALOG-NAME = catalogname,...)

The "schema" references the desired database schema (see SESAM handbook).

The "user" argument references one of the users which are allowed to access this "catalog" / "schema" combination. Note that "user" is completely independent from both the system's user id's and from HTTP user/password protection. It appears in the SESAM configuration only.

See also sesam_disconnect().

Példa 1. Connect to a SESAM database

<?php
if (!sesam_connect ("mycatalog", "myschema", "otto")) {
    die("Unable to connect to SESAM");
}
?>

sesam_diagnostic

(PHP 3 CVS only)

sesam_diagnostic --  Return status information for last SESAM call

Description

array sesam_diagnostic ( void )

Returns an associative array of status and return codes for the last SQL query/statement/command. Elements of the array are:

Táblázat 1. Status information returned by sesam_diagnostic()

ElementContents
$array["sqlstate"] 5 digit SQL return code (see the SESAM manual for the description of the possible values of SQLSTATE)
$array["rowcount"] number of affected rows in last update/insert/delete (set after "immediate" statements only)
$array["errmsg"] "human readable" error message string (set after errors only)
$array["errcol"] error column number of previous error (0-based; or -1 if undefined. Set after errors only)
$array["errlin"] error line number of previous error (0-based; or -1 if undefined. Set after errors only)

In the following example, a syntax error (E SEW42AE ILLEGAL CHARACTER) is displayed by including the offending SQL statement and pointing to the error location:

Példa 1. Displaying SESAM error messages with error position

<?php
// Function which prints a formatted error message,
// displaying a pointer to the syntax error in the
// SQL statement
function PrintReturncode($exec_str) 
{
    $err = Sesam_Diagnostic();
    $colspan=4; // 4 cols for: sqlstate, errlin, errcol, rowcount
    if ($err["errlin"] == -1)
        --$colspan;
    if ($err["errcol"] == -1)
        --$colspan;
    if ($err["rowcount"] == 0)
        --$colspan;
    echo "<table border=\"1\">\n";
    echo "<tr><th colspan=\"" . $colspan . "\"><span class=\"spanred\">ERROR:</span> ".
          	htmlspecialchars($err["errmsg"]) . "</th></tr>\n";
    if ($err["errcol"] >= 0) {
        echo "<tr><td colspan=\"" . $colspan . "\"><pre>\n";
        $errstmt = $exec_str . "\n";
        for ($lin=0; $errstmt != ""; ++$lin) {
            if ($lin != $err["errlin"]) { // $lin is less or greater than errlin
                if (!($i = strchr($errstmt, "\n")))
                    $i = "";
                $line = substr ($errstmt, 0, strlen($errstmt)-strlen($i)+1);
                $errstmt = substr($i, 1);
                if ($line != "\n")
                    echo htmlspecialchars($line);
            } else {
                if (! ($i = strchr ($errstmt, "\n")))
                    $i = "";
                $line = substr ($errstmt, 0, strlen ($errstmt)-strlen($i)+1);
                $errstmt = substr($i, 1);
                for ($col=0; $col < $err["errcol"]; ++$col) {
                    echo (substr($line, $col, 1) == "\t") ? "\t" : ".";
                }
                echo "<span class=\"spanred\">\\</span>\n";
                echo "<span class=\"normal\">" . htmlspecialchars($line) . "</span>";
                for ($col=0; $col < $err["errcol"]; ++$col) {
                    echo (substr ($line, $col, 1) == "\t") ? "\t" : ".";
                }
                echo "<span class=\"spanred\">/</span>\n";
            }
        }
        echo "</pre></td></tr>\n";
    }
    echo "<tr>\n";
    echo " <td>sqlstate=" . $err["sqlstate"] . "</td>\n";
    if ($err["errlin"] != -1)
        echo " <td>errlin=" . $err["errlin"] . "</td>\n";
    if ($err["errcol"] != -1)
        echo " <td>errcol=" . $err["errcol"] . "</td>\n";
    if ($err["rowcount"] != 0)
         echo " <td>rowcount=" . $err["rowcount"] . "</td>\n";
    echo "</tr>\n";
    echo "</table>\n";
}

if (!sesam_connect ("mycatalog", "phoneno", "otto"))
  die ("cannot connect");

$stmt = "SELECT * FROM phone\n" .
        " WHERE@ LASTNAME='KRAEMER'\n" .
        " ORDER BY FIRSTNAME";
if (!($result = sesam_query ($stmt)))
    PrintReturncode ($stmt);
?>

See also: sesam_errormsg() for simple access to the error string only

sesam_disconnect

(PHP 3 CVS only)

sesam_disconnect -- Detach from SESAM connection

Description

bool sesam_disconnect ( void )

Returns: always TRUE.

sesam_disconnect() closes the logical link to a SESAM database (without actually disconnecting and unloading the driver).

Note that this isn't usually necessary, as the open connection is automatically closed at the end of the script's execution. Uncommitted data will be discarded, because an implicit sesam_rollback() is executed.

sesam_disconnect() will not close the persistent link, it will only invalidate the currently defined "catalog", "schema" and "user" triple, so that any sesam function called after sesam_disconnect() will fail.

Példa 1. Closing a SESAM connection

<?php
if (sesam_connect ("mycatalog", "myschema", "otto")) {
    /* ... some queries and stuff ... */
    sesam_disconnect(); 
}
?>

See also sesam_connect().

sesam_errormsg

(PHP 3 CVS only)

sesam_errormsg -- Returns error message of last SESAM call

Description

string sesam_errormsg ( void )

Returns the SESAM error message associated with the most recent SESAM error.

Példa 1. sesam_errormsg() example

<?php
if (!sesam_execimm($stmt)) {
  echo sesam_errormsg() . "<br />\n";
}
?>

See also sesam_diagnostic() for the full set of SESAM SQL status information.

sesam_execimm

(PHP 3 CVS only)

sesam_execimm -- Execute an "immediate" SQL-statement

Description

string sesam_execimm ( string query)

Returns: A SESAM "result identifier" on success, or FALSE on error.

sesam_execimm() executes an "immediate" statement (i.e., a statement like UPDATE, INSERT or DELETE which returns no result, and has no INPUT or OUTPUT variables). "select type" queries can not be used with sesam_execimm(). Sets the affected_rows value for retrieval by the sesam_affected_rows() function.

Note that sesam_query() can handle both "immediate" and "select-type" queries. Use sesam_execimm() only if you know beforehand what type of statement will be executed. An attempt to use SELECT type queries with sesam_execimm() will return $err["sqlstate"] == "42SBW".

The returned "result identifier" can not be used for retrieving anything but the sesam_affected_rows(); it is only returned for symmetry with the sesam_query() function.

<?php
$stmt = "INSERT INTO mytable VALUES ('one', 'two')";
$result = sesam_execimm($stmt);
$err = sesam_diagnostic();
echo "sqlstate = " . $err["sqlstate"] . "\n".
       "Affected rows = " . $err["rowcount"] . " == " .
       sesam_affected_rows($result) . "\n";
?>

See also sesam_query() and sesam_affected_rows().

sesam_fetch_array

(PHP 3 CVS only)

sesam_fetch_array -- Fetch one row as an associative array

Description

array sesam_fetch_array ( string result_id [, int whence [, int offset]])

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

sesam_fetch_array() is an alternative version of sesam_fetch_row(). Instead of storing the data in the numeric indices of the result array, it stores the data in associative indices, using the field names as keys.

result_id is a valid result id returned by sesam_query() (select type queries only!).

For the valid values of the optional whenceand offset parameters, see the sesam_fetch_row() function for details.

sesam_fetch_array() fetches one row of data from the result associated with the specified result identifier. The row is returned as an associative array. Each result column is stored with an associative index equal to its column (aka. field) name. The column names are converted to lower case.

Columns without a field name (e.g., results of arithmetic operations) and empty fields are not stored in the array. Also, if two or more columns of the result have the same column names, the later column will take precedence. In this situation, either call sesam_fetch_row() or make an alias for the column.

SELECT TBL1.COL AS FOO, TBL2.COL AS BAR FROM TBL1, TBL2

A special handling allows fetching "multiple field" columns (which would otherwise all have the same column names). For each column of a "multiple field", the index name is constructed by appending the string "(n)" where n is the sub-index of the multiple field column, ranging from 1 to its declared repetition factor. The indices are NOT zero based, in order to match the nomenclature used in the respective query syntax. For a column declared as:

CREATE TABLE ... ( ... MULTI(3) INT )

the associative indices used for the individual "multiple field" columns would be "multi(1)", "multi(2)", and "multi(3)" respectively.

Subsequent calls to sesam_fetch_array() would return the next (or prior, or n'th next/prior, depending on the scroll attributes) row in the result set, or FALSE if there are no more rows.

Példa 1. SESAM fetch array

<?php
$result = sesam_query("SELECT * FROM phone\n" .
                       "  WHERE LASTNAME='" . strtoupper($name) . "'\n".
                       "  ORDER BY FIRSTNAME", 1);
if (!$result) {
    /* ... error ... */
}
// print the table:
echo "<table border=\"1\">\n";
while (($row = sesam_fetch_array($result)) && count($row) > 0) {
    echo "<tr>\n";
    echo "<td>" . htmlspecialchars($row["firstname"]) . "</td>\n";
    echo "<td>" . htmlspecialchars($row["lastname"]) . "</td>\n";
    echo "<td>" . htmlspecialchars($row["phoneno"]) . "</td>\n";
    echo "</tr>\n";
}
echo "</table>\n";
sesam_free_result($result);
?>

See also: sesam_fetch_row() which returns an indexed array.

sesam_fetch_result

(PHP 3 CVS only)

sesam_fetch_result -- Return all or part of a query result

Description

mixed sesam_fetch_result ( string result_id [, int max_rows])

Returns a mixed array with the query result entries, optionally limited to a maximum of max_rows rows. Note that both row and column indexes are zero-based.

Táblázat 1. Mixed result set returned by sesam_fetch_result()

Array ElementContents
int $arr["count"] number of columns in result set (or zero if this was an "immediate" query)
int $arr["rows"] number of rows in result set (between zero and max_rows)
bool $arr["truncated"] TRUE if the number of rows was at least max_rows, FALSE otherwise. Note that even when this is TRUE, the next sesam_fetch_result() call may return zero rows because there are no more result entries.
mixed $arr[col][row] result data for all the fields at row(row) and column(col), (where the integer index row is between 0 and $arr["rows"]-1, and col is between 0 and $arr["count"]-1). Fields may be empty, so you must check for the existence of a field by using the php isset() function. The type of the returned fields depend on the respective SQL type declared for its column (see SESAM overview for the conversions applied). SESAM "multiple fields" are "inlined" and treated like a sequence of columns.
Note that the amount of memory used up by a large query may be gigantic. Use the max_rows parameter to limit the maximum number of rows returned, unless you are absolutely sure that your result will not use up all available memory.

See also: sesam_fetch_row(), and sesam_field_array() to check for "multiple fields". See the description of the sesam_query() function for a complete example using sesam_fetch_result().

sesam_fetch_row

(PHP 3 CVS only)

sesam_fetch_row -- Fetch one row as an array

Description

array sesam_fetch_row ( string result_id [, int whence [, int offset]])

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

The number of columns in the result set is returned in an associative array element $array["count"]. Because some of the result columns may be empty, the count() function can not be used on the result row returned by sesam_fetch_row().

result_id is a valid result id returned by sesam_query() (select type queries only!).

whence is an optional parameter for a fetch operation on "scrollable" cursors, which can be set to the following predefined constants:

Táblázat 1. Valid values for "whence" parameter

ValueConstantMeaning
0SESAM_SEEK_NEXT read sequentially (after fetch, the internal default is set to SESAM_SEEK_NEXT)
1SESAM_SEEK_PRIOR read sequentially backwards (after fetch, the internal default is set to SESAM_SEEK_PRIOR)
2SESAM_SEEK_FIRST rewind to first row (after fetch, the default is set to SESAM_SEEK_NEXT)
3SESAM_SEEK_LAST seek to last row (after fetch, the default is set to SESAM_SEEK_PRIOR)
4SESAM_SEEK_ABSOLUTE seek to absolute row number given as offset (Zero-based. After fetch, the internal default is set to SESAM_SEEK_ABSOLUTE, and the internal offset value is auto-incremented)
5SESAM_SEEK_RELATIVE seek relative to current scroll position, where offset can be a positive or negative offset value.
This parameter is only valid for "scrollable" cursors.

When using "scrollable" cursors, the cursor can be freely positioned on the result set. If the whence parameter is omitted, the global default values for the scrolling type (initialized to: SESAM_SEEK_NEXT, and settable by sesam_seek_row()) are used. If whence is supplied, its value replaces the global default.

offset is an optional parameter which is only evaluated (and required) if whence is either SESAM_SEEK_RELATIVE or SESAM_SEEK_ABSOLUTE. This parameter is only valid for "scrollable" cursors.

sesam_fetch_row() fetches one row of data from the result associated with the specified result identifier. The row is returned as an array (indexed by values between 0 and $array["count"]-1). Fields may be empty, so you must check for the existence of a field by using the isset() function. The type of the returned fields depend on the respective SQL type declared for its column (see SESAM overview for the conversions applied). SESAM "multiple fields" are "inlined" and treated like a sequence of columns.

Subsequent calls to sesam_fetch_row() would return the next (or prior, or n'th next/prior, depending on the scroll attributes) row in the result set, or FALSE if there are no more rows.

Példa 1. SESAM fetch rows

<?php
$result = sesam_query("SELECT * FROM phone\n" .
                       "  WHERE LASTNAME='" . strtoupper($name) . "'\n" .
                       "  ORDER BY FIRSTNAME", 1);
if (!$result) {
    /* ... error ... */
}
// print the table in backward order
echo "<table border=\"1\">\n";
$row = sesam_fetch_row($result, SESAM_SEEK_LAST);
while (is_array($row)) {
    echo "<tr>\n";
    for ($col = 0; $col < $row["count"]; ++$col) {
        echo "<td>" . htmlspecialchars($row[$col]) . "</td>\n";
    }
    echo "</tr>\n";
    // use implied SESAM_SEEK_PRIOR
    $row = sesam_fetch_row($result);
}
echo "</table>\n";
sesam_free_result($result);
?>

See also: sesam_fetch_array() which returns an associative array, and sesam_fetch_result() which returns many rows per invocation.

sesam_field_array

(PHP 3 CVS only)

sesam_field_array --  Return meta information about individual columns in a result

Description

array sesam_field_array ( string result_id)

result_id is a valid result id returned by sesam_query().

Returns a mixed associative/indexed array with meta information (column name, type, precision, ...) about individual columns of the result after the query associated with result_id.

Táblázat 1. Mixed result set returned by sesam_field_array()

Array ElementContents
int $arr["count"] Total number of columns in result set (or zero if this was an "immediate" query). SESAM "multiple fields" are "inlined" and treated like the respective number of columns.
string $arr[col]["name"] column name for column(col), where col is between 0 and $arr["count"]-1. The returned value can be the empty string (for dynamically computed columns). SESAM "multiple fields" are "inlined" and treated like the respective number of columns, each with the same column name.
string $arr[col]["count"] The "count" attribute describes the repetition factor when the column has been declared as a "multiple field". Usually, the "count" attribute is 1. The first column of a "multiple field" column however contains the number of repetitions (the second and following column of the "multiple field" contain a "count" attribute of 1). This can be used to detect "multiple fields" in the result set. See the example shown in the sesam_query() description for a sample use of the "count" attribute.
string $arr[col]["type"] PHP variable type of the data for column(col), where col is between 0 and $arr["count"]-1. The returned value can be one of

depending on the SQL type of the result. SESAM "multiple fields" are "inlined" and treated like the respective number of columns, each with the same PHP type.
string $arr[col]["sqltype"] SQL variable type of the column data for column(col), where col is between 0 and $arr["count"]-1. The returned value can be one of

  • "CHARACTER"

  • "VARCHAR"

  • "NUMERIC"

  • "DECIMAL"

  • "INTEGER"

  • "SMALLINT"

  • "FLOAT"

  • "REAL"

  • "DOUBLE"

  • "DATE"

  • "TIME"

  • "TIMESTAMP"

describing the SQL type of the result. SESAM "multiple fields" are "inlined" and treated like the respective number of columns, each with the same SQL type.
string $arr[col]["length"] The SQL "length" attribute of the SQL variable in column(col), where col is between 0 and $arr["count"]-1. The "length" attribute is used with "CHARACTER" and "VARCHAR" SQL types to specify the (maximum) length of the string variable. SESAM "multiple fields" are "inlined" and treated like the respective number of columns, each with the same length attribute.
string $arr[col]["precision"] The "precision" attribute of the SQL variable in column(col), where col is between 0 and $arr["count"]-1. The "precision" attribute is used with numeric and time data types. SESAM "multiple fields" are "inlined" and treated like the respective number of columns, each with the same precision attribute.
string $arr[col]["scale"] The "scale" attribute of the SQL variable in column(col), where col is between 0 and $arr["count"]-1. The "scale" attribute is used with numeric data types. SESAM "multiple fields" are "inlined" and treated like the respective number of columns, each with the same scale attribute.

See also sesam_query() for an example of the sesam_field_array() use.

sesam_field_name

(PHP 3 CVS only)

sesam_field_name --  Return one column name of the result set

Description

int sesam_field_name ( string result_id, int index)

Returns the name of a field (i.e., the column name) in the result set, or FALSE on error.

For "immediate" queries, or for dynamic columns, an empty string is returned.

Megjegyzés: The column index is zero-based, not one-based as in SESAM.

See also: sesam_field_array(). It provides an easier interface to access the column names and types, and allows for detection of "multiple fields".

sesam_free_result

(PHP 3 CVS only)

sesam_free_result -- Releases resources for the query

Description

int sesam_free_result ( string result_id)

Releases resources for the query associated with result_id. Returns FALSE on error.

sesam_num_fields

(PHP 3 CVS only)

sesam_num_fields --  Return the number of fields/columns in a result set

Description

int sesam_num_fields ( string result_id)

After calling sesam_query() with a "select type" query, this function gives you the number of columns in the result. Returns an integer describing the total number of columns (aka. fields) in the current result_id result set or FALSE on error.

For "immediate" statements, the value zero is returned. The SESAM "multiple field" columns count as their respective dimension, i.e., a three-column "multiple field" counts as three columns.

See also: sesam_query() and sesam_field_array() for a way to distinguish between "multiple field" columns and regular columns.

sesam_query

(PHP 3 CVS only)

sesam_query -- Perform a SESAM SQL query and prepare the result

Description

string sesam_query ( string query [, bool scrollable])

Returns: A SESAM "result identifier" on success, or FALSE on error.

A "result_id" resource is used by other functions to retrieve the query results.

sesam_query() sends a query to the currently active database on the server. It can execute both "immediate" SQL statements and "select type" queries. If an "immediate" statement is executed, then no cursor is allocated, and any subsequent sesam_fetch_row() or sesam_fetch_result() call will return an empty result (zero columns, indicating end-of-result). For "select type" statements, a result descriptor and a (scrollable or sequential, depending on the optional boolean scrollable parameter) cursor will be allocated. If scrollable is omitted, the cursor will be sequential.

When using "scrollable" cursors, the cursor can be freely positioned on the result set. For each "scrollable" query, there are global default values for the scrolling type (initialized to: SESAM_SEEK_NEXT) and the scrolling offset which can either be set once by sesam_seek_row() or each time when fetching a row using sesam_fetch_row().

For "immediate" statements, the number of affected rows is saved for retrieval by the sesam_affected_rows() function.

See also: sesam_fetch_row() and sesam_fetch_result().

Példa 1. Show all rows of the "phone" table as a HTML table

<?php
if (!sesam_connect("phonedb", "demo", "otto"))
    die("cannot connect");
$result = sesam_query("select * from phone");
if (!$result) {
    $err = sesam_diagnostic();
    die $err["errmsg"]);
}
echo "<table border>\n";
// Add title header with column names above the result:
if ($cols = sesam_field_array($result)) {
    echo "<tr><th colspan=" . $cols["count"] . ">Result:</th></tr>\n";
    echo "<tr>\n";
    for ($col = 0; $col < $cols["count"]; ++$col) {
        $colattr = $cols[$col];
        /* Span the table head over SESAM's "Multiple Fields": */
        if ($colattr["count"] > 1) {
            echo "<th colspan=\"" . $colattr["count"] . "\">" . $colattr["name"] .
                "(1.." . $colattr["count"] . ")</th>\n";
            $col += $colattr["count"] - 1;
        } else
            echo "<th>" . $colattr["name"] . "</th>\n";
    }
    echo "</tr>\n";
}

do {
    // Fetch the result in chunks of 100 rows max.
    $ok = sesam_fetch_result($result, 100);
    for ($row=0; $row < $ok["rows"]; ++$row) {
        echo " <tr>\n";
        for ($col = 0; $col < $ok["cols"]; ++$col) {
            if (isset($ok[$col][$row])) {
                echo "<td>" . $ok[$col][$row] . "</td>\n";
            } else {
                echo "<td>-empty-</td>\n";
            }
        }
        echo "</tr>\n";
    }
} while ($ok["truncated"]); // while there may be more data

echo "</table>\n";
// free result id
sesam_free_result($result);
?>

sesam_rollback

(PHP 3 CVS only)

sesam_rollback --  Discard any pending updates to the SESAM database

Description

bool sesam_rollback ( void )

Returns: TRUE on success, FALSE on errors

sesam_rollback() discards any pending updates to the database. Also affected are result cursors and result descriptors.

At the end of each script, and as part of the sesam_disconnect() function, an implied sesam_rollback() is executed, discarding any pending changes to the database.

See also: sesam_commit().

Példa 1. Discarding an update to the SESAM database

<?php
if (sesam_connect ("mycatalog", "myschema", "otto")) {
    if (sesam_execimm ("INSERT INTO mytable VALUES (*, 'Small Test', <0, 8, 15>)")
        && sesam_execimm ("INSERT INTO othertable VALUES (*, 'Another Test', 1)")) {
        sesam_commit();
    } else {
        sesam_rollback();
    }
}
?>

sesam_seek_row

(PHP 3 CVS only)

sesam_seek_row --  Set scrollable cursor mode for subsequent fetches

Description

bool sesam_seek_row ( string result_id, int whence [, int offset])

result_id is a valid result id (select type queries only, and only if a "scrollable" cursor was requested when calling sesam_query()).

whence sets the global default value for the scrolling type, it specifies the scroll type to use in subsequent fetch operations on "scrollable" cursors, which can be set to the following predefined constants:

Táblázat 1. Valid values for "whence" parameter

ValueConstantMeaning
0SESAM_SEEK_NEXTread sequentially
1SESAM_SEEK_PRIORread sequentially backwards
2SESAM_SEEK_FIRST fetch first row (after fetch, the default is set to SESAM_SEEK_NEXT)
3SESAM_SEEK_LAST fetch last row (after fetch, the default is set to SESAM_SEEK_PRIOR)
4SESAM_SEEK_ABSOLUTE fetch absolute row number given as offset (Zero-based. After fetch, the default is set to SESAM_SEEK_ABSOLUTE, and the offset value is auto-incremented)
5SESAM_SEEK_RELATIVE fetch relative to current scroll position, where offset can be a positive or negative offset value (this also sets the default "offset" value for subsequent fetches).

offset is an optional parameter which is only evaluated (and required) if whence is either SESAM_SEEK_RELATIVE or SESAM_SEEK_ABSOLUTE.

sesam_settransaction

(PHP 3 CVS only)

sesam_settransaction -- Set SESAM transaction parameters

Description

bool sesam_settransaction ( int isolation_level, int read_only)

Returns: TRUE if the values are valid, and the settransaction() operation was successful, FALSE otherwise.

sesam_settransaction() overrides the default values for the "isolation level" and "read-only" transaction parameters (which are set in the SESAM configuration file), in order to optimize subsequent queries and guarantee database consistency. The overridden values are used for the next transaction only.

sesam_settransaction() can only be called before starting a transaction, not after the transaction has been started already.

To simplify the use in PHP scripts, the following constants have been predefined in PHP (see SESAM handbook for detailed explanation of the semantics):

Táblázat 1. Valid values for "Isolation_Level" parameter

ValueConstantMeaning
1SESAM_TXISOL_READ_UNCOMMITTEDRead Uncommitted
2SESAM_TXISOL_READ_COMMITTEDRead Committed
3SESAM_TXISOL_REPEATABLE_READRepeatable Read
4SESAM_TXISOL_SERIALIZABLESerializable

Táblázat 2. Valid values for "Read_Only" parameter

ValueConstantMeaning
0SESAM_TXREAD_READWRITERead/Write
1SESAM_TXREAD_READONLYRead-Only

The values set by sesam_settransaction() will override the default setting specified in the SESAM configuration file.

Példa 1. Setting SESAM transaction parameters

<?php
sesam_settransaction (SESAM_TXISOL_REPEATABLE_READ,
                     SESAM_TXREAD_READONLY);
?>

XCVI. Munkamenet kezelő függvények

A PHP munkamenet kezelése lehetővé teszi adatok megőrzését az egymást követő oldal lekérdezések között. Ez képessé tesz még testreszabhatóbb oldalak készítésére.

Ha ismered a PHPLIB munkamenet kezelését, sok hasonlóságot fogsz felfedezni a PHP munkamenet kezelő függvényeit illetően.

Minden webhelyedre látogató egy-egy egyedi azonosítót kap, az úgynevezett munkamenet azonosítót (session azonosítót). Ez vagy egy sütiben (cookie) tárolódik a látogató gépén, vagy az URL-ben közlekedik oldalról oldalra.

A munkamenet támogatás lehetővé teszi tetszőleges számú változó megőrzését a PHP oldal lekérdezések között. Ha egy látogató érkezik webhelyedre, háromféleképpen kezdődhet el, vagy folytatódhat a munkamenete. Mindhárom esetben a PHP egy munkamenet azonosító érkezését várja. Ha nem érkezik, új munkamenetet indít.

Ha a session.auto_start be van kapcsolva, a PHP automatikusan megkezdni / folytatja a munkamenetet. Ha ez nincs bekapcsolva, akkor közvetlenül a session_start() függvénnyel, vagy közvetve a session_register() függvénnyel tudod a munkamenetet folytatni / megkezdeni. Ha egy érvényes azonosító érkezett, a korábban beállított munkamenet környezet visszaállításra kerül.

Minden a munkamenethez rendelt változó szerializálódik a PHP oldal futásának befejeződésekor. A nem definiált, de munkamenethez rendelt változók a későbbi folytatásokban nem jönnek újból létre.

A track_vars és register_globals ini beállítások befolyásolják a munkamenet változók tárolásának és visszaállításának módját.

Megjegyzés: A PHP 4.0.3 verziótól kezdve a track_vars mindig be van kapcsolva, kikapcsolására nincs mód.

Megjegyzés: A 4.1.0 verziótól kezdve a $_SESSION szuperglobális változó rendelkezésre áll, csakúgy mint a $_POST, $_GET, $_REQUEST és így tovább. A $HTTP_SESSION_VARS változótól eltérően a $_SESSION mindig elérhető (szuperglobális). Ezért a global kulcsszóval nem szabad egyűtt használni a $_SESSION változót.

Ha a track_vars be van kapcsolva, és a register_globals ki van kapcsolva, csak a $HTTP_SESSION_VARS asszociatív tömb elemei a munkamenet változók. A visszaállított munkamenet változók is csak a $HTTP_SESSION_VARS tömbben lesznek megtalálhatóak.

Példa 1. Változó bejegyzése a munkamenetbe a track_vars bekapcsolt állapotában.

<?php
session_start();
if (isset($HTTP_SESSION_VARS['szamlalo'])) {
   $HTTP_SESSION_VARS['szamlalo']++;
}
else {
   $HTTP_SESSION_VARS['szamlalo'] = 0;
}
?>

A $_SESSION változó használata (vagy a $HTTP_SESSION_VARS változó használata PHP 4.0.6 vagy régebbi verzió esetén) javasolt biztonsági és olvashatósági szempontok miatt. A $_SESSION vagy $HTTP_SESSION_VARS használatával nincs szükség a session_register()/session_unregister()/session_is_registered() függvényekre. A programozók éppen úgy dolgozhatnak a munkamenet változókkal, mint a "normális" változókkal.

Példa 2. Változó bejegyzése a munkamenetbe a $_SESSION tömbbel.

<?php
session_start();
// Használd a $HTTP_SESSION_VARS tömböt PHP 4.0.6 vagy régebbi verzióban
if (!isset($_SESSION['szamlalo'])) {
    $_SESSION['szamlalo'] = 0;
} else {
    $_SESSION['szamlalo']++;
}
?>

Példa 3. Változó bejegyzés törlése a $_SESSION tömbbel.

<?php
session_start();
// Használd a $HTTP_SESSION_VARS tömböt PHP 4.0.6 vagy régebbi verzióban
unset($_SESSION['szamlalo']);
?>

Ha a register_globals be van kapcsolva, akkor minden globális változó lehet munkamenet változóként regisztrálva, és a munkamenet későbbi folytatásaiban is létre fognak jönni globális változókként a bejegyzett változók. Mivel ebben az esetben a PHP-nek tudnia kell, hogy mely globális változók bejegyzett munkamenet változók is egyben, a programozónak a session_register() függvényt kell használnia. Emlékeztetőként a $HTTP_SESSION_VARS/$_SESSION tömbök használatakor nincs szükség a session_register() függvényre.

Figyelem

Ha a $HTTP_SESSION_VARS/$_SESSION tömböt használod és kikapcsolod a register_globals beállítást, ne használd a session_register(), session_is_registered() és session_unregister() függvényeket.

Ha bekapcsolod a register_globals beállítást, a session_unregister() függvényt kell használnod, mivel a munkamenet változók globális változókban jelennek meg. A register_globals kikapcsolása javasolt mind biztonsági, mind teljesítmény szempontokból.

Példa 4. Változó bejegyzése a register_globals bekapcsolt állapota mellett.

<?php
if (!session_is_registered('szamlalo')) {
    session_register("szamlalo");
    $szamlalo = 0;
}
else {
    $szamlalo++;
}
?>

Ha mind a track_vars, mind a register_globals beállítások be vannak kapcsolva, a globális változók és a $HTTP_SESSION_VARS/$_SESSION tömbök elemei ugynazokra az értékekre fognak mutatni a már bejegyzett változókat illetően.

Ha a programozó a session_register() függvényt használja munkamenet változók bejegyzésére, akkor ebben az esetben a $HTTP_SESSION_VARS/$_SESSION tömbökben nem fog megjelenni ez a változó a következő munkamenet folytatása előtt (azaz a következő PHP program futás előtt).

Kétféleképpen "közlekedhet" a munkamenet azonosító:

  • Süti formájában

  • URL / űrlap paraméterben

A munkamenetkezelő modul mindkét formát támogatja. A sütik optimálisak, de sajnos nem megbízhatóak (sokan nem fogadják a sütiket), ezért nem lehet rájuk biztonsággal építeni. A második módszer az azonosítót közvetlenül az URL-ekbe és űrlapokba helyezi.

A PHP képes ezutóbbi azonosító terjesztést átlátszóan végezni, ha az --enable-trans-sid opcióval fodítottad. Ha ezt az opciót bekapcsolod, a reltív URL-ekhez és űrlapokhoz automatikusan hozzáteszi a PHP a munkamenet azonosítót. Alternatív módszerként használhatod a SID konstanst, ami definiált, ha a kliens nem küldte vissza a megfelelő sütit. A SID vagy session_name=session_id (munkamenet név, munkamenet azonosító) formátumú, vagy egy üres karektersorozat.

A következő példa egy változó bejegyzést, és egy következő oldalra mutató link készítését mutatja,

Példa 5. Egy látogató által lehívott oldalak számlálása

<?php
if (!session_is_registered('szamlalo')) {
    session_register('szamlalo');
    $szamlalo = 1;
}
else {
    $szamlalo++;
}
?>

Üdv látogató, eddig <?php echo $szamlalo; ?> alkalommal
láttad ezt az oldalt.<p>

<?php
# Az <?php echo SID?> szükséges, hogy a munkamenet azonosítót
# megőrizzük abban az esetben is, ha a látogató nem fogadja
# a sütit. (<?=SID?> használható, ha a rövid tagek engedélyezettek)
?>

A továbblépéshez <A HREF="kovoldal.php?<?php echo SID?>">kattints ide</A>.

A <?=SID?> nem szükséges, ha az --enable-trans-sid opcióval fordítottad a PHP-t.

Megjegyzés: A nem relatív hivatkozások feltételezetten külső oldalakra mutatnak, ezért nem egészülnek ki automatikusan a SID-el. Komoly biztonsági problémákat okozna, ha a SID-ek elkerülnének egy másik kiszolgálóhoz.

A munkamenethez tartozó adatok állományokban tárolódnak. Ha adatbázisban, vagy más tároló eszközön szeretnéd rögzíteni a munkamenethez tartozó adatokat, a session_set_save_handler() függvényt kell használnod a saját tároló függvényeid bejegyzéséhez.

A munkamenet kezelő függvények számos beállítási lehetőséget biztosítanak, amiket a php.ini állományban helyezhetsz el. Egy rövid áttekintés következik.

  • A session.save_handler beállítás adja meg a használt tárolás kezelőt, ami a munkamenet adatok elmentésére, és visszakeresésére szolgál. Az alapértéke files.

  • A session.save_path beállítás az a paraméter, amit a tárolás kezelő megkap. Ha az alapértelmezett állomány kezelőt használod, ez a munkamenetek tárolására használt ideiglenes állományok könytárának elérési útja. Alapértelmezése /tmp. Ha a session.save_path mélysége több mint kettő, az automatikus szemét takarítás nem fog működni.

    Figyelem

    Ha ezt az értéket egy mindenki által olvasható könyvtárra állítod (mint az alapbeállítású /tmp), akkor a kiszolgálón lévő többi felhasználó el tudja kapni a munkameneteidet a könyvtárban lévő állományok neve és tartalma alapján.

  • A session.name a munkamenet neve, amit a PHP a süti beállításakor, az URL / űrlap paraméterek felvételekor és a munkamenet folytatásakor használ. Csak alfanumerikus karaktereket tartalmazhat. Alapértéke PHPSESSID.

  • A session.auto_start beállítás adja meg, hogy a PHP kezdjen-e / folytasson-e minden PHP oldal futattásnál automatikusan munkamenetet. Alapértéke 0 (kikapcsolt).

  • A session.cookie_lifetime a beállított süti élettartalmát szabályozza másodpercekben megadva. A nulla érték azt jelenti, hogy "amíg a böngészőt be nem zárják". Alapértéke éppen 0.

  • A session.serialize_handler a szerializáláshoz használt kezelő nevét adja meg. Jelenleg egy beépített PHP formátum (php néven) és egy WDDX formátum támogatott (wddx néven). A WDDX formátumhoz szükséges, hogy a WDDX támogatás a PHP-be legyen fordítva. Lásd WDDX. Alapértéke a beépített php kezelő.

  • A session.gc_probability megadja, hogy mekkora valószínűséggel indul el a gc (garbage collection - szemétgyűjtés) az egyes PHP lekérdezésekkor. Az értéket százalékban kell megadni. Alapértéke 1.

  • A session.gc_maxlifetime megadja, hogy hány másodperc elteltével tekinti a szemétgyűtjtő szemétnek, és eltakarítandónak a munkamenet adatokat.

  • A session.referer_check azt a rész-karaktersorozatot tartalmazza, amit minden HTTP Referer fejlécben keresni szeretnél a munkamenetek még biztonságosabb azonosítása céljából. Ha a megadott rész-karaktersorozatot nem találja meg a PHP a Refererben, a küldött munkamenet azonosítót nem fogja elfogadni. Alapértéke az üres karaktersorozat.

  • A session.entropy_file egy elérési utat határoz meg ahhoz az "állományhoz", amit a PHP külső entrópia forrásnak használ a munkamenet azonosító előállításakor. Ez lehet például /dev/random vagy /dev/urandom. Ezek sok Unix rendszeren elérhetőek.

  • A session.entropy_length az olvasott byte-ok számát adja meg, amennyit a fent említett állományból olvas a PHP. Alapértéke 0 (kikapcsolt).

  • A session.use_cookies határozza meg, hogy a PHP használ-e sütiket a munkamenet azonosító tárolására a kliens oldalon. Alapértéke 1 (engedélyezett).

  • A session.use_only_cookies beállításával elérhető, hogy a PHP kizárólag süti útján érkezett munkamenet azonosítókkal törődjön. Alapértéke 0 (kikapcsolt, visszafele kompatibilitás miatt). Ezen beállítás engedélyezésével megelőzhetőek azon támadási formák, melyek a munkamenet azonosítók URL-ben való megadásával manipulálnak. Ez a beállítási lehetőség a PHP 4.3.0-ás változatától vehető használatba.

  • A session.cookie_path azt az elérési utat határozza meg, amit a munkamenet sütiben beállít a PHP. Alapértéke /.

  • A session.cookie_domain azt a domain értéket határozza meg, amit a PHP a munkamenet sütiben beállít. Alapértéke semmi.

  • A session.cache_limiter azt a cache metódust határozza meg, amit a munkamenet oldalakra alkalmazni kell. Lehetséges értékei: none, nocache, private, private_no_expire és public. Alapértéke nocache.

  • A session.cache_expire megadja, hogy hány percig legyen aktuális a cache-ben egy munkamenetet használó oldal. Ennek nincs hatása, ha nocache módot választasz. Alapértéke 180.

  • A session.use_trans_sid szabályozza, hogy az átlátszó SID hozzáadás be van-e kapcsolva vagy nincs. Ehhez szükséges, hogy a --enable-trans-sid opcióval fordítsd korábban a PHP-t. Alapértéke 1 (engedélyezett).

  • Az url_rewriter.tags adja meg, hogy mely HTML elemeket kell átírni, ha a munkamenet azonosítók átlátszó elhelyezése be van kapcsolva. Alapértéke a=href,area=href,frame=src,input=src,form=fakeentry

Megjegyzés: A munkamenetek támogatása a PHP 4.0 verzióban jelent meg.

Tartalom
session_cache_expire -- Az aktuális cache lejárat lekérdezése
session_cache_limiter -- Az aktuális munkamenet cache korlátozás lekérdezése / beállítása
session_decode -- Visszakódolja a munkamenet adatokat egy karaktersorozatból
session_destroy -- Adott munkamenethez tartozó minden adat törlése
session_encode --  Elkódolja a munkamenet adatokat egy karaktersorozatba
session_get_cookie_params --  Lekérdezi a munkamenet süti paramétereit
session_id -- Az aktuális munkamenet azonosító lekérdezése / beállítása
session_is_registered --  Egy változó bejegyzettségét ellenőrzi
session_module_name -- Az aktuális munkamenet modul lekérdezése / beállítása
session_name -- Az aktuális munkamenet név lekérdezése / beállítása
session_regenerate_id --  Update the current session id with a newly generated one
session_register --  Egy vagy több változó bejegyzése munkamenet változókként
session_save_path -- Az aktuális munkamenet mentési könyvtár lekérdezése / beállítása
session_set_cookie_params --  A munkamenet süti paramétereit állítja be
session_set_save_handler --  Felhasználói szintű munkamenet tároló függvényeket állít be
session_start -- Munkamenet megkezdése / folytatása
session_unregister --  Munkamenet változó törlése a munkamenetből
session_unset --  Minden munkamenet változó felszabadítása
session_write_close -- A munkamenet adatok kiírása és a munkamenet lezárása

session_cache_expire

(PHP 4 >= 4.2.0)

session_cache_expire -- Az aktuális cache lejárat lekérdezése

Leírás

int session_cache_expire ( [int new_cache_expire])

A session_cache_expire() visszatér az aktuális cache lejárati idővel. Ha a new_cache_expire paramétert is megadod, az érték a new_cache_expire-ben megadottra változik.

session_cache_limiter

(PHP 4 >= 4.0.3)

session_cache_limiter -- Az aktuális munkamenet cache korlátozás lekérdezése / beállítása

Leírás

string session_cache_limiter ( [string cache_limiter])

A session_cache_limiter() visszatér az aktuális munkamenet cache korlátozás értékével. Ha a cache_limiter paraméter is meg van adva, a cache korlátozás a megadott értékre változik.

A cache korlátozás szabályozza a cache befolyásoló HTTP fejléceket, amiket a PHP a böngészőnek küld. Ezek a fejlécek szabályozzák, hogy a munkameneteket használó oldalak hogyan jelenjenek meg a gyorsítótárakban. Ha a nocache értéket állítod be, minden kliens oldali cache-elést letiltasz. A public értékkel éppen ellenkezőleg engedélyezed a cache-elést. Ezen kívül még a private értéket is meg tudod adni, ami valamivel korlátozottabb, mint a public.

private módban az Expire fejléc, amit a böngésző kap gondot okozhat a feldolgozásban néhány böngészőnél, mint pl. a Mozilla. Ezt a problémát a private_no_expire mód bekapcsolásával tudod orvosolni. Az Expire fejlécet ebben a módban nem küldi el a PHP a kliensnek.

Megjegyzés: A private_no_expire a 4.2.0dev verzióban került a lehetőségek közé.

A korlátozó érték a php.ini session.cache_limiter beállítására áll vissza a PHP program kérések végrehajtásakor. Ezért minden programban, ahol az alapértelmezett korlátozás nem megfelelő, meg kell hívnod a session_cache_limiter() függvényt a session_start() hívása előtt.

Példa 1. session_cache_limiter() példák

<?php

# A korlátozó 'private' értékre állítása

session_cache_limiter('private');
$cache_limiter = session_cache_limiter();

echo "A cache korlátozás értéke $cache_limiter<p>";
?>

session_decode

(PHP 4 )

session_decode -- Visszakódolja a munkamenet adatokat egy karaktersorozatból

Leírás

bool session_decode ( string data)

A session_decode() visszakódolja a munkamenet adatokat a data karaktersorozatból, beállítva a munkamenetben lévő változókat.

session_destroy

(PHP 4 )

session_destroy -- Adott munkamenethez tartozó minden adat törlése

Leírás

bool session_destroy ( void )

A session_destroy() az aktuális munkamenethez tartozó minden adatot töröl. Nem törli azonban a globális változókat, vagy a munkamenethez beállított sütit.

Ez a függvény TRUE értékkel tér vissza siker esetén, FALSE értékkel tér vissza, ha nem tudja a munkamenet adatait törölni.

Példa 1. Munkamenet törlése

<?php

// Munkamenet megkezdése / folytatása.
// Ha használsz session_name("valami") hívást, ne feledd itt!
session_start();
// Minden munkamenet változó törlése.
session_unset();
// A munkamenet törlése.
session_destroy();

?>

Példa 2. Munkamenet törlése a $_SESSION tömbbel

<?php

// Munkamenet megkezdése / folytatása.
// Ha használsz session_name("valami") hívást, ne feledd itt!
session_start();
// Minden munkamenet változó törlése.
$_SESSION = array();
// A munkamenet törlése.
session_destroy();

?>

session_encode

(PHP 4 )

session_encode --  Elkódolja a munkamenet adatokat egy karaktersorozatba

Leírás

string session_encode ( void )

A session_encode() visszatér az aktuális munkamenet adatainak egy karaktersorozatba kódolt változatával.

session_get_cookie_params

(PHP 4 )

session_get_cookie_params --  Lekérdezi a munkamenet süti paramétereit

Leírás

array session_get_cookie_params ( void )

A session_get_cookie_params() visszaadja a munkamanet süti paramétereit egy asszociatív tömbben. Ez a tömb a következő elemeket tartalmazza:

  • "lifetime" - A süti élettartalma.

  • "path" - A süti elérési út korlátozása.

  • "domain" - A süti domain név korlátozása.

  • "secure" - A süti csak biztonságos kapcsolaton keresztül közlekedhet. (Ez a PHP 4.0.4 verzió óta lehetséges.)

session_id

(PHP 4 )

session_id -- Az aktuális munkamenet azonosító lekérdezése / beállítása

Leírás

string session_id ( [string id])

A session_id() visszatér az aktuális munkamenet azonosítójával. Ha az id paramétert is megadod, akkor az az érték lesz az új munkamenet azonosító.

A SID konstans is használható az aktuális munkemenet név és azonosító lekérdezésére, ha URL-be szeretnéd tenni az azonosítót.

session_is_registered

(PHP 4 )

session_is_registered --  Egy változó bejegyzettségét ellenőrzi

Leírás

bool session_is_registered ( string name)

A session_is_registered() TRUE értékkel tér vissza, ha a name nevű változó be van jegyezve az aktuális munkamenet változójaként.

Megjegyzés: Ha a $_SESSION (vagy $HTTP_SESSION_VARS PHP 4.0.6 vagy korábbi verziókban) tömböket használod, az isset() függvény hívásával derítheted ki, hogy a változó be van-e jegyezve a munkamenetbe.

Figyelem

A $HTTP_SESSION_VARS vagy $_SESSION tömbök használata esetén ne hívd meg a session_register(), session_is_registered() vagy session_unregister() függvényeket.

session_module_name

(PHP 4 )

session_module_name -- Az aktuális munkamenet modul lekérdezése / beállítása

Leírás

string session_module_name ( [string module])

A session_module_name() visszatér az aktuális munkamenet modul nevével. Ha a module paramétert is megadod, a modult a megadottra állítja át.

session_name

(PHP 4 )

session_name -- Az aktuális munkamenet név lekérdezése / beállítása

Leírás

string session_name ( [string name])

A session_name() visszaadja az aktuális munkamenet nevét. Ha a name paraméter meg van adva, az aktuális munkamenet neve erre változik.

A munkamenet neve azonosítja a munkamenetet a sütikben, URL-ekben és űrlapokban. Csak alfanumerikus karaktereket tartalmazhat, rövidnek és érthetőnek kell lennie (azon látogatók számára, akik például bekapcsolt süti figyelmeztetők olvasása alapján döntik el a süti engedélyezését). A munkamenet neve visszatér a php.ini session.name beállítására a PHP program futása kezdetén. Ezért mindig meg kell hívni a session_name() függvényt a kívánt névvel a session_start() és/vagy session_register() hívások előtt, ha nem az alapértelmezett munkamenet nevet szeretnéd használni.

Példa 1. session_name() példa

<?php

// a munkamenet nevét webhelyneve-re állíjtuk

$elozo_nev = session_name("webhelyneve");

echo "A megelőző munkamenet név $elozo_nev volt.<p>";
?>

session_regenerate_id

(PHP 4 >= 4.3.2)

session_regenerate_id --  Update the current session id with a newly generated one

Description

bool session_regenerate_id ( void )

session_regenerate_id() will replace the current session id with a new one, and keep the current session information.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Példa 1. A session_regenerate_id() example

<?php
session_start();

$old_sessionid = session_id();

session_regenerate_id();

$new_sessionid = session_id();

echo "Old Session: $old_sessionid<br />";
echo "New Session: $new_sessionid<br />";

print_r($_SESSION);
?>

Megjegyzés: As of PHP 4.3.3, if session cookies are enabled, use of session_regenerate_id() will also submit a new session cookie with the new session id.

See also session_id(), session_start(), and session_name().

session_register

(PHP 4 )

session_register --  Egy vagy több változó bejegyzése munkamenet változókként

Leírás

bool session_register ( mixed name [, mixed ...])

A session_register() függvényt tetszőleges számú paraméterrel hívhatod. Bármely paraméter lehet egy karaktersorozat, ami egy változó neve, vagy egy tömb, ami változóneveket vagy újabb tömböket tartalmaz. A session_register() minden megadott nevű globális változót bejegyzi az aktuális munkamenet változójaként.

Figyelem

Ez a függvény globális változók regisztrálására használható. Ha egy függvényen belül szeretnél munkamenet változót bejegyezni, előbb globálissá kell tenned a global() kulcsszó használatával, vagy a munkamenet tömböket kell használnod, ahogy lentebb leírjuk.

Figyelem

Ha a $HTTP_SESSION_VARS vagy $_SESSION tömböket használod, ne használd a session_register(), session_is_registered() és session_unregister() függvényeket változók bejegyzésére!

Ez a függvény TRUE értékkel tér vissza, ha minden megadott nevű változó sikeresen bejegyzésre került a munkamenetben.

Ha a session_start() függvényt nem hívtad meg ennek a függvénynek a hívása előtt, a session_register() meghívásával a PHP közvetve automatikusan meghívja a session_start() függvényt paraméterek nélkül.

Egyszerűbben jegyezheted be a munkamenet változókat, ha a $HTTP_SESSION_VARS vagy $_SESSION (PHP >= 4.1.0) asszociatív tömbök egyikében hozol létre egy új kulcsot és értéket.

$barney = "Egy bíborszínű dinoszaurusz.";
session_register("barney");

$HTTP_SESSION_VARS["zim"] = "Támadó egy másik bolygóról.";

# A szuperglobális $_SESSION tömb a PHP 4.1.0 verzió óta használható
$_SESSION["spongebob"] = "Szögletes nadrágja van.";

Megjegyzés: Jelenleg nem lehetséges erőforrások bejegyzése munkamenetekben. Nem lehetséges például egy adatbázis kapcsolat létrehozása, regisztrálása a munkamenetben, és a következő munkamenet folytatáskor az adatbázis kapcsolat használata. Az erőforrásokkal visszatérő függvények arról ismerhetőek fel, hogy a leírásukban resource a megadott visszatérési típus. Az erőforrásokkal visszatérő függvények listája megtalálható az erőforrás típusok függelékben.

A $_SESSION (vagy $HTTP_SESSION_VARS PHP 4.0.6 vagy korábbi verziókban) használatakor új asszociatív indexet kell létrehozni a $_SESSION tömbben. Például $_SESSION['valtozo'] = 'ABC';

Lásd még session_is_registered() és session_unregister().

session_save_path

(PHP 4 )

session_save_path -- Az aktuális munkamenet mentési könyvtár lekérdezése / beállítása

Leírás

string session_save_path ( [string path])

A session_save_path() visszatér az aktuális munkamenet mentési könyvtárral, ahol a PHP a munkamenet adatokat tárolja. Ha a path paraméter meg van adva, a mentési könyvtár megváltozik.

Megjegyzés: Néhány operációs renszeren lehetőség van arra, hogy olyan elérési utat adjál meg, ami egy kis állományokat hatékonyabban kezelő állományrendszeren van. Linuxon például a reiserfs állományrendszer jobb teljesítménnyel kezeli a PHP munkamenet állományait, mint az ext2fs.

session_set_cookie_params

(PHP 4 )

session_set_cookie_params --  A munkamenet süti paramétereit állítja be

Leírás

void session_set_cookie_params ( int lifetime [, string path [, string domain [, bool secure]]])

A php.ini állományban definiált süti paraméterek felülírása. Ezen függvény hatása csak az aktuális program futásának végéig tart.

Megjegyzés: A secure paraméter a PHP 4.0.4 verziója óta használható.

session_set_save_handler

(PHP 4 )

session_set_save_handler --  Felhasználói szintű munkamenet tároló függvényeket állít be

Leírás

void session_set_save_handler ( string open, string close, string read, string write, string destroy, string gc)

A session_set_save_handler() beállítja a programozó által PHP-ben megírt munkamenet tároló függvényeket. Ezeket használja majd a PHP a munkamenet adatainak tárolására és lekérdezésére. Ez a lehetőség akkor hasznos, ha a PHP által kínált módszerek nem megfelelőek. Másfajta tárolás lehetséges az adatok lokális adatbázisban történő rögzítésével.

Megjegyzés: A php.ini session.save_handler beállítását mindenképpen user értékre kell állítanod, hogy a session_set_save_handler() függvény hívásának legyen hatása.

Megjegyzés: Az írás kezelő csak a PHP program kimenetének elküldése után hívódik meg. Ezért az írás kezelőben a böngésző számára kiírt, tipikusan hibakeresést szolgáló adatok nem lesznek sohasem láthatóak a böngészőben. Ha a hibakereséshez adatok kiírása szükséges, javasolt napló állomány használata erre a célra.

Az alább látható példa állmoány alapú munkamenet adat tárolást valósít meg, hasonlóan a PHP alapértelmezésű files kezelőjéhez. Ez a példa könnyen kiterjeszthető egy adatbázis tárolást alkalmazó kezelővé, felhasználva a kedvenc adatbáziskezelőd függvényeit.

Az olvasó függvénynek mindig karaktersorozattal kell visszatérnie, hogy a mentést végző kezelő helyesen működjön. Üres karaktersorozattal kell visszatérni, ha nincs adat, amit olvasni lehetne. Más kezelők visszatérési értékei logikai típusúvá alakulnak. Igaz értéket kell visszaadni siker estén, hamisat hiba esetén.

Példa 1. session_set_save_handler() példa

<?php
function open ($save_path, $session_name) {
  global $sess_save_path, $sess_session_name;
       
  $sess_save_path = $save_path;
  $sess_session_name = $session_name;
  return(true);
}

function close() {
  return(true);
}

function read ($id) {
  global $sess_save_path, $sess_session_name;

  $sess_file = "$sess_save_path/sess_$id";
  if ($fp = @fopen($sess_file, "r")) {
    $sess_data = fread($fp, filesize($sess_file));
    return($sess_data);
  } else {
    return(""); // Itt mindenképpen "" a visszatérési érték.
  }

}

function write ($id, $sess_data) {
  global $sess_save_path, $sess_session_name;

  $sess_file = "$sess_save_path/sess_$id";
  if ($fp = @fopen($sess_file, "w")) {
    return(fwrite($fp, $sess_data));
  } else {
    return(false);
  }

}

function destroy ($id) {
  global $sess_save_path, $sess_session_name;
       
  $sess_file = "$sess_save_path/sess_$id";
  return(@unlink($sess_file));
}

/*********************************************
 * FIGYELEM - Itt mindenképpen meg kell      *
 * valósítani valamiféle szemétgyűjtést.     *
 *********************************************/
function gc ($maxlifetime) {
  return true;
}

session_set_save_handler ("open", "close", "read", "write", "destroy", "gc");

session_start();

// Ezután hagyományosan használható a munkamenet

?>

session_start

(PHP 4 )

session_start -- Munkamenet megkezdése / folytatása

Leírás

bool session_start ( void )

A session_start() elkezd egy új munkamenetet, vagy folytat egy korábbit, ha a PHP érvényes munkamenet azonosító érkezését érzékelte GET/POST paraméterben vagy sütiben.

Ha az alapbeállítású névtől eltérő nevet szeretnél használni a munkamenet számára, használd a session_name() függvényt a session_start() meghívása előtt.

Ez a függvény mindig TRUE értékkel tér vissza.

Megjegyzés: Ha süti alapú munkameneteket használsz, a session_start() hívásnak minden kimenetet meg kell előznie.

A session_start() egy belső kimenet kezelőt regisztrál az URL-ek és űrlapok átírására, ha a trans-sid funkció be van kapcsolva. Ha az ob_gzhandler-t vagy más hasonló kimenet kezelőket használsz az ob_start() függvénnyel, a kimenet kezelők sorrendje fontos a megfelelő kimenet érdekében. Ezért az ob_gzhandler-t a munkamenet megkezdése előtt kell regisztrálni.

Megjegyzés: A zlib.output_compression használata javasolt az ob_gzhandler helyett.

session_unregister

(PHP 4 )

session_unregister --  Munkamenet változó törlése a munkamenetből

Leírás

bool session_unregister ( string name)

A session_unregister() törli (elfelejti) a name paraméterben megadott nevű globális munkamenet változót, az aktuális munkamenetből.

Ez a függvény TRUE értékkel tér vissza, ha a változó törlése sikeresen megtörtént az aktuális munkamenetet érintően.

Megjegyzés: A $_SESSION (vagy $HTTP_SESSION_VARS PHP 4.0.6 vagy korábbi verziókban) használatakor az unset() függvényt kell használni munkamenet változó törlésére, paraméterként átadva a tömb változóhoz tartozó elemét.

Figyelem

Ez a függvény nem törli a munkamenet változóhoz tartozó globális name nevű változót, csak megszünteti a változó és a munkamenet kapcsolatát. Meg kell hívnod az unset() függvényt a változóra, ha törölni szeretnéd a globális változót is.

Figyelem

A $HTTP_SESSION_VARS vagy $_SESSION tömbök használata esetén ne hívd meg a session_register(), session_is_registered() vagy session_unregister() függvényeket.

session_unset

(PHP 4 )

session_unset --  Minden munkamenet változó felszabadítása

Leírás

void session_unset ( void )

A session_unset() függvény minden éppen bejegyzett munkamenet változót felszabadít.

Megjegyzés: Ha a $_SESSION (vagy $HTTP_SESSION_VARS PHP 4.0.6 vagy korábbi verziókban) tömböket használod, az unset() függvénnyel tudsz egyes változókat törlni. A teljes törléshez használd a $_SESSION = array(); sort.

session_write_close

(PHP 4 >= 4.0.4)

session_write_close -- A munkamenet adatok kiírása és a munkamenet lezárása

Leírás

void session_write_close ( void )

Az aktuális munkamenet befejezése, és a munkamenet adatok tárolása.

A munkamenet adatok elmentésre kerülnek a programod futásának végeztével, anélkül, hogy meghívnád a session_write_close() függvényt, de mivel a munkamenet adatok zároltak az egyidőben írások elkerülésére, egyszerre csak egy program tud dolgozni a munkamenettel. Ha kereteket használsz a weboldaladon a munkamenetekkel együtt, észre fogod venni, hogy a keretek egyesével töltődnek le emiatt a zárolás miatt. A keretek betöltéséhez szükséges időt lerövidítheted, ha rögtön meghívod ezt a függvényt a programodban, amikor már biztos, hogy minden munkamenet változtatást elvégeztél.

XCVII. Shared Memory Functions

Bevezetés

Shmop is an easy to use set of functions that allows PHP to read, write, create and delete Unix shared memory segments. Note that versions of Windows previous to Windows 2000 do not support shared memory.

Megjegyzés: In PHP 4.0.3, these functions were prefixed by shm rather than shmop.


Követelmények

Az itt leírt függvények használatához semmilyen külső függvénykönyvtár megléte nem szükségeltetik.


Telepítés

To use shmop you will need to compile PHP with the --enable-shmop parameter in your configure line.


Futásidejű beállítások

Ez a kiterjesztés semmilyen konfigurációs beállításokat nem definiál a php.ini állományban.


Erőforrás típusok


Előre definiált állandók

Ez a kiterjesztés semmilyen konstans értéket nem definiál.


Példák

Példa 1. Shared Memory Operations Overview

<?php
   
// Create 100 byte shared memory block with system id if 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);
   
?>

Tartalom
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

shmop_close

(PHP 4 >= 4.0.4)

shmop_close -- Close shared memory block

Description

int shmop_close ( int shmid)

shmop_close() is used to close a shared memory block.

shmop_close() takes the shmid, which is the shared memory block identifier created by shmop_open().

Példa 1. Closing shared memory block

<?php
shmop_close($shm_id);
?>

This example will close shared memory block identified by $shm_id.

shmop_delete

(PHP 4 >= 4.0.4)

shmop_delete -- Delete shared memory block

Description

int shmop_delete ( int shmid)

shmop_delete() is used to delete a shared memory block.

shmop_delete() takes the shmid, which is the shared memory block identifier created by shmop_open(). On success 1 is returned, on failure 0 is returned.

Példa 1. Deleting shared memory block

<?php
shmop_delete($shm_id);
?>

This example will delete shared memory block identified by $shm_id.

shmop_open

(PHP 4 >= 4.0.4)

shmop_open -- Create or open shared memory block

Description

int shmop_open ( int key, string flags, int mode, int size)

shmop_open() can create or open a shared memory block.

shmop_open() takes 4 parameters: key, which is the system's id for the shared memory block, this parameter can be passed as a decimal or hex. The second parameter are 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.

The third parameter is the mode, which are 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 ex. 0644. The last parameter is size of the shared memory block you wish to create in bytes.

Megjegyzés: Note: the 3rd and 4th should be entered as 0 if you are opening an existing memory segment. On success shmop_open() will return an id that you can use to access the shared memory segment you've created.

Példa 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().

shmop_read

(PHP 4 >= 4.0.4)

shmop_read -- Read data from shared memory block

Description

string shmop_read ( int shmid, int start, int count)

shmop_read() will read a string from shared memory block.

shmop_read() takes 3 parameters: shmid, which is the shared memory block identifier created by shmop_open(), offset from which to start reading and count on the number of bytes to read.

Példa 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.

shmop_size

(PHP 4 >= 4.0.4)

shmop_size -- Get size of shared memory block

Description

int shmop_size ( int shmid)

shmop_size() is used to get the size, in bytes of the shared memory block.

shmop_size() takes the shmid, which is the shared memory block identifier created by shmop_open(), the function will return and int, which represents the number of bytes the shared memory block occupies.

Példa 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_write

(PHP 4 >= 4.0.4)

shmop_write -- Write data into shared memory block

Description

int shmop_write ( int shmid, string data, int offset)

shmop_write() will write a string into shared memory block.

shmop_write() takes 3 parameters: shmid, which is the shared memory block identifier created by shmop_open(), data, a string that you want to write into shared memory block and offset, which specifies where to start writing data inside the shared memory segment.

Példa 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.

XCVIII. SimpleXML functions

Bevezetés

Figyelem

Ez a kiterjesztés KÍSÉRLETI JELLEGGEL MŰKÖDIK. Ez azt jelenti, hogy minden itt dokumentált működés, beleértve a függvények nevét, működését vagy bármi más, amit a kiterjesztés kapcsán leírtunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a kiterjesztést csak a saját felelősségedre használd!

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.


Telepítés

This extension is only available if PHP was configured with --enable-simplexml. The PHP configuration script does this by default.


Példák

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

Példa 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&oacute;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>
  <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.

Példa 2. Getting <plot>

<?php
include 'example.php';

$xml = simplexml_load_string($xmlstr);

echo $xml->movie[0]->plot; // "So this language. It's like..."
?>

Példa 3. 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';

$xml = simplexml_load_string($xmlstr);

/* For each <movie> node, we echo a separate <plot>. */
foreach($xml->movie as $movie) {
   echo $movie->plot,'<br/>';
}

?>

Példa 4. 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';

$xml = simplexml_load_string($xmlstr);

/* Access the <rating> nodes of the first movie.
 * Output the rating scale, too.                 */
foreach($xml->movie[0]->rating as $rating) {
    switch($rating['type']) { // Get attributes as element indices
    case 'thumbs':
        echo $rating, ' thumbs up';
        break;
    case 'stars':
        echo $rating, ' stars';
        break;
    }
}
?>

Példa 5. Using XPATH

SimpleXML includes builtin XPATH support. To find all <character> elements:

<?php
include 'example.php';
$xml = simplexml_load_string($xmlstr);

foreach($xml->xpath('//character') as $character) {
    echo $character->name, 'played by ', $character->actor, '<br/>';
}
?>

'//' serves as a wildcard. To specify absolute paths, omit one of the slashes.

Példa 6. 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';
$xml = simplexml_load_string($xmlstr);

$xml->movie[0]->actor[0]->age = '21';

echo $xml->asXML();
?>

The above code will output a new XML document, just like the original, except that the new XML will define Ms. Coder's age as 21.

Példa 7. 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.

Megjegyzés: This will only work with DOM in PHP 5, but SimpleXML wasn't available before that version, so you should be fine.

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

Tartalom
simplexml_element->asXML --  Return a well-formed XML string based on SimpleXML element.
simplexml_element->attributes --  Identifies an element's attributes.
simplexml_element->children --  Finds children of given node.
simplexml_element->xpath --  Runs XPATH query on XML data.
simplexml_load_dom --  Get a simplexml_element 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.

simplexml_element->asXML

(no version information, might be only in CVS)

simplexml_element->asXML --  Return a well-formed XML string based on SimpleXML element.

Description

string simplexml_element->asXML ( void )

The asXML method formats the parent object's data in XML version 1.0.

Példa 1. Get XML

<?php
$string = <<<XML
<a>
 <b>
  <c>text</c>
  <c>stuff</c>
 </b>
 <d>
  <c>code</c>
 </d>
</a>
XML;

$xml = simplexml_load_string($string);

echo $xml->asXML(); // <?xml ... <a><b><c>text</c><c>stuff</c> ...

?>

asXML also works on XPATH results:

Példa 2. Using asXML() on 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(); // <c>text</c> and <c>stuff</c>
}
?>

simplexml_element->attributes

(no version information, might be only in CVS)

simplexml_element->attributes --  Identifies an element's attributes.

Description

object simplexml_element simplexml_element->attributes ( string data)

This function provides the attributes and values defined within an xml tag.

Példa 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";
}
?>

This script will display:

name="one"
game="lonely"

simplexml_element->children

(no version information, might be only in CVS)

simplexml_element->children --  Finds children of given node.

Description

object simplexml_element simplexml_element->children ( void )

This method finds the children of the element of which it is a member. The result follows normal iteration rules.

Megjegyzés: Like most other SimpleXML methods, children() has iterative properties which cannot be viewed using var_dump() or anything else which can examine objects.

Példa 1. Traversing a children() pseudo-array

<?php
$xml = simplexml_load_string(
'<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'];
        }
    }
}
?>

This script will output:

The person begot a son who begot a daughter; The person
begot a daughter who begot a son; and that son begot a son

simplexml_element->xpath

(no version information, might be only in CVS)

simplexml_element->xpath --  Runs XPATH query on XML data.

Description

array simplexml_element->xpath ( string path)

The xpath method searches the SimpleXML node for children matching the XPATH path. It always returns an array of simplexml_element objects.

Példa 1. XPATH

<?php
$string = <<<XML
<a>
 <b>
  <c>text</c>
  <c>stuff</c>
 </b>
 <d>
  <c>code</c>
 </d>
</a>
XML;

$xml = simplexml_load_string($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";
}
?>

This script will display:

/a/b/c: text
/a/b/c: stuff
b/c: text
b/c: stuff

Notice that the two results are equal.

simplexml_load_dom

(no version information, might be only in CVS)

simplexml_load_dom --  Get a simplexml_element object from a DOM node.

Description

object simplexml_element simplexml_load_dom ( domNode node)

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. If any errors occur, it returns FALSE.

Példa 1. Import 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;
?>

This code should output:

blah

simplexml_load_file

(no version information, might be only in CVS)

simplexml_load_file --  Interprets an XML file into an object.

Description

object simplexml_element simplexml_load_file ( string filename)

This function will convert the well-formed XML document in the file specified by filename to an object of class simplexml_element. If any errors occur during file access or interpretation, the function returns FALSE.

Példa 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');
 
    var_dump($xml);
} else {
    exit('Failed to open test.xml.');
}
?>

This script will display, on success:

simplexml_element Object
(
  [title] => Example Title
  ...
)

At this point, you can go about using $xml->title and any other elements.

See also: simplexml_load_string()

simplexml_load_string

(no version information, might be only in CVS)

simplexml_load_string --  Interprets a string of XML into an object.

Description

object simplexml_element simplexml_load_string ( string data)

This function will take the well-formed xml string data and return an object with properties containing the data held within the xml document. If any errors occur, it returns FALSE.

Példa 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)

var_dump($xml);
?>

This script will display:

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

See also: simplexml_load_file().

XCIX. SQLite

Bevezetés

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.

Megjegyzés: For further information see the SQLite Website (http://sqlite.org/).


Installation

Read the INSTALL file, which comes with the package. Or just use the PEAR installer with "pear install sqlite". SQLite itself is already included, You do not need to install any additional software.

Windows users may download the DLL version of the SQLite extension here: (php_sqlite.dll).


Követelmények

In order to have these functions available, you must compile PHP with SQLite support, or load the SQLite extension dynamically from your php.ini.


Erőforrás típusok

There are two resources used in the SQLite Interface. The first one is the database connection, the second one the result set.


Predefined Constants

The functions sqlite_fetch_array() and sqlite_current() use a constant for the different types of result arrays. The following constants are defined:

Táblázat 1. SQLite fetch constants

constantmeaning
SQLITE_ASSOC Columns are returned into the array having the fieldname as the array index.
SQLITE_BOTH Columns are returned into the array having both a numerical index and the fieldname as the array index.
SQLITE_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.


Futásidejű beállítások

Az alábbi függvények viselkedése befolyásolható a php.ini segítségével.

Táblázat 2. SQLite Configuration Options

NameDefaultChangeable
sqlite.assoc_case0PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().

Here's a short explanation of the configuration directives.

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.

Tartalom
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_fetch_array -- Fetches the next row from a result set as an array.
sqlite_fetch_single -- Fetches the first column of a result set as a string.
sqlite_fetch_string -- Alias of sqlite_fetch_single()
sqlite_field_name -- Returns the name of a particular field.
sqlite_has_more -- Returns whether or not more rows are available.
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 a SQLite database. Will create the database if it does not exist
sqlite_popen --  Opens a persistent handle to an SQLite database. Will create the database if it does not exist.
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_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_array_query

(no version information, might be only in CVS)

sqlite_array_query -- Execute a query against a given database and returns an array.

Description

array sqlite_array_query ( resource dbhandle, string query [, int result_type [, bool decode_binary]])

array sqlite_array_query ( string query, resource dbhandle [, int result_type [, bool decode_binary]])

sqlite_array_query() is similar to calling sqlite_query() and then sqlite_fetch_array() for each row of the result set and storing it into an array, as shown in the example below. Calling sqlite_array_query() is significantly faster than using such a script.

Példa 1. sqlite_array_query() implemented yourself

<?php
$q = sqlite_query($dbhandle, "SELECT * from foo LIMIT 100");
$rows = array();
while ($r = sqlite_fetch_array($q)) {
    $rows[] = $r;
}
?>

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

See also sqlite_query(), sqlite_fetch_array(), and sqlite_fetch_string().

sqlite_busy_timeout

(no version information, might be only in CVS)

sqlite_busy_timeout -- Set busy timeout duration, or disable busy handlers.

Description

void sqlite_busy_timeout ( resource dbhandle, int milliseconds)

Set the maximum time that sqlite will wait for a dbhandle to become ready for use to milliseconds. If milliseconds is 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.

Megjegyzés: There are one thousand (1000) milliseconds in one second.

See also sqlite_open().

sqlite_changes

(no version information, might be only in CVS)

sqlite_changes --  Returns the number of rows that were changed by the most recent SQL statement.

Description

int sqlite_changes ( resource dbhandle)

Returns the numbers of rows that were changed by the most recent SQL statement executed against the dbhandle database handle.

See also sqlite_num_rows().

sqlite_close

(no version information, might be only in CVS)

sqlite_close -- Closes an open SQLite database.

Description

void sqlite_close ( resource dbhandle)

Closes the given database handle. If the database was persistent, it will be closed and removed from the persistent list.

See also sqlite_open() and sqlite_popen().

sqlite_column

(no version information, might be only in CVS)

sqlite_column -- Fetches a column from the current row of a result set.

Description

mixed sqlite_column ( resource result, mixed index_or_name [, bool decode_binary])

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. The decode binary flag operates in the same way as described under sqlite_fetch_array().

Use this function when you are iterating a large result set with many columns, or with columns that contain large amounts of data.

See also sqlite_fetch_string().

sqlite_create_aggregate

(no version information, might be only in CVS)

sqlite_create_aggregate -- Register an aggregating UDF for use in SQL statements.

Description

bool sqlite_create_aggregate ( resource dbhandle, string function_name, mixed step_func, mixed finalize_func [, int num_args])

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.

Példa 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.

Megjegyzés: 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.

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

Tipp: You can use sqlite_create_function() and sqlite_create_aggregate() to override SQLite native SQL functions.

See also sqlite_create_function(), sqlite_udf_encode_binary() and sqlite_udf_decode_binary().

sqlite_create_function

(no version information, might be only in CVS)

sqlite_create_function --  Registers a "regular" User Defined Function for use in SQL statements.

Description

bool sqlite_create_function ( resource dbhandle, string function_name, mixed callback [, int num_args])

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.

dbhandle specifies the database handle that you wish to extend, function_name specifies the name of the function that you will use in your SQL statements, callback is any valid PHP callback to specify a PHP function that should be called to handle the SQL function. The optional parameter num_args is used as a hint by the SQLite expression parser/evaluator. It is recommended that you specify a value if your function will only ever accept a fixed number of parameters.

The UDF can be used in any SQL statement that can call functions, such as SELECT and UPDATE statements and also in triggers.

Példa 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.

Példa 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

Megjegyzés: 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.

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

Tipp: You can use sqlite_create_function() and sqlite_create_aggregate() to override SQLite native SQL functions.

See also sqlite_create_aggregate().

sqlite_current

(no version information, might be only in CVS)

sqlite_current -- Fetches the current row from a result set as an array.

Description

array sqlite_current ( resource result [, int result_type [, bool decode_binary]])

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.

If the current position is beyond the final row, this function returns FALSE

Megjegyzés: This function will not work on unbuffered result handles.

See also sqlite_seek(), sqlite_next(), and sqlite_fetch_array().

sqlite_error_string

(no version information, might be only in CVS)

sqlite_error_string -- Returns the textual description of an error code.

Description

string sqlite_error_string ( int error_code)

Returns a human readable description of the error_code returned from sqlite_last_error().

See also sqlite_last_error().

sqlite_escape_string

(no version information, might be only in CVS)

sqlite_escape_string -- Escapes a string for use as a query parameter

Description

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.

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.

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

Figyelem

addslashes() should NOT be used to quote your strings for SQLite queries; it will lead to strange results when retrieving your data.

Megjegyzés: 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.

See also sqlite_udf_encode_binary().

sqlite_fetch_array

(no version information, might be only in CVS)

sqlite_fetch_array -- Fetches the next row from a result set as an array.

Description

array sqlite_fetch_array ( resource result [, int result_type [, bool decode_binary]])

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.

result_type can be used to specify how you want the results to be returned. The default value is SQLITE_BOTH which returns columns indexed by their ordinal column number and by column name. SQLITE_ASSOC causes the array to be indexed only by column names, and SQLITE_NUM to be indexed only by ordinal column numbers.

The column names returned by SQLITE_ASSOC and SQLITE_BOTH will be case-folded according to the value of the sqlite.assoc_case configuration option.

When decode_binary is set to TRUE (the default), PHP will decode the binary encoding it applied to the data if it was encoded using the sqlite_escape_string(). You will usually always leave this value at its default, unless you are interoperating with databases created by other sqlite capable applications.

See also sqlite_array_query() and sqlite_fetch_string().

sqlite_fetch_single

(no version information, might be only in CVS)

sqlite_fetch_single -- Fetches the first column of a result set as a string.

Description

string sqlite_fetch_single ( resource result [, int result_type [, bool decode_binary]])

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.

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

See also sqlite_fetch_array().

sqlite_fetch_string

sqlite_fetch_string -- Alias of sqlite_fetch_single()

Description

This function is an alias of sqlite_fetch_single().

sqlite_field_name

(no version information, might be only in CVS)

sqlite_field_name -- Returns the name of a particular field.

Description

string sqlite_field_name ( resource result, int field_index)

Given the ordinal column number, field_index, returns the name of that field in the result handle result.

sqlite_has_more

(no version information, might be only in CVS)

sqlite_has_more -- Returns whether or not more rows are available.

Description

bool sqlite_has_more ( resource result)

sqlite_has_more() returns TRUE if there are more rows available from the result handle, or FALSE otherwise.

See also sqlite_num_rows() and sqlite_changes().

sqlite_last_error

(no version information, might be only in CVS)

sqlite_last_error -- Returns the error code of the last error for a database.

Description

int sqlite_last_error ( resource dbhandle)

Returns the error code from the last operation performed on dbhandle, the database handle. A human readable description of the error code can be retrieved using sqlite_error_string().

See also sqlite_error_string().

sqlite_last_insert_rowid

(no version information, might be only in CVS)

sqlite_last_insert_rowid -- Returns the rowid of the most recently inserted row.

Description

int sqlite_last_insert_rowid ( resource dbhandle)

Returns the rowid of the row that was most recently inserted into the database dbhandle, if it was created as an auto-increment field.

Tipp: You can create auto-increment fields in SQLite by declaring them as INTEGER PRIMARY KEY in your table schema.

sqlite_libencoding

(no version information, might be only in CVS)

sqlite_libencoding -- Returns the encoding of the linked SQLite library.

Description

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.

Figyelem

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.

Figyelem

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.

See also sqlite_libversion().

sqlite_libversion

(no version information, might be only in CVS)

sqlite_libversion -- Returns the version of the linked SQLite library.

Description

string sqlite_libversion ( void )

Returns the version of the linked SQLite library as a string.

See also sqlite_libencoding().

sqlite_next

(no version information, might be only in CVS)

sqlite_next -- Seek to the next row number.

Description

bool sqlite_next ( resource result)

sqlite_next() advances the result handle result to the next row. Returns FALSE if there are no more rows, TRUE otherwise.

Megjegyzés: This function cannot be used with unbuffered result handles.

See also sqlite_seek(), sqlite_current() and sqlite_rewind().

sqlite_num_fields

(no version information, might be only in CVS)

sqlite_num_fields -- Returns the number of fields in a result set.

Description

int sqlite_num_fields ( resource result)

Returns the number of fields in the result set.

See also sqlite_column() and sqlite_num_rows().

sqlite_num_rows

(no version information, might be only in CVS)

sqlite_num_rows -- Returns the number of rows in a buffered result set.

Description

int sqlite_num_rows ( resource result)

Returns the number of rows in the buffered result set.

Megjegyzés: This function cannot be used with unbuffered result sets.

See also sqlite_changes() and sqlite_query().

sqlite_open

(no version information, might be only in CVS)

sqlite_open -- Opens a SQLite database. Will create the database if it does not exist

Description

resource sqlite_open ( string filename [, int mode [, string &error_message]])

Returns a resource (database handle) on success, FALSE on error.

The filename parameter is the name of the database. It can be a relative or absolute path to the file that sqlite will use to store your data. If the file does not exist, sqlite will attempt to create it. You MUST have write permissions to the file if you want to insert data or modify the database schema.

The mode parameter specifies the mode of the file and is 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 to use if you need access to the errmessage parameter.

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

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

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

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

Megjegyzés: 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.

Megjegyzés: SQLite is safe mode and open_basedir aware.

See also sqlite_popen(), sqlite_close() and sqlite_query().

sqlite_popen

(no version information, might be only in CVS)

sqlite_popen --  Opens a persistent handle to an SQLite database. Will create the database if it does not exist.

Description

resource sqlite_popen ( string filename [, int mode [, 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).

Megjegyzés: 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.

See also sqlite_open(), sqlite_close() and sqlite_query().

sqlite_query

(no version information, might be only in CVS)

sqlite_query --  Executes a query against a given database and returns a result handle.

Description

resource sqlite_query ( resource dbhandle, string query)

resource sqlite_query ( string query, resource dbhandle)

Executes an SQL statement given by the query against a given database handle (specified by the dbhandle parameter).

For queries that return rows, this function will return a result handle which can then be used with functions such as sqlite_fetch_array() and sqlite_seek().

For other kinds of queries, this function will return a boolean result; TRUE for success or FALSE for failure.

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.

Megjegyzés: Two alternative syntaxes are supported for compatibility with other database extensions (such as MySQL). The preferred form is the first one, where the db parameter is the first parameter to the function.

Figyelem

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.

When executing multiple queries, the return value of this function will be FALSE if the was an error, but undefined otherwise (it might be TRUE for success or it might return a result handle).

See also sqlite_unbuffered_query() and sqlite_array_query().

sqlite_rewind

(no version information, might be only in CVS)

sqlite_rewind -- Seek to the first row number.

Description

bool sqlite_rewind ( resource result)

sqlite_rewind() seeks back to the first row in the result set. Returns FALSE if there are no rows in the result set, TRUE otherwise.

Megjegyzés: This function cannot be used with unbuffered result sets.

See also sqlite_next(), sqlite_current(), and sqlite_seek().

sqlite_seek

(no version information, might be only in CVS)

sqlite_seek -- Seek to a particular row number of a buffered result set.

Description

bool sqlite_seek ( resource result, int rownum)

sqlite_seek() seeks to the row given by the parameter rownum. The row number is zero-based (0 is the first row). Returns FALSE if the row does not exist, TRUE otherwise.

Megjegyzés: This function cannot be used with unbuffered result handles.

See also sqlite_next(), sqlite_current() and sqlite_rewind().

sqlite_udf_decode_binary

(no version information, might be only in CVS)

sqlite_udf_decode_binary -- Decode binary data passed as parameters to an UDF.

Description

string sqlite_udf_decode_binary ( string data)

sqlite_udf_decode_binary() decodes the binary encoding that was applied to the parameter by either sqlite_udf_encode_binary() or sqlite_escape_string().

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.

Példa 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'));

?>

See also sqlite_udf_encode_binary(), sqlite_create_function() and sqlite_create_aggregate().

sqlite_udf_encode_binary

(no version information, might be only in CVS)

sqlite_udf_encode_binary -- Encode binary data before returning it from an UDF.

Description

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.

Megjegyzés: 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!

See also sqlite_udf_decode_binary(), sqlite_escape_string(), sqlite_create_function() and sqlite_create_aggregate().

sqlite_unbuffered_query

(no version information, might be only in CVS)

sqlite_unbuffered_query -- Execute a query that does not prefetch and buffer all data

Description

resource sqlite_unbuffered_query ( resource dbhandle, string query)

resource sqlite_unbuffered_query ( string query, resource dbhandle)

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.

Megjegyzés: 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().

See also sqlite_query().

C. Shockwave Flash functions

Bevezetés

PHP offers the ability to create Shockwave Flash files via Paul Haeberli's libswf module.

Megjegyzés: SWF support was added in PHP 4 RC2.

The libswf does not have support for Windows. The development of that library has been stopped, and the source is not available to port it to another systems.

For up to date SWF support take a look at the MING functions.


Követelmények

You need the libswf library to compile PHP with support for this extension. You can download libswf at ftp://ftp.sgi.com/sgi/graphics/grafica/flash/.


Telepítés

Once you have libswf all you need to do is to configure --with-swf[=DIR] where DIR is a location containing the directories include and lib. The include directory has to contain the swf.h file and the lib directory has to contain the libswf.a file. If you unpack the libswf distribution the two files will be in one directory. Consequently you will have to copy the files to the proper location manually.


Futásidejű beállítások

Ez a kiterjesztés semmilyen konfigurációs beállításokat nem definiál a php.ini állományban.


Erőforrás típusok

Ez a kiterjesztés semmilyen erőforrás típust nem definiál.


Előre definiált állandók

Az itt listázott állandókat ez a kiterjesztés definiálja, és csak akkor elérhetőek, ha az adott kiterjesztés be van fordítva a PHP-be, vagy dinamikusan betöltött.

MOD_COLOR (integer)

MOD_MATRIX (integer)

TYPE_PUSHBUTTON (integer)

TYPE_MENUBUTTON (integer)

BSHitTest (float)

BSDown (float)

BSOver (float)

BSUp (float)

OverDowntoIdle (integer)

IdletoOverDown (integer)

OutDowntoIdle (integer)

OutDowntoOverDown (integer)

OverDowntoOutDown (integer)

OverUptoOverDown (integer)

OverUptoIdle (integer)

IdletoOverUp (integer)

ButtonEnter (integer)

ButtonExit (integer)

MenuEnter (integer)

MenuExit (integer)


Példák

Once you've successfully installed PHP with Shockwave Flash support you can then go about creating Shockwave files from PHP. You would be surprised at what you can do, take the following code:

Példa 1. SWF example

<?php
swf_openfile("test.swf", 256, 256, 30, 1, 1, 1);
swf_ortho2(-100, 100, -100, 100);
swf_defineline(1, -70, 0, 70, 0, .2);
swf_definerect(4, 60, -10, 70, 0, 0);
swf_definerect(5, -60, 0, -70, 10, 0);
swf_addcolor(0, 0, 0, 0);

swf_definefont(10, "Mod");
swf_fontsize(5);
swf_fontslant(10);
swf_definetext(11, "This be Flash wit PHP!", 1);

swf_pushmatrix();
swf_translate(-50, 80, 0);
swf_placeobject(11, 60);
swf_popmatrix();

for ($i = 0; $i < 30; $i++) {
    $p = $i/(30-1);
    swf_pushmatrix();
    swf_scale(1-($p*.9), 1, 1);
    swf_rotate60*$p,  'z');
    swf_translate(20+20*$p, $p/1.5, 0);
    swf_rotate(270*$p,  'z');
    swf_addcolor($p, 0, $p/1.2, -$p);
    swf_placeobject(1, 50);
    swf_placeobject(4, 50);
    swf_placeobject(5, 50);
    swf_popmatrix();
    swf_showframe();
}

for ($i = 0; $i < 30; $i++) {
    swf_removeobject(50);
    if (($i%4) == 0) {
        swf_showframe();
    }
}

swf_startdoaction();
swf_actionstop();
swf_enddoaction();

swf_closefile();
?>

Tartalom
swf_actiongeturl -- Get a URL from a Shockwave Flash movie
swf_actiongotoframe -- Play a frame and then stop
swf_actiongotolabel --  Display a frame with the specified label
swf_actionnextframe -- Go forward one frame
swf_actionplay --  Start playing the flash movie from the current frame
swf_actionprevframe -- Go backwards one frame
swf_actionsettarget -- Set the context for actions
swf_actionstop --  Stop playing the flash movie at the current frame
swf_actiontogglequality --  Toggle between low and high quality
swf_actionwaitforframe --  Skip actions if a frame has not been loaded
swf_addbuttonrecord --  Controls location, appearance and active area of the current button
swf_addcolor --  Set the global add color to the rgba value specified
swf_closefile -- Close the current Shockwave Flash file
swf_definebitmap -- Define a bitmap
swf_definefont --  Defines a font
swf_defineline -- Define a line
swf_definepoly --  Define a polygon
swf_definerect -- Define a rectangle
swf_definetext -- Define a text string
swf_endbutton --  End the definition of the current button
swf_enddoaction -- End the current action
swf_endshape --  Completes the definition of the current shape
swf_endsymbol -- End the definition of a symbol
swf_fontsize -- Change the font size
swf_fontslant -- Set the font slant
swf_fonttracking -- Set the current font tracking
swf_getbitmapinfo -- Get information about a bitmap
swf_getfontinfo --  The height in pixels of a capital A and a lowercase x
swf_getframe -- Get the frame number of the current frame
swf_labelframe -- Label the current frame
swf_lookat -- Define a viewing transformation
swf_modifyobject -- Modify an object
swf_mulcolor --  Sets the global multiply color to the rgba value specified
swf_nextid -- Returns the next free object id
swf_oncondition --  Describe a transition used to trigger an action list
swf_openfile -- Open a new Shockwave Flash file
swf_ortho2 --  Defines 2D orthographic mapping of user coordinates onto the current viewport
swf_ortho --  Defines an orthographic mapping of user coordinates onto the current viewport
swf_perspective --  Define a perspective projection transformation
swf_placeobject -- Place an object onto the screen
swf_polarview --  Define the viewer's position with polar coordinates
swf_popmatrix --  Restore a previous transformation matrix
swf_posround --  Enables or Disables the rounding of the translation when objects are placed or moved
swf_pushmatrix --  Push the current transformation matrix back unto the stack
swf_removeobject -- Remove an object
swf_rotate -- Rotate the current transformation
swf_scale -- Scale the current transformation
swf_setfont -- Change the current font
swf_setframe -- Switch to a specified frame
swf_shapearc -- Draw a circular arc
swf_shapecurveto3 -- Draw a cubic bezier curve
swf_shapecurveto --  Draw a quadratic bezier curve between two points
swf_shapefillbitmapclip --  Set current fill mode to clipped bitmap
swf_shapefillbitmaptile --  Set current fill mode to tiled bitmap
swf_shapefilloff -- Turns off filling
swf_shapefillsolid --  Set the current fill style to the specified color
swf_shapelinesolid -- Set the current line style
swf_shapelineto -- Draw a line
swf_shapemoveto -- Move the current position
swf_showframe -- Display the current frame
swf_startbutton -- Start the definition of a button
swf_startdoaction --  Start a description of an action list for the current frame
swf_startshape -- Start a complex shape
swf_startsymbol -- Define a symbol
swf_textwidth -- Get the width of a string
swf_translate -- Translate the current transformations
swf_viewport -- Select an area for future drawing

swf_actiongeturl

(PHP 4 <= 4.3.2)

swf_actiongeturl -- Get a URL from a Shockwave Flash movie

Description

void swf_actiongeturl ( string url, string target)

The swf_actiongeturl() function gets the URL specified by the parameter url with the target target.

swf_actiongotoframe

(PHP 4 <= 4.3.2)

swf_actiongotoframe -- Play a frame and then stop

Description

void swf_actiongotoframe ( int framenumber)

The swf_actiongotoframe() function will go to the frame specified by framenumber, play it, and then stop.

swf_actiongotolabel

(PHP 4 <= 4.3.2)

swf_actiongotolabel --  Display a frame with the specified label

Description

void swf_actiongotolabel ( string label)

The swf_actiongotolabel() function displays the frame with the label given by the label parameter and then stops.

swf_actionnextframe

(PHP 4 <= 4.3.2)

swf_actionnextframe -- Go forward one frame

Description

void swf_actionnextframe ( void )

Go forward one frame.

swf_actionplay

(PHP 4 <= 4.3.2)

swf_actionplay --  Start playing the flash movie from the current frame

Description

void swf_actionplay ( void )

Start playing the flash movie from the current frame.

swf_actionprevframe

(PHP 4 <= 4.3.2)

swf_actionprevframe -- Go backwards one frame

Description

void swf_actionprevframe ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

swf_actionsettarget

(PHP 4 <= 4.3.2)

swf_actionsettarget -- Set the context for actions

Description

void swf_actionsettarget ( string target)

The swf_actionsettarget() function sets the context for all actions. You can use this to control other flash movies that are currently playing.

swf_actionstop

(PHP 4 <= 4.3.2)

swf_actionstop --  Stop playing the flash movie at the current frame

Description

void swf_actionstop ( void )

Stop playing the flash movie at the current frame.

swf_actiontogglequality

(PHP 4 <= 4.3.2)

swf_actiontogglequality --  Toggle between low and high quality

Description

void swf_actiontogglequality ( void )

Toggle the flash movie between high and low quality.

swf_actionwaitforframe

(PHP 4 <= 4.3.2)

swf_actionwaitforframe --  Skip actions if a frame has not been loaded

Description

void swf_actionwaitforframe ( int framenumber, int skipcount)

The swf_actionwaitforframe() function will check to see if the frame, specified by the framenumber parameter has been loaded, if not it will skip the number of actions specified by the skipcount parameter. This can be useful for "Loading..." type animations.

swf_addbuttonrecord

(PHP 4 <= 4.3.2)

swf_addbuttonrecord --  Controls location, appearance and active area of the current button

Description

void swf_addbuttonrecord ( int states, int shapeid, int depth)

The swf_addbuttonrecord() function allows you to define the specifics of using a button. The first parameter, states, defines what states the button can have, these can be any or all of the following constants: BSHitTest, BSDown, BSOver or BSUp. The second parameter, the shapeid is the look of the button, this is usually the object id of the shape of the button. The depth parameter is the placement of the button in the current frame.

Példa 1. swf_addbuttonrecord() example

<?php
swf_startButton($objid, TYPE_MENUBUTTON);
swf_addButtonRecord(BSDown|BSOver, $buttonImageId, 340);
swf_onCondition(MenuEnter);
swf_actionGetUrl("http://www.example.com", "_level1");
swf_onCondition(MenuExit);
swf_actionGetUrl("", "_level1");
swf_endButton();
?>

swf_addcolor

(PHP 4 <= 4.3.2)

swf_addcolor --  Set the global add color to the rgba value specified

Description

void swf_addcolor ( float r, float g, float b, float a)

The swf_addcolor() function sets the global add color to the rgba color specified. This color is then used (implicitly) by the swf_placeobject(), swf_modifyobject() and the swf_addbuttonrecord() functions. The color of the object will be add by the rgba values when the object is written to the screen.

Megjegyzés: The rgba values can be either positive or negative.

swf_closefile

(PHP 4 <= 4.3.2)

swf_closefile -- Close the current Shockwave Flash file

Description

void swf_closefile ( [int return_file])

Close a file that was opened by the swf_openfile() function. If the return_file parameter is set then the contents of the SWF file are returned from the function.

Példa 1. Creating a simple flash file based on user input and outputting it and saving it in a database

<?php

// The $text variable is submitted by the
// user

// Global variables for database
// access (used in the swf_savedata() function)
$DBHOST = "localhost";
$DBUSER = "sterling";
$DBPASS = "secret";

swf_openfile("php://stdout", 256, 256, 30, 1, 1, 1);

    swf_definefont(10, "Ligon-Bold");
        swf_fontsize(12);
        swf_fontslant(10);
    
    swf_definetext(11, $text, 1);
    
    swf_pushmatrix();
        swf_translate(-50, 80, 0);
        swf_placeobject(11, 60);
    swf_popmatrix();

    swf_showframe();
  
    swf_startdoaction();
        swf_actionstop();
    swf_enddoaction();

$data = swf_closefile(1);

$data ?
  swf_savedata($data) :
  die("Error could not save SWF file");

// void swf_savedata(string data)
// Save the generated file a database
// for later retrieval
function swf_savedata($data) 
{
    global $DBHOST, 
           $DBUSER,
           $DBPASS;
    
    $dbh = @mysql_connect($DBHOST, $DBUSER, $DBPASS);

    if (!$dbh) {
        die (sprintf("Error [%d]: %s",
                      mysql_errno(), mysql_error()));
    }

    $stmt = "INSERT INTO swf_files (file) VALUES ('$data')";

    $sth = @mysql_query($stmt, $dbh);

    if (!$sth) {
        die (sprintf("Error [%d]: %s",
                      mysql_errno(), mysql_error()));
    }

    @mysql_free_result($sth);
    @mysql_close($dbh);
}
?>

swf_definebitmap

(PHP 4 <= 4.3.2)

swf_definebitmap -- Define a bitmap

Description

void swf_definebitmap ( int objid, string image_name)

The swf_definebitmap() function defines a bitmap given a GIF, JPEG, RGB or FI image. The image will be converted into a Flash JPEG or Flash color map format.

swf_definefont

(PHP 4 <= 4.3.2)

swf_definefont --  Defines a font

Description

void swf_definefont ( int fontid, string fontname)

The swf_definefont() function defines a font given by the fontname parameter and gives it the id specified by the fontid parameter. It then sets the font given by fontname to the current font.

swf_defineline

(PHP 4 <= 4.3.2)

swf_defineline -- Define a line

Description

void swf_defineline ( int objid, float x1, float y1, float x2, float y2, float width)

The swf_defineline() defines a line starting from the x coordinate given by x1 and the y coordinate given by y1 parameter. Up to the x coordinate given by the x2 parameter and the y coordinate given by the y2 parameter. It will have a width defined by the width parameter.

swf_definepoly

(PHP 4 <= 4.3.2)

swf_definepoly --  Define a polygon

Description

void swf_definepoly ( int objid, array coords, int npoints, float width)

The swf_definepoly() function defines a polygon given an array of x, y coordinates (the coordinates are defined in the parameter coords). The parameter npoints is the number of overall points that are contained in the array given by coords. The width is the width of the polygon's border, if set to 0.0 the polygon is filled.

swf_definerect

(PHP 4 <= 4.3.2)

swf_definerect -- Define a rectangle

Description

void swf_definerect ( int objid, float x1, float y1, float x2, float y2, float width)

The swf_definerect() defines a rectangle with an upper left hand coordinate given by the x, x1, and the y, y1. And a lower right hand coordinate given by the x coordinate, x2, and the y coordinate, y2 . Width of the rectangles border is given by the width parameter, if the width is 0.0 then the rectangle is filled.

swf_definetext

(PHP 4 <= 4.3.2)

swf_definetext -- Define a text string

Description

void swf_definetext ( int objid, string str, int docenter)

Define a text string (the str parameter) using the current font and font size. The docenter is where the word is centered, if docenter is 1, then the word is centered in x.

swf_endbutton

(PHP 4 <= 4.3.2)

swf_endbutton --  End the definition of the current button

Description

void swf_endbutton ( void )

The swf_endbutton() function ends the definition of the current button.

swf_enddoaction

(PHP 4 <= 4.3.2)

swf_enddoaction -- End the current action

Description

void swf_enddoaction ( void )

Ends the current action started by the swf_startdoaction() function.

swf_endshape

(PHP 4 <= 4.3.2)

swf_endshape --  Completes the definition of the current shape

Description

void swf_endshape ( void )

The swf_endshape() completes the definition of the current shape.

swf_endsymbol

(PHP 4 <= 4.3.2)

swf_endsymbol -- End the definition of a symbol

Description

void swf_endsymbol ( void )

The swf_endsymbol() function ends the definition of a symbol that was started by the swf_startsymbol() function.

swf_fontsize

(PHP 4 <= 4.3.2)

swf_fontsize -- Change the font size

Description

void swf_fontsize ( float size)

The swf_fontsize() function changes the font size to the value given by the size parameter.

swf_fontslant

(PHP 4 <= 4.3.2)

swf_fontslant -- Set the font slant

Description

void swf_fontslant ( float slant)

Set the current font slant to the angle indicated by the slant parameter. Positive values create a forward slant, negative values create a negative slant.

swf_fonttracking

(PHP 4 <= 4.3.2)

swf_fonttracking -- Set the current font tracking

Description

void swf_fonttracking ( float tracking)

Set the font tracking to the value specified by the tracking parameter. This function is used to increase the spacing between letters and text, positive values increase the space and negative values decrease the space between letters.

swf_getbitmapinfo

(PHP 4 <= 4.3.2)

swf_getbitmapinfo -- Get information about a bitmap

Description

array swf_getbitmapinfo ( int bitmapid)

The swf_getbitmapinfo() function returns an array of information about a bitmap given by the bitmapid parameter. The returned array has the following elements:

  • "size" - The size in bytes of the bitmap.

  • "width" - The width in pixels of the bitmap.

  • "height" - The height in pixels of the bitmap.

swf_getfontinfo

(PHP 4 <= 4.3.2)

swf_getfontinfo --  The height in pixels of a capital A and a lowercase x

Description

array swf_getfontinfo ( void )

The swf_getfontinfo() function returns an associative array with the following parameters:

  • Aheight - The height in pixels of a capital A.

  • xheight - The height in pixels of a lowercase x.

swf_getframe

(PHP 4 <= 4.3.2)

swf_getframe -- Get the frame number of the current frame

Description

int swf_getframe ( void )

The swf_getframe() function gets the number of the current frame.

swf_labelframe

(PHP 4 <= 4.3.2)

swf_labelframe -- Label the current frame

Description

void swf_labelframe ( string name)

Label the current frame with the name given by the name parameter.

swf_lookat

(PHP 4 <= 4.3.2)

swf_lookat -- Define a viewing transformation

Description

void swf_lookat ( float view_x, float view_y, float view_z, float reference_x, float reference_y, float reference_z, float twist)

The swf_lookat() function defines a viewing transformation by giving the viewing position (the parameters view_x, view_y, and view_z) and the coordinates of a reference point in the scene, the reference point is defined by the reference_x, reference_y , and reference_z parameters. The twist controls the rotation along with viewer's z axis.

swf_modifyobject

(PHP 4 <= 4.3.2)

swf_modifyobject -- Modify an object

Description

void swf_modifyobject ( int depth, int how)

Updates the position and/or color of the object at the specified depth, depth. The parameter how determines what is updated. how can either be the constant MOD_MATRIX or MOD_COLOR or it can be a combination of both (MOD_MATRIX|MOD_COLOR).

MOD_COLOR uses the current mulcolor (specified by the function swf_mulcolor()) and addcolor (specified by the function swf_addcolor()) to color the object. MOD_MATRIX uses the current matrix to position the object.

swf_mulcolor

(PHP 4 <= 4.3.2)

swf_mulcolor --  Sets the global multiply color to the rgba value specified

Description

void swf_mulcolor ( float r, float g, float b, float a)

The swf_mulcolor() function sets the global multiply color to the rgba color specified. This color is then used (implicitly) by the swf_placeobject(), swf_modifyobject() and the swf_addbuttonrecord() functions. The color of the object will be multiplied by the rgba values when the object is written to the screen.

Megjegyzés: The rgba values can be either positive or negative.

swf_nextid

(PHP 4 <= 4.3.2)

swf_nextid -- Returns the next free object id

Description

int swf_nextid ( void )

The swf_nextid() function returns the next available object id.

swf_oncondition

(PHP 4 <= 4.3.2)

swf_oncondition --  Describe a transition used to trigger an action list

Description

void swf_oncondition ( int transition)

The swf_oncondition() function describes a transition that will trigger an action list. There are several types of possible transitions, the following are for buttons defined as TYPE_MENUBUTTON:

  • IdletoOverUp

  • OverUptoIdle

  • OverUptoOverDown

  • OverDowntoOverUp

  • IdletoOverDown

  • OutDowntoIdle

  • MenuEnter (IdletoOverUp|IdletoOverDown)

  • MenuExit (OverUptoIdle|OverDowntoIdle)

For TYPE_PUSHBUTTON there are the following options:

  • IdletoOverUp

  • OverUptoIdle

  • OverUptoOverDown

  • OverDowntoOverUp

  • OverDowntoOutDown

  • OutDowntoOverDown

  • OutDowntoIdle

  • ButtonEnter (IdletoOverUp|OutDowntoOverDown)

  • ButtonExit (OverUptoIdle|OverDowntoOutDown)

swf_openfile

(PHP 4 <= 4.3.2)

swf_openfile -- Open a new Shockwave Flash file

Description

void swf_openfile ( string filename, float width, float height, float framerate, float r, float g, float b)

The swf_openfile() function opens a new file named filename with a width of width and a height of height a frame rate of framerate and background with a red color of r a green color of g and a blue color of b.

The swf_openfile() must be the first function you call, otherwise your script will cause a segfault. If you want to send your output to the screen make the filename: "php://stdout" (support for this is in 4.0.1 and up).

swf_ortho2

(PHP 4 <= 4.3.2)

swf_ortho2 --  Defines 2D orthographic mapping of user coordinates onto the current viewport

Description

void swf_ortho2 ( float xmin, float xmax, float ymin, float ymax)

The swf_ortho2() function defines a two dimensional orthographic mapping of user coordinates onto the current viewport, this defaults to one to one mapping of the area of the Flash movie. If a perspective transformation is desired, the swf_perspective () function can be used.

swf_ortho

(4.0.1 - 4.3.2 only)

swf_ortho --  Defines an orthographic mapping of user coordinates onto the current viewport

Description

void swf_ortho ( float xmin, float xmax, float ymin, float ymax, float zmin, float zmax)

The swf_ortho() function defines an orthographic mapping of user coordinates onto the current viewport.

swf_perspective

(PHP 4 <= 4.3.2)

swf_perspective --  Define a perspective projection transformation

Description

void swf_perspective ( float fovy, float aspect, float near, float far)

The swf_perspective() function defines a perspective projection transformation. The fovy parameter is field-of-view angle in the y direction. The aspect parameter should be set to the aspect ratio of the viewport that is being drawn onto. The near parameter is the near clipping plane and the far parameter is the far clipping plane.

Megjegyzés: Various distortion artifacts may appear when performing a perspective projection, this is because Flash players only have a two dimensional matrix. Some are not to pretty.

swf_placeobject

(PHP 4 <= 4.3.2)

swf_placeobject -- Place an object onto the screen

Description

void swf_placeobject ( int objid, int depth)

Places the object specified by objid in the current frame at a depth of depth. The objid parameter and the depth must be between 1 and 65535.

This uses the current mulcolor (specified by swf_mulcolor()) and the current addcolor (specified by swf_addcolor()) to color the object and it uses the current matrix to position the object.

Megjegyzés: Full RGBA colors are supported.

swf_polarview

(PHP 4 <= 4.3.2)

swf_polarview --  Define the viewer's position with polar coordinates

Description

void swf_polarview ( float dist, float azimuth, float incidence, float twist)

The swf_polarview() function defines the viewer's position in polar coordinates. The dist parameter gives the distance between the viewpoint to the world space origin. The azimuth parameter defines the azimuthal angle in the x,y coordinate plane, measured in distance from the y axis. The incidence parameter defines the angle of incidence in the y,z plane, measured in distance from the z axis. The incidence angle is defined as the angle of the viewport relative to the z axis. Finally the twist specifies the amount that the viewpoint is to be rotated about the line of sight using the right hand rule.

swf_popmatrix

(PHP 4 <= 4.3.2)

swf_popmatrix --  Restore a previous transformation matrix

Description

void swf_popmatrix ( void )

The swf_popmatrix() function pushes the current transformation matrix back onto the stack.

swf_posround

(PHP 4 <= 4.3.2)

swf_posround --  Enables or Disables the rounding of the translation when objects are placed or moved

Description

void swf_posround ( int round)

The swf_posround() function enables or disables the rounding of the translation when objects are placed or moved, there are times when text becomes more readable because rounding has been enabled. The round is whether to enable rounding or not, if set to the value of 1, then rounding is enabled, if set to 0 then rounding is disabled.

swf_pushmatrix

(PHP 4 <= 4.3.2)

swf_pushmatrix --  Push the current transformation matrix back unto the stack

Description

void swf_pushmatrix ( void )

The swf_pushmatrix() function pushes the current transformation matrix back onto the stack.

swf_removeobject

(PHP 4 <= 4.3.2)

swf_removeobject -- Remove an object

Description

void swf_removeobject ( int depth)

Removes the object at the depth specified by depth.

swf_rotate

(PHP 4 <= 4.3.2)

swf_rotate -- Rotate the current transformation

Description

void swf_rotate ( float angle, string axis)

The swf_rotate() rotates the current transformation by the angle given by the angle parameter around the axis given by the axis parameter. Valid values for the axis are 'x' (the x axis), 'y' (the y axis) or 'z' (the z axis).

swf_scale

(PHP 4 <= 4.3.2)

swf_scale -- Scale the current transformation

Description

void swf_scale ( float x, float y, float z)

The swf_scale() scales the x coordinate of the curve by the value of the x parameter, the y coordinate of the curve by the value of the y parameter, and the z coordinate of the curve by the value of the z parameter.

swf_setfont

(PHP 4 <= 4.3.2)

swf_setfont -- Change the current font

Description

void swf_setfont ( int fontid)

The swf_setfont() sets the current font to the value given by the fontid parameter.

swf_setframe

(PHP 4 <= 4.3.2)

swf_setframe -- Switch to a specified frame

Description

void swf_setframe ( int framenumber)

The swf_setframe() changes the active frame to the frame specified by framenumber.

swf_shapearc

(PHP 4 <= 4.3.2)

swf_shapearc -- Draw a circular arc

Description

void swf_shapearc ( float x, float y, float r, float ang1, float ang2)

The swf_shapearc() function draws a circular arc from angle A given by the ang1 parameter to angle B given by the ang2 parameter. The center of the circle has an x coordinate given by the x parameter and a y coordinate given by the y, the radius of the circle is given by the r parameter.

swf_shapecurveto3

(PHP 4 <= 4.3.2)

swf_shapecurveto3 -- Draw a cubic bezier curve

Description

void swf_shapecurveto3 ( float x1, float y1, float x2, float y2, float x3, float y3)

Draw a cubic bezier curve using the x,y coordinate pairs x1, y1 and x2,y2 as off curve control points and the x,y coordinate x3, y3 as an endpoint. The current position is then set to the x,y coordinate pair given by x3,y3.

swf_shapecurveto

(PHP 4 <= 4.3.2)

swf_shapecurveto --  Draw a quadratic bezier curve between two points

Description

void swf_shapecurveto ( float x1, float y1, float x2, float y2)

The swf_shapecurveto() function draws a quadratic bezier curve from the current location, though the x coordinate given by x1 and the y coordinate given by y1 to the x coordinate given by x2 and the y coordinate given by y2. The current position is then set to the x,y coordinates given by the x2 and y2 parameters

swf_shapefillbitmapclip

(PHP 4 <= 4.3.2)

swf_shapefillbitmapclip --  Set current fill mode to clipped bitmap

Description

void swf_shapefillbitmapclip ( int bitmapid)

Sets the fill to bitmap clipped, empty spaces will be filled by the bitmap given by the bitmapid parameter.

swf_shapefillbitmaptile

(PHP 4 <= 4.3.2)

swf_shapefillbitmaptile --  Set current fill mode to tiled bitmap

Description

void swf_shapefillbitmaptile ( int bitmapid)

Sets the fill to bitmap tile, empty spaces will be filled by the bitmap given by the bitmapid parameter (tiled).

swf_shapefilloff

(PHP 4 <= 4.3.2)

swf_shapefilloff -- Turns off filling

Description

void swf_shapefilloff ( void )

The swf_shapefilloff() function turns off filling for the current shape.

swf_shapefillsolid

(PHP 4 <= 4.3.2)

swf_shapefillsolid --  Set the current fill style to the specified color

Description

void swf_shapefillsolid ( float r, float g, float b, float a)

The swf_shapefillsolid() function sets the current fill style to solid, and then sets the fill color to the values of the rgba parameters.

swf_shapelinesolid

(PHP 4 <= 4.3.2)

swf_shapelinesolid -- Set the current line style

Description

void swf_shapelinesolid ( float r, float g, float b, float a, float width)

The swf_shapelinesolid() function sets the current line style to the color of the rgba parameters and width to the width parameter. If 0.0 is given as a width then no lines are drawn.

swf_shapelineto

(PHP 4 <= 4.3.2)

swf_shapelineto -- Draw a line

Description

void swf_shapelineto ( float x, float y)

The swf_shapelineto() draws a line to the x,y coordinates given by the x parameter & the y parameter. The current position is then set to the x,y parameters.

swf_shapemoveto

(PHP 4 <= 4.3.2)

swf_shapemoveto -- Move the current position

Description

void swf_shapemoveto ( float x, float y)

The swf_shapemoveto() function moves the current position to the x coordinate given by the x parameter and the y position given by the y parameter.

swf_showframe

(PHP 4 <= 4.3.2)

swf_showframe -- Display the current frame

Description

void swf_showframe ( void )

The swf_showframe function will output the current frame.

swf_startbutton

(PHP 4 <= 4.3.2)

swf_startbutton -- Start the definition of a button

Description

void swf_startbutton ( int objid, int type)

The swf_startbutton() function starts off the definition of a button. The type parameter can either be TYPE_MENUBUTTON or TYPE_PUSHBUTTON. The TYPE_MENUBUTTON constant allows the focus to travel from the button when the mouse is down, TYPE_PUSHBUTTON does not allow the focus to travel when the mouse is down.

swf_startdoaction

(PHP 4 <= 4.3.2)

swf_startdoaction --  Start a description of an action list for the current frame

Description

void swf_startdoaction ( void )

The swf_startdoaction() function starts the description of an action list for the current frame. This must be called before actions are defined for the current frame.

swf_startshape

(PHP 4 <= 4.3.2)

swf_startshape -- Start a complex shape

Description

void swf_startshape ( int objid)

The swf_startshape() function starts a complex shape, with an object id given by the objid parameter.

swf_startsymbol

(PHP 4 <= 4.3.2)

swf_startsymbol -- Define a symbol

Description

void swf_startsymbol ( int objid)

Define an object id as a symbol. Symbols are tiny flash movies that can be played simultaneously. The objid parameter is the object id you want to define as a symbol.

swf_textwidth

(PHP 4 <= 4.3.2)

swf_textwidth -- Get the width of a string

Description

float swf_textwidth ( string str)

The swf_textwidth() function gives the width of the string, str, in pixels, using the current font and font size.

swf_translate

(PHP 4 <= 4.3.2)

swf_translate -- Translate the current transformations

Description

void swf_translate ( float x, float y, float z)

The swf_translate() function translates the current transformation by the x, y, and z values given.

swf_viewport

(PHP 4 <= 4.3.2)

swf_viewport -- Select an area for future drawing

Description

void swf_viewport ( float xmin, float xmax, float ymin, float ymax)

The swf_viewport() function selects an area for future drawing for xmin to xmax and ymin to ymax, if this function is not called the area defaults to the size of the screen.

CI. SNMP functions

Bevezetés


Követelmények

In order to use the SNMP functions on Unix you need to install the UCD SNMP or NET-SNMP package. On Windows these functions are only available on NT and not on Win95/98.


Telepítés

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

The Windows distribution contains support files for SNMP in the mibs directory. This directory should be moved to DRIVE:\usr\mibs, where DRIVE must be replaced with the driveletter where PHP is installed on, e.g.: c:\usr\mibs.


Futásidejű beállítások

Ez a kiterjesztés semmilyen konfigurációs beállításokat nem definiál a php.ini állományban.


Erőforrás típusok


Előre definiált állandók

Ez a kiterjesztés semmilyen konstans értéket nem definiál.

Tartalom
snmp_get_quick_print --  Fetches the current value of the UCD library's quick_print setting
snmp_set_quick_print -- Set the value of quick_print within the UCD SNMP library
snmpget -- Fetch an SNMP object
snmprealwalk --  Return all objects including their respective object ID within the specified one
snmpset -- Set 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

(PHP 3>= 3.0.8, PHP 4 )

snmp_get_quick_print --  Fetches the current value of the UCD library's quick_print setting

Description

bool snmp_get_quick_print ( void )

Returns the current value stored in the UCD Library for quick_print. quick_print is off by default.

Példa 1. snmp_get_quick_print() example

<?php
  $quickprint = snmp_get_quick_print();
?>

Above function call would return FALSE if quick_print is off, and TRUE if quick_print is on.

snmp_get_quick_print() is only available when using the UCD SNMP library. This function is not available when using the Windows SNMP library.

See also snmp_set_quick_print() for a full description of what quick_print does.

snmp_set_quick_print

(PHP 3>= 3.0.8, PHP 4 )

snmp_set_quick_print -- Set the value of quick_print within the UCD SNMP library

Description

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

Setting quick_print is often used when using the information returned rather then displaying it.

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

The first value printed might be: 'Timeticks: (0) 0:00:00.00', whereas with quick_print enabled, just '0:00:00.00' would be printed.

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.

snmp_set_quick_print() is only available when using the UCD SNMP library. This function is not available when using the Windows SNMP library.

snmpget

(PHP 3, PHP 4 )

snmpget -- Fetch an SNMP object

Description

string snmpget ( string hostname, string community, string object_id [, int timeout [, int retries]])

Returns SNMP object value on success and FALSE on error.

The snmpget() function is used to read the value of an SNMP object specified by the object_id. SNMP agent is specified by the hostname and the read community is specified by the community parameter.

<?php
$syscontact = snmpget("127.0.0.1", "public", "system.SysContact.0");
?>

snmprealwalk

(PHP 3>= 3.0.8, PHP 4 )

snmprealwalk --  Return all objects including their respective object ID within the specified one

Description

array snmprealwalk ( string host, string community, string object_id [, int timeout [, int retries]])

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

snmpset

(PHP 3>= 3.0.12, PHP 4 )

snmpset -- Set an SNMP object

Description

bool snmpset ( string hostname, string community, string object_id, string type, mixed value [, int timeout [, int retries]])

Sets the specified SNMP object value, returning TRUE on success and FALSE on error.

The snmpset() function is used to set the value of an SNMP object specified by the object_id. SNMP agent is specified by the hostname and the read community is specified by the community parameter.

snmpwalk

(PHP 3, PHP 4 )

snmpwalk -- Fetch all the SNMP objects from an agent

Description

array snmpwalk ( string hostname, string community, string object_id [, int timeout [, int retries]])

Returns an array of SNMP object values starting from the object_id as root and FALSE on error.

snmpwalk() function is used to read all the values from an SNMP agent specified by the hostname. Community specifies the read community for that agent. A 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.

<?php
$a = snmpwalk("127.0.0.1", "public", ""); 
?>

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

<?php
for ($i=0; $i < count($a); $i++) {
    echo $a[$i];
}
?>

snmpwalkoid

(PHP 3>= 3.0.8, PHP 4 )

snmpwalkoid -- Query for a tree of information about a network entity

Description

array snmpwalkoid ( string hostname, string community, string object_id [, int timeout [, int retries]])

Returns an associative array with object ids and their respective object value starting from the object_id as root and FALSE on error.

snmpwalkoid() function is used to read all object ids and their respective values from an SNMP agent specified by the hostname. Community specifies the read community for that agent. A 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.

The existence of snmpwalkoid() and snmpwalk() has historical reasons. Both functions are provided for backward compatibility.

<?php
$a = snmpwalkoid("127.0.0.1", "public", ""); 
?>

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

<?php
for (reset($a); $i = key($a); next($a)) {
    echo "$i: $a[$i]<br />\n";
}
?>

CII. Socket functions

Bevezetés

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.

Figyelem

Ez a kiterjesztés KÍSÉRLETI JELLEGGEL MŰKÖDIK. Ez azt jelenti, hogy minden itt dokumentált működés, beleértve a függvények nevét, működését vagy bármi más, amit a kiterjesztés kapcsán leírtunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a kiterjesztést csak a saját felelősségedre használd!


Követelmények

Az itt leírt függvények használatához semmilyen külső függvénykönyvtár megléte nem szükségeltetik.


Telepítés

The socket functions described here are part of an extension to PHP which must be enabled at compile time by giving the --enable-sockets option to configure.

Megjegyzés: IPv6 Support was added with PHP 5.0.0 .


Futásidejű beállítások

Ez a kiterjesztés semmilyen konfigurációs beállításokat nem definiál a php.ini állományban.


Erőforrás típusok

Ez a kiterjesztés semmilyen erőforrás típust nem definiál.


Előre definiált állandók

Az itt listázott állandókat ez a kiterjesztés definiálja, és csak akkor elérhetőek, ha az adott kiterjesztés be van fordítva a PHP-be, vagy dinamikusan betöltött.

AF_UNIX (integer)

AF_INET (integer)

AF_INET6 (integer)

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)

SO_DEBUG (integer)

SO_REUSEADDR (integer)

SO_KEEPALIVE (integer)

SO_DONTROUTE (integer)

SO_LINGER (integer)

SO_BROADCAST (integer)

SO_OOBINLINE (integer)

SO_SNDBUF (integer)

SO_RCVBUF (integer)

SO_SNDLOWAT (integer)

SO_RCVLOWAT (integer)

SO_SNDTIMEO (integer)

SO_RCVTIMEO (integer)

SO_TYPE (integer)

SO_ERROR (integer)

SOL_SOCKET (integer)

PHP_NORMAL_READ (integer)

PHP_BINARY_READ (integer)

SOL_TCP (integer)

SOL_UDP (integer)


Socket Errors

The socket extension was written to provide a useable 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.

Megjegyzés: 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


Példák

Példa 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)) < 0) {
    echo "socket_create() failed: reason: " . socket_strerror($sock) . "\n";
}

if (($ret = socket_bind($sock, $address, $port)) < 0) {
    echo "socket_bind() failed: reason: " . socket_strerror($ret) . "\n";
}

if (($ret = socket_listen($sock, 5)) < 0) {
    echo "socket_listen() failed: reason: " . socket_strerror($ret) . "\n";
}

do {
    if (($msgsock = socket_accept($sock)) < 0) {
        echo "socket_accept() failed: reason: " . socket_strerror($msgsock) . "\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($ret) . "\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);
?>

Példa 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 < 0) {
    echo "socket_create() failed: reason: " . socket_strerror($socket) . "\n";
} else {
    echo "OK.\n";
}

echo "Attempting to connect to '$address' on port '$service_port'...";
$result = socket_connect($socket, $address, $service_port);
if ($result < 0) {
    echo "socket_connect() failed.\nReason: ($result) " . socket_strerror($result) . "\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";
?>

Tartalom
socket_accept -- Accepts a connection on a socket
socket_bind -- Binds a name to a socket
socket_clear_error -- Clears the error on the socket or the last error code
socket_close -- Closes a socket resource
socket_connect -- Initiates a connection on a socket
socket_create_listen -- Opens a socket on port to accept connections
socket_create_pair -- Creates a pair of indistinguishable sockets and stores them in fds.
socket_create -- Create a socket (endpoint for communication)
socket_get_option -- Gets socket options for the socket
socket_getpeername --  Queries the remote side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type.
socket_getsockname --  Queries the local side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type.
socket_iovec_add -- Adds a new vector to the scatter/gather array
socket_iovec_alloc --  Builds a 'struct iovec' for use with sendmsg, recvmsg, writev, and readv
socket_iovec_delete -- Deletes a vector from an array of vectors
socket_iovec_fetch -- Returns the data held in the iovec specified by iovec_id[iovec_position]
socket_iovec_free -- Frees the iovec specified by iovec_id
socket_iovec_set -- Sets the data held in iovec_id[iovec_position] to new_val
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_readv -- Reads from an fd, using the scatter-gather array defined by iovec_id
socket_recv -- Receives data from a connected socket
socket_recvfrom -- Receives data from a socket, connected or not
socket_recvmsg -- Used to receive messages on a socket, whether connection-oriented or not
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 -- Sends a message to a socket, regardless of whether it is connection-oriented or not
socket_sendto -- Sends a message to a socket, whether it is connected or not
socket_set_block --  Sets blocking mode on a socket resource
socket_set_nonblock -- Sets nonblocking mode for file descriptor fd
socket_set_option -- Sets socket options for the socket
socket_shutdown -- Shuts down a socket for receiving, sending, or both.
socket_strerror -- Return a string describing a socket error
socket_write -- Write to a socket
socket_writev -- Writes to a file descriptor, fd, using the scatter-gather array defined by iovec_id

socket_accept

(PHP 4 >= 4.1.0)

socket_accept -- Accepts a connection on a socket

Description

resource socket_accept ( resource socket)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

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.

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.

See also socket_bind(), socket_connect(), socket_listen(), socket_create(), and socket_strerror().

socket_bind

(PHP 4 >= 4.1.0)

socket_bind -- Binds a name to a socket

Description

bool socket_bind ( resource socket, string address [, int port])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

socket_bind() binds the name given in address to the socket described by socket, which must be a valid socket resource created with socket_create().

The address parameter is either an IP address in dotted-quad notation (e.g. 127.0.0.1), if the socket is of the AF_INET family; or the pathname of a Unix-domain socket, if the socket family is AF_UNIX.

The port parameter is only used when connecting to an AF_INET socket, and designates the port on the remote host to which a connection should be made.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad. 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 that socket_last_error() is reported to return an invalid error code in case you are trying to bind the socket to a wrong address that does not belong to your Windows 9x/ME machine.

See also socket_connect(), socket_listen(), socket_create(), socket_last_error() and socket_strerror().

socket_clear_error

(PHP 4 >= 4.2.0)

socket_clear_error -- Clears the error on the socket or the last error code

Description

void socket_clear_error ( [resource socket])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

This function clears the error code on the given socket or the global last socket error.

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.

See also socket_last_error() and socket_strerror().

socket_close

(PHP 4 >= 4.1.0)

socket_close -- Closes a socket resource

Description

void socket_close ( resource socket)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

socket_close() closes the socket resource given by socket.

Megjegyzés: socket_close() can't be used on PHP file resources created with fopen(), popen(), fsockopen(), or pfsockopen(); it is meant for sockets created with socket_create() or socket_accept().

See also socket_bind(), socket_listen(), socket_create() and socket_strerror().

socket_connect

(PHP 4 >= 4.1.0)

socket_connect -- Initiates a connection on a socket

Description

bool socket_connect ( resource socket, string address [, int port])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Initiates a connection using the socket resource socket, which must be a valid socket resource created with socket_create().

The address parameter is either an IP address in dotted-quad notation (e.g. 127.0.0.1), if the socket is of the AF_INET family; or the pathname of a Unix domain socket, if the socket family is AF_UNIX.

The port parameter is only used when connecting to an AF_INET socket, and designates the port on the remote host to which a connection should be made.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad. 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.

See also socket_bind(), socket_listen(), socket_create(), socket_last_error() and socket_strerror().

socket_create_listen

(PHP 4 >= 4.1.0)

socket_create_listen -- Opens a socket on port to accept connections

Description

resource socket_create_listen ( int port [, int backlog])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

This function is meant to ease the task of creating a new socket which only listens to accept new connections.

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.

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.

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.

Megjegyzés: 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().

See also socket_create(), socket_bind(), socket_listen(), socket_last_error() and socket_strerror().

socket_create_pair

(PHP 4 >= 4.1.0)

socket_create_pair -- Creates a pair of indistinguishable sockets and stores them in fds.

Description

bool socket_create_pair ( int domain, int type, int protocol, array &fd)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

socket_create_pair() creates two connected and indistinguishable sockets, and stores them in &fd. This function is commonly used in IPC (InterProcess Communication).

The domain parameter specifies the protocol family to be used by the socket.

Táblázat 1. Available address/protocol families

DomainDescription
AF_INET IPv4 Internet based protocols. TCP and UDP are common protocols of this protocol family. Supported only in windows.
AF_INET6 IPv6 Internet based protocols. TCP and UDP are common protocols of this protocol family. Support added in PHP 5.0.0. Supported only in windows.
AF_UNIX Local communication protocol family. High efficiency and low overhead make it a great form of IPC (Interprocess Communication).

The type parameter selects the type of communication to be used by the socket.

Táblázat 2. Available socket types

TypeDescription
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, traceroute, etc).
SOCK_RDM Provides a reliable datagram layer that does not guarantee ordering. This is most likely not implemented on your operating system.

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.

Táblázat 3. Common protocols

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

Példa 1. socket_create_pair() example

<?php
$sockets = array();
$uniqid = uniqid("");
if (file_exists("/tmp/$uniqid.sock"))
	die('Temporary socket already exists.');

/* Setup socket pair */
if(!socket_create_pair(AF_UNIX, SOCK_STREAM, 0, $sockets))
    echo socket_strerror(socket_last_error());

/* Send and Recieve Data */
if(!socket_write($sockets[0], "ABCdef123\n", strlen("ABCdef123\n")))
    echo socket_strerror(socket_last_error());

if(!$data = socket_read($sockets[1], strlen("ABCdef123\n"), PHP_BINARY_READ))
    echo socket_strerror(socket_last_error());

var_dump($data);

/* Close sockets */
socket_close($sockets[0]);
socket_close($sockets[1]);
?>

Példa 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))
    echo 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))
    	echo socket_strerror(socket_last_error());
	if(socket_read($ary[1], strlen($strtwo), PHP_BINARY_READ) == $strtwo)
        echo 'Recieved ', $strtwo;
} else {
    /*child*/
    socket_close($ary[1]);
    if(!socket_write($ary[0], $strtwo, strlen($strtwo))
        echo socket_strerror(socket_last_error());
    if(socket_read($ary[0], strlen($strone), PHP_BINARY_READ) == $strone)
        echo 'Recieved ', $strone;
}
?>

socket_create

(PHP 4 >= 4.1.0)

socket_create -- Create a socket (endpoint for communication)

Description

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.

The domain parameter specifies the protocol family to be used by the socket.

Táblázat 1. Available address/protocol families

DomainDescription
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. Support added in PHP 5.0.0.
AF_UNIX Local communication protocol family. High efficiency and low overhead make it a great form of IPC (Interprocess Communication).

The type parameter selects the type of communication to be used by the socket.

Táblázat 2. Available socket types

TypeDescription
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, traceroute, etc).
SOCK_RDM Provides a reliable datagram layer that does not guarantee ordering. This is most likely not implemented on your operating system.

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.

Táblázat 3. Common protocols

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

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.

Megjegyzés: 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.

See also socket_accept(), socket_bind(), socket_connect(), socket_listen(), socket_last_error(), and socket_strerror().

socket_get_option

(PHP 4 >= 4.3.0)

socket_get_option -- Gets socket options for the socket

Description

mixed socket_get_option ( resource socket, int level, int optname)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

The socket_get_option() function retrieves the value for the option specified by the optname parameter for the socket specified by the socket parameter. socket_get_option() will return FALSE on failure.

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.

Táblázat 1. Available Socket Options

OptionDescription
SO_DEBUG Reports whether debugging information is being recorded.
SO_ACCEPTCONN Reports whether socket listening is enabled.
SO_BROADCAST Reports whether transmission of broadcast messages is supported.
SO_REUSEADDR Reports whether local addresses can be reused.
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.
SO_LINGER Reports whether the socket lingers on socket_close() if data is present.
SO_OOBINLINE Reports whether the socket leaves out-of-band data inline.
SO_SNDBUF Reports send buffer size information.
SO_RCVBUF Reports recieve buffer size information.
SO_ERROR Reports information about error status and clears it.
SO_TYPE Reports the socket type.
SO_DONTROUTE Reports whether outgoing messages bypass the standard routing facilities.
SO_RCVLOWAT Reports the minimum number of bytes to process for socket input operations. ( Defaults to 1 )
SO_RCVTIMEO Reports the timeout value for input operations.
SO_SNDLOWAT Reports the minimum number of bytes to process for socket output operations.
SO_SNDTIMEO Reports the timeout value specifying the amount of time that an output function blocks because flow control prevents data from being sent.

Megjegyzés: This function used to be called socket_getopt() prior to PHP 4.3.0

socket_getpeername

(PHP 4 >= 4.1.0)

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.

Description

bool socket_getpeername ( resource socket, string &addr [, int &port])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

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.

Megjegyzés: 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.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad. 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.

See also socket_getsockname(), socket_last_error() and socket_strerror().

socket_getsockname

(PHP 4 >= 4.1.0)

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.

Description

bool socket_getsockname ( resource socket, string &addr [, int &port])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

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.

Megjegyzés: 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.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad. 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.

See also socket_getpeername(), socket_last_error() and socket_strerror().

socket_iovec_add

(PHP 4 >= 4.1.0)

socket_iovec_add -- Adds a new vector to the scatter/gather array

Description

bool socket_iovec_add ( resource iovec, int iov_len)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

socket_iovec_alloc

(PHP 4 >= 4.1.0)

socket_iovec_alloc --  Builds a 'struct iovec' for use with sendmsg, recvmsg, writev, and readv

Description

resource socket_iovec_alloc ( int num_vectors [, int ])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

socket_iovec_delete

(PHP 4 >= 4.1.0)

socket_iovec_delete -- Deletes a vector from an array of vectors

Description

bool socket_iovec_delete ( resource iovec, int iov_pos)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

socket_iovec_fetch

(PHP 4 >= 4.1.0)

socket_iovec_fetch -- Returns the data held in the iovec specified by iovec_id[iovec_position]

Description

string socket_iovec_fetch ( resource iovec, int iovec_position)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

socket_iovec_free

(PHP 4 >= 4.1.0)

socket_iovec_free -- Frees the iovec specified by iovec_id

Description

bool socket_iovec_free ( resource iovec)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

socket_iovec_set

(PHP 4 >= 4.1.0)

socket_iovec_set -- Sets the data held in iovec_id[iovec_position] to new_val

Description

bool socket_iovec_set ( resource iovec, int iovec_position, string new_val)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

socket_last_error

(PHP 4 >= 4.1.0)

socket_last_error -- Returns the last error on the socket

Description

int socket_last_error ( [resource socket])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

This function returns a socket error code.

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 in particular 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.
<?php
if (false == ($socket = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP))) {
    die("Couldn't create socket, error code is: " . socket_last_error() .
        ",error message is: " . socket_strerror(socket_last_error()));
}
?>

Megjegyzés: socket_last_error() does not clear the error code, use socket_clear_error() for this purpose.

socket_listen

(PHP 4 >= 4.1.0)

socket_listen -- Listens for a connection on a socket

Description

bool socket_listen ( resource socket [, int backlog])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

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.

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.

Megjegyzés: 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.

socket_listen() is applicable only to sockets of type SOCK_STREAM or SOCK_SEQPACKET.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad. 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.

See also socket_accept(), socket_bind(), socket_connect(), socket_create() and socket_strerror().

socket_read

(PHP 4 >= 4.1.0)

socket_read -- Reads a maximum of length bytes from a socket

Description

string socket_read ( resource socket, int length [, int type])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

The function socket_read() reads from the socket resource socket created by the socket_create() or socket_accept() functions. 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).

socket_read() returns the data as a string 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 representation of the error.

Megjegyzés: socket_read() may return a zero length string ("") indicating the end of communication (i.e. the remote end point has closed the connection).

Optional type parameter is a named constant:

  • PHP_BINARY_READ - use the system read() function. Safe for reading binary data. (Default in PHP >= 4.1.0)

  • PHP_NORMAL_READ - reading stops at \n or \r. (Default in PHP <= 4.0.6)

See also socket_accept(), socket_bind(), socket_connect(), socket_listen(), socket_last_error(), socket_strerror() and socket_write().

socket_readv

(PHP 4 >= 4.1.0)

socket_readv -- Reads from an fd, using the scatter-gather array defined by iovec_id

Description

bool socket_readv ( resource socket, resource iovec_id)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

socket_recv

(PHP 4 >= 4.1.0)

socket_recv -- Receives data from a connected socket

Description

int socket_recv ( resource socket, string &buf, int len, int flags)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

socket_recvfrom

(PHP 4 >= 4.1.0)

socket_recvfrom -- Receives data from a socket, connected or not

Description

int socket_recvfrom ( resource socket, string &buf, int len, int flags, string &name [, int &port])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

socket_recvmsg

(PHP 4 >= 4.1.0)

socket_recvmsg -- Used to receive messages on a socket, whether connection-oriented or not

Description

bool socket_recvmsg ( resource socket, resource iovec, array &control, int &controllen, int &flags, string &addr [, int &port])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

socket_select

(PHP 4 >= 4.1.0)

socket_select --  Runs the select() system call on the given arrays of sockets with a specified timeout

Description

int socket_select ( array &read, array &write, array &except, int tv_sec [, int tv_usec])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

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.

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

The sockets listed in the write array will be watched to see if a write will not block.

The sockets listed in the except array will be watched for exceptions.

Figyelem

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.

Példa 1. socket_select() example

<?php
/* Prepare the read array */
$read = array($socket1, $socket2);

$num_changed_sockets = socket_select($read, $write = NULL, $except = NULL, 0);

if ($num_changed_sockets === false) {
    /* Error handling */
} else if ($num_changed_sockets > 0) {
    /* At least at one of the sockets something interesting happened */
}
?>

Megjegyzés: 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:

Példa 2. Using NULL with socket_select()

<?php
socket_select($r, $w, $e = NULL, 0);
?>

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.

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

Megjegyzés: 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:

Példa 3. Understanding socket_select()'s result

<?php
if (false === socket_select($r, $w, $e = NULL, 0)) {
    echo "socket_select() failed, reason: " .
        socket_strerror(socket_last_error()) . "\n";
}
?>

Megjegyzés: 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.

See also socket_read(), socket_write(), socket_last_error() and socket_strerror().

socket_send

(PHP 4 >= 4.1.0)

socket_send -- Sends data to a connected socket

Description

int socket_send ( resource socket, string buf, int len, int flags)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

The function socket_send() sends len bytes to the socket socket from buf

The value of flags can be any ORed combination of the following:

Táblázat 1. possible values for flags

0x1 Process OOB (out-of-band) data
0x2 Peek at incoming message
0x4 Bypass routing, use direct interface
0x8 Data completes record
0x100 Data completes transaction

See also socket_sendmsg() and socket_sendto().

socket_sendmsg

(PHP 4 >= 4.1.0)

socket_sendmsg -- Sends a message to a socket, regardless of whether it is connection-oriented or not

Description

bool socket_sendmsg ( resource socket, resource iovec, int flags, string addr [, int port])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

socket_sendto

(PHP 4 >= 4.1.0)

socket_sendto -- Sends a message to a socket, whether it is connected or not

Description

int socket_sendto ( resource socket, string buf, int len, int flags, string addr [, int port])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

The function socket_sendto() sends len bytes from buf through the socket socket to the port at the address addr

The value of flags can be one of the following:

Táblázat 1. possible values for flags

0x1 Process OOB (out-of-band) data.
0x2 Peek at incoming message.
0x4 Bypass routing, use direct interface.
0x8 Data completes record.
0x100 Data completes transaction.

Példa 1. socket_sendto() Example

<?php
    $sh = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    if (socket_bind($sh, '127.0.0.1', 4242)) {
        echo "Socket bound correctly";
    }
    $buf = 'Test Message';
    $len = strlen($buf);
    if (socket_sendto($sh, $buf, $len, 0x100, '192.168.0.2', 4242) !== false) {
        echo "Message sent correctly";
    }
    socket_close($sh);
?>

See also socket_send() and socket_sendmsg().

socket_set_block

(PHP 4 >= 4.2.0)

socket_set_block --  Sets blocking mode on a socket resource

Description

bool socket_set_block ( resource socket)

The socket_set_block() function removes the O_NONBLOCK flag on the socket specified by the socket parameter.

Példa 1. socket_set_block() example

<?php

$port = 9090;
if (!$socket = socket_create_listen($port)) {
    echo socket_strerror(socket_last_error());
}

if (!socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1)) {
    echo socket_strerror(socket_last_error());
}

if (!socket_set_nonblock($socket)) { // $socket is now nonblocking
    echo socket_strerror(socket_last_error());
}

if(!socket_set_block($socket)) {     // $socket is now blocking
    echo socket_strerror(socket_last_error());
}

?>

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

See also socket_set_nonblock() and socket_set_option()

socket_set_nonblock

(PHP 4 >= 4.1.0)

socket_set_nonblock -- Sets nonblocking mode for file descriptor fd

Description

bool socket_set_nonblock ( resource socket)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

The socket_set_nonblock() function sets the O_NONBLOCK flag on the socket specified by the socket parameter.

Példa 1. socket_set_nonblock() example

<?php
$port = 9090;
if (!$socket = socket_create_listen($port)) {
    echo socket_strerror(socket_last_error());
}

if (!socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1)) {
    echo socket_strerror(socket_last_error());
}

if (!socket_set_nonblock($socket)) {
    echo socket_strerror(socket_last_error());
}
?>

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

See also socket_set_block() and socket_set_option()

socket_set_option

(PHP 4 >= 4.3.0)

socket_set_option -- Sets socket options for the socket

Description

bool socket_set_option ( resource socket, int level, int optname, mixed optval)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

The socket_set_option() function sets the option specified by the optname parameter, at the protocol level specified by the level parameter, to the value pointed to by the optval parameter for the socket specified by the socket parameter. socket_set_option() will return FALSE on failure.

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.

The available socket options are the same as those for the socket_get_option() function.

Megjegyzés: This function used to be called socket_setopt() prior to PHP 4.3.0

socket_shutdown

(PHP 4 >= 4.1.0)

socket_shutdown -- Shuts down a socket for receiving, sending, or both.

Description

bool socket_shutdown ( resource socket [, int how])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

The socket_shutdown() function allows you to stop incoming, outgoing or all data (the default) from being sent through the socket

The value of how can be one of the following:

Táblázat 1. possible values for how

0 Shutdown socket reading
1 Shutdown socket writing
2 Shutdown socket reading and writing

socket_strerror

(PHP 4 >= 4.1.0)

socket_strerror -- Return a string describing a socket error

Description

string socket_strerror ( int errno)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

socket_strerror() takes as its errno parameter a socket error code as returned by socket_last_error() and returns the corresponding explanatory text. This makes it a bit more pleasant to figure out why something didn't work; for instance, instead of having to track down a system include file to find out what '-111' means, you just pass it to socket_strerror(), and it tells you what happened.

Példa 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

See also socket_accept(), socket_bind(), socket_connect(), socket_listen(), and socket_create().

socket_write

(PHP 4 >= 4.1.0)

socket_write -- Write to a socket

Description

int socket_write ( resource socket, string buffer [, int length])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

The function socket_write() writes to the socket socket from buffer.

The optional parameter length can specify an alternate length of bytes written to the socket. If this length is greater then the buffer length, it is silently truncated to the length of the buffer.

Returns the number of bytes successfully written to the socket or FALSE one 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.

Megjegyzés: 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.

Megjegyzés: 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.

See also socket_accept(), socket_bind(), socket_connect(), socket_listen(), socket_read() and socket_strerror().

socket_writev

(PHP 4 >= 4.1.0)

socket_writev -- Writes to a file descriptor, fd, using the scatter-gather array defined by iovec_id

Description

bool socket_writev ( resource socket, resource iovec_id)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

CIII. Stream functions

Bevezetés

Streams were introduced with PHP 4.3.0 as a way of generalizing file, network, data compression, and other operations which share a common set of functions and uses. In its simplest definition, a stream is a resource object which exhibits streamable behavior. That is, it can be read from or written to in a linear fashion, and may be able to fseek() to an arbitrary locations within the stream.

A wrapper is additional code which tells the stream how to handle specific protocols/encodings. For example, the http wrapper knows how to translate a URL into an HTTP/1.0 request for a file on a remote server. There are many wrappers built into PHP by default (See J Függelék), 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 43 fejezet. 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 J Függelék for a list of PHP builtin 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 J Függelék for a description of targets for builtin 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 43 fejezet. To access the list of currently registered filters, use stream_get_filters().


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 with the list of built-in wrappers (See J Függelék).

In addition, parameters may be set on a context using stream_context_set_params(). Currently the only context parameter supported by PHP is notification. The value of this parameter must be the name of a function to be called when an event occurs on a stream. The notification function called during an event should accept the following six parameters:

void my_notifier ( int notification_code, int severity, string message, int message_code, int bytes_transferred, int bytes_max)

notification_code and severity are numerical values which correspond to the STREAM_NOTIFY_* constants listed below. If a descriptive message is available from the stream, message and message_code will be populated with the appropriate values. The meaning of these values is dependent on the specific wrapper in use. bytes_transferred and bytes_max will be populated when applicable.


Telepítés

Streams are an integral part of PHP as of version 4.3.0. No steps are required to enable them.


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.


Előre definiált állandók

Az itt listázott állandókat ez a kiterjesztés definiálja, és csak akkor elérhetőek, ha az adott kiterjesztés be van fordítva a PHP-be, vagy dinamikusan betöltött.

ConstantDescription
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_ONReturn Code indicating that the userspace filter returned buckets in $out.
PSFS_FEED_MEReturn Code indicating that the userspace filter did not return buckets in $out (i.e. No data available).
PSFS_ERR_FATALReturn Code indicating that the userspace filter encountered an unrecoverable error (i.e. Invalid data received).
STREAM_USE_PATHFlag indicating if the stream used the include path.
STREAM_REPORT_ERRORSFlag 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_CONNECTOpen client socket asynchronously. Used with stream_socket_client().
STREAM_CLIENT_PERSISTENTClient socket opened with stream_socket_client() should remain persistent between page loads.
STREAM_SERVER_BINDTells a stream created with stream_socket_server() to bind to the specified target. Server sockets should always include this flag.
STREAM_SERVER_LISTENTells a stream created with stream_socket_server() and bound using the STREAM_SERVER_BIND flag to start listening on the socket. Server sockets should always include this flag.
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 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.


Példák

Példa 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");
?>

Példa 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");

fputs($sock, "POST /form_action.php HTTP/1.0\r\n");
fputs($sock, "Host: secure.example.com\r\n");
fputs($sock, "Content-type: application/x-www-form-urlencoded\r\n");
fputs($sock, "Content-length: " . strlen($data) . "\r\n");
fputs($sock, "Accept: */*\r\n");
fputs($sock, "\r\n");
fputs($sock, "$data\r\n");
fputs($sock, "\r\n");

$headers = "";
while ($str = trim(fgets($sock, 4096)))
  $headers .= "$str\n";

echo "\n";

$body = "";
while (!feof($sock))
  $body .= fgets($sock, 4096);

fclose($sock);
?>

Példa 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);
?>

Tartalom
stream_context_create -- Create a streams context
stream_context_get_options -- Retrieve options for a stream/wrapper/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_filter_append -- Attach a filter to a stream.
stream_filter_prepend -- Attach a filter to a stream.
stream_filter_register --  Register a stream filter implemented as a PHP class derived from php_user_filter
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_register_wrapper -- Alias of stream_wrapper_register()
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_timeout -- Set timeout period on a stream
stream_set_write_buffer -- Sets 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_get_name -- Retrieve the name of the local or remote sockets
stream_socket_recvfrom -- Receives data from a socket, connected or not
stream_socket_sendto -- Sends a message to a socket, whether it is connected or not
stream_socket_server --  Create an Internet or Unix domain server socket
stream_wrapper_register -- Register a URL wrapper implemented as a PHP class

stream_context_create

(PHP 4 >= 4.3.0)

stream_context_create -- Create a streams context

Description

resource stream_context_create ( array options)

Creates and returns a stream context with any options supplied in options preset.

options must be an associative array of associative arrays in the format $arr['wrapper']['option'] = $value.

Példa 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);
?>

See Also: stream_context_set_option(), and Listing of supported wrappers with context options (J Függelék)

stream_context_get_options

(PHP 4 >= 4.3.0)

stream_context_get_options -- Retrieve options for a stream/wrapper/context

Description

array stream_context_get_options ( resource stream|context)

Returns an array of options on the specified stream or context.

stream_context_set_option

(PHP 4 >= 4.3.0)

stream_context_set_option -- Sets an option for a stream/wrapper/context

Description

bool stream_context_set_option ( resource context|stream, string wrapper, string option, mixed value)

Sets an option on the specified context. value is set to option for wrapper

stream_context_set_params

(PHP 4 >= 4.3.0)

stream_context_set_params -- Set parameters for a stream/wrapper/context

Description

bool stream_context_set_params ( resource stream|context, array params)

params should be an associative array of the structure: $params['paramname'] = "paramvalue";.

Táblázat 1. Parameters

ParametersPurpose
notification Name of user-defined callback function to be called whenever a stream triggers a notification.

stream_copy_to_stream

(PHP 5 CVS only)

stream_copy_to_stream -- Copies data from one stream to another

Description

int stream_copy_to_stream ( resource source, resource dest [, int maxlength])

Makes a copy of up to maxlength bytes of data from the current position in source to dest. If maxlength is not specified, all remaining content in source will be copied. Returns the total count of bytes copied.

Példa 1. 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";

?>

See also copy().

stream_filter_append

(PHP 4 >= 4.3.0)

stream_filter_append -- Attach a filter to a stream.

Description

bool stream_filter_append ( resource stream, string filtername [, int read_write [, mixed params]])

Adds filtername to the list of filters attached to stream. 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().

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.

Példa 1. Controlling where filters are applied

<?php
/* Open a test file for reading and writing */
$fp = fopen("test.txt", "rw");

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

 */
?>

When using custom (user) filters: stream_filter_register() must be called first in order to register the desired user filter to filtername.

See also stream_filter_register(), and stream_filter_prepend()

stream_filter_prepend

(PHP 4 >= 4.3.0)

stream_filter_prepend -- Attach a filter to a stream.

Description

bool stream_filter_prepend ( resource stream, string filtername [, int read_write [, mixed params]])

Adds filtername to the list of filters attached to stream. 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().

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.

When using custom (user) filters: stream_filter_register() must be called first in order to register the desired user filter to filtername.

See also stream_filter_register(), and stream_filter_append()

stream_filter_register

(PHP 5 CVS only)

stream_filter_register --  Register a stream filter implemented as a PHP class derived from php_user_filter

Description

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

To implement a filter, you need to define a class as an extension of php_user_filter with a number of member functions as defined below. When performing read/write operations on the stream to which your filter is attached, PHP will pass the data through your filter (and any other filters attached to that stream) so that the data may be modified as desired. You must implement the methods exactly as described below - doing otherwise will lead to undefined behaviour.

stream_filter_register() will return FALSE if the filtername is already defined.

int filter ( resource in, resource out, int &consumed, bool closing)

This method is called whenever data is read from or written to the attached stream (such as with fread() or fwrite()). in is a resource pointing to a bucket brigade which contains one or more bucket objects containing data to be filtered. out is a resource pointing to a second bucket brigade into which your modified buckets should be placed. consumed, which must always be declared by reference, should be incremented by the length of the data which your filter reads in and alters. In most cases this means you will increment consumed by $bucket->datalen for each $bucket. If the stream is in the process of closing (and therefore this is the last pass through the filterchain), the closing parameter will be set to TRUE The filter method must return one of three values upon completion.

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

void oncreate ( void )

This method is called during instantiation of the filter class object. If your filter allocates or initializes any other resources (such as a buffer), this is the place to do it. Your implementation of this method should return FALSE on failure, or TRUE on success.

When your filter is first instantiated, and yourfilter->oncreate() is called, a number of properties will be available as shown in the table below.

PropertyContents
FilterClass->filternameA 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->paramsThe contents of the params parameter passed to stream_filter_append() or stream_filter_prepend().

void onclose ( void )

This method is called upon filter shutdown (typically, this is also during stream shutdown), and is executed after the flush method is called. If any resources were allocated or initialzed during oncreate this would be the time to destroy or dispose of them.

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.

Példa 1. Filter for capitalizing characters on foo-bar.txt 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");

?>

Output

LINE1
WORD - 2
EASY AS 123

Példa 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");

/* Output
 * ------

LINE1
WORD - 2
EASY AS 123

 */

?>

See Also: stream_wrapper_register(), stream_filter_prepend(), and stream_filter_append()

stream_get_contents

(no version information, might be only in CVS)

stream_get_contents -- Reads remainder of a stream into a string

Description

string stream_get_contents ( resource handle [, int maxlength])

Identical to file_get_contents(), except that stream_get_contents() operates on an already open file resource and returns the remaining contents, up to maxlength bytes, in a string.

Megjegyzés: Ez a függvény "binary-safe", azaz helyesen kezeli a 127-es ASCII kód feletti karaktereket is.

See also: fgets(), fread(), and fpassthru().

stream_get_filters

(PHP 5 CVS only)

stream_get_filters -- Retrieve list of registered filters

Description

array stream_get_filters ( void )

Returns an indexed array containing the name of all stream filters available on the running system.

Példa 1. Using stream_get_filters()

<?php
$streamlist = stream_get_filters();
print_r($streamlist);
?>

Output will be similar to the following Note: there may be more or fewer filters in your version of PHP.

Array (
  [0] => string.rot13
  [1] => string.toupper
  [2] => string.tolower
  [3] => string.base64
  [4] => string.quoted-printable
)

See also stream_filter_register(), and stream_get_wrappers()

stream_get_line

(PHP 5 CVS only)

stream_get_line -- Gets line from stream resource up to a given delimiter

Description

string stream_get_line ( resource handle, int length, string ending)

Returns a string of up to length bytes read from the file pointed to by handle. Reading ends when length bytes have been read, when the string specified by ending is found (which is notincluded in the return value), or on EOF (whichever comes first).

If an error occurs, returns FALSE.

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.

See also fread(), fgets(), and fgetc(),

stream_get_meta_data

(PHP 4 >= 4.3.0)

stream_get_meta_data -- Retrieves header/meta data from streams/file pointers

Description

array stream_get_meta_data ( resource stream)

Returns information about an existing stream. The stream can be any stream created by fopen(), fsockopen() and pfsockopen(). 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 read buffer.

The following items were added in PHP 4.3:

  • 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 J Függelék for more information about wrappers.

  • wrapper_data (mixed) - wrapper specific data attached to this stream. See J Függelék for more information about wrappers and their wrapper data.

  • filters (array) - and array containing the names of any filters that have been stacked onto this stream. Filters are currently undocumented.

Megjegyzés: This function was introduced in PHP 4.3, but prior to this version, socket_get_status() could be used to retrieve the first four items, for socket based streams only.

In PHP 4.3 and later, socket_get_status() is an alias for this function.

Megjegyzés: This function does NOT work on sockets created by the Socket extension.

stream_get_transports

(PHP 5 CVS only)

stream_get_transports -- Retrieve list of registered socket transports

Description

array stream_get_transports ( void )

Returns an indexed array containing the name of all socket transports available on the running system.

Példa 1. Using stream_get_transports()

<?php
$xportlist = stream_get_transports();
print_r($xportlist);
?>

Output will be similar to the following Note: there may be more or fewer transports in your version of PHP

Array (
  [0] => tcp
  [1] => udp
  [2] => unix
  [3] => udg
)

See also stream_get_filters(), and stream_get_wrappers()

stream_get_wrappers

(PHP 5 CVS only)

stream_get_wrappers -- Retrieve list of registered streams

Description

array stream_get_wrappers ( void )

Returns an indexed array containing the name of all stream wrappers available on the running system.

See also stream_wrapper_register()

stream_register_wrapper

stream_register_wrapper -- Alias of stream_wrapper_register()

Description

This function is an alias of stream_wrapper_register(). This function is included for compatability with PHP 4.3.0 and PHP 4.3.1 only. stream_wrapper_register() should be used instead.

stream_select

(PHP 4 >= 4.3.0)

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

Description

int stream_select ( resource &read, resource &write, resource &except, int tv_sec [, int tv_usec])

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.

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

The streams listed in the write array will be watched to see if a write will not block.

The streams listed in the except array will be watched for high priority exceptional ("out-of-band") data arriving.

Megjegyzés: When stream_select() returns, the arrays read, write and except are modified to indicate which stream resource(s) actually changed status.

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

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

Figyelem

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.

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.

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

if (false === ($num_changed_streams = stream_select($read, $write = NULL, $except = NULL, 0))) {
    /* Error handling */
} elseif ($num_changed_streams > 0) {
    /* At least on one of the streams something interesting happened */
}
?>

Megjegyzés: 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
stream_select($r, $w, $e = NULL, 0);
?>

Megjegyzés: 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
if (false === stream_select($r, $w, $e = NULL, 0)) {
    echo "stream_select() failed\n";
}
?>

Megjegyzés: 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.

Windows 98 Note: stream_select() used on a pipe returned from proc_open() may cause data loss under Windows 98.

See also stream_set_blocking()

stream_set_blocking

(PHP 4 >= 4.3.0)

stream_set_blocking -- Set blocking/non-blocking mode on a stream

Description

bool stream_set_blocking ( resource stream, int 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.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

This function was previously called as set_socket_blocking() and later socket_set_blocking() but this usage is deprecated.

Megjegyzés: Prior to PHP 4.3, this function only worked on socket based streams. Since PHP 4.3, this function works for any stream that supports non-blocking mode (currently, regular files and socket streams).

See also stream_select().

stream_set_timeout

(PHP 4 >= 4.3.0)

stream_set_timeout -- Set timeout period on a stream

Description

bool stream_set_timeout ( resource stream, int seconds [, int microseconds])

Sets the timeout value on stream, expressed in the sum of seconds and microseconds. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Példa 1. stream_set_timeout() example

<?php
$fp = fsockopen("www.example.com", 80);
if (!$fp) {
    echo "Unable to open\n";
} else {
    fputs($fp, "GET / HTTP/1.0\n\n");
    stream_set_timeout($fp, 2);
    $res = fread($fp, 2000);
    var_dump(stream_get_meta_data($fp));
    fclose($fp);
    echo $res;
}
?>

Megjegyzés: 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.

This function was previously called as set_socket_timeout() and later socket_set_timeout() but this usage is deprecated.

See also: fsockopen() and fopen().

stream_set_write_buffer

(PHP 4 >= 4.3.0)

stream_set_write_buffer -- Sets file buffering on the given stream

Description

int stream_set_write_buffer ( resource stream, int buffer)

Output using fwrite() is normally buffered at 8K. This means that if there are two processes wanting to write to the same output stream (a file), each is paused after 8K of data to allow the other to write. stream_set_write_buffer() sets the buffering for write operations on the given filepointer stream to buffer bytes. 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.

The function returns 0 on success, or EOF if the request cannot be honored.

The following example demonstrates how to use stream_set_write_buffer() to create an unbuffered stream.

Példa 1. stream_set_write_buffer() example

<?php
$fp = fopen($file, "w");
if ($fp) {
  stream_set_write_buffer($fp, 0);
  fputs($fp, $output);
  fclose($fp);
}
?>

See also fopen() and fwrite().

stream_socket_accept

(PHP 5 CVS only)

stream_socket_accept --  Accept a connection on a socket created by stream_socket_server()

Description

resource stream_socket_accept ( resource server_socket [, int timeout [, string &peername]])

Accept a connection on a socket previously created by stream_socket_server(). If timeout is specified, the default socket accept timeout will be overridden with the time specified in seconds. The name (address) of the client which connected will be passed back in peername if included and available from the selected transport.

peername can also be determined later using stream_socket_get_name().

If the call fails, it will return FALSE.

See also stream_socket_server(), stream_socket_get_name(), stream_set_blocking(), stream_set_timeout(), fgets(), fgetss(), fputs(), fclose(), feof(), and the Curl extension.

stream_socket_client

(PHP 5 CVS only)

stream_socket_client --  Open Internet or Unix domain socket connection

Description

resource stream_socket_client ( string remote_socket [, int &errno [, string &errstr [, float timeout [, int flags [, 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. The optional timeout can be used to set a timeout in seconds for the connect system call. flags is a bitmask field which may be set to any combination of connection flags. Currently the selection of connection flags is limited to STREAM_CLIENT_ASYNC_CONNECT and STREAM_CLIENT_PERSISTENT.

Megjegyzés: If you need to set a timeout for reading/writing data over the socket, use stream_set_timeout(), as the timeout parameter to stream_socket_client() only applies while connecting the socket.

stream_socket_client() returns a stream resource which may be used together with the other file functions (such as fgets(), fgetss(), fputs(), fclose(), and feof()).

If the call fails, it will return FALSE and 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 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.

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 K Függelék for a list of built in transports.

The stream will by default be opened in blocking mode. You can switch it to non-blocking mode by using stream_set_blocking().

Példa 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 {
    fputs($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);
}
?>
The example below shows how to retrieve the day and time from the UDP service "daytime" (port 13) in your own machine.

Példa 2. Using UDP connection

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

Figyelem

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.

Megjegyzés: When specifying a numerical IPv6 address (e.g. fe80::1) you must enclose the IP in square brackets. For example, tcp://[fe80::1]:80.

See also stream_socket_server(), stream_set_blocking(), stream_set_timeout(), fgets(), fgetss(), fputs(), fclose(), feof(), and the Curl extension.

stream_socket_get_name

(PHP 5 CVS only)

stream_socket_get_name -- Retrieve the name of the local or remote sockets

Description

string stream_socket_get_name ( resource handle, bool want_peer)

Returns the local or remote name of a given socket connection. If want_peer is set to TRUE the remote socket name will be returned, if it is set to FALSE the local socket name will be returned.

See also stream_socket_accept()

stream_socket_recvfrom

(no version information, might be only in CVS)

stream_socket_recvfrom -- Receives data from a socket, connected or not

Description

string stream_socket_recvfrom ( resource socket, int length [, int flags [, string &address]])

The function stream_socket_recvfrom() accepts data from a remote socket up to length bytes. If address is provided it will be populated with the address of the remote socket.

The value of flags can be any combination of the following:

Táblázat 1. 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.

Példa 1. stream_socket_sendto() 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);
?>

See also stream_socket_sendto(), stream_socket_client(), and stream_socket_server().

stream_socket_sendto

(no version information, might be only in CVS)

stream_socket_sendto -- Sends a message to a socket, whether it is connected or not

Description

int stream_socket_sendto ( resource socket, string data [, int flags [, string address]])

The function stream_socket_sendto() sends the data specified by data through the socket specified by socket. The address specified when the socket stream was created will be used unless an alternate address is specified in address.

The value of flags can be any combination of the following:

Táblázat 1. possible values for flags

STREAM_OOB Process OOB (out-of-band) data.

Példa 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);
?>

See also stream_socket_recvfrom(), stream_socket_client(), and stream_socket_server().

stream_socket_server

(PHP 5 CVS only)

stream_socket_server --  Create an Internet or Unix domain server socket

Description

resource stream_socket_server ( string local_socket [, int &errno [, string &errstr [, int flags [, resource context]]]])

Creates a stream or datagram socket on the specified 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. flags is a bitmask field which may be set to any combination of socket creation flags. The default value of flags is STREAM_SERVER_BIND | STREAM_SERVER_LISTEN.

This function only creates a socket, to begin accepting connections use stream_socket_accept().

If the call fails, it will return FALSE and 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.

Depending on the environment, Unix domain sockets may not be available. A list of available transports can be retrieved using stream_get_transports(). See K Függelék for a list of bulitin transports.

stream_socket_server().

Példa 1. stream_socket_server() Example

<?php
$socket = stream_socket_server("tcp://0.0.0.0:8000", $errno, $errstr, STREAM_SERVER_BIND);
if (!$socket) {
  echo "$errstr ($errno)<br />\n";
} else {
  while ($conn = stream_socket_accept($socket)) {
    fputs($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().

Megjegyzés: Most systems require root access to create a server socket on a port below 1024.

Példa 2. Using UDP server sockets

<?php
$socket = stream_socket_server("udp://0.0.0.0:13", $errno, $errstr);
if (!$socket) {
    echo "ERROR: $errno - $errstr<br />\n";
} else {
  while ($conn = stream_socket_accept($socket)) {
    fwrite($conn, date("D M j H:i:s Y\r\n"));
    fclose($conn);
  }
  fclose($socket);
}
?>

Megjegyzés: When specifying a numerical IPv6 address (e.g. fe80::1) you must enclose the IP in square brackets. For example, tcp://[fe80::1]:80.

See also stream_socket_client(), stream_set_blocking(), stream_set_timeout(), fgets(), fgetss(), fputs(), fclose(), feof(), and the Curl extension.

stream_wrapper_register

(PHP 4 >= 4.3.2)

stream_wrapper_register -- Register a URL wrapper implemented as a PHP class

Description

bool stream_wrapper_register ( string protocol, string classname)

stream_wrapper_register() allows you to implement your own protocol handlers and streams for use with all the other filesystem functions (such as fopen(), fread() etc.).

To implement a wrapper, you need to define a class with a number of member functions, as defined below. When someone fopens your stream, PHP will create an instance of classname and then call methods on that instance. You must implement the methods exactly as described below - doing otherwise will lead to undefined behaviour.

Megjegyzés: As of PHP 5.0.0 the instance of classname will be populated with a context property referencing a Context Resource which may be accessed with stream_context_get_options(). If no context was passed to the stream creation function, context will be set to NULL.

stream_wrapper_register() will return FALSE if the protocol already has a handler.

bool stream_open ( string path, string mode, int options, string opened_path)

This method is called immediately after your stream object is created. path specifies the URL that was passed to fopen() and that this object is expected to retrieve. You can use parse_url() to break it apart.

mode is the mode used to open the file, as detailed for fopen(). You are responsible for checking that 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.

FlagDescription
STREAM_USE_PATHIf path is relative, search for the resource using the include_path.
STREAM_REPORT_ERRORSIf 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.

If the path is opened successfully, and STREAM_USE_PATH is set in options, you should set opened_path to the full path of the file/resource that was actually opened.

If the requested resource was opened successfully, you should return TRUE, otherwise you should return FALSE

void stream_close ( void )

This method is called when the stream is closed, using fclose(). You must release any resources that were locked or allocated by the stream.

string stream_read ( int count)

This method is called in response to fread() and fgets() calls on the stream. You must return up-to count bytes of data from the current read/write position as a string. 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. You must also update the read/write position of the stream by the number of bytes that were successfully read.

int stream_write ( string data)

This method is called in response to fwrite() calls on the stream. You should store data into the underlying storage used by your stream. If there is not enough room, try to store as many bytes as possible. You should return the number of bytes that were successfully stored in the stream, or 0 if none could be stored. You must also update the read/write position of the stream by the number of bytes that were successfully written.

bool stream_eof ( void )

This method is called in response to feof() calls on the stream. You 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.

int stream_tell ( void )

This method is called in response to ftell() calls on the stream. You should return the current read/write position of the stream.

bool stream_seek ( int offset, int whence)

This method is called in response to fseek() calls on the stream. You should update the read/write position of the stream according to offset and whence. See fseek() for more information about these parameters. Return TRUE if the position was updated, FALSE otherwise.

bool stream_flush ( void )

This method is called in response to fflush() calls on the stream. If you have cached data in your stream but not yet stored it into the underlying storage, you should do so now. 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.

array stream_stat ( void )

This method is called in response to fstat() calls on the stream and should return an array containing the same values as appropriate for the stream.

bool unlink ( string path)

This method is called in response to unlink() calls on URL paths associated with the wrapper and should attempt to delete the item specified by path. It should return TRUE on success or FALSE on failure. In order for the appropriate error message to be returned, do not define this method if your wrapper does not support unlinking.

Megjegyzés: Userspace wrapper unlink method is not supported prior to PHP 5.0.0.

bool rename ( string path_from, string path_to)

This method is called in response to rename() calls on URL paths associated with the wrapper and should attempt to rename the item specified by path_from to the specification given by path_to. It should return TRUE on success or FALSE on failure. In order for the appropriate error message to be returned, do not define this method if your wrapper does not support renaming.

Megjegyzés: Userspace wrapper rename method is not supported prior to PHP 5.0.0.

bool mkdir ( string path, int mode, int options)

This method is called in response to mkdir() calls on URL paths associated with the wrapper and should attempt to create the directory specified by path. It should return TRUE on success or FALSE on failure. In order for the appropriate error message to be returned, do not define this method if your wrapper does not support creating directories. Posible values for options include STREAM_REPORT_ERRORS and STREAM_MKDIR_RECURSIVE.

Megjegyzés: Userspace wrapper mkdir method is not supported prior to PHP 5.0.0.

bool rmdir ( string path, int options)

This method is called in response to rmdir() calls on URL paths associated with the wrapper and should attempt to remove the directory specified by path. It should return TRUE on success or FALSE on failure. In order for the appropriate error message to be returned, do not define this method if your wrapper does not support removing directories. Possible values for options include STREAM_REPORT_ERRORS.

Megjegyzés: Userspace wrapper rmdir method is not supported prior to PHP 5.0.0.

bool dir_opendir ( string path, int options)

This method is called immediately when your stream object is created for examining directory contents with opendir(). path specifies the URL that was passed to opendir() and that this object is expected to explore. You can use parse_url() to break it apart.

array url_stat ( string path, int flags)

This method is called in response to stat() calls on the URL paths associated with the wrapper and should return as many elements in common with the system function as possible. Unknown or unavailable values should be set to a rational value (usually 0).

flags holds additional flags set by the streams API. It can hold one or more of the following values OR'd together.

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

string dir_readdir ( void )

This method is called in response to readdir() and should return a string representing the next filename in the location opened by dir_opendir().

bool dir_rewinddir ( void )

This method is called in response to rewinddir() and should reset the output generated by dir_readdir(). i.e.: The next call to dir_readdir() should return the first entry in the location returned by dir_opendir().

bool dir_closedir ( void )

This method is called in response to closedir(). You should release any resources which were locked or allocated during the opening and use of the directory stream.

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

Példa 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;
        }
    }
}

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

?>

CIV. String functions

Bevezetés

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.


Követelmények

Az itt leírt függvények használatához semmilyen külső függvénykönyvtár megléte nem szükségeltetik.


Telepítés

Semmilyen telepítés nem szükséges ezen függvények használatához, a PHP alapelemei.


Előre definiált állandók

Az itt listázott állandókat ez a kiterjesztés definiálja, és csak akkor elérhetőek, ha az adott kiterjesztés be van fordítva a PHP-be, vagy dinamikusan betöltött.

CRYPT_SALT_LENGTH integer

CRYPT_STD_DES integer

CRYPT_EXT_DES integer

CRYPT_MD5 integer

CRYPT_BLOWFISH integer

HTML_SPECIALCHARS (integer)

HTML_ENTITIES (integer)

ENT_COMPAT (integer)

ENT_QUOTES (integer)

ENT_NOQUOTES (integer)

CHAR_MAX (integer)

LC_CTYPE (integer)

LC_NUMERIC (integer)

LC_TIME (integer)

LC_COLLATE (integer)

LC_MONETARY (integer)

LC_ALL (integer)

LC_MESSAGES (integer)

STR_PAD_LEFT (integer)

STR_PAD_RIGHT (integer)

STR_PAD_BOTH (integer)


Lásd még

For even more powerful string handling and manipulating functions take a look at the POSIX regular expression functions and the Perl compatible regular expression functions.

Tartalom
addcslashes -- Quote string with slashes in a C style
addslashes -- Quote string with slashes
bin2hex --  Convert binary data into hexadecimal representation
chop -- Alias of 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
count_chars --  Return information about characters used in a string
crc32 -- Calculates the crc32 polynomial of a string
crypt -- One-way string encryption (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
html_entity_decode --  Convert all HTML entities to their applicable characters
htmlentities --  Convert all applicable characters to HTML entities
htmlspecialchars --  Convert special characters to HTML entities
implode -- Join array elements with a string
join -- Alias for implode()
levenshtein --  Calculate Levenshtein distance between two strings
localeconv -- Get numeric formatting information
ltrim --  Strip whitespace from the beginning of a string
md5_file -- Calculates the md5 hash of a given filename
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
quotemeta -- Quote meta characters
rtrim --  Strip whitespace 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_ireplace --  Case-insensitive version of str_replace().
str_pad --  Pad a string to a certain length with another string
str_repeat -- Repeat a string
str_replace --  Replace all occurrences of the search string with the replacement string
str_rot13 -- Perform the rot13 transform on a string
str_shuffle -- Randomly shuffles a string
str_split --  Convert a string to an array
str_word_count --  Return information about words used in a string
strcasecmp --  Binary safe case-insensitive string comparison
strchr -- Alias for 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 position of first occurrence of a case-insensitive string
stripslashes --  Un-quote string quoted with addslashes()
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
strpos --  Find position of first occurrence of a string
strrchr --  Find the last occurrence of a character in a string
strrev -- Reverse a string
strripos --  Find position of last occurrence of a case-insensitive string in a string
strrpos --  Find position of last occurrence of a char in a string
strspn --  Find length of initial segment matching mask
strstr -- Find first occurrence of a string
strtok -- Tokenize string
strtolower -- Make a string lowercase
strtoupper -- Make a string uppercase
strtr -- Translate certain characters
substr_compare --  Binary safe optionally case insensitive comparison of 2 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 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
vprintf -- Output a formatted string
vsprintf -- Return a formatted string
wordwrap --  Wraps a string to a given number of characters using a string break character.

addcslashes

(PHP 4 )

addcslashes -- Quote string with slashes in a C style

Description

string addcslashes ( string str, string charlist)

Returns a string with backslashes before characters that are listed in charlist parameter. It escapes \n, \r etc. in C-like style, characters with ASCII code lower than 32 and higher than 126 are converted to octal representation.

Be careful if you choose to escape characters 0, a, b, f, n, r, t and v. They will be converted to \0, \a, \b, \f, \n, \r, \t and \v. In PHP \0 (NULL), \r (carriage return), \n (newline) and \t (tab) are predefined escape sequences, while in C all of these are predefined escape sequences.

charlist like "\0..\37", which would escape all characters with ASCII code between 0 and 37.

Példa 1. addcslashes() example

<?php
$escaped = addcslashes($not_escaped, "\0..\37!@\177..\377");
?>

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 [\]^_` and any tabs, line
// feeds, carriage returns, etc.
?>

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['\.']
?>

See also stripcslashes(), stripslashes(), htmlspecialchars(), and quotemeta().

addslashes

(PHP 3, PHP 4 )

addslashes -- Quote string with slashes

Description

string addslashes ( string str)

Returns a string with backslashes before characters that need to be quoted in database queries etc. These characters are single quote ('), double quote ("), backslash (\) and NUL (the NULL byte).

An example use of addslashes() is when you're entering data into a database. For example, to insert the name O'reilly into a database, you will need to escape it. Most databases do this with a \ which would mean O\'reilly. This would only be to get the data into the database, the extra \ will not be inserted. Having the PHP directive magic_quotes_sybase set to on will mean ' is instead escaped with another '.

The PHP directive magic_quotes_gpc is on by default, and it essentially runs addslashes() on all GET, POST, and COOKIE data. Do not use addslashes() on strings that have already been escaped with magic_quotes_gpc as you'll then do double escaping. The function get_magic_quotes_gpc() may come in handy for checking this.

Példa 1. An addslashes() example

<?php
$str = "Is your name O'reilly?";

// Outputs: Is your name O\'reilly?
echo addslashes($str);
?>

See also stripslashes(), htmlspecialchars(), quotemeta(), and get_magic_quotes_gpc().

bin2hex

(PHP 3>= 3.0.9, PHP 4 )

bin2hex --  Convert binary data into hexadecimal representation

Description

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.

See also pack() and unpack().

chop

chop -- Alias of rtrim()

Description

This function is an alias of rtrim().

Megjegyzés: chop() is different than the Perl chop() function, which removes the last character in the string.

chr

(PHP 3, PHP 4 )

chr -- Return a specific character

Description

string chr ( int ascii)

Returns a one-character string containing the character specified by ascii.

Példa 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);
?>

You can find an ASCII-table over here: http://www.asciitable.com.

This function complements ord(). See also sprintf() with a format string of %c.

chunk_split

(PHP 3>= 3.0.6, PHP 4 )

chunk_split -- Split a string into smaller chunks

Description

string chunk_split ( string body [, int chunklen [, string end]])

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 (defaults to "\r\n") every chunklen characters (defaults to 76). It returns the new string leaving the original string untouched.

Példa 1. chunk_split() example

<?php
// format $data using RFC 2045 semantics
$new_string = chunk_split(base64_encode($data));
?>

See also str_split(), explode(), split(), wordwrap() and RFC 2045.

convert_cyr_string

(PHP 3>= 3.0.6, PHP 4 )

convert_cyr_string --  Convert from one Cyrillic character set to another

Description

string convert_cyr_string ( string str, string from, string to)

This function returns the given string converted from one Cyrillic character set to another. The from and to arguments are single characters that represent the source and target Cyrillic character sets. The supported types are:

  • k - koi8-r

  • w - windows-1251

  • i - iso8859-5

  • a - x-cp866

  • d - x-cp866

  • m - x-mac-cyrillic

count_chars

(PHP 4 )

count_chars --  Return information about characters used in a string

Description

mixed count_chars ( string string [, int mode])

Counts the number of occurrences of every byte-value (0..255) in string and returns it in various ways. The optional parameter mode default to 0. 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 used byte-values is returned.

  • 4 - a string containing all not used byte-values is returned.

Példa 1. count_chars() example

<?php

$data = "Two Ts and one F.";

$result = count_chars($data, 0);

for ($i=0; $i < count($result); $i++) {
   if ($result[$i] != 0)
       echo "There were $result[$i] instance(s) of \"" , chr($i) , "\" in the string.\n";
}

?>

This will output :

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.

See also strpos() and substr_count().

crc32

(PHP 4 >= 4.0.1)

crc32 -- Calculates the crc32 polynomial of a string

Description

int crc32 ( string str)

Generates the cyclic redundancy checksum polynomial of 32-bit lengths of the str. This is usually used to validate the integrity of data being transmitted.

Because PHP's integer type is signed, and many crc32 checksums will result in negative integers, you need to use the "%u" formatter of sprintf() or printf() to get the string representation of the unsigned crc32 checksum.

This second example shows how to print a converted checksum with the printf() function:

Példa 1. Displaying a crc32 checksum

<?php
$checksum = crc32("The quick brown fox jumped over the lazy dog.");
printf("%u\n", $checksum);
?>

See also md5() and sha1().

crypt

(PHP 3, PHP 4 )

crypt -- One-way string encryption (hashing)

Description

string crypt ( string str [, string salt])

crypt() will return an encrypted string using the standard Unix DES-based encryption algorithm or alternative algorithms that may be available on the system. Arguments are a string to be encrypted and an optional salt string to base the encryption on. See the Unix man page for your crypt function for more information.

If the salt argument is not provided, one will be randomly generated by PHP.

Some operating systems support more than one type of encryption. In fact, sometimes the standard DES-based encryption is replaced by an MD5-based encryption algorithm. The encryption type is triggered by the salt argument. At install time, PHP determines the capabilities of the crypt function and will accept salts for other encryption types. If no salt is provided, PHP will auto-generate a standard two character salt by default, unless the default encryption type on the system is MD5, in which case a random MD5-compatible salt is generated. PHP sets a constant named CRYPT_SALT_LENGTH which tells you whether a regular two character salt applies to your system or the longer twelve character salt is applicable.

If you are using the supplied salt, you should be aware that the salt is generated once. If you are calling this function recursively, this may impact both appearance and security.

The standard DES-based encryption 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 encryption types, the following constants are set to 0 or 1 depending on whether the given type is available:

  • CRYPT_STD_DES - Standard DES-based encryption with a two character salt

  • CRYPT_EXT_DES - Extended DES-based encryption with a nine character salt

  • CRYPT_MD5 - MD5 encryption with a twelve character salt starting with $1$

  • CRYPT_BLOWFISH - Blowfish encryption with a sixteen character salt starting with $2$

Megjegyzés: There is no decrypt function, since crypt() uses a one-way algorithm.

Példa 1. crypt() examples

<?php
$password = crypt("My1sTpassword"); // let salt be generated

# You should pass the entire results of crypt() as the salt for comparing a
# password, to avoid problems when different hashing algorithms are used. (As
# it says above, standard DES-based password hashing uses a 2-character salt,
# but MD5-based hashing uses 12.)
if (crypt($user_input, $password) == $password) {
   echo "Password verified!";
}
?>

See also md5() and the Mcrypt extension.

echo

(PHP 3, PHP 4 )

echo -- Output one or more strings

Description

void echo ( string arg1 [, string argn...])

Outputs all parameters.

echo() is not actually a function (it is a language construct) so you are not required to use parentheses with it. In fact, if you want to pass more than one parameter to echo, you must not enclose the parameters within parentheses.

Példa 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
$bar = array("value" => "foo");

echo "this is {$bar['value']} !"; // this is foo !

// Using single quotes will print the variable name, not the value
echo 'foo is $foo'; // foo is $foo

// If you are not using any other characters, you can just echo variables
echo $foo;          // foobar
echo $foo,$bar;     // foobarbarbaz

// Some people prefer passing multiple parameters to echo over concatenation.
echo 'This ', 'string ', 'was ', 'made ', 'with multiple parameters.', chr(10);
echo 'This ' . 'string ' . 'was ' . 'made ' . 'with concatenation.' . "\n";

echo <<<END
This uses the "here document" syntax to output
multiple lines with $variable interpolation. Note
that the here document terminator must appear on a
line with just a semicolon. no extra whitespace!
END;

// Because echo is not a function, following code is invalid. 
($some_var) ? echo 'true' : echo 'false';

// However, the following examples will work:
($some_var) ? print('true'): print('false'); // print is a function
echo $some_var ? 'true': 'false'; // changing the statement around
?>

echo() also has a shortcut syntax, where you can immediately follow the opening tag with an equals sign. This short syntax only works with the short_open_tag configuration setting enabled.

I have <?=$foo?> foo.

For a short discussion about the differences between print() and echo(), see this FAQTs Knowledge Base Article: http://www.faqts.com/knowledge_base/view.phtml/aid/1/fid/40

Megjegyzés: Because this is a language construct and not a function, it cannot be called using variable functions

See also print(), printf(), and flush().

explode

(PHP 3, PHP 4 )

explode -- Split a string by string

Description

array explode ( string separator, string string [, int limit])

Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string separator. If limit is set, the returned array will contain a maximum of limit elements with the last element containing the rest of string.

If separator is an empty string (""), explode() will return FALSE. If separator contains a value that is not contained in string, then explode() will return an array containing string.

Although implode() can, for historical reasons, accept its parameters in either order, explode() cannot. You must ensure that the separator argument comes before the string argument.

Megjegyzés: The limit parameter was added in PHP 4.0.1

Példa 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; // *

?>

See also preg_split(), spliti(), split(), and implode().

fprintf

(PHP 5 CVS only)

fprintf -- Write a formatted string to a stream

Description

int fprintf ( resource handle, string format [, mixed args])

Write a string produced according to the formatting string format to the stream resource specified by handle..

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 fprintf(), sprintf(), and printf().

Each conversion specification consists of a percent sign (%), followed by one or more of these elements, in order:

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

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

  3. An optional number, a width specifier that says how many characters (minimum) this conversion should result in.

  4. An optional precision specifier that says how many decimal digits should be displayed for floating-point numbers. This option has no effect for other types than float. (Another function useful for formatting numbers is number_format().)

  5. 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.
    u - the argument is treated as an integer, and presented as an unsigned decimal number.
    f - the argument is treated as a float, and presented as a floating-point number.
    o - the argument is treated as an integer, and presented as an octal number.
    s - the argument is treated as and presented as a string.
    x - the argument is treated as an integer and presented as a hexadecimal number (with lowercase letters).
    X - the argument is treated as an integer and presented as a hexadecimal number (with uppercase letters).

See also: printf(), sprintf(), sscanf(), fscanf(), vsprintf(), and number_format().

Examples

Példa 1. sprintf(): zero-padded integers

<?php
$isodate = sprintf("%04d-%02d-%02d", $year, $month, $day);
?>

Példa 2. 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"
?>

get_html_translation_table

(PHP 4 )

get_html_translation_table --  Returns the translation table used by htmlspecialchars() and htmlentities()

Description

array get_html_translation_table ( int table [, int quote_style])

get_html_translation_table() will return the translation table that is used internally for htmlspecialchars() and htmlentities().

There are two new constants (HTML_ENTITIES, HTML_SPECIALCHARS) that allow you to specify the table you want. And as in the htmlspecialchars() and htmlentities() functions you can optionally specify the quote_style you are working with. The default is ENT_COMPAT mode. See the description of these modes in htmlspecialchars().

Példa 1. Translation Table Example

<?php
$trans = get_html_translation_table(HTML_ENTITIES);
$str = "Hallo & <Frau> & Krämer";
$encoded = strtr($str, $trans);
?>
The $encoded variable will now contain: "Hallo &amp; &lt;Frau&gt; &amp; Kr&auml;mer".

Another interesting use of this function is to, with help of array_flip(), change the direction of the translation.

<?php
$trans = array_flip($trans);
$original = strtr($encoded, $trans);
?>

The content of $original would be: "Hallo & <Frau> & Krämer".

See also htmlspecialchars(), htmlentities(), strtr(), and array_flip().

hebrev

(PHP 3, PHP 4 )

hebrev --  Convert logical Hebrew text to visual text

Description

string hebrev ( string hebrew_text [, int max_chars_per_line])

The optional parameter max_chars_per_line indicates maximum number of characters per line will be output. The function tries to avoid breaking words.

See also hebrevc()

hebrevc

(PHP 3, PHP 4 )

hebrevc --  Convert logical Hebrew text to visual text with newline conversion

Description

string hebrevc ( string hebrew_text [, int max_chars_per_line])

This function is similar to hebrev() with the difference that it converts newlines (\n) to "<br>\n". The optional parameter max_chars_per_line indicates maximum number of characters per line will be output. The function tries to avoid breaking words.

See also hebrev()

html_entity_decode

(PHP 4 >= 4.3.0)

html_entity_decode --  Convert all HTML entities to their applicable characters

Description

string html_entity_decode ( string string [, int quote_style [, string charset]])

html_entity_decode() is the opposite of htmlentities() in that it converts all HTML entities to their applicable characters from string.

The optional second quote_style parameter lets you define what will be done with 'single' and "double" quotes. It takes on one of three constants with the default being ENT_COMPAT:

Táblázat 1. Available quote_style constants

Constant NameDescription
ENT_COMPATWill convert double-quotes and leave single-quotes alone.
ENT_QUOTESWill convert both double and single quotes.
ENT_NOQUOTESWill leave both double and single quotes unconverted.

The ISO-8859-1 character set is used as default for the optional third charset. This defines the character set used in conversion. Support for this third argument was added in PHP 4.1.0.

Following character sets are supported in PHP 4.3.0 and later.

Táblázat 2. Supported charsets

CharsetAliasesDescription
ISO-8859-1ISO8859-1 Western European, Latin-1
ISO-8859-15ISO8859-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.
cp866ibm866, 866 DOS-specific Cyrillic charset. This charset is supported in 4.3.2.
cp1251Windows-1251, win-1251, 1251 Windows-specific Cyrillic charset. This charset is supported in 4.3.2.
cp1252Windows-1252, 1252 Windows specific charset for Western European.
KOI8-Rkoi8-ru, koi8r Russian. This charset is supported in 4.3.2.
BIG5950 Traditional Chinese, mainly used in Taiwan.
GB2312936 Simplified Chinese, national standard character set.
BIG5-HKSCS  Big5 with Hong Kong extensions, Traditional Chinese.
Shift_JISSJIS, 932 Japanese
EUC-JPEUCJP Japanese

Megjegyzés: Any other character sets are not recognized and ISO-8859-1 will be used instead.

Példa 1. Decoding HTML entities

<?php
$orig = "I'll \"walk\" the <b>dog</b> now";

$a = htmlentities($orig);

$b = html_entity_decode($a);

echo $a; // I'll &quot;walk&quot; the &lt;b&gt;dog&lt;/b&gt; now

echo $b; // I'll "walk" the <b>dog</b> now


// For users prior to PHP 4.3.0 you may do this:
function unhtmlentities($string) 
{
    $trans_tbl = get_html_translation_table(HTML_ENTITIES);
    $trans_tbl = array_flip($trans_tbl);
    return strtr($string, $trans_tbl);
}

$c = unhtmlentities($a);

echo $c; // I'll "walk" the <b>dog</b> now

?>

Megjegyzés: You might wonder why trim(html_entity_decode('&nbsp;')); doesn't reduce the string to an empty string, that's because the '&nbsp;' entity is not ASCII code 32 (which is stripped by trim()) but ASCII code 160 (0xa0) in the default ISO 8859-1 characterset.

See also htmlentities(), htmlspecialchars(), get_html_translation_table(), htmlspecialchars() and urldecode().

htmlentities

(PHP 3, PHP 4 )

htmlentities --  Convert all applicable characters to HTML entities

Description

string htmlentities ( string string [, int quote_style [, string charset]])

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.

Like htmlspecialchars(), the optional second quote_style parameter lets you define what will be done with 'single' and "double" quotes. It takes on one of three constants with the default being ENT_COMPAT:

Táblázat 1. Available quote_style constants

Constant NameDescription
ENT_COMPATWill convert double-quotes and leave single-quotes alone.
ENT_QUOTESWill convert both double and single quotes.
ENT_NOQUOTESWill leave both double and single quotes unconverted.

Support for the optional quote parameter was added in PHP 4.0.3.

Like htmlspecialchars(), it takes an optional third argument charset which defines character set used in conversion. Support for this argument was added in PHP 4.1.0. Presently, the ISO-8859-1 character set is used as the default.

Following character sets are supported in PHP 4.3.0 and later.

Táblázat 2. Supported charsets

CharsetAliasesDescription
ISO-8859-1ISO8859-1 Western European, Latin-1
ISO-8859-15ISO8859-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.
cp866ibm866, 866 DOS-specific Cyrillic charset. This charset is supported in 4.3.2.
cp1251Windows-1251, win-1251, 1251 Windows-specific Cyrillic charset. This charset is supported in 4.3.2.
cp1252Windows-1252, 1252 Windows specific charset for Western European.
KOI8-Rkoi8-ru, koi8r Russian. This charset is supported in 4.3.2.
BIG5950 Traditional Chinese, mainly used in Taiwan.
GB2312936 Simplified Chinese, national standard character set.
BIG5-HKSCS  Big5 with Hong Kong extensions, Traditional Chinese.
Shift_JISSJIS, 932 Japanese
EUC-JPEUCJP Japanese

Megjegyzés: Any other character sets are not recognized and ISO-8859-1 will be used instead.

If you're wanting to decode instead (the reverse) you can use html_entity_decode().

Példa 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);
?>

See also html_entity_decode(), get_html_translation_table(), htmlspecialchars(), nl2br(), and urlencode().

htmlspecialchars

(PHP 3, PHP 4 )

htmlspecialchars --  Convert special characters to HTML entities

Description

string htmlspecialchars ( string string [, int quote_style [, string charset]])

Certain characters have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings. This function returns a string with some of these conversions made; the translations made are those most useful for everyday web programming. If you require all HTML character entities to be translated, use htmlentities() instead.

This function is useful in preventing user-supplied text from containing HTML markup, such as in a message board or guest book application. The optional second argument, quote_style, tells the function what to do with single and double quote characters. The default mode, ENT_COMPAT, is the backwards compatible mode which only translates the double-quote character and leaves the single-quote untranslated. If ENT_QUOTES is set, both single and double quotes are translated and if ENT_NOQUOTES is set neither single nor double quotes are translated.

The translations performed are:

  • '&' (ampersand) becomes '&amp;'

  • '"' (double quote) becomes '&quot;' when ENT_NOQUOTES is not set.

  • ''' (single quote) becomes '&#039;' only when ENT_QUOTES is set.

  • '<' (less than) becomes '&lt;'

  • '>' (greater than) becomes '&gt;'

Példa 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 that this function does not translate anything beyond what is listed above. For full entity translation, see htmlentities(). Support for the optional second argument was added in PHP 3.0.17 and PHP 4.0.3.

The third argument charset defines character set used in conversion. The default character set is ISO-8859-1. Support for this third argument was added in PHP 4.1.0.

Following character sets are supported in PHP 4.3.0 and later.

Táblázat 1. Supported charsets

CharsetAliasesDescription
ISO-8859-1ISO8859-1 Western European, Latin-1
ISO-8859-15ISO8859-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.
cp866ibm866, 866 DOS-specific Cyrillic charset. This charset is supported in 4.3.2.
cp1251Windows-1251, win-1251, 1251 Windows-specific Cyrillic charset. This charset is supported in 4.3.2.
cp1252Windows-1252, 1252 Windows specific charset for Western European.
KOI8-Rkoi8-ru, koi8r Russian. This charset is supported in 4.3.2.
BIG5950 Traditional Chinese, mainly used in Taiwan.
GB2312936 Simplified Chinese, national standard character set.
BIG5-HKSCS  Big5 with Hong Kong extensions, Traditional Chinese.
Shift_JISSJIS, 932 Japanese
EUC-JPEUCJP Japanese

Megjegyzés: Any other character sets are not recognized and ISO-8859-1 will be used instead.

See also get_html_translation_table(), strip_tags(), htmlentities(), and nl2br().

implode

(PHP 3, PHP 4 )

implode -- Join array elements with a string

Description

string implode ( string glue, array pieces)

Returns a string containing a string representation of all the array elements in the same order, with the glue string between each element.

Példa 1. implode() example

<?php

$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);

echo $comma_separated; // lastname,email,phone

?>

Megjegyzés: 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.

Megjegyzés: As of PHP 4.3.0, the glue parameter of implode() is optional and defaults to the empty string(''). This is not the preferred usage of implode(). We recommend to always use two parameters for compatibility with older versions.

See also explode(), and split().

join

join -- Alias for implode()

Description

This function is an alias of implode().

levenshtein

(PHP 3>= 3.0.17, PHP 4 >= 4.0.1)

levenshtein --  Calculate Levenshtein distance between two strings

Description

int levenshtein ( string str1, string str2)

int levenshtein ( string str1, string str2, int cost_ins, int cost_rep, int cost_del)

int levenshtein ( string str1, string str2, function cost)

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 (255 should be more than enough for name or dictionary comparison, and nobody serious would be doing genetic analysis with PHP).

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.

The third variant (which is not implemented yet) will be the most general and adaptive, but also the slowest alternative. It will call a user-supplied function that will determine the cost for every possible operation.

The user-supplied function will be called with the following arguments:

  • operation to apply: 'I', 'R' or 'D'

  • actual character in string 1

  • actual character in string 2

  • position in string 1

  • position in string 2

  • remaining characters in string 1

  • remaining characters in string 2

The user-supplied function has to return a positive integer describing the cost for this particular operation, but it may decide to use only some of the supplied arguments.

The user-supplied function approach offers the possibility to take into account the relevance of and/or difference between certain symbols (characters) or even the context those symbols appear in to determine the cost of insert, replace and delete operations, but at the cost of losing all optimizations done regarding cpu register utilization and cache misses that have been worked into the other two variants.

See also soundex(), similar_text(), and metaphone().

localeconv

(PHP 4 >= 4.0.5)

localeconv -- Get numeric formatting information

Description

array localeconv ( void )

Returns an associative array containing localized numeric and monetary formatting information.

localeconv() returns data based upon the current locale as set by setlocale(). The associative array that is returned contains the following fields:

Array elementDescription
decimal_pointDecimal point character
thousands_sepThousands separator
groupingArray containing numeric groupings
int_curr_symbolInternational currency symbol (i.e. USD)
currency_symbolLocal currency symbol (i.e. $)
mon_decimal_pointMonetary decimal point character
mon_thousands_sepMonetary thousands separator
mon_groupingArray containing monetary groupings
positive_signSign for positive values
negative_signSign for negative values
int_frac_digitsInternational fractional digits
frac_digitsLocal 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 grouping fields contain arrays that define the way numbers should be grouped. For example, the grouping field for the en_US locale, 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.

Példa 1. localeconv() example

<?php
setlocale(LC_ALL, "en_US");

$locale_info = localeconv();

echo "<pre>\n";
echo "--------------------------------------------\n";
echo "  Monetary information for current locale:  \n";
echo "--------------------------------------------\n\n";

echo "int_curr_symbol:   {$locale_info["int_curr_symbol"]}\n";
echo "currency_symbol:   {$locale_info["currency_symbol"]}\n";
echo "mon_decimal_point: {$locale_info["mon_decimal_point"]}\n";
echo "mon_thousands_sep: {$locale_info["mon_thousands_sep"]}\n";
echo "positive_sign:     {$locale_info["positive_sign"]}\n";
echo "negative_sign:     {$locale_info["negative_sign"]}\n";
echo "int_frac_digits:   {$locale_info["int_frac_digits"]}\n";
echo "frac_digits:       {$locale_info["frac_digits"]}\n";
echo "p_cs_precedes:     {$locale_info["p_cs_precedes"]}\n";
echo "p_sep_by_space:    {$locale_info["p_sep_by_space"]}\n";
echo "n_cs_precedes:     {$locale_info["n_cs_precedes"]}\n";
echo "n_sep_by_space:    {$locale_info["n_sep_by_space"]}\n";
echo "p_sign_posn:       {$locale_info["p_sign_posn"]}\n";
echo "n_sign_posn:       {$locale_info["n_sign_posn"]}\n";
echo "</pre>\n";
?>

The constant CHAR_MAX is also defined for the use mentioned above.

See also setlocale().

ltrim

(PHP 3, PHP 4 )

ltrim --  Strip whitespace from the beginning of a string

Description

string ltrim ( string str [, string charlist])

Megjegyzés: The second parameter was added in PHP 4.1.0

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.

You can also specify the characters you want to strip, by means of the charlist parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.

Példa 1. Usage example of ltrim()

<?php

$text = "\t\tThese are a few words :) ...  ";
$trimmed = ltrim($text);
// $trimmed = "These are a few words :) ...  "
$trimmed = ltrim($text, " \t.");
// $trimmed = "These are a few words :) ...  "
$clean = ltrim($binary, "\0x00..\0x1F");
// trim the ASCII control characters at the beginning of $binary 
// (from 0 to 31 inclusive)

?>

See also trim() and rtrim().

md5_file

(PHP 4 >= 4.2.0)

md5_file -- Calculates the md5 hash of a given filename

Description

string md5_file ( string filename [, bool raw_output])

Calculates the MD5 hash of the specified filename using the RSA Data Security, Inc. MD5 Message-Digest Algorithm, and returns that hash. The hash is a 32-character hexadecimal number. 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.

Megjegyzés: The optional raw_output parameter was added in PHP 5.0.0 and defaults to FALSE

This function has the same purpose of the command line utility md5sum.

See also md5(), crc32(), and sha1_file().

md5

(PHP 3, PHP 4 )

md5 -- Calculate the md5 hash of a string

Description

string md5 ( string str [, bool raw_output])

Calculates the MD5 hash of str using the RSA Data Security, Inc. MD5 Message-Digest Algorithm, and returns that hash. The hash is a 32-character hexadecimal number. 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.

Megjegyzés: The optional raw_output parameter was added in PHP 5.0.0 and defaults to FALSE

Példa 1. A md5() example

<?php
$str = 'apple';

if (md5($str) === '1f3870be274f6c49b3e31a0c6728957f') {
    echo "Would you like a green or red apple?";
    exit;
}
?>

See also crc32(), md5_file(), and sha1().

metaphone

(PHP 4 )

metaphone -- Calculate the metaphone key of a string

Description

string metaphone ( string str)

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

money_format

(PHP 4 >= 4.3.0)

money_format -- Formats a number as a currency string

Description

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.

Megjegyzés: 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.

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 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: DM1.234,56).

%

Returns the % character.

Megjegyzés: 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.

Characters before and after the formatting string will be returned unchanged.

Példa 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";
// L. 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";
// DEM 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)

?>

See also: setlocale(), number_format(),sprintf(), printf() and sscanf().

nl_langinfo

(PHP 4 >= 4.1.0)

nl_langinfo --  Query language and locale information

Description

string nl_langinfo ( int item)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

nl2br

(PHP 3, PHP 4 )

nl2br --  Inserts HTML line breaks before all newlines in a string

Description

string nl2br ( string string)

Returns string with '<br />' inserted before all newlines.

Megjegyzés: Starting with PHP 4.0.5, nl2br() is now XHTML compliant. All versions before 4.0.5 will return string with '<br>' inserted before newlines instead of '<br />'.

Példa 1. using nl2br()

<?php
echo nl2br("foo isn't\n bar");
?>

this will output :

foo isn't<br />
 bar

See also htmlspecialchars(), htmlentities(), wordwrap(), and str_replace().

number_format

(PHP 3, PHP 4 )

number_format -- Format a number with grouped thousands

Description

string number_format ( float number [, int decimals])

string number_format ( float number, int decimals, string dec_point, string thousands_sep)

number_format() returns a formatted version of number. 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.

Only the first character of thousands_sep is used. For example, if you use foo as thousands_sep on the number 1000, number_format() will return 1f000.

Példa 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,234

// French notation
$nombre_format_francais = number_format($number, 2, ',', ' ');
// 1 234,56

$number = 1234.5678;

// english notation without thousands seperator
$english_format_number = number_format($number, 2, '.', '');
// 1234.57

?>

See also: sprintf(), printf() and sscanf().

ord

(PHP 3, PHP 4 )

ord -- Return ASCII value of character

Description

int ord ( string string)

Returns the ASCII value of the first character of string. This function complements chr().

Példa 1. ord() example

<?php
if (ord($str) == 10) {
    echo "The first character of \$str is a line feed.\n";
}
?>

You can find an ASCII-table over here: http://www.asciitable.com.

See also chr().

parse_str

(PHP 3, PHP 4 )

parse_str -- Parses the string into variables

Description

void parse_str ( string str [, array arr])

Parses str as if it were the query string passed via a URL and sets variables in the current scope. If the second parameter arr is present, variables are stored in this variable as array elements instead.

Megjegyzés: Support for the optional second parameter was added in PHP 4.0.3.

Megjegyzés: 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 outside of PHP.

Példa 1. Using parse_str()

<?php
$str = "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str);
echo $first;  // value
echo $arr[0]; // foo bar
echo $arr[1]; // baz

parse_str($str, $output);
echo $output['first'];  // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz

?>

See also parse_url(), pathinfo(), set_magic_quotes_runtime(), and urldecode().

print

(PHP 3, PHP 4 )

print -- Output a string

Description

int print ( string arg)

Outputs arg. Returns 1, always.

print() is not actually a real function (it is a language construct) so you are not required to use parentheses with its argument list.

Példa 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 of 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;
?>

For a short discussion about the differences between print() and echo(), see this FAQTs Knowledge Base Article: http://www.faqts.com/knowledge_base/view.phtml/aid/1/fid/40

Megjegyzés: Because this is a language construct and not a function, it cannot be called using variable functions

See also echo(), printf(), and flush().

printf

(PHP 3, PHP 4 )

printf -- Output a formatted string

Description

void printf ( string format [, mixed args])

Produces output according to format, which is described in the documentation for sprintf().

See also print(), sprintf(), vprintf(), sscanf(), fscanf() and flush().

quoted_printable_decode

(PHP 3>= 3.0.6, PHP 4 )

quoted_printable_decode --  Convert a quoted-printable string to an 8 bit string

Description

string quoted_printable_decode ( string str)

This function returns an 8-bit binary string corresponding to the decoded quoted printable string. This function is similar to imap_qprint(), except this one does not require the IMAP module to work.

quotemeta

(PHP 3, PHP 4 )

quotemeta -- Quote meta characters

Description

string quotemeta ( string str)

Returns a version of str with a backslash character (\) before every character that is among these:
. \\ + * ? [ ^ ] ( $ )

See also addslashes(), htmlentities(), htmlspecialchars(), nl2br(), and stripslashes().

rtrim

(PHP 3, PHP 4 )

rtrim --  Strip whitespace from the end of a string

Description

string rtrim ( string str [, string charlist])

Megjegyzés: The second parameter was added in PHP 4.1.0

This function returns a string with whitespace stripped from the end of str. Without the second parameter, rtrim() will strip these characters:

  • " " (ASCII 32 (0x20)), an ordinary space.

  • "\t" (ASCII 9 (0x09)), a tab.

  • "\n" (ASCII 10 (0x0A)), a new line (line feed).

  • "\r" (ASCII 13 (0x0D)), a carriage return.

  • "\0" (ASCII 0 (0x00)), the NUL-byte.

  • "\x0B" (ASCII 11 (0x0B)), a vertical tab.

You can also specify the characters you want to strip, by means of the charlist parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.

Példa 1. Usage example of rtrim()

<?php

$text = "\t\tThese are a few words :) ...  ";
$trimmed = rtrim($text);
// $trimmed = "\t\tThese are a few words :) ..."
$trimmed = rtrim($text, " \t.");
// $trimmed = "\t\tThese are a few words :)"
$clean = rtrim($binary, "\0x00..\0x1F");
// trim the ASCII control characters at the end of $binary 
// (from 0 to 31 inclusive)

?>

See also trim() and ltrim().

setlocale

(PHP 3, PHP 4 )

setlocale -- Set locale information

Description

string setlocale ( mixed category, string locale [, string ...])

string setlocale ( mixed category, array locale)

Category is a named constant (or string) 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()

If locale is 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 NULL or "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.

Megjegyzés: Passing multiple locales is not available before PHP 4.3.0

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

Megjegyzés: The return value of setlocale() depends on the system that PHP is running. It returns exactly what the system setlocale function returns.

Tipp: Windows users will find useful information about locale strings at Microsoft's MSDNwebsite. Supported language strings can be found at http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_crt_language_strings.asp and supported country/region strings at http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_crt_country_strings.asp. Windows systems support the three letter codes for country/region specified by ISO 3166-Alpha-3, which can be found at this Unicode website .

Példa 1. setlocale() Examples

<?php
/* Set locale to Dutch */
setlocale(LC_ALL, 'nl_NL');

/* Output: vrijdag 22 december 1978 */
echo strftime("%A %e %B %Y", mktime(0, 0, 0, 12, 22, 1978));

/* try different possible locale names for german as of PHP 4.3.0 */
$loc_de = setlocale(LC_ALL, 'de_DE@euro', 'de_DE', 'de', 'ge');
echo "Preferred locale for german on this system is '$loc_de'";
?>

Példa 2. setlocale() Examples for Windows

<?php
/* Set locale to Dutch */
setlocale(LC_ALL, 'nld_nld');

/* Output: vrijdag 22 december 1978 */
echo strftime("%A %d %B %Y", mktime(0, 0, 0, 12, 22, 1978));

/* try different possible locale names for german as of PHP 4.3.0 */
$loc_de = setlocale(LC_ALL, 'de_DE@euro', 'de_DE', 'deu_deu');
echo "Preferred locale for german on this system is '$loc_de'";
?>

sha1_file

(PHP 4 >= 4.3.0)

sha1_file -- Calculate the sha1 hash of a file

Description

string sha1_file ( string filename [, bool raw_output])

Calculates the sha1 hash of filename using the US Secure Hash Algorithm 1, and returns that hash. The hash is a 40-character hexadecimal number. Upon failure, FALSE is returned. 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.

Megjegyzés: The optional raw_output parameter was added in PHP 5.0.0 and defaults to FALSE

See also sha1(), crc32(), and md5_file()

sha1

(PHP 4 >= 4.3.0)

sha1 -- Calculate the sha1 hash of a string

Description

string sha1 ( string str [, bool raw_output])

Calculates the sha1 hash of str using the US Secure Hash Algorithm 1, and returns that hash. The hash is a 40-character hexadecimal number. 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.

Megjegyzés: The optional raw_output parameter was added in PHP 5.0.0 and defaults to FALSE

Példa 1. A sha1() example

<?php
$str = 'apple';
                     
if (sha1($str) === 'd0be2dc421be4fcd0172e5afceea3970e2f3d940') {
    echo "Would you like a green or red apple?";
    exit;
}
?>

See also sha1_file(), crc32(), and md5()

similar_text

(PHP 3>= 3.0.7, PHP 4 )

similar_text --  Calculate the similarity between two strings

Description

int similar_text ( string first, string second [, float percent])

This calculates the similarity between two strings as described in Oliver [1993]. Note that this implementation does not use a stack as in Oliver's pseudo code, but recursive calls which may or may not speed up the whole process. Note also that the complexity of this algorithm is O(N**3) where N is the length of the longest string.

By passing a reference as third argument, similar_text() will calculate the similarity in percent for you. It returns the number of matching chars in both strings.

soundex

(PHP 3, PHP 4 )

soundex -- Calculate the soundex key of a string

Description

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.

Példa 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
?>

See also levenshtein(), metaphone(), and similar_text().

sprintf

(PHP 3, PHP 4 )

sprintf -- Return a formatted string

Description

string sprintf ( string format [, mixed args])

Returns a string produced according to the formatting string 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 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.

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

  3. An optional number, a width specifier that says how many characters (minimum) this conversion should result in.

  4. An optional precision specifier that says how many decimal digits should be displayed for floating-point numbers. This option has no effect for other types than float. (Another function useful for formatting numbers is number_format().)

  5. 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.
    u - the argument is treated as an integer, and presented as an unsigned decimal number.
    f - the argument is treated as a float, and presented as a floating-point number.
    o - the argument is treated as an integer, and presented as an octal number.
    s - the argument is treated as and presented as a string.
    x - the argument is treated as an integer and presented as a hexadecimal number (with lowercase letters).
    X - the argument is treated as an integer and presented as a hexadecimal number (with uppercase letters).

As of PHP version 4.0.6 the format string supports argument numbering/swapping. Here is an example:

Példa 1. Argument swapping

<?php
$format = "There are %d monkeys in the %s";
printf($format, $num, $location);
?>
This might 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:

Példa 2. Argument swapping

<?php
$format = "The %s contains %d monkeys";
printf($format, $num, $location);
?>
We now have a problem. The order of the placeholders in the format string does not match the order of the arguments in the code. We would like to leave the code as is and simply indicate in the format string which arguments the placeholders refer to. We would write the format string like this instead:

Példa 3. Argument swapping

<?php
$format = "The %2\$s contains %1\$d monkeys";
printf($format, $num, $location);
?>
An added benefit here is that you can repeat the placeholders without adding more arguments in the code. For example:

Példa 4. Argument swapping

<?php
$format = "The %2\$s contains %1\$d monkeys.
           That's a nice %2\$s full of %1\$d monkeys.";
printf($format, $num, $location);
?>

See also printf(), sscanf(), fscanf(), vsprintf(), and number_format().

Examples

Példa 5. sprintf(): zero-padded integers

<?php
$isodate = sprintf("%04d-%02d-%02d", $year, $month, $day);
?>

Példa 6. 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"
?>

sscanf

(PHP 4 >= 4.0.1)

sscanf --  Parses input from a string according to a format

Description

mixed sscanf ( string str, string format [, string var1])

The function sscanf() is the input analog of printf(). sscanf() reads from the string str and interprets it according to the specified format. If only two parameters were passed to this function, the values parsed will be returned as an array.

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.

Példa 1. sscanf() Example

<?php
// getting the serial number
$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. The optional parameters must be passed by reference.

Példa 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";
?>

See also fscanf(), printf(), and sprintf().

str_ireplace

(PHP 5 CVS only)

str_ireplace --  Case-insensitive version of str_replace().

Description

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 eregi_replace() or preg_replace() with the i modifier.

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.

If search and replace are arrays, then str_ireplace() takes a value from each array and uses them to do 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.

Példa 1. str_ireplace() example

<?php
$bodytag = str_ireplace("%body%", "black", "<body text=%BODY%>");
?>

This function is binary safe.

Megjegyzés: As of PHP 5.0.0 the number of matched and replaced needles will be returned in count which is passed by reference. Prior to PHP 5.0.0 this parameter is not available.

See also: str_replace(), ereg_replace(), preg_replace(), and strtr().

str_pad

(PHP 4 >= 4.0.1)

str_pad --  Pad a string to a certain length with another string

Description

string str_pad ( string input, int pad_length [, string pad_string [, int pad_type]])

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.

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.

If the value of pad_length is negative or less than the length of the input string, no padding takes place.

Példa 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_"
?>

Megjegyzés: The pad_string may be truncated if the required number of padding characters can't be evenly divided by the pad_string's length.

str_repeat

(PHP 4 )

str_repeat -- Repeat a string

Description

string str_repeat ( string input, int multiplier)

Returns input_str repeated multiplier times. multiplier has to be greater than or equal to 0. If the multiplier is set to 0, the function will return an empty string.

Példa 1. str_repeat() example

<?php
echo str_repeat("-=", 10);
?>

This will output "-=-=-=-=-=-=-=-=-=-=".

See also for, str_pad(), and substr_count().

str_replace

(PHP 3>= 3.0.6, PHP 4 )

str_replace --  Replace all occurrences of the search string with the replacement string

Description

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, you should always use this function instead of ereg_replace() or preg_replace().

As of PHP 4.0.5, every parameter in str_replace() can be an array.

Figyelem

In PHP versions prior to 4.3.3 a bug existed when using arrays as both search and replace parameters which caused empty search indexes to be skipped without advancing the internal pointer on the replace array. This has been corrected in PHP 4.3.3, any scripts which relied on this bug should remove empty search values prior to calling this function in order to mimick the original behavior.

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.

If search and replace are arrays, then str_replace() takes a value from each array and uses them to do 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.

Példa 1. 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);

// Use of the count parameter is available as of PHP 5.0.0
$str = str_replace("ll", "", "good golly miss molly!", $count);
echo $count; // 2
?>

Megjegyzés: Ez a függvény "binary-safe", azaz helyesen kezeli a 127-es ASCII kód feletti karaktereket is.

Megjegyzés: As of PHP 5.0.0 the number of matched and replaced needles (search) will be returned in count which is passed by reference. Prior to PHP 5.0.0 this parameter is not available.

See also str_ireplace(), substr_replace(), ereg_replace(), preg_replace(), and strtr().

str_rot13

(PHP 4 >= 4.2.0)

str_rot13 -- Perform the rot13 transform on a string

Description

string str_rot13 ( string str)

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

Példa 1. str_rot13() example

<?php

echo str_rot13('PHP 4.3.0'); // CUC 4.3.0

?>

Megjegyzés: The behaviour of this function was buggy until PHP 4.3.0. Before this, the str was also modified, as if passed by reference.

str_shuffle

(PHP 4 >= 4.3.0)

str_shuffle -- Randomly shuffles a string

Description

string str_shuffle ( string str)

str_shuffle() shuffles a string. One permutation of all possible is created.

Példa 1. str_shuffle() example

<?php
$str = 'abcdef';
$shuffled = str_shuffle($str);

// This will echo something like: bfdaec
echo $shuffled;
?>

See also shuffle() and rand().

str_split

(PHP 5 CVS only)

str_split --  Convert a string to an array

Description

array str_split ( string string [, int split_length])

Converts a string to an array. 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.

Példa 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);

?>

Output may look like:

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
)

Példa 2. Examples related to str_split()

<?php

$str = "Hello Friend";

echo $str{0};  // H
echo $str{8};  // i

// Creates: array('H','e','l','l','o',' ','F','r','i','e','n','d')
$arr1 = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);

?>

See also chunk_split(), preg_split(), split(), count_chars(), str_word_count(), and for.

str_word_count

(PHP 4 >= 4.3.0)

str_word_count --  Return information about words used in a string

Description

mixed str_word_count ( string string [, int format])

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.

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

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.

Példa 1. Example uses for str_word_count()

<?php

$str = "Hello friend, you're
        looking          good today!";

$a   = str_word_count($str, 1);
$b   = str_word_count($str, 2);
$c   = str_word_count($str);

print_r($a);
print_r($b);
echo $c;
?>

Output may look like:

Array
(
    [0] => Hello
    [1] => friend
    [2] => you're
    [3] => looking
    [4] => good
    [5] => today
)

Array
(
    [0] => Hello
    [6] => friend
    [14] => you're
    [29] => looking
    [46] => good
    [51] => today
)

6

See also explode(), preg_split(), split(), count_chars(), and substr_count().

strcasecmp

(PHP 3>= 3.0.2, PHP 4 )

strcasecmp --  Binary safe case-insensitive string comparison

Description

int strcasecmp ( string str1, string str2)

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

Példa 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';
}
?>

See also ereg(), strcmp(), substr(), stristr(), strncasecmp(), and strstr().

strchr

strchr -- Alias for strstr()

Description

This function is an alias of strstr().

strcmp

(PHP 3, PHP 4 )

strcmp -- Binary safe string comparison

Description

int strcmp ( string str1, string str2)

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

Note that this comparison is case sensitive.

See also ereg(), strcasecmp(), substr(), stristr(), strncasecmp(), strncmp(), and strstr().

strcoll

(PHP 4 >= 4.0.5)

strcoll -- Locale based string comparison

Description

int strcoll ( string str1, string str2)

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal. strcoll() uses the current locale for doing the comparisons. If the current locale is C or POSIX, this function is equivalent to strcmp().

Note that this comparison is case sensitive, and unlike strcmp() this function is not binary safe.

Megjegyzés: strcoll() was added in PHP 4.0.5, but was not enabled for win32 until 4.2.3.

See also ereg(), strcmp(), strcasecmp(), substr(), stristr(), strncasecmp(), strncmp(), strstr(), and setlocale().

strcspn

(PHP 3>= 3.0.3, PHP 4 )

strcspn --  Find length of initial segment not matching mask

Description

int strcspn ( string str1, string str2)

Returns the length of the initial segment of str1 which does not contain any of the characters in str2.

See also strspn().

strip_tags

(PHP 3>= 3.0.8, PHP 4 )

strip_tags -- Strip HTML and PHP tags from a string

Description

string strip_tags ( string str [, string allowable_tags])

This function tries to return a string with all HTML and PHP tags stripped from a given str. It errors on the side of caution in case of incomplete or bogus tags. It uses the same tag stripping state machine as the fgetss() function.

You can use the optional second parameter to specify tags which should not be stripped.

Megjegyzés: allowable_tags was added in PHP 3.0.13 and PHP 4.0b3. Since PHP 4.3.0, HTML comments are also stripped.

Példa 1. strip_tags() example

<?php
$text = '
<p>Test paragraph.</p>
<!-- Comment -->
Other text';

echo strip_tags($text);

echo "\n\n-------\n";

// allow <p>
echo strip_tags($text, '<p>');
?>

The above example will output:

Test paragraph.

Other text

-------

<p>Test paragraph.</p>

Other text

Figyelem

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.

See also htmlspecialchars().

stripcslashes

(PHP 4 )

stripcslashes --  Un-quote string quoted with addcslashes()

Description

string stripcslashes ( string str)

Returns a string with backslashes stripped off. Recognizes C-like \n, \r ..., octal and hexadecimal representation.

See also addcslashes().

stripos

(PHP 5 CVS only)

stripos --  Find position of first occurrence of a case-insensitive string

Description

int stripos ( string haystack, string needle [, int offset])

Returns the numeric position of the first occurrence of needle in the haystack string. Unlike strpos(), stripos() is case-insensitive.

Note that the needle may be a string of one or more characters.

If needle is not found, stripos() will return boolean FALSE.

Figyelem

Ez a függvény a logikai típusú FALSE értékkel is visszatérhet, olyan nem logikai típusú értékek mellett, amik szintén FALSE értékként jelenhetnek meg (mint pl. 0 vagy ""). Olvasd el a Logikai típusról szóló részt további információkért. Használd a === operátort a visszatérési érték ellenőrzésére.

Példa 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";
}
?>

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.

The optional offset parameter allows you to specify which character in haystack to start searching. The position returned is still relative to the the beginning of haystack.

See also strpos(), strrpos(), strrchr(), substr(), stristr(), strstr(), strripos() and str_ireplace().

stripslashes

(PHP 3, PHP 4 )

stripslashes --  Un-quote string quoted with addslashes()

Description

string stripslashes ( string str)

Returns a string with backslashes stripped off. (\' becomes ' and so on.) Double backslashes (\\) are made into a single backslash (\).

An example use of stripslashes() is when the PHP directive magic_quotes_gpc is on (it's on by default), and you aren't inserting this data into a place (such as a database) that requires escaping. For example, if you're simply outputting data straight from an HTML form.

Példa 1. A stripslashes() example

<?php
$str = "Is your name O\'reilly?";

// Outputs: Is your name O'reilly?
echo stripslashes($str);
?>

See also addslashes() and get_magic_quotes_gpc().

stristr

(PHP 3>= 3.0.6, PHP 4 )

stristr --  Case-insensitive strstr()

Description

string stristr ( string haystack, string needle)

Returns all of haystack from the first occurrence of needle to the end. needle and haystack are examined in a case-insensitive manner.

If needle is not found, returns FALSE.

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.

Példa 1. stristr() example

<?php
  $email = 'USER@EXAMPLE.com';
  $domain = stristr($email, 'e');
  echo $domain; 
// outputs ER@EXAMPLE.com
?>

See also strchr(), strrchr(), substr(), and ereg().

strlen

(PHP 3, PHP 4 )

strlen -- Get string length

Description

int strlen ( string str)

Returns the length of string.

Példa 1. A strlen() example

<?php
$str = 'abcdef';
echo strlen($str); // 6

$str = ' ab cd ';
echo strlen($str); // 7
?>

See also count().

strnatcasecmp

(PHP 4 )

strnatcasecmp --  Case insensitive string comparisons using a "natural order" algorithm

Description

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.

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.

See also ereg(), strcasecmp(), substr(), stristr(), strcmp(), strncmp(), strncasecmp(), strnatcmp(), and strstr().

strnatcmp

(PHP 4 )

strnatcmp --  String comparisons using a "natural order" algorithm

Description

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

The code above will generate the following output:

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.

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.

Note that this comparison is case sensitive.

See also ereg(), strcasecmp(), substr(), stristr(), strcmp(), strncmp(), strncasecmp(), strnatcasecmp(), strstr(), natsort() and natcasesort().

strncasecmp

(PHP 4 >= 4.0.2)

strncasecmp --  Binary safe case-insensitive string comparison of the first n characters

Description

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 (len) from each string to be used in the comparison.

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

See also ereg(), strcasecmp(), strcmp(), substr(), stristr(), and strstr().

strncmp

(PHP 4 )

strncmp --  Binary safe string comparison of the first n characters

Description

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 (len) from each string to be used in the comparison.

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

Note that this comparison is case sensitive.

See also ereg(), strncasecmp(), strcasecmp(), substr(), stristr(), strcmp(), and strstr().

strpos

(PHP 3, PHP 4 )

strpos --  Find position of first occurrence of a string

Description

int strpos ( string haystack, string needle [, int offset])

Returns the numeric position of the first occurrence of needle in the haystack string. Unlike the strrpos(), this function can take a full string as the needle parameter and the entire string will be used.

If needle is not found, strpos() will return boolean FALSE.

Figyelem

Ez a függvény a logikai típusú FALSE értékkel is visszatérhet, olyan nem logikai típusú értékek mellett, amik szintén FALSE értékként jelenhetnek meg (mint pl. 0 vagy ""). Olvasd el a Logikai típusról szóló részt további információkért. Használd a === operátort a visszatérési érték ellenőrzésére.

Példa 1. strpos() examples

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

// We can search for the character, ignoring anything before the offset
$newstring = 'abcdef abcdef';
$pos = strpos($newstring, 'a', 1); // $pos = 7, not 0
?>

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.

The optional offset parameter allows you to specify which character in haystack to start searching. The position returned is still relative to the the beginning of haystack.

See also strrpos(), stripos(), strripos(), strrchr(), substr(), stristr(), and strstr().

strrchr

(PHP 3, PHP 4 )

strrchr --  Find the last occurrence of a character in a string

Description

string strrchr ( string haystack, char needle)

This function returns the portion of haystack which starts at the last occurrence of needle and goes until the end of haystack.

Returns FALSE if needle is not found.

If needle contains more than one character, only the first is used. This behavior is different from that of strchr().

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.

Példa 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 );
?>

See also strchr(), substr(), stristr(), and strstr().

strrev

(PHP 3, PHP 4 )

strrev -- Reverse a string

Description

string strrev ( string string)

Returns string, reversed.

Példa 1. Reversing a string with strrev()

<?php
echo strrev("Hello world!"); // outputs "!dlrow olleH"
?>

strripos

(PHP 5 CVS only)

strripos --  Find position of last occurrence of a case-insensitive string in a string

Description

int strripos ( string haystack, string needle [, int offset])

Returns the numeric position of the last occurrence of needle in the haystack string. Unlike strrpos(), strripos() is case-insensitive. Also note that string positions start at 0, and not 1.

Note that the needle may be a string of one or more characters.

If needle is not found, FALSE is returned.

Figyelem

Ez a függvény a logikai típusú FALSE értékkel is visszatérhet, olyan nem logikai típusú értékek mellett, amik szintén FALSE értékként jelenhetnek meg (mint pl. 0 vagy ""). Olvasd el a Logikai típusról szóló részt további információkért. Használd a === operátort a visszatérési érték ellenőrzésére.

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

Outputs:

Congratulations!
   We found the last (aB) in (ababcd) at position (2)

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.

See also strrpos(), strrchr(), substr(), stripos() and stristr().

strrpos

(PHP 3, PHP 4 )

strrpos --  Find position of last occurrence of a char in a string

Description

int strrpos ( string haystack, string needle [, int offset])

Returns the numeric position of the last occurrence of needle in the haystack string. Note that the needle in this case can only be a single character in PHP 4. If a string is passed as the needle, then only the first character of that string will be used.

If needle is not found, returns FALSE.

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

// in PHP 4.0b3 and newer:
$pos = strrpos($mystring, "b");
if ($pos === false) { // note: three equal signs
    // not found...
}

// in versions older than 4.0b3:
$pos = strrpos($mystring, "b");
if (is_bool($pos) && !$pos) {
    // not found...
}
?>

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.

Megjegyzés: As of PHP 5.0.0 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.

Megjegyzés: The needle may be a string of more than one character as of PHP 5.0.0.

See also strpos(), strripos(), strrchr(), substr(), stristr(), and strstr().

strspn

(PHP 3>= 3.0.3, PHP 4 )

strspn --  Find length of initial segment matching mask

Description

int strspn ( string str1, string str2)

Returns the length of the initial segment of str1 which consists entirely of characters in str2.

The line of code:

<?php
$var = strspn("42 is the answer, what is the question ...", "1234567890");
?>

will assign 2 to $var, because the string "42" will be the longest segment containing characters from "1234567890".

See also strcspn().

strstr

(PHP 3, PHP 4 )

strstr -- Find first occurrence of a string

Description

string strstr ( string haystack, string needle)

Returns part of haystack string from the first occurrence of needle to the end of haystack.

If needle is not found, returns FALSE.

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.

Megjegyzés: This function is case-sensitive. For case-insensitive searches, use stristr().

Példa 1. strstr() example

<?php
$email = 'user@example.com';
$domain = strstr($email, '@');
echo $domain; // prints @example.com
?>

Megjegyzés: If you only want to determine if a particular needle occurs within haystack, use the faster and less memory intensive function strpos() instead.

See also ereg(), preg_match(), strchr(), stristr(), strpos(), strrchr(), and substr().

strtok

(PHP 3, PHP 4 )

strtok -- Tokenize string

Description

string strtok ( string arg1, string arg2)

strtok() splits a string (arg1) into smaller strings (tokens), with each token being delimited by any character from arg2. 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.

Példa 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) {
    echo "Word=$tok<br />";
    $tok = strtok(" \n\t");
}
?>

Note that only the first call to strtok uses the string argument. Every subsequent call to strtok only needs the token to use, as it keeps track of where it is in the current string. To start over, or to tokenize a new string you simply call strtok with the string argument again to initialize it. Note that you may put multiple tokens in the token parameter. The string will be tokenized when any one of the characters in the argument are found.

The behavior when an empty part was found changed with PHP 4.1.0. The old behavior returned an empty string, while the new, correct, behavior simply skips the part of the string:

Példa 2. Old strtok() behavior

<?php
$first_token  = strtok('/something', '/');
$second_token = strtok('/');
var_dump($first_token, $second_token);
?>

Output:

string(0) ""
    string(9) "something"

Példa 3. New strtok() behavior

<?php
$first_token  = strtok('/something', '/');
$second_token = strtok('/');
var_dump($first_token, $second_token);
?>

Output:

string(9) "something"
    bool(false)

Also be careful that your tokens may be equal to "0". This evaluates to FALSE in conditional expressions.

See also split() and explode().

strtolower

(PHP 3, PHP 4 )

strtolower -- Make a string lowercase

Description

string strtolower ( string str)

Returns string with all alphabetic characters converted to lowercase.

Note that 'alphabetic' is determined by the current locale. This means that in i.e. the default "C" locale, characters such as umlaut-A (Ä) will not be converted.

Példa 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
?>

See also strtoupper(), ucfirst(), and ucwords().

strtoupper

(PHP 3, PHP 4 )

strtoupper -- Make a string uppercase

Description

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.

Példa 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
?>

See also strtolower(), ucfirst(), and ucwords().

strtr

(PHP 3, PHP 4 )

strtr -- Translate certain characters

Description

string strtr ( string str, string from, string to)

string strtr ( string str, array replace_pairs)

This function returns a copy of str, translating all occurrences of each character in from to the corresponding character in to and returning the result.

If from and to are different lengths, the extra characters in the longer of the two are ignored.

Példa 1. strtr() example

<?php
$addr = strtr($addr, "äĺö", "aao");
?>

strtr() may be called with only two arguments. If called with two arguments it behaves in a new way: from then has to be an array that contains string -> string pairs that will be replaced in the source string. strtr() will always look for the longest possible match first and will *NOT* try to replace stuff that it has already worked on.

Példa 2. strtr() example with two arguments

<?php
$trans = array("hello" => "hi", "hi" => "hello");
echo strtr("hi all, I said hello", $trans);
?>

This will show:

hello all, I said hi

Megjegyzés: This optional to and from parameters were added in PHP 4.0.0

See also ereg_replace().

substr_compare

(no version information, might be only in CVS)

substr_compare --  Binary safe optionally case insensitive comparison of 2 strings from an offset, up to length characters

Description

int substr_compare ( string main_str, string str, int offset [, int length [, bool case_sensitivity]])

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

substr_count

(PHP 4 )

substr_count -- Count the number of substring occurrences

Description

int substr_count ( string haystack, string needle)

substr_count() returns the number of times the needle substring occurs in the haystack string.

Példa 1. substr_count() example

<?php
echo substr_count("This is a test", "is"); // prints out 2
?>

See also count_chars(), strpos(), substr(), and strstr().

substr_replace

(PHP 4 )

substr_replace -- Replace text within a portion of a string

Description

string substr_replace ( string string, string replacement, int start [, int length])

substr_replace() replaces a copy of string delimited by the start and (optionally) length parameters with the string given in replacement. The result is returned.

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.

If length is 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.

Példa 1. substr_replace() example

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

See also str_replace() and substr().

substr

(PHP 3, PHP 4 )

substr -- Return part of a string

Description

string substr ( string string, int start [, int length])

substr() returns the portion of string specified by the start and length parameters.

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.

Példa 1. Basic substr() usage

<?php
$rest = substr("abcdef", 1);    // returns "bcdef"
$rest = substr("abcdef", 1, 3); // returns "bcd"
$rest = substr("abcdef", 0, 4); // returns "abcd"
$rest = substr("abcdef", 0, 8); // returns "abcdef"

// Accessing via curly braces is another option
$string = 'abcdef';
echo $string{0};                // returns a
echo $string{3};                // returns d
?>

If start is negative, the returned string will start at the start'th character from the end of string.

Példa 2. Using a negative start

<?php
$rest = substr("abcdef", -1);    // returns "f"
$rest = substr("abcdef", -2);    // returns "ef"
$rest = substr("abcdef", -3, 1); // returns "d"
?>

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 string is less than start characters long, FALSE will be returned.

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 a position beyond this truncation, an empty string will be returned.

Példa 3. 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 ""
$rest = substr("abcdef", -3, -1); // returns "de"
?>

See also strrchr(), substr_replace(), ereg(), and trim().

trim

(PHP 3, PHP 4 )

trim --  Strip whitespace from the beginning and end of a string

Description

string trim ( string str [, string charlist])

Megjegyzés: The optional charlist parameter was added in PHP 4.1.0

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.

You can also specify the characters you want to strip, by means of the charlist parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.

Példa 1. Usage example of trim()

<?php

$text = "\t\tThese are a few words :) ...  ";
$trimmed = trim($text);
// $trimmed = "These are a few words :) ..."
$trimmed = trim($text, " \t.");
// $trimmed = "These are a few words :)"
$clean = trim($binary, "\0x00..\0x1F");
// trim the ASCII control characters at the beginning and end of $binary
// (from 0 to 31 inclusive)

?>

See also ltrim() and rtrim().

ucfirst

(PHP 3, PHP 4 )

ucfirst -- Make a string's first character uppercase

Description

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.

Példa 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!
?>

See also strtolower(), strtoupper(), and ucwords().

ucwords

(PHP 3>= 3.0.3, PHP 4 )

ucwords --  Uppercase the first character of each word in a string

Description

string ucwords ( string str)

Returns a string with the first character of each word in str capitalized, if that character is alphabetic.

The definition of a word is any string of characters that is immediately after a whitespace (These are: space, form-feed, newline, carriage return, horizontal tab, and vertical tab).

Példa 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!
?>

See also strtoupper(), strtolower() and ucfirst().

vprintf

(PHP 4 >= 4.1.0)

vprintf -- Output a formatted string

Description

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

See also printf(), sprintf(), vsprintf()

vsprintf

(PHP 4 >= 4.1.0)

vsprintf -- Return a formatted string

Description

string vsprintf ( string format, array args)

Return array values as a formatted string according to format (which is described in the documentation for sprintf()).

Operates as sprintf() but accepts an array of arguments, rather than a variable number of arguments.

See also sprintf() and vprintf()

wordwrap

(PHP 4 >= 4.0.2)

wordwrap --  Wraps a string to a given number of characters using a string break character.

Description

string wordwrap ( string str [, int width [, string break [, boolean cut]]])

Returns a string with str wrapped at the column number specified by the optional width parameter. The line is broken using the (optional) break parameter.

wordwrap() will automatically wrap at column 75 and break using '\n' (newline) if width or break are not given.

If the cut is set to 1, the string is always wrapped at the specified width. So if you have a word that is larger than the given width, it is broken apart. (See second example).

Megjegyzés: The optional cut parameter was added in PHP 4.0.3

Példa 1. wordwrap() example

<?php
$text = "The quick brown fox jumped over the lazy dog.";
$newtext = wordwrap($text, 20, "<br />");

echo "$newtext\n";
?>

This example would display:

The quick brown fox
jumped over the 
lazy dog.

Példa 2. wordwrap() example

<?php
$text = "A very long woooooooooooord.";
$newtext = wordwrap($text, 8, "\n", 1);

echo "$newtext\n";
?>

This example would display:

A very
long
wooooooo
ooooord.

See also nl2br().

CV. Sybase functions

Bevezetés


Követelmények


Telepítés

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.


Futásidejű beállítások

Az alábbi függvények viselkedése befolyásolható a php.ini segítségével.

Táblázat 1. Sybase configuration options

NameDefaultChangeable
sybase.allow_persistent"On"PHP_INI_SYSTEM
sybase.max_persistent"-1"PHP_INI_SYSTEM
sybase.max_links"-1"PHP_INI_SYSTEM
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"Off"PHP_INI_SYSTEM
magic_quotes_sybase"Off"PHP_INI_ALL

Here's a short explanation of the configuration directives.

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.

sybase.compatability_mode boolean

Compatability mode with old versions of PHP 3.0. If on, this will cause PHP to automatically assign types to results according to their Sybase type, instead of treating them all as strings. This compatability mode will probably not stay around forever, so try applying whatever necessary changes to your code, and turn it off.

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.

Megjegyzés: 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.

Táblázat 2. Sybase-CT configuration options

NameDefaultChangeable
sybct.allow_persistent"On"PHP_INI_SYSTEM
sybct.max_persistent"-1"PHP_INI_SYSTEM
sybct.max_links"-1"PHP_INI_SYSTEM
sybct.min_server_severity"10"PHP_INI_ALL
sybct.min_client_severity"10"PHP_INI_ALL
sybct.hostnameNULLPHP_INI_ALL
sybct.deadlock_retry_count"-1"PHP_INI_ALL

Here's a short explanation of the configuration directives.

sybct.allow_persistent boolean

Whether to allow persistent Sybase-CT connections. The default is on.

sybct.max_persistent integer

The maximum number of persistent Sybase-CT connections per process. The default is -1 meaning unlimited.

sybct.max_links integer

The maximum number of Sybase-CT connections per process, including persistent connections. The default is -1 meaning unlimited.

sybct.min_server_severity integer

Server messages with severity greater than or equal to sybct.min_server_severity will be reported as warnings. This value can also be set from a script by calling sybase_min_server_severity(). The default is 10 which reports errors of information severity or greater.

sybct.min_client_severity integer

Client library messages with severity greater than or equal to sybct.min_client_severity will be reported as warnings. This value can also be set from a script by calling sybase_min_client_severity(). The default is 10 which effectively disables reporting.

sybct.hostname string

The name of the host you claim to be connecting from, for display by sp_who. The default is none.

sybct.deadlock_retry_count int

Allows you to to define how often deadlocks are to be retried. The default is -1, or "forever".

For further details and definition of the PHP_INI_* constants see ini_set().


Erőforrás típusok


Előre definiált állandók

Ez a kiterjesztés semmilyen konstans értéket nem definiál.

Tartalom
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

sybase_affected_rows

(PHP 3>= 3.0.6, PHP 4 )

sybase_affected_rows -- Gets number of affected rows in last query

Description

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. If the link identifier isn't specified, the last opened link is assumed.

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

The above example would produce the following output:

Records deleted: 10

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

Megjegyzés: This function is only available using the CT library interface to Sybase, and not the DB library.

See also sybase_num_rows().

sybase_close

(PHP 3, PHP 4 )

sybase_close -- Closes a Sybase connection

Description

bool sybase_close ( [resource link_identifier])

sybase_close() closes the link to a Sybase database that's associated with the specified link link_identifier. If the link identifier isn't specified, the last opened link is assumed.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

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

See also sybase_connect() and sybase_pconnect().

sybase_connect

(PHP 3, PHP 4 )

sybase_connect -- Opens a Sybase server connection

Description

resource sybase_connect ( [string servername [, string username [, string password [, string charset [, string appname]]]]])

Returns a positive Sybase link identifier on success, or FALSE on failure.

sybase_connect() establishes a connection to a Sybase server. The servername argument has to be a valid servername that is defined in the 'interfaces' file.

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

Példa 1. sybase_connect() example

<?php
    $link = sybase_connect('SYBASE', '', '')
            or die("Could not connect !");
    echo "Connected successfully";
    sybase_close($link);
?>

See also sybase_pconnect() and sybase_close().

sybase_data_seek

(PHP 3, PHP 4 )

sybase_data_seek -- Moves internal row pointer

Description

bool sybase_data_seek ( resource result_identifier, int row_number)

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

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.

See also sybase_fetch_row().

sybase_deadlock_retry_count

(PHP 4 >= 4.3.0)

sybase_deadlock_retry_count -- Sets the deadlock retry count

Description

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.

Táblázat 1. Values for retry_count

-1Retry forever (default)
0Do not retry
nRetry n times

Megjegyzés: This function is only available using the CT library interface to Sybase, and not the DB library.

sybase_fetch_array

(PHP 3, PHP 4 )

sybase_fetch_array -- Fetch row as array

Description

array sybase_fetch_array ( resource result)

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

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.

Megjegyzés: 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.

Példa 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)
}

See also sybase_fetch_row(), sybase_fetch_assoc() and sybase_fetch_object().

sybase_fetch_assoc

(PHP 4 >= 4.3.0)

sybase_fetch_assoc -- Fetch a result row as an associative array

Description

array sybase_fetch_assoc ( resource result)

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

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.

See also sybase_fetch_array(), sybase_fetch_object() and sybase_fetch_row().

sybase_fetch_field

(PHP 3, PHP 4 )

sybase_fetch_field -- Get field information from a result

Description

object sybase_fetch_field ( resource result [, int field_offset])

Returns an object containing field information.

sybase_fetch_field() can be used in order to obtain information about fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by sybase_fetch_field() is retrieved.

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

See also sybase_field_seek().

sybase_fetch_object

(PHP 3, PHP 4 )

sybase_fetch_object -- Fetch a row as an object

Description

object sybase_fetch_object ( resource result [, mixed object])

Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows.

sybase_fetch_object() is similar to sybase_fetch_assoc(), with one difference - an object is returned, instead of an array.

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.

Megjegyzés: As of PHP 4.3.0, this function will no longer return numeric object members.

Old behaviour:
object(stdclass)(3) {
  [0]=>
  string(3) "foo"
  ["foo"]=>
  string(3) "foo"
  [1]=>
  string(3) "bar"
  ["bar"]=>
  string(3) "bar"
}
New behaviour:
object(stdclass)(3) {
  ["foo"]=>
  string(3) "foo"
  ["bar"]=>
  string(3) "bar"
}

Példa 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());
    // {...]
?>

Speed-wise, the function is identical to sybase_fetch_array(), and almost as quick as sybase_fetch_row() (the difference is insignificant).

See also sybase_fetch_array() and sybase_fetch_row().

sybase_fetch_row

(PHP 3, PHP 4 )

sybase_fetch_row -- Get a result row as an enumerated array

Description

array sybase_fetch_row ( resource result)

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

sybase_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 sybase_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.

Táblázat 1. Data types

PHPSybase
stringVARCHAR, TEXT, CHAR, IMAGE, BINARY, VARBINARY, DATETIME
intNUMERIC (w/o precision), DECIMAL (w/o precision), INT, BIT, TINYINT, SMALLINT
floatNUMERIC (w/ precision), DECIMAL (w/ precision), REAL, FLOAT, MONEY
NULLNULL

See also sybase_fetch_array(), sybase_fetch_assoc(), sybase_fetch_object(), sybase_data_seek() and sybase_result().

sybase_field_seek

(PHP 3, PHP 4 )

sybase_field_seek -- Sets field offset

Description

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.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

See also sybase_fetch_field().

sybase_free_result

(PHP 3, PHP 4 )

sybase_free_result -- Frees result memory

Description

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.

sybase_get_last_message

(PHP 3, PHP 4 )

sybase_get_last_message -- Returns the last message from the server

Description

string sybase_get_last_message ( void )

sybase_get_last_message() returns the last message reported by the server.

See also sybase_min_message_severity().

sybase_min_client_severity

(PHP 3, PHP 4 )

sybase_min_client_severity -- Sets minimum client severity

Description

void sybase_min_client_severity ( int severity)

sybase_min_client_severity() sets the minimum client severity level.

Megjegyzés: This function is only available using the CT library interface to Sybase, and not the DB library.

See also sybase_min_server_severity().

sybase_min_error_severity

(PHP 3, PHP 4 )

sybase_min_error_severity -- Sets minimum error severity

Description

void sybase_min_error_severity ( int severity)

sybase_min_error_severity() sets the minimum error severity level.

See also sybase_min_message_severity().

sybase_min_message_severity

(PHP 3, PHP 4 )

sybase_min_message_severity -- Sets minimum message severity

Description

void sybase_min_message_severity ( int severity)

sybase_min_message_severity() sets the minimum message severity level.

See also sybase_min_error_severity().

sybase_min_server_severity

(PHP 3, PHP 4 )

sybase_min_server_severity -- Sets minimum server severity

Description

void sybase_min_server_severity ( int severity)

sybase_min_server_severity() sets the minimum server severity level.

Megjegyzés: This function is only available using the CT library interface to Sybase, and not the DB library.

See also sybase_min_client_severity().

sybase_num_fields

(PHP 3, PHP 4 )

sybase_num_fields -- Gets the number of fields in a result set

Description

int sybase_num_fields ( resource result)

sybase_num_fields() returns the number of fields in a result set.

See also sybase_query(), sybase_fetch_field() and sybase_num_rows().

sybase_num_rows

(PHP 3, PHP 4 )

sybase_num_rows -- Get number of rows in a result set

Description

int sybase_num_rows ( resource result)

sybase_num_rows() returns the number of rows in a result set.

See also sybase_num_fields(), sybase_query() and sybase_fetch_row().

sybase_pconnect

(PHP 3, PHP 4 )

sybase_pconnect -- Open persistent Sybase connection

Description

resource sybase_pconnect ( [string servername [, string username [, string password [, string charset [, string appname]]]]])

Returns a positive Sybase persistent link identifier on success, or FALSE on error.

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

See also sybase_connect().

sybase_query

(PHP 3, PHP 4 )

sybase_query -- Sends a Sybase query

Description

resource sybase_query ( string query, resource link_identifier)

Returns a positive Sybase result identifier on success, or FALSE on error.

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

See also sybase_select_db() and sybase_connect().

sybase_result

(PHP 3, PHP 4 )

sybase_result -- Get result data

Description

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.

sybase_result() returns the contents of one cell from a Sybase result set. 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.

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

sybase_select_db

(PHP 3, PHP 4 )

sybase_select_db -- Selects a Sybase database

Description

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

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Every subsequent call to sybase_query() will be made on the active database.

See also sybase_connect(), sybase_pconnect() and sybase_query()

sybase_set_message_handler

(PHP 4 >= 4.3.0)

sybase_set_message_handler -- Sets the handler called when a server message is raised

Description

bool sybase_set_message_handler ( callback handler)

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.

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.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

Példa 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');
?>

Példa 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'));
?>

Példa 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');
?>

sybase_unbuffered_query

(PHP 4 >= 4.3.0)

sybase_unbuffered_query -- Send a Sybase query and do not block

Description

resource sybase_unbuffered_query ( string query, resource link_identifier)

Returns a positive Sybase result identifier on success, or FALSE on error.

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.

Megjegyzés: 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.

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.

Példa 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[0];
               if ($i++ > 40000) break;
       }
       sybase_free_result($q);
       sybase_close($dbh);
?>

CVI. Tidy Functions

Bevezetés

Tidy is a binding for the Tidy HTML clean and repair utility which allows you to not only clean and otherwise manipluate HTML documents, but also traverse the document tree.


Követelmények

To use Tidy, you will need libtidy installed, available on the tidy homepage http://tidy.sourceforge.net/.


Telepítés

Tidy is currently available for PHP 4.3.x and PHP 5 as a PECL extension from http://pecl.php.net/package/tidy.

Megjegyzés: Tidy 1.0 is just for PHP 4.3.x, while Tidy 2.0 is just for PHP 5.

If PEAR is available on your *nix-like system you can use the pear installer to install the tidy extension, by the following command: pear -v install tidy.

You can always download the tar.gz package and install tidy by hand:

Példa 1. tidy install by hand

gunzip tidy-xxx.tgz
tar -xvf tidy-xxx.tar
cd tidy-xxx
phpize
./configure && make && make install

Windows users can download the extension dll php_tidy.dll from http://snaps.php.net/win32/PECL_STABLE/.


Futásidejű beállítások

Az alábbi függvények viselkedése befolyásolható a php.ini segítségével.

Táblázat 1. Tidy Configuration Options

NameDefaultChangeableFunction
tidy.default_config""PHP_INI_SYSTEMdefault path for tidy config file
tidy.clean_output0PHP_INI_PERDIRturns on/off the output repairing by Tidy
For further details and definition of the PHP_INI_* constants see ini_set().

Figyelem

Do not turn on tidy.clean_output if you are generating non-html content such as dynamic images.


Erőforrás típusok

Ez a kiterjesztés semmilyen erőforrás típust nem definiál.


Előre definiált állandók

Az itt listázott állandókat ez a kiterjesztés definiálja, és csak akkor elérhetőek, ha az adott kiterjesztés be van fordítva a PHP-be, vagy dinamikusan betöltött.

The following constants are defined:

Táblázat 2. tidy tag constants

constantdescription
TIDY_TAG_UNKNOWN 
TIDY_TAG_A 
TIDY_TAG_ABBR 
TIDY_TAG_ACRONYM 
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_6 
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_NOSAFE 
TIDY_TAG_NOSCRIPT 
TIDY_TAG_OBJECT 
TIDY_TAG_OL 
TIDY_TAG_OPTGROUP 
TIDY_TAG_OPTION 
TIDY_TAG_P 
TIDY_TAG_PARAM 
TIDY_TAG_PLAINTEXT 
TIDY_TAG_PRE 
TIDY_TAG_Q 
TIDY_TAG_RP 
TIDY_TAG_RT 
TIDY_TAG_RTC 
TIDY_TAG_RUBY 
TIDY_TAG_S 
TIDY_TAG_SAMP 
TIDY_TAG_SCRIPT 
TIDY_TAG_SELECT 
TIDY_TAG_SERVER 
TIDY_TAG_SERVLET 
TIDY_TAG_SMALL 
TIDY_TAG_SPACER 
TIDY_TAG_SPAN 
TIDY_TAG_STRIKE 
TIDY_TAG_STRONG 
TIDY_TAG_STYLE 
TIDY_TAG_SUB 
TIDY_TAG_TABLE 
TIDY_TAG_TBODY 
TIDY_TAG_TD 
TIDY_TAG_TEXTAREA 
TIDY_TAG_TFOOT 
TIDY_TAG_TH 
TIDY_TAG_THEAD 
TIDY_TAG_TITLE 
TIDY_TAG_TR 
TIDY_TAG_TR 
TIDY_TAG_TT 
TIDY_TAG_U 
TIDY_TAG_UL 
TIDY_TAG_VAR 
TIDY_TAG_WBR 
TIDY_TAG_XMP 

Táblázat 3. tidy attribute constants

constantdescription
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 

Táblázat 4. tidy nodetype constants

constantdescription
TIDY_NODETYPE_ROOT 
TIDY_NODETYPE_DOCTYPE 
TIDY_NODETYPE_COMMENT 
TIDY_NODETYPE_PROCINS 
TIDY_NODETYPE_TEXT 
TIDY_NODETYPE_START 
TIDY_NODETYPE_END 
TIDY_NODETYPE_STARTEND 
TIDY_NODETYPE_CDATA 
TIDY_NODETYPE_SECTION 
TIDY_NODETYPE_ASP 
TIDY_NODETYPE_JSTE 
TIDY_NODETYPE_PHP 
TIDY_NODETYPE_XMLDECL 

Tartalom
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_clean_repair --  Execute configured cleanup and repair operations on parsed markup
tidy_config_count --  Returns the Number of Tidy configuration errors encountered for specified document.
tidy_diagnose --  Run configured diagnostics on parsed and repaired markup.
tidy_error_count --  Returns the Number of Tidy errors encountered for specified document.
tidy_get_body --  Returns a TidyNode Object starting from the <body> tag of the tidy parse tree
tidy_get_config --  Get current Tidy configuration
tidy_get_error_buffer --  Return warnings and errors which occurred parsing the specified document
tidy_get_head --  Returns a TidyNode Object starting from the <head> tag of the tidy parse tree
tidy_get_html_ver --  Get the Detected HTML version for the specified document.
tidy_get_html --  Returns a TidyNode Object starting from the <html> tag of the tidy parse tree
tidy_get_output --  Return a string representing the parsed tidy markup
tidy_get_release --  Get release date (version) for Tidy library
tidy_get_root --  Returns a TidyNode Object representing the root of the tidy parse tree
tidy_get_status --  Get status of specified document.
tidy_getopt --  Returns the value of the specified configuration option for the tidy document.
tidy_is_xhtml --  Indicates if the document is a XHTML document.
tidy_is_xml --  Indicates if the document is a generic (non HTML/XHTML) XML document.
tidy_load_config --  Load an ASCII Tidy configuration file with the specified encoding
tidy_node->attributes --  Returns an array of attribute objects for node
tidy_node->children --  Returns an array of child nodes
tidy_node->get_attr --  Return the attribute with the provided attribute id
tidy_node->get_nodes --  Return an array of nodes under this node with the specified id
tidy_node->has_children --  Returns true if this node has children
tidy_node->has_siblings --  Returns true if this node has siblings
tidy_node->is_asp --  Returns true if this node is ASP
tidy_node->is_comment --  Returns true if this node represents a comment
tidy_node->is_html --  Returns true if this node is part of a HTML document
tidy_node->is_jsp --  Returns true if this node is JSP
tidy_node->is_jste --  Returns true if this node is JSTE
tidy_node->is_text --  Returns true if this node represents text (no markup)
tidy_node->is_xhtml --  Returns true if this node is part of a XHTML document
tidy_node->is_xml --  Returns true if this node is part of a XML document
tidy_node->next --  Returns the next sibling to this node
tidy_node->prev --  Returns the previous sibling to this node
tidy_node->tidy_node --  Constructor.
tidy_parse_file --  Parse markup in file or URI
tidy_parse_string --  Parse a document stored in a string
tidy_repair_file --  Repair a file using an optionally provided configuration file
tidy_repair_string --  Repair a string using an optionally provided configuration file
tidy_reset_config --  Restore Tidy configuration to default values
tidy_save_config --  Save current settings to named file. Only non-default values are written.
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.

ob_tidyhandler

(no version information, might be only in CVS)

ob_tidyhandler --  ob_start callback function to repair the buffer

Description

string ob_tidyhandler ( string input [, int mode])

ob_tidyhandler() is intended to be used as a callback function for ob_start() to repair the buffer.

Példa 1. ob_tidyhandler() example

<?php
ob_start('ob_tidyhandler');

echo '<p>test</i>';
?>

The above example will output:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
<head>
<title></title>
</head>
<body>
<p>test</p>
</body>
</html>

See also ob_start().

tidy_access_count

(no version information, might be only in CVS)

tidy_access_count --  Returns the Number of Tidy accessibility warnings encountered for specified document.

Description

int tidy_access_count ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

tidy_clean_repair

(no version information, might be only in CVS)

tidy_clean_repair --  Execute configured cleanup and repair operations on parsed markup

Description

bool tidy_clean_repair ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

tidy_config_count

(no version information, might be only in CVS)

tidy_config_count --  Returns the Number of Tidy configuration errors encountered for specified document.

Description

int tidy_config_count ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

tidy_diagnose

(no version information, might be only in CVS)

tidy_diagnose --  Run configured diagnostics on parsed and repaired markup.

Description

bool tidy_diagnose ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

tidy_error_count

(no version information, might be only in CVS)

tidy_error_count --  Returns the Number of Tidy errors encountered for specified document.

Description

int tidy_error_count ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

tidy_get_body

(no version information, might be only in CVS)

tidy_get_body --  Returns a TidyNode Object starting from the <body> tag of the tidy parse tree

Description

object tidy_get_body ( resource tidy)

This function returns a TidyNode object starting from the <body> tag of the tidy parse tree.

Példa 1. tidy_get_body() example

<?php
$html = '
<html>
  <head>
    <title>test</title>
  </head>
  <body>
    <p>paragraph</p>
  </body>
</html>';

$tidy = tidy_parse_string($html);

$body = tidy_get_body($tidy);
echo $body->value;
?>

The above example will output:

<body>
<p>paragraph</p>
</body>

Megjegyzés: This function is only available with Zend Engine 2, this means PHP >= 5.0.0.

See also tidy_get_head() and tidy_get_html().

tidy_get_config

(no version information, might be only in CVS)

tidy_get_config --  Get current Tidy configuration

Description

array tidy_get_config ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

tidy_get_error_buffer

(no version information, might be only in CVS)

tidy_get_error_buffer --  Return warnings and errors which occurred parsing the specified document

Description

string tidy_get_error_buffer ( [bool detailed])

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

tidy_get_head

(no version information, might be only in CVS)

tidy_get_head --  Returns a TidyNode Object starting from the <head> tag of the tidy parse tree

Description

object tidy_get_head ( resource tidy)

This function returns a TidyNode object starting from the <head> tag of the tidy parse tree.

Példa 1. tidy_get_head() example

<?php
$html = '
<html>
  <head>
    <title>test</title>
  </head>
  <body>
    <p>paragraph</p>
  </body>
</html>';

$tidy = tidy_parse_string($html);

$head = tidy_get_head($tidy);
echo $head->value;
?>

The above example will output:

<head>
<title>test</title>
</head>

Megjegyzés: This function is only available with Zend Engine 2, this means PHP >= 5.0.0.

See also tidy_get_body() and tidy_get_html().

tidy_get_html_ver

(no version information, might be only in CVS)

tidy_get_html_ver --  Get the Detected HTML version for the specified document.

Description

int tidy_get_html_ver ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

tidy_get_html

(no version information, might be only in CVS)

tidy_get_html --  Returns a TidyNode Object starting from the <html> tag of the tidy parse tree

Description

object tidy_get_html ( resource tidy)

This function returns a TidyNode object starting from the <html> tag of the tidy parse tree.

Példa 1. tidy_get_html() example

<?php
$html = '
<html>
  <head>
    <title>test</title>
  </head>
  <body>
    <p>paragraph</p>
  </body>
</html>';

$tidy = tidy_parse_string($html);

$html = tidy_get_html($tidy);
echo $html->value;
?>

The above example will output:

<html>
<head>
<title>test</title>
</head>
<body>
<p>paragraph</p>
</body>
</html>

Megjegyzés: This function is only available with Zend Engine 2, this means PHP >= 5.0.0.

See also tidy_get_body() and tidy_get_head().

tidy_get_output

(no version information, might be only in CVS)

tidy_get_output --  Return a string representing the parsed tidy markup

Description

string tidy_get_output ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

tidy_get_release

(no version information, might be only in CVS)

tidy_get_release --  Get release date (version) for Tidy library

Description

string tidy_get_release ( void )

This function returns a string with the release date of the Tidy library.

tidy_get_root

(no version information, might be only in CVS)

tidy_get_root --  Returns a TidyNode Object representing the root of the tidy parse tree

Description

object tidy_get_root ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

Megjegyzés: This function is only available with Zend Engine 2, this means PHP >= 5.0.0.

tidy_get_status

(no version information, might be only in CVS)

tidy_get_status --  Get status of specified document.

Description

int tidy_get_status ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

tidy_getopt

(no version information, might be only in CVS)

tidy_getopt --  Returns the value of the specified configuration option for the tidy document.

Description

mixed tidy_getopt ( string option)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

tidy_is_xhtml

(no version information, might be only in CVS)

tidy_is_xhtml --  Indicates if the document is a XHTML document.

Description

bool tidy_is_xhtml ( resource tidy)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

tidy_is_xml

(no version information, might be only in CVS)

tidy_is_xml --  Indicates if the document is a generic (non HTML/XHTML) XML document.

Description

bool tidy_is_xml ( resource tidy)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

tidy_load_config

(no version information, might be only in CVS)

tidy_load_config --  Load an ASCII Tidy configuration file with the specified encoding

Description

void tidy_load_config ( string filename, string encoding)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

Megjegyzés: This function is only avaliable in Tidy 1.0. It became obsolete in Tidy 2.0 and thus has been removed.

tidy_node->attributes

(no version information, might be only in CVS)

tidy_node->attributes --  Returns an array of attribute objects for node

Description

array tidy_node->attributes ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

tidy_node->children

(no version information, might be only in CVS)

tidy_node->children --  Returns an array of child nodes

Description

array tidy_node->children ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

tidy_node->get_attr

(no version information, might be only in CVS)

tidy_node->get_attr --  Return the attribute with the provided attribute id

Description

tidy_attr tidy_node->get_attr ( int attrib_id)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

tidy_node->get_nodes

(no version information, might be only in CVS)

tidy_node->get_nodes --  Return an array of nodes under this node with the specified id

Description

array tidy_node->get_nodes ( int node_id)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

tidy_node->has_children

(no version information, might be only in CVS)

tidy_node->has_children --  Returns true if this node has children

Description

bool tidy_node->has_children ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

tidy_node->has_siblings

(no version information, might be only in CVS)

tidy_node->has_siblings --  Returns true if this node has siblings

Description

bool tidy_node->has_siblings ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

tidy_node->is_asp

(no version information, might be only in CVS)

tidy_node->is_asp --  Returns true if this node is ASP

Description

bool tidy_node->is_asp ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

tidy_node->is_comment

(no version information, might be only in CVS)

tidy_node->is_comment --  Returns true if this node represents a comment

Description

bool tidy_node->is_comment ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

tidy_node->is_html

(no version information, might be only in CVS)

tidy_node->is_html --  Returns true if this node is part of a HTML document

Description

bool tidy_node->is_html ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

tidy_node->is_jsp

(no version information, might be only in CVS)

tidy_node->is_jsp --  Returns true if this node is JSP

Description

bool tidy_node->is_jsp ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

tidy_node->is_jste

(no version information, might be only in CVS)

tidy_node->is_jste --  Returns true if this node is JSTE

Description

bool tidy_node->is_jste ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

tidy_node->is_text

(no version information, might be only in CVS)

tidy_node->is_text --  Returns true if this node represents text (no markup)

Description

bool tidy_node->is_text ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

tidy_node->is_xhtml

(no version information, might be only in CVS)

tidy_node->is_xhtml --  Returns true if this node is part of a XHTML document

Description

bool tidy_node->is_xhtml ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

tidy_node->is_xml

(no version information, might be only in CVS)

tidy_node->is_xml --  Returns true if this node is part of a XML document

Description

bool tidy_node->is_xml ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

tidy_node->next

(no version information, might be only in CVS)

tidy_node->next --  Returns the next sibling to this node

Description

tidy_node tidy_node->next ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

tidy_node->prev

(no version information, might be only in CVS)

tidy_node->prev --  Returns the previous sibling to this node

Description

tidy_node tidy_node->prev ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

tidy_node->tidy_node

(no version information, might be only in CVS)

tidy_node->tidy_node --  Constructor.

Description

void tidy_node->tidy_node ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

tidy_parse_file

(no version information, might be only in CVS)

tidy_parse_file --  Parse markup in file or URI

Description

bool tidy_parse_file ( string file [, array config_options [, bool use_include_path]])

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

tidy_parse_string

(no version information, might be only in CVS)

tidy_parse_string --  Parse a document stored in a string

Description

bool tidy_parse_string ( string input)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

tidy_repair_file

(no version information, might be only in CVS)

tidy_repair_file --  Repair a file using an optionally provided configuration file

Description

bool tidy_repair_file ( string filename [, string config_file [, bool use_include_path]])

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

tidy_repair_string

(no version information, might be only in CVS)

tidy_repair_string --  Repair a string using an optionally provided configuration file

Description

bool tidy_repair_string ( string data [, string config_file [, string encoding]])

This function repairs the given string.

Példa 1. tidy_repair_string() example

<?php
ob_start();
?>

<html>
  <head>
    <title>test</title>
  </head>
  <body>
    <p>error</i>
  </body>
</html>

<?php

$buffer = ob_get_clean();
$tidy = tidy_repair_string($buffer);

echo $tidy;
?>

The above example will output:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
<head>
<title>test</title>
</head>
<body>
<p>error</p>
</body>
</html>

See also tidy_parse_file(), tidy_parse_string() and tidy_repair_file().

Megjegyzés: The optional parameters config_options and enconding were added in Tidy 2.0.

tidy_reset_config

(no version information, might be only in CVS)

tidy_reset_config --  Restore Tidy configuration to default values

Description

string tidy_reset_config ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

Megjegyzés: This function is only avaliable in Tidy 1.0. It became obsolete in Tidy 2.0 and thus has been removed.

tidy_save_config

(no version information, might be only in CVS)

tidy_save_config --  Save current settings to named file. Only non-default values are written.

Description

bool tidy_save_config ( string filename)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

Megjegyzés: This function is only avaliable in Tidy 1.0. It became obsolete in Tidy 2.0 and thus has been removed.

tidy_set_encoding

(no version information, might be only in CVS)

tidy_set_encoding --  Set the input/output character encoding for parsing markup.

Description

bool tidy_set_encoding ( string encoding)

Sets the encoding for input/output documents. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad. Possible values for encoding are ascii, latin1, raw, utf8, iso2022, mac, win1252, utf16le, utf16be, utf16, big5, and shiftjis.

Megjegyzés: This function is only avaliable in Tidy 1.0. It became obsolete in Tidy 2.0 and thus has been removed.

tidy_setopt

(no version information, might be only in CVS)

tidy_setopt --  Updates the configuration settings for the specified tidy document.

Description

bool tidy_setopt ( string option, mixed newvalue)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

Megjegyzés: This function is only avaliable in Tidy 1.0. It became obsolete in Tidy 2.0 and thus has been removed.

tidy_warning_count

(no version information, might be only in CVS)

tidy_warning_count --  Returns the Number of Tidy warnings encountered for specified document.

Description

int tidy_warning_count ( void )

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

CVII. Tokenizer functions

Bevezetés

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.


Követelmények

Az itt leírt függvények használatához semmilyen külső függvénykönyvtár megléte nem szükségeltetik.


Telepítés

Beginning with PHP 4.3.0 these functions are enabled by default. For older versions you have to configure and compile PHP with --enable-tokenizer. You can disable tokenizer support with --disable-tokenizer.

A PHP Windowsos változata beépített támogatással rendelkezik eme kiterjesztéshez. nincs szükség semmilyen kiterjesztés betöltésére, hogy az itt felsorolt függvnyeket használhasd.

Megjegyzés: Builtin support for tokenizer is available with PHP 4.3.0.


Előre definiált állandók

Az itt listázott állandókat ez a kiterjesztés definiálja, és csak akkor elérhetőek, ha az adott kiterjesztés be van fordítva a PHP-be, vagy dinamikusan betöltött.

T_INCLUDE (integer)

T_INCLUDE_ONCE (integer)

T_EVAL (integer)

T_REQUIRE (integer)

T_REQUIRE_ONCE (integer)

T_LOGICAL_OR (integer)

T_LOGICAL_XOR (integer)

T_LOGICAL_AND (integer)

T_PRINT (integer)

T_PLUS_EQUAL (integer)

T_MINUS_EQUAL (integer)

T_MUL_EQUAL (integer)

T_DIV_EQUAL (integer)

T_CONCAT_EQUAL (integer)

T_MOD_EQUAL (integer)

T_AND_EQUAL (integer)

T_OR_EQUAL (integer)

T_XOR_EQUAL (integer)

T_SL_EQUAL (integer)

T_SR_EQUAL (integer)

T_BOOLEAN_OR (integer)

T_BOOLEAN_AND (integer)

T_IS_EQUAL (integer)

T_IS_NOT_EQUAL (integer)

T_IS_IDENTICAL (integer)

T_IS_NOT_IDENTICAL (integer)

T_IS_SMALLER_OR_EQUAL (integer)

T_IS_GREATER_OR_EQUAL (integer)

T_SL (integer)

T_SR (integer)

T_INC (integer)

T_DEC (integer)

T_INT_CAST (integer)

T_DOUBLE_CAST (integer)

T_STRING_CAST (integer)

T_ARRAY_CAST (integer)

T_OBJECT_CAST (integer)

T_BOOL_CAST (integer)

T_UNSET_CAST (integer)

T_NEW (integer)

T_EXIT (integer)

T_IF (integer)

T_ELSEIF (integer)

T_ELSE (integer)

T_ENDIF (integer)

T_LNUMBER (integer)

T_DNUMBER (integer)

T_STRING (integer)

T_STRING_VARNAME (integer)

T_VARIABLE (integer)

T_NUM_STRING (integer)

T_INLINE_HTML (integer)

T_CHARACTER (integer)

T_BAD_CHARACTER (integer)

T_ENCAPSED_AND_WHITESPACE (integer)

T_CONSTANT_ENCAPSED_STRING (integer)

T_ECHO (integer)

T_DO (integer)

T_WHILE (integer)

T_ENDWHILE (integer)

T_FOR (integer)

T_ENDFOR (integer)

T_FOREACH (integer)

T_ENDFOREACH (integer)

T_DECLARE (integer)

T_ENDDECLARE (integer)

T_AS (integer)

T_SWITCH (integer)

T_ENDSWITCH (integer)

T_CASE (integer)

T_DEFAULT (integer)

T_BREAK (integer)

T_CONTINUE (integer)

T_OLD_FUNCTION (integer)

T_FUNCTION (integer)

T_CONST (integer)

T_RETURN (integer)

T_USE (integer)

T_GLOBAL (integer)

T_STATIC (integer)

T_VAR (integer)

T_UNSET (integer)

T_ISSET (integer)

T_EMPTY (integer)

T_CLASS (integer)

T_EXTENDS (integer)

T_OBJECT_OPERATOR (integer)

T_DOUBLE_ARROW (integer)

T_LIST (integer)

T_ARRAY (integer)

T_LINE (integer)

T_FILE (integer)

T_COMMENT (integer)

T_ML_COMMENT (integer)

Megjegyzés: T_ML_COMMENT is not defined in PHP 5. All comments in PHP 5 are of token T_COMMENT.

T_DOC_COMMENT (integer)

Megjegyzés: T_DOC_COMMENT was introduced in PHP 5.

T_OPEN_TAG (integer)

T_OPEN_TAG_WITH_ECHO (integer)

T_CLOSE_TAG (integer)

T_WHITESPACE (integer)

T_START_HEREDOC (integer)

T_END_HEREDOC (integer)

T_DOLLAR_OPEN_CURLY_BRACES (integer)

T_CURLY_OPEN (integer)

T_PAAMAYIM_NEKUDOTAYIM (integer)

T_DOUBLE_COLON (integer)


Példák

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.

Példa 1. Strip comments with the tokenizer

<?php
  $source = file_get_contents("somefile.php");
  $tokens = token_get_all($source);
  /* 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 PHP5-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);
  }
  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;
      }
    }
  }
?>
Tartalom
token_get_all -- Split given source into PHP tokens
token_name -- Get the symbolic name of a given PHP token

token_get_all

(PHP 4 >= 4.2.0)

token_get_all -- Split given source into PHP tokens

Description

array token_get_all ( string source)

token_get_all() parses the given source string into PHP language tokens using the Zend engine's lexical scanner. The function returns an array of token identifiers. Each individual token identifier is either a single character (i.e.: ;, ., >, !, etc...), or a two element array containing the token index in element 0, and the string content of the original token in element 1.

For a list of parser tokens, see M Függelék, or use token_name() to translate a token value into its string representation.

Példa 1. token_get_all() examples

<?php
  $tokens = token_get_all('<?php'); // => array(array(T_OPEN_TAG, '<?'));
  $tokens = token_get_all('<?php echo; ?>'); /* => array(
                                                    array(T_OPEN_TAG, '<?php'), 
                                                    array(T_ECHO, 'echo'),
                                                    ';',
                                                    array(T_CLOSE_TAG, '?>') ); */

/* Note in the following example that the string is parsed as T_INLINE_HTML
   rather than the otherwise expected T_COMMENT (T_ML_COMMENT in PHP <5).
   This is because no open/close tags were used in the "code" provided.
   This would be equivalent to putting a comment outside of <?php ?> tags in a normal file. */
  $tokens = token_get_all('/* comment */'); // => array(array(T_INLINE_HTML, '/* comment */'));
?>

token_name

(PHP 4 >= 4.2.0)

token_name -- Get the symbolic name of a given PHP token

Description

string token_name ( int token)

token_name() returns the symbolic name for a PHP token value. The symbolic name returned matches the name of the matching token constant.

Példa 1. token_name() example

<?php
  // 260 is the token value for the T_REQUIRE token
  echo token_name(260);        // -> "T_REQUIRE"

  // a token constant maps to its own name
  echo token_name(T_FUNCTION); // -> "T_FUNCTION"
?>

CVIII. URL függvények

Tartalom
base64_decode -- MIME base64-el kódolt adatot dekódol
base64_encode -- Adatot kódol MIME base64 kódolással
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 -- Feldolgoz egy URL-t, és visszaadja a komponenseit
rawurldecode -- URL-kódolt karakterláncot kódol vissza
rawurlencode -- URL-kódolást végez az RFC1738 szerint
urldecode -- Dekódol egy URL-kódolt karakterláncot
urlencode -- URL-kódol egy karakterláncot

base64_decode

(PHP 3, PHP 4 )

base64_decode -- MIME base64-el kódolt adatot dekódol

Leírás

string base64_decode ( string encoded_data)

A base64_decode() dekódolja az encoded_data paraméterben megadott adatot, és visszaadja az eredeti adatot. A visszaadott adat lehet bináris.

Lásd még: base64_encode(), RFC-2045 6.8. rész.

base64_encode

(PHP 3, PHP 4 )

base64_encode -- Adatot kódol MIME base64 kódolással

Leírás

string base64_encode ( string data)

A base64_encode() visszaadja a data paraméterben megadott adat base64 kódolt alakját. A kódolást úgy tervezték, hogy a bináris adatok is túléljék az olyan közvetítő csatornákat, amelyek nem képesek 8 bites adattovábbításra (pl. mail üzenetek).

A base64-kódolt adat megközelítőleg 33%-kal nagyobb az eredeti méreténél.

Lásd még: base64_decode(), chunk_split(), RFC-2045 6.8 rész.

get_meta_tags

(PHP 3>= 3.0.4, PHP 4 )

get_meta_tags --  Extracts all meta tag content attributes from a file and returns an array

Description

array get_meta_tags ( string filename [, int use_include_path])

Opens filename and parses it line by line for <meta> tags in the file. This can be a local file or an URL. The parsing stops at </head>.

Setting use_include_path to 1 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.

Példa 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).

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.

Példa 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
?>

Megjegyzés: As of PHP 4.0.5, get_meta_tags() supports unquoted HTML attributes.

See also htmlentities() and urlencode().

http_build_query

(no version information, might be only in CVS)

http_build_query -- Generate URL-encoded query string

Description

string http_build_query ( array formdata [, string numeric_prefix])

Generates a URL-encoded query string from the associative (or indexed) array provided. formdata may be an array or object containing properties. A formdata array may be a simple one-dimensional structure, or an array of arrays (who in turn may contain other arrays). If numeric indices are used in the base array and a numeric_prefix is provided, it will be prepended to the numeric index for elements in the base array only. This is to allow for legal variable names when the data is decoded by PHP or another CGI application later on.

Példa 1. Simple usage of http_build_query()

<?php
$data = array('foo'=>'bar',
              'baz'=>'boom',
              'cow'=>'milk',
              'php'=>'hypertext processor');
              
echo http_build_query($data);
/* Outputs:
      foo=bar&baz=boom&cow=milk&php=hypertext+processor
 */
?>

Példa 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);
/* Outputs:
      0=foo&1=bar&2=baz&3=boom&cow=milk&php=hypertext+processor
 */
 
echo http_build_query($data, 'myvar_');
/* Outputs:
      myvar_0=foo&myvar_1=bar&myvar_2=baz&myvar_3=boom&cow=milk&php=hypertext+processor
 */
?>

Példa 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[name]=Bob+Smith&user[age]=47&user[sex]=M&user[dob]=5%1F12%1F1956&
pastimes[0]=golf&pastimes[1]=opera&pastimes[2]=poker&pastimes[3]=rap&
children[bobby][age]=12&children[bobby][sex]=M&children[sally][age]=8&
children[sally][sex]=F&flags_0=CEO

Megjegyzés: 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.

Példa 4. Using http_build_query() with an object

<?php
class myClass {
  var $foo;
  var $baz;
  
  function myClass() 
  {
    $this->foo = 'bar';
    $this->baz = 'boom';
  }
}

$data = new myClass();

echo http_build_query($data);
/* Outputs:
      foo=bar&baz=boom
 */
?>

See also: parse_str(), parse_url(), urlencode(), and array_walk()

parse_url

(PHP 3, PHP 4 )

parse_url -- Feldolgoz egy URL-t, és visszaadja a komponenseit

Leírás

array parse_url ( string url)

Ez a függvény olyan asszociatív tömböt ad vissza, amely tartalmazza az alábbi elemek közül azokat, amelyek az url részei:

  • scheme - pl.: http://

  • host

  • port

  • user

  • pass

  • path

  • query - ? utáni rész

  • fragment - # utáni rész

Lásd még: pathinfo()!

rawurldecode

(PHP 3, PHP 4 )

rawurldecode -- URL-kódolt karakterláncot kódol vissza

Leírás

string rawurldecode ( string str)

A str-ben megadott sztringet visszakódolja úgy, hogy minden százalékjelet (%) és utána álló két hexadecimális számjegyet a megjelölt sorszámú karakterrel cserél fel. Például a
foo%20bar%40baz
karaktersorozatból
foo bar@baz
lesz.

Megjegyzés: rawurldecode() nem cseréli le a plusz jelet ('+') szóközzé, amint azt az urldecode() teszi.

Lásd még: rawurlencode(), urldecode() és urlencode()!

rawurlencode

(PHP 3, PHP 4 )

rawurlencode -- URL-kódolást végez az RFC1738 szerint

Leírás

string rawurlencode ( string str)

Olyan stringgel tér vissza, amelyben az str nem alfanumerikus karakterei - kivéve a
-_.
karaktereket - egy szézalékjelre (%) és azt követő két hexadecimális számjegyre lesz lecserélve. Ez az RFC1738-ben leírt kódolásnak megfelelő, amely feloldja a speciális karakterek az URL-ekben történő használatát nehezítő problémát, illetve a közvetítő média által végrehajtott kódolás okozta hibákat kiküszöböli. Ha egy jelszót kell például elhelyezni egy FTP URL-ben:

Példa 1. Első rawurlencode() példa

echo '<a href="ftp://user:', rawurlencode ('foo @+%/'),
     '@ftp.domain.hu/titkos.txt">';
Előfordulhat azonban, hogy az URL PATH_INFO komponensében kell adatot átadni:

Példa 2. Második rawurlencode() példa

echo '<a href="http://domain.hu/kirendeltsegek_listazo/',
    rawurlencode ('kereskedelmi és marketing/Pécs'), '">';

Lásd még: rawurldecode(), urlencode() és urldecode()!

urldecode

(PHP 3, PHP 4 )

urldecode -- Dekódol egy URL-kódolt karakterláncot

Leírás

string urldecode ( string str)

Dekódol bármilyen %## kódolást a megadott karakterláncban. A dekódolt szöveget adja vissza.

Példa 1. urldecode() példa

$a = split('&', $querystring);
$i = 0;
while ($i < count($a)) {
    $b = split('=', $a[$i]);
    echo 'A(z) ', htmlspecialchars(urldecode($b[0])),
         ' paraméter értéke ', htmlspecialchars(urldecode($b[1])), "<br>";
    $i++;
}

Lásd még: urlencode()!

urlencode

(PHP 3, PHP 4 )

urlencode -- URL-kódol egy karakterláncot

Leírás

string urlencode ( string str)

Visszaad egy karakterláncot, amiben minden nem alfanumerikus karakter, kivéve a -_. karaktereket, százalék jelre (%) és két hexa számra cserélt, és a szóközök helyén plusz jelek (+) állnak. Ez az a kódolási forma, amivel a kérdőívekkel küldött adatok a weben közlekednek, azaz az application/x-www-form-urlencoded média típus. Ez annyiban különbözik az RFC1738 kódolástól (rawurlencode()), hogy történelmi okok miatt a szóközök itt plusz (+) jelekké alakulnak. Ez a függvény kényelmes lehetőséget ad arra, hogy az URL kérdőjel utáni részébe írjunk, változókat átadva a következő oldalnak:

Példa 1. urlencode() példa

echo '<a href="ujoldal.php?ize=', urlencode($valtozo), '">';

Figyelem: Vigyázz az olyan változókkal, amelyek neve HTML entitások nevével kezdődik. Az olyan karaktersorozatokat, mint &amp, &copy és &pound a böngészők lecserélik a megfelelő entitásra, és nem a várt eredményt kapod. Ez egy nyilvánvaló probléma, amire a W3C már évekkel ezelőtt felhívta a figyelmet. A referencia itt olvasható: http://www.w3.org/TR/html4/appendix/notes.html#h-B.2.2. A PHP támogatja a paraméter-elválasztó karakter megváltoztatását, a W3C által javasolt pontosvesszőre, az arg_separator nevű .ini beállítással. Sajnálatosan a legtöbb böngésző nem támogatja ezt az elválasztókaraktert. Egy hordozhatóbb módszer az &amp; használata az & karakter helyett elválasztóként. Így nem kell megváltoztatnod a PHP arg_separator beállítását sem. Hagyd ezt & értéken, de használd az URL kódoláshoz a htmlentities()(urlencode($adat)) módszert.

Példa 2. urlencode/htmlentities() példa

echo '<a href="ujoldal.php?ize=', htmlentities(urlencode($valtozo)), '">';

Lásd még: urldecode(), htmlentities(), rawurldecode() és rawurlencode()!

CIX. Változókkal kapcsolatos függvények

A változók viselkedéséről további információkat kaphatsz a változók témakörben a nyelv alapjai című részben.

Tartalom
doubleval -- A floatval() másik neve
empty -- Változó ürességének tesztelése
floatval -- Változó lebegőpontos értékének visszaadása
get_defined_vars --  Minden definiált változó lekérdezése
get_resource_type --  Erőforrás típus lekérdezése
gettype -- Változó típusának visszaadása
import_request_variables -- A GET/POST/Cookie változók betöltése a globális környezetbe
intval -- Változó egész értékének visszaadása
is_array -- Változó tömb típusba tartozásának ellenőrzése
is_bool --  Változó logikai típusba tartozásának ellenőrzése
is_callable --  Hívható tulajdonság ellenőrzése
is_double -- Az is_float() másik neve
is_float -- Változó lebegőpontos típusba tartozásának ellenőrzése
is_int -- Változó egész szám típusba tartozásának ellenőrzése
is_integer -- A is_int() másik neve
is_long -- A is_int() másik neve
is_null --  Változó NULL típusba tartozásának ellenőrzése
is_numeric --  Változó numerikus vagy numerikus szöveg típusba tartozásának ellenőrzése
is_object -- Változó objektum típusba tartozásának ellenőrzése
is_real -- Az is_float() másik neve
is_resource --  Változó erőforrás típusba tartozásának ellenőrzése
is_scalar --  Változó skalár típusba tartozásának ellenőrzése
is_string -- Változó karaktersorozat típusba tartozásának ellenőrzése
isset -- Változó beállítottságának ellenőrzése
print_r --  Ember számára olvasható információ egy változóról
serialize --  Karaktersorozat előállítása egy értékből
settype -- Változó típusának beállítása
strval -- Egy változó karaktersorozat értékét adja vissza
unserialize --  PHP értéket állít elő egy kódolt karaktersorozatból
unset -- Adott változó felszabadítása
var_dump -- Információ egy változóról
var_export -- Érvényes PHP kód reprezentációt ad egy változóról

doubleval

doubleval -- A floatval() másik neve

Leírás

Ez a függvény a floatval() függvény másik neve.

Megjegyzés: Ez a függvény egy átnevezés maradványa. Régebbi PHP verziókban ezt a nevet kell használnod, ha az új floatval() név még nem elérhető.

empty

(PHP 3, PHP 4 )

empty -- Változó ürességének tesztelése

Leírás

boolean empty ( mixed var)

Megjegyzés: Az empty() egy nyelvi szerkezet.

Ez a (boolean) var, ellentetje, kivéve hogy nem kapsz figyelmeztetést, ha a változó nincs beállítva. Lásd még a logikai értékké alakítás című részt.

$valtozo = 0;

if (empty($valtozo)) { // igazat ad vissza 
    print '$valtozo nulla vagy nincs beállítva';
}

if (!isset($valtozo)) { // hamisat ad vissza
    print '$valtozo egyáltalán nincs beállítva';
}

Értelmetlen kifejezésekre használni ezt a függvényt, mint pl. empty (addslashes ($nev)), mivel nincs jelentése annak, hogy valami, ami nem is változó, változó-e üres értékkel...

Lásd még isset() és unset().

floatval

(PHP 4 >= 4.2.0)

floatval -- Változó lebegőpontos értékének visszaadása

Leírás

float floatval ( mixed var)

Visszaddja var float típusúvá alakított értékét.

A var lehet bármilye skaláris típus. Nem használhatod azonban a floatval() függvényt tömbökön vagy objektumokon.

$valtozo = '122.34343szöveg';
$lebegopontos_ertek = floatval($valtozo);
print $lebegopontos_ertek; // kiírja, hogy 122.34343

Lásd még intval(), strval(), settype() és Buvészkedés a típusokkal.

get_defined_vars

(PHP 4 >= 4.0.4)

get_defined_vars --  Minden definiált változó lekérdezése

Leírás

array get_defined_vars ( void )

Ez a függvény egy többdimenziós tömbbel tér vissza az összes definiált változóval, legyenek azok akár környezeti, szerver vagy felhasználó által létrehozott változók.

$b = array(1,1,2,3,5,8);

$tomb = get_defined_vars();

// $b kiírása
print_r($tomb["b"]);

// A PHP feldolgozó elérési útja (ha CGI-ként használod)
// például /usr/local/bin/php
echo $tomb["_"];

// A parancssori paraméterek kiírása (ha vannak)
print_r($tomb["argv"]);

// Minden szerver változó kiírása
print_r($tomb["_SERVER"]);

// A változók tömbjéből minden kulcs kiírása
print_r(array_keys(get_defined_vars()));

Lásd még get_defined_functions() és get_defined_constants().

get_resource_type

(PHP 4 >= 4.0.2)

get_resource_type --  Erőforrás típus lekérdezése

Leírás

string get_resource_type ( resource handle)

Ez a függvény az erőforrás típust (resource) reprezentáló karaktersorozattal tér vissza. Ha a paraméter nem érvényes erőforrás, hibát kapsz.

$kapcs = mysql_connect();
echo get_resource_type($kapcs)."\n";
// kiírja: mysql link

$ize = fopen("ize","w");
echo get_resource_type($ize)."\n";
// kiírja: file

$dok = new_xmldoc("1.0");
echo get_resource_type($dok->doc)."\n";
// kiírja: domxml document

gettype

(PHP 3, PHP 4 )

gettype -- Változó típusának visszaadása

Leírás

string gettype ( mixed var)

Visszaadja a var paraméterben megadott PHP változó típusát.

Figyelem

Soha ne használd a gettype() függvényt egy bizonyos típusba tartozás vizsgálatához, mivel a visszaadott karaktersorozat megváltozhat későbbi PHP verziókban. Ráadásul lassabb, mint egy bizonyos típus vizsgálata, mivel karaktersorozat általakítást használ.

Ehelyett használd az is_* függvényeket.

A lehetséges visszatérési értékek:

  • "boolean" - logikai típus (a PHP 4-esben)

  • "integer" - egész típus

  • "double" (történeti okokból "double" a visszatérési érték a float lebegőpontos típusra, és nem "float")

  • "string" - karaktersorozat

  • "array" - tömb

  • "object" - objektum

  • "resource" - erőforrás (a PHP 4-esben)

  • "NULL" - NULL (a PHP 4-esben)

  • "user function" - felhasználói függvény (csak a PHP 3-asban!)

  • "unknown type" - ismeretlen típus

A PHP 4-esben, a function_exists() és method_exists() függvényeket kell használnod, a korábbi "user function" visszatérési értéket tesztelő PHP 3-as gettype() hívások helyett.

Lásd még settype(), is_array(), is_bool(), is_float(), is_integer(), is_null(), is_numeric(), is_object(), is_resource(), is_scalar() és is_string().

import_request_variables

(PHP 4 >= 4.1.0)

import_request_variables -- A GET/POST/Cookie változók betöltése a globális környezetbe

Leírás

bool import_request_variables ( string types [, string prefix])

Ez a függvény a GET/POST/Cookie változókat betölti a globális környezetbe. Hasznos lehet, ha kikapcsoltad a register_globals beállítást, de szeretnél látni néhány változót a globális környezetben.

A types paraméter használatával meg tudod adni, hogy milyen típusú változókat importáljon a PHP. Használhatod a 'G', 'P' és 'C' karaktereket a GET, POST és Cookie változókhoz értelemszerűen. Ezek a karakterek nem érzékenyek a kis- és nagybetűs írásra, ezért használhatod a 'g', 'p' és 'c' karaktereket is. A POST típus magában foglalja a POST-al feltöltött állomány információkat is. Fontos, hogy a betűk sorrendje számít, mivel például "gp" használatakor az azonos nevű POST változók felül fogják írni a GET változókat. A GPC-n kívüli betűket nem veszi figyelembe a függvény.

A prefix paraméter megadásával a beimportált változók nevekhez előtagot rendelhetsz. Tehát ha például a GET adatok közt érkezik egy "userid" nevű, és prefix értéknek megadtad a "pref_" értéket, eredményül elgy $pref_userid nevű változót kapsz.

Ha netán szükségesnek érzed, hogy egyéb változúértékeket is behúzz a globális változóid közé, mint például a SERVER változókat, használd az extract() függvényt!

Megjegyzés: Habár a prefix paraméter opcionális, egy E_NOTICE szintű hibaüzenetet fogsz kapni, ha nem adod meg, vagy egy üres karaktersorozatot adsz meg. Ez egy lehetséges biztonsági rés ugyanis. A megjegyzés szintű hibák nem kerülnek kiírásra az error_reporting alapbeállítás szintje szerint.

// Importáljuk a GET és POST változókat az
// "rvar_" előtagot odatéve minden név elé
import_request_variables("gP", "rvar_");

print $rvar_foo;

Lásd még $_REQUEST, register_globals, Előre definiált változók és extract().

intval

(PHP 3, PHP 4 )

intval -- Változó egész értékének visszaadása

Leírás

int intval ( mixed var [, int base])

Visszadja a var változó értékét egész típussá alakítva, felhasználva a base-ben megadott számrendszert (ez alapbeállításban 10).

A var bármilyen skalár típus lehet. Nem alkalmazhatod azonban az intval()-t tömbökre vagy objektumokra.

Megjegyzés: A base paraméternek csak akkor van hatása, ha a var karaktersorozat.

Lásd még floatval(), strval(), settype() és Buvészkedés a típusokkal.

is_array

(PHP 3, PHP 4 )

is_array -- Változó tömb típusba tartozásának ellenőrzése

Leírás

bool is_array ( mixed var)

TRUE értéket ad vissza, ha a var tömb, FALSE értéket ad egyébként.

Lásd még is_float(), is_int(), is_integer(), is_string() és is_object().

is_bool

(PHP 4 )

is_bool --  Változó logikai típusba tartozásának ellenőrzése

Leírás

bool is_bool ( mixed var)

TRUE értéket ad vissza, ha a var logikai típusú, FALSE értéket ad egyébként.

Lásd még is_array(), is_float(), is_int(), is_integer(), is_string() és is_object().

is_callable

(PHP 4 >= 4.0.6)

is_callable --  Hívható tulajdonság ellenőrzése

Leírás

bool is_callable ( mixed var [, bool syntax_only [, string callable_name]])

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

is_double

is_double -- Az is_float() másik neve

Leírás

Az is_float() másik neve.

is_float

(PHP 3, PHP 4 )

is_float -- Változó lebegőpontos típusba tartozásának ellenőrzése

Leírás

bool is_float ( mixed var)

TRUE értéket ad vissza, ha a var lebegőpontos, FALSE értéket ad egyébként.

Megjegyzés: Ha azt szeretnéd ellenőrizni, hogy egy változó szám, vagy egy számot tartalmazó karaktersorozat (mint például egy űrlap érték, ami mindig karaktersorozat), használd az is_numeric() függvényt.

Lásd még is_bool(), is_int(), is_integer(), is_numeric(), is_string(), is_array() és is_object().

is_int

(PHP 3, PHP 4 )

is_int -- Változó egész szám típusba tartozásának ellenőrzése

Leírás

bool is_int ( mixed var)

TRUE értéket ad vissza, ha a var egész szám, FALSE értéket ad egyébként.

Megjegyzés: Ha azt szeretnéd ellenőrizni, hogy egy változó szám, vagy egy számot tartalmazó karaktersorozat (mint például egy űrlap érték, ami mindig karaktersorozat), használd az is_numeric() függvényt.

Lásd még: is_bool(), is_float(), is_integer(), is_numeric(), is_string(), is_array() és is_object().

is_integer

is_integer -- A is_int() másik neve

Leírás

Ez a függvény az is_int() másik neve.

is_long

is_long -- A is_int() másik neve

Leírás

Ez a függvény az is_int() másik neve.

is_null

(PHP 4 >= 4.0.4)

is_null --  Változó NULL típusba tartozásának ellenőrzése

Leírás

bool is_null ( mixed var)

TRUE értéket ad vissza, ha a var NULL, FALSE értéket ad egyébként.

Arról, hogy egy változóérték mikor számít NULL értékűnek és mikor nem, bővebben olvashatsz a NULL kapcsolódó oldalán.

Lásd még NULL, is_bool(), is_numeric(), is_float(), is_int(), is_string(), is_object(), is_array(), is_integer() és is_real()

is_numeric

(PHP 4 )

is_numeric --  Változó numerikus vagy numerikus szöveg típusba tartozásának ellenőrzése

Leírás

bool is_numeric ( mixed var)

TRUE értéket ad vissza, ha a var numerikus vagy numerikus szöveg, FALSE értéket ad egyébként.

Lásd még is_bool(), is_float(), is_int(), is_string(), is_object(), is_array() és is_integer().

is_object

(PHP 3, PHP 4 )

is_object -- Változó objektum típusba tartozásának ellenőrzése

Leírás

bool is_object ( mixed var)

TRUE értéket ad vissza, ha a var objektum, FALSE értéket ad egyébként.

Lásd még is_bool(), is_int(), is_integer(), is_float(), is_string() és is_array().

is_real

is_real -- Az is_float() másik neve

Leírás

Ez a függvény az is_float() másik neve.

is_resource

(PHP 4 )

is_resource --  Változó erőforrás típusba tartozásának ellenőrzése

Leírás

bool is_resource ( mixed var)

Az is_resource() TRUE értéket ad vissza, ha a var paraméter által megadott változó erőforrásazonosító, FALSE értéket ad egyébként.

Lásd a resource típus dokumentációját további információkért.

is_scalar

(PHP 4 >= 4.0.5)

is_scalar --  Változó skalár típusba tartozásának ellenőrzése

Leírás

bool is_scalar ( mixed var)

Az is_scalar() TRUE értéket ad, ha a var változó skalár, egyébként FALSE értéket ad.

A skaláris változók csoportja az integer, float, string és boolean típusokat tartalmazza. Az array, object és resource típusok nem skalárok.

function valtozo_kiiras($valtozo) {
    if (is_scalar($valtozo)) {
        echo $valtozo;
    } else {
        var_dump($valtozo);
    }
}
$pi = 3.1416;
$proteinek = array("hemoglobin", "cytochrome c oxidase", "ferredoxin");

valtozo_kiiras($pi);
// kiírja: 3.1416

változo_kiiras($proteinek)
// kiírja:
// array(3) {
//   [0]=>
//   string(10) "hemoglobin"
//   [1]=>
//   string(20) "cytochrome c oxidase"
//   [2]=>
//   string(10) "ferredoxin"
// }

Megjegyzés: Az is_scalar() nem tekinti a resource (erőforrás) típusú értékeket skalároknak, mivel az erőforrás absztrakt adattípus, jelenleg az egész számokra építve. Ez a megvalósítási részlet azonban nem vehető figyelembe, mivel később megváltozhat.

Lásd még is_bool(), is_numeric(), is_float(), is_int(), is_real(), is_string(), is_object(), is_array() és is_integer().

is_string

(PHP 3, PHP 4 )

is_string -- Változó karaktersorozat típusba tartozásának ellenőrzése

Leírás

bool is_string ( mixed var)

TRUE értéket ad vissza, ha a var karaktersorozat, FALSE értéket ad egyébként.

Lásd még is_bool(), is_int(), is_integer(), is_float(), is_real(), is_object() és is_array().

isset

(PHP 3, PHP 4 )

isset -- Változó beállítottságának ellenőrzése

Leírás

boolean isset ( mixed var [, mixed var [, ...]])

Megjegyzés: Az isset() egy nyelvi szerkezet.

TRUE értéket ad vissza, ha var létezik, FALSE értéket ad egyébként.

Ha egy változót megszüntettél unset()-el, az isset() hamisat fog adni. Az isset() továbbá FALSE érétket fog adni, ha az ellenőrzött változó értéke NULL. Szintén fontos, hogy a NULL bájt ("\0") nem egyezik meg a PHP NULL konstans értékével.

$a = "próba";
$b = "még egy próba";

echo isset ($a);     // TRUE
echo isset ($a, $b)  // TRUE

unset ($a);
echo isset ($a);     // FALSE
echo isset ($a, $b); // FALSE

$ize = NULL;
print isset ($ize);  // FALSE

Lásd még empty() és unset().

print_r

(PHP 4 )

print_r --  Ember számára olvasható információ egy változóról

Leírás

void print_r ( mixed expression)

Ez a függvény egy ember számára olvasható formában ad vissza információt a megadott változóról. Ha egy string, integer vagy float típusú értéket kap, magát az értéket írja ki. Ha tömböt kap, az elemek kulcs-érték párjait írja ki. Hasonlóan viselkedik objektumok esetében is.

A print_r() a tömb belső mutatóját a tömb végére mozgatja. Használd a reset() függvényt, ha előre kell mozgatnod a mutatót.

Tipp: Mint bármilyen más esetben, amikor a kimenet közvetlenül a böngészőhöz kerül, használhatod az kimenet szabályozó függvényeket, hogy a függvény kimenetét "elkapd", és elmentsd például egy string-ben.

<?php
    $tomb = array ('a' => 'alma', 'b' => 'banán', 'c' => array ('x','y','z'));
    print_r($tomb);
?>

Kimenete:
<pre>
Array
(
    [a] => alma
    [b] => banán
    [c] => Array
        (
            [0] => x
            [1] => y
            [2] => z
        )
)
</pre>

Megjegyzés: Ez a függvény a PHP 4.0.4 verzió előtt a 'végtelenségig' futott, ha egy direkt, vagy indirekt magára mutató tömböt vagy objektumot adtál át paraméterül. Egy példa erre a print_r($GLOBALS), hívás, mivel a $GLOBALS magában egy globális változó, és így magára is tartalmaz referenciát.

Lásd még ob_start(), var_dump(), és var_export().

serialize

(PHP 3>= 3.0.5, PHP 4 )

serialize --  Karaktersorozat előállítása egy értékből

Leírás

string serialize ( mixed value)

A serialize() egy karaktersorozattal tér vissza, ami a value paraméterben megadott érték karaktersorozatba kódolt megfelelője. Így bárhol tárolható.

Ez a függvény hasznos PHP értékek tárolására és továbbítására anélkül, hogy a szerkezetük és/vagy típusuk elveszne.

Ha ismét PHP értékbe szeretnéd tenni a "szerializált" karaktersorozatot, használd az unserialize() függvényt. A serialize() minden típust kezel a resource típus kivételével. Szerializálhatsz akár olyan tömböket is, amik magukra tartalmaznak referenciát. A referenciák, amiket a tömbben/objektumban tárolsz, szintén bekerülnek a kódolt karaktersorozatba.

Megjegyzés: A PHP 3-ban az objektum tulajdonságok szerializálódnak, de a metódusok elvesznek. A PHP 4-esben ilyen probléma nem lép fel. Lásd az objektumok szerializációja részt a Osztályok, objektumok című fejezetben.

Példa 1. serialize() példa

// A $munkamenet_adat egy többdimenziós tömb, az aktuális
// felhasználó munkamenet adataival. A serialize()-t használjuk
// az adatok adatbázisban történő tárolására a kérés végén.

$conn = odbc_connect ("webdb", "php", "csirke");
$stmt = odbc_prepare ($conn,
      "UPDATE munkamenetek SET adat = ? WHERE id = ?");
$sqladat = array (serialize($munkamenet_adat), $PHP_AUTH_USER);
if (!odbc_execute ($stmt, &$sqladat)) {
    $stmt = odbc_prepare($conn,
     "INSERT INTO munkamenetek (id, adat) VALUES(?, ?)");
    if (!odbc_execute($stmt, &$sqladat)) {
    /* Valami nem jött össze, hibakezelés */
    }
}

Lásd még unserialize().

settype

(PHP 3, PHP 4 )

settype -- Változó típusának beállítása

Leírás

bool settype ( mixed var, string type)

Beállítja a var változó típusát type típusra.

Lehetséges type értékek:

  • "boolean" (vagy a PHP 4.2.0 óta "bool")

  • "integer" (vagy a PHP 4.2.0 óta "int")

  • "float" (csak a PHP 4.2.0 óta, korábban "double")

  • "string"

  • "array"

  • "object"

  • "null" (a PHP 4.2.0 óta)

TRUE értéket ad siker esetén, FALSE értéket egyébként.

Példa 1. settype() példa

$ize    = "5valami"; // string
$valami = true;      // boolean

settype($ize, "integer"); // $ize most 5 (integer)
settype($valami, "string");  // $valami most "1" (string)

Lásd még gettype(), típus átalakítás és bűvészkedés a típusokkal.

strval

(PHP 3, PHP 4 )

strval -- Egy változó karaktersorozat értékét adja vissza

Leírás

string strval ( mixed var)

Visszaadja a karaktersorozattá alakított értékét a var paraméterben megadott változónak. Lásd a string típus dokumentációját az átalakítás leírásához.

A var bármilyen skalár típus lehet. Nem alkalmazhatod azonban az strval() függvényt tömbökön vagy objektumokon.

Lásd még floatval(), intval(), settype() és bűvészkedés a típusokkal.

unserialize

(PHP 3>= 3.0.5, PHP 4 )

unserialize --  PHP értéket állít elő egy kódolt karaktersorozatból

Leírás

mixed unserialize ( string str)

Az unserialize() egy szerializált értéket vár, (lásd a serialize() függvényt) és visszaalakítja PHP értékké azt. Az átalakított értéket adja vissza, ami lehet integer, float, string, array vagy object típusú.

Megjegyzés: Definiálhatsz egy callback függvényt, amit a PHP akkor hív meg, ha egy nemlétező osztályból kell példányt létrehoznia a deszerializáció során. Erre akkor lehet szükség, ha nem szeretnél egy tökéletlen "__PHP_Incomplete_Class" objektumot kapni. Használd a php.ini, ini_set() vagy .htaccess segítségével beállítható 'unserialize_callback_func' értéket a függvény beállítására. Minden alkalommal, amikor egy nem definiált osztályból kell példányt létrehozni, ezt a függvényt fogja a PHP meghívni. Ha ki szeretnéd kapcsolni ezt a szolgáltatást, állítsd üresre ezt a beállítást.

Példa 1. unserialize_callback_func példa

$szerializalt_obj='O:1:"a":1:{s:5:"value";s:3:"100";}';

ini_set('unserialize_callback_func','mycallback'); // saját callback függvény

function mycallback($osztaly_neve) {
    // Itt be tudod tölteni azt a külső állományt, ami az
    // osztály definícióját tartalmazza. Az osztály nevét
    // kapod paraméterül, az alapján dönthetsz.
}

Megjegyzés: A PHP 3-ban az objektum tulajdonságok szerializálódnak, de a metódusok elvesznek. A PHP 4-esben ilyen probléma nem lép fel. Lásd az objektumok szerializációja részt a Osztályok, objektumok című fejezetben.

Példa 2. unserialize() példa

// Itt az unserialize() függvényt használjuk, miután az adatbázisból
// lekérdeztük a munkamenet adatot a $munkamenet_adat változóba.
// Ez a példa kiegészíti a serialize() példáját.

$conn = odbc_connect ("webdb", "php", "csirke");
$stmt = odbc_prepare ($conn, "SELECT adat FROM munkamenetek WHERE id = ?");
$sqladat = array ($PHP_AUTH_USER);
if (!odbc_execute ($stmt, &$sqladat) || !odbc_fetch_into ($stmt, &$tmp)) {
    // Ha az execute() vagy a fetch() hibás, üres tömböt veszünk
    $munkamenet_adat = array();
} else {
    // Most már a deszerializált adatokat a $tmp[0]-ban találjuk
    $munkamenet_adat = unserialize($tmp[0]);
    if (!is_array($munkamenet_adat)) {
        // Valami rosszul ment, üres tömböt veszünk
        $munkamenet_adat = array();
    }
}

Lásd még serialize().

unset

(PHP 3, PHP 4 )

unset -- Adott változó felszabadítása

Leírás

void unset ( mixed var [, mixed var [, ...]])

Megjegyzés: Az unset() egy nyelvi szerkezet.

Az unset() megszünteti az adott változókat. A PHP 3-ban mindig TRUE értékkel tér vissza (egészen pontosan az 1 értékű egész számmal). A PHP 4-esben az unset() többé már nem függvény, hanem parancs. Ezért nincs visszatérési érték, és a visszatérési érték használata feldolgozási hibát jelent.

Példa 1. unset() példa

// Egy változó törlése
unset ($ize);

// Egy tömbelem törlése (nem az egész tömb törlése!)
unset ($valami['barmi']);

// Több mint egy változó törlése
unset ($ize1, $ize2, $ize3);

Az unset() hatása egy függvényen belül attól függ, hogy milyen típusú változót próbálsz meg törölni.

Ha egy globális környezetből betöltött változót próbálsz meg törölni a függvényben, csak a lokális változót törlöd. A hívó környezetben lévő változó megtartja unset() hívás előtti értékét.

function ize_torlese() {
    global $ize;
    unset($ize);
}

$ize = 'valami';
ize_torlese();
echo $ize;

A fenti példa a következőt írja ki:

valami

Ha egy olyan változót törölsz egy függvényben, amit referenciaképzéssel adtál át, csak a helyi változót törlöd. A hívó környezetben lévő változó megtartja unset() hívás előtti értékét.

function ize(&$valami) {
    unset($valami);
    $valami = "másmilyen szöveg";
}

$valami = 'valamilyen szöveg';
echo "$valami\n";

foo($valami);
echo "$valami\n";

A fenti példa kimenete:

valamilyen szöveg
valamilyen szöveg

Ha egy statikus változót törölsz egy függvényben, az unset() törli a változót, és minden rá mutató referenciát.

function ize() {
    static $a;
    $a++;
    echo "$a\n";
    unset($a);
}

ize();
ize();
ize();

A fenti példa kimenete:

1
2
3

Ha egy globális változót szeretnél törölni egy függvényen belül, használd a $GLOBALS tömböt erre a célra:

function ize() {
    unset($GLOBALS['valami']);
}

$valami = "bármi";
ize();

Lásd még isset() és empty().

var_dump

(PHP 3>= 3.0.5, PHP 4 )

var_dump -- Információ egy változóról

Leírás

void var_dump ( mixed expression [, mixed expression [, ...]])

Ez a függvény strukturált információt ad egy vagy több kifejezésről, az értékek és típusok kiírásával. A tömbök rekurzívan kerülnek feldolgozásra, az értékek bekezdésével, hogy lásd a struktúrát.

Tipp: Mint bármilyen más esetben, amikor a kimenet közvetlenül a böngészőhöz kerül, használhatod az kimenet szabályozó függvényeket, hogy a függvény kimenetét "elkapd", és elmentsd például egy string-ben.

Hasonlítsd össze a var_dump() függvényt és a print_r() függvényt.

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

/* kimenete:
array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  array(3) {
    [0]=>
    string(1) "a"
    [1]=>
    string(1) "b"
    [2]=>
    string(1) "c"
  }
}

*/

$b = 3.1;
$c = TRUE;
var_dump($b,$c);

/* kimenete:
float(3.1)
bool(true)

*/
?>
</pre>

var_export

(PHP 4 >= 4.2.0)

var_export -- Érvényes PHP kód reprezentációt ad egy változóról

Leírás

mixed var_export ( mixed expression [, bool return])

Ez a függvény a paraméterben átadott érték struktúrált karaktersorozat reprezentációját adja vissza. Hasonlít a var_dump() függvényhez, azzal a kivétellel, hogy a var_export() előállított értéke érvényes PHP kód.

Az előállított érték alapesetben kiíródik, de ha a második paraméterben a TRUE értéket adod meg a függvény visszatér az előállított értékkel.

Hasonlítsd össze a var_export() és a var_dump() függvényeket.

<pre>
<?php
$a = array (1, 2, array ("a", "b", "c"));
var_export ($a);

/* kimenete:
array (
  0 => 1,
  1 => 2,
  2 => 
  array (
    0 => 'a',
    1 => 'b',
    2 => 'c',
  ),
)
*/

$b = 3.1;
$v = var_export($b, TRUE);
echo $v;

/* kimenete:
3.1
*/
?>
</pre>

CX. vpopmail függvények

Bevezetés

Figyelem

Ez a kiterjesztés KÍSÉRLETI JELLEGGEL MŰKÖDIK. Ez azt jelenti, hogy minden itt dokumentált működés, beleértve a függvények nevét, működését vagy bármi más, amit a kiterjesztés kapcsán leírtunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a kiterjesztést csak a saját felelősségedre használd!

Tartalom
vpopmail_add_alias_domain_ex -- Egy már meglévő virtuális tartományhoz (domain) alias hozzáadása
vpopmail_add_alias_domain -- Egy virtiális tartományhoz alias rendelése
vpopmail_add_domain_ex -- Új virtuális tartomány létrehozása
vpopmail_add_domain -- Új virtuális tartomány létrehozása
vpopmail_add_user -- Adott virtuális tarományba új felhasználó felvétele
vpopmail_alias_add -- Virtuális felhasználó-alias beszúrása
vpopmail_alias_del_domain -- Egy tartományhoz tartozó összes alias eltávolítása
vpopmail_alias_del -- Egy felhasználónév összes aliasának törlése
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 -- Egy felhasználó jelszavas azonosítása, adott tartományban, igaz/hamis visszatérő értékkel
vpopmail_del_domain_ex -- Virtuális tartomány eltávolítása
vpopmail_del_domain -- Virtuális tartomány eltávolítása
vpopmail_del_user -- Egy virtuális tartományból adott felhasználó eltávolítása
vpopmail_error -- A legutóbbi vpopmail hibaüzenet kinyerése
vpopmail_passwd -- Egy meglevő virtuális felhasználó jelszavának módisítása
vpopmail_set_user_quota -- Egy virtuális felhasználó kvótájának módosítása

vpopmail_add_alias_domain_ex

(4.0.5 - 4.2.3 only)

vpopmail_add_alias_domain_ex -- Egy már meglévő virtuális tartományhoz (domain) alias hozzáadása

Leírás

bool vpopmail_add_alias_domain_ex ( string eredeti tartománynév, string alias tartománynév)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

vpopmail_add_alias_domain

(4.0.5 - 4.2.3 only)

vpopmail_add_alias_domain -- Egy virtiális tartományhoz alias rendelése

Leírás

bool vpopmail_add_alias_domain ( string tartomány, string alias tartomány)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

vpopmail_add_domain_ex

(4.0.5 - 4.2.3 only)

vpopmail_add_domain_ex -- Új virtuális tartomány létrehozása

Leírás

bool vpopmail_add_domain_ex ( string tartomány, string jelszó [, string kvóta [, string visszapattanó cím [, bool apop]]])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

vpopmail_add_domain

(4.0.5 - 4.2.3 only)

vpopmail_add_domain -- Új virtuális tartomány létrehozása

Leírás

bool vpopmail_add_domain ( string tartomány, string könyvtár, int uid, int gid)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

vpopmail_add_user

(4.0.5 - 4.2.3 only)

vpopmail_add_user -- Adott virtuális tarományba új felhasználó felvétele

Leírás

bool vpopmail_add_user ( string felhasználónév, string tartomány, string jelszó [, string gecos [, bool apop]])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

vpopmail_alias_add

(4.1.0 - 4.2.3 only)

vpopmail_alias_add -- Virtuális felhasználó-alias beszúrása

Leírás

bool vpopmail_alias_add ( string felhasználónév, string tartomány, string alias)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

vpopmail_alias_del_domain

(4.1.0 - 4.2.3 only)

vpopmail_alias_del_domain -- Egy tartományhoz tartozó összes alias eltávolítása

Leírás

bool vpopmail_alias_del_domain ( string tartomány)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

vpopmail_alias_del

(4.1.0 - 4.2.3 only)

vpopmail_alias_del -- Egy felhasználónév összes aliasának törlése

Leírás

bool vpopmail_alias_del ( string felhasználónév, string tartomány)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

vpopmail_alias_get_all

(4.1.0 - 4.2.3 only)

vpopmail_alias_get_all -- get all lines of an alias for a domain

Description

array vpopmail_alias_get_all ( string domain)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

vpopmail_alias_get

(4.1.0 - 4.2.3 only)

vpopmail_alias_get -- get all lines of an alias for a domain

Description

array vpopmail_alias_get ( string alias, string domain)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

vpopmail_auth_user

(4.0.5 - 4.2.3 only)

vpopmail_auth_user -- Egy felhasználó jelszavas azonosítása, adott tartományban, igaz/hamis visszatérő értékkel

Leírás

bool vpopmail_auth_user ( string felhasználónév, string tartomány, string jelszó [, string apop])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

vpopmail_del_domain_ex

(4.0.5 - 4.2.3 only)

vpopmail_del_domain_ex -- Virtuális tartomány eltávolítása

Leírás

bool vpopmail_del_domain_ex ( string tartomány)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

vpopmail_del_domain

(4.0.5 - 4.2.3 only)

vpopmail_del_domain -- Virtuális tartomány eltávolítása

Leírás

bool vpopmail_del_domain ( string tartomány)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

vpopmail_del_user

(4.0.5 - 4.2.3 only)

vpopmail_del_user -- Egy virtuális tartományból adott felhasználó eltávolítása

Leírás

bool vpopmail_del_user ( string felhasználó, string tartomány)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

vpopmail_error

(4.0.5 - 4.2.3 only)

vpopmail_error -- A legutóbbi vpopmail hibaüzenet kinyerése

Leírás

string vpopmail_error ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

vpopmail_passwd

(4.0.5 - 4.2.3 only)

vpopmail_passwd -- Egy meglevő virtuális felhasználó jelszavának módisítása

Leírás

bool vpopmail_passwd ( string felhasználónév, string tartomány, string jelszó)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

vpopmail_set_user_quota

(4.0.5 - 4.2.3 only)

vpopmail_set_user_quota -- Egy virtuális felhasználó kvótájának módosítása

Leírás

bool vpopmail_set_user_quota ( string felhasználónév, string tartomány, string kvóta)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

CXI. W32api functions

Bevezetés

This extension is a generic extension API to DLLs. This was originally written to allow access to the Win32 API from PHP, although you can also access other functions exported via other DLLs.

Currently supported types are generic PHP types (strings, booleans, floats, integers and nulls) and types you define with w32api_deftype().

Figyelem

Ez a kiterjesztés KÍSÉRLETI JELLEGGEL MŰKÖDIK. Ez azt jelenti, hogy minden itt dokumentált működés, beleértve a függvények nevét, működését vagy bármi más, amit a kiterjesztés kapcsán leírtunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a kiterjesztést csak a saját felelősségedre használd!


Követelmények

This extension will only work on Windows systems.


Telepítés

Semmilyen telepítés nem szükséges ezen függvények használatához, a PHP alapelemei.


Futásidejű beállítások

Ez a kiterjesztés semmilyen konfigurációs beállításokat nem definiál a php.ini állományban.


Erőforrás típusok

This extension defines one resource type, used for user defined types. The name of this resource is "dynaparm".


Előre definiált állandók

Az itt listázott állandókat ez a kiterjesztés definiálja, és csak akkor elérhetőek, ha az adott kiterjesztés be van fordítva a PHP-be, vagy dinamikusan betöltött.

DC_MICROSOFT (integer)

DC_BORLAND (integer)

DC_CALL_CDECL (integer)

DC_CALL_STD (integer)

DC_RETVAL_MATH4 (integer)

DC_RETVAL_MATH8 (integer)

DC_CALL_STD_BO (integer)

DC_CALL_STD_MS (integer)

DC_CALL_STD_M8 (integer)

DC_FLAG_ARGPTR (integer)


Példák

This example gets the amount of time the system has been running and displays it in a message box.

Példa 1. Get the uptime and display it in a message box

<?php
// Define constants needed, taken from
// Visual Studio/Tools/Winapi/WIN32API.txt
define("MB_OK", 0);

// Load the extension in
dl("php_w32api.dll");

// Register the GetTickCount function from kernel32.dll
w32api_register_function("kernel32.dll", 
                         "GetTickCount",
                         "long");
                         
// Register the MessageBoxA function from User32.dll
w32api_register_function("User32.dll",
                         "MessageBoxA",
                         "long");

// Get uptime information
$ticks = GetTickCount();

// Convert it to a nicely displayable text
$secs  = floor($ticks / 1000);
$mins  = floor($secs / 60);
$hours = floor($mins / 60);

$str = sprintf("You have been using your computer for:" .
                "\r\n %d Milliseconds, or \r\n %d Seconds" .
                "or \r\n %d mins or\r\n %d hours %d mins.",
                $ticks,
                $secs,
                $mins,
                $hours,
                $mins - ($hours*60));

// Display a message box with only an OK button and the uptime text
MessageBoxA(NULL, 
            $str, 
            "Uptime Information", 
            MB_OK);
?>
Tartalom
w32api_deftype -- Defines a type for use with other w32api_functions
w32api_init_dtype --  Creates an instance of the data type typename and fills it with the values passed
w32api_invoke_function -- Invokes function funcname with the arguments passed after the function name
w32api_register_function -- Registers function function_name from library with PHP
w32api_set_call_method -- Sets the calling method used

w32api_deftype

(4.2.0 - 4.2.3 only)

w32api_deftype -- Defines a type for use with other w32api_functions

Description

bool w32api_deftype ( string typename, string member1_type, string member1_name [, string ... [, string ...]])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

If you would like to define a type for a w32api call, you need to call w32api_deftype(). This function takes 2n+1 arguments, where n is the number of members the type has. The first argument is the name of the type. After that is the type of the member followed by the members name (in pairs). A member type can be a user defined type. All the type names are case sensitive. Built in type names should be provided in lowercase. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

w32api_init_dtype

(4.2.0 - 4.2.3 only)

w32api_init_dtype --  Creates an instance of the data type typename and fills it with the values passed

Description

resource w32api_init_dtype ( string typename, mixed value [, mixed ...])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

This function creates an instance of the data type named typename, filling in the values of the data type. The typename parameter is case sensitive. You should give the values in the same order as you defined the data type with w32api_deftype(). The type of the resource returned is dynaparm.

w32api_invoke_function

(4.2.0 - 4.2.3 only)

w32api_invoke_function -- Invokes function funcname with the arguments passed after the function name

Description

mixed w32api_invoke_function ( string funcname, mixed argument [, mixed ...])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

w32api_invoke_function() tries to find the previously registered function, named funcname, passing the parameters you provided. The return type is the one you set when you registered the function, the value is the one returned by the function itself. Any of the arguments can be of any PHP type or w32api_deftype() defined type, as needed.

w32api_register_function

(4.2.0 - 4.2.3 only)

w32api_register_function -- Registers function function_name from library with PHP

Description

bool w32api_register_function ( string library, string function_name, string return_type)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

This function tries to find the function_name function in libary, and tries to import it into PHP. The function will be registered with the given return_type. This type can be a generic PHP type, or a type defined with w32api_deftype(). All type names are case sensitive. Built in type names should be provided in lowercase. Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

w32api_set_call_method

(4.2.0 - 4.2.3 only)

w32api_set_call_method -- Sets the calling method used

Description

void w32api_set_call_method ( int method)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

This function sets the method call type. The parameter can be one of the constants DC_CALL_CDECL or DC_CALL_STD. The extension default is DC_CALL_STD.

CXII. WDDX függvények

Ezek a függvények a WDDX-szel dolgoznak.

Ahhoz, hogy használhasd a WDDX-et, telepítened kell az expat programkönyvtárat (ami az Apache 1.3.7 vagy későbbi verziók része) és újra kell fordítanod a PHP-t a --with-xml és --enable-wddx paraméterekkel.

Megjegyzés: Ha nemcsak ASCII karaktereket kell használni, akkor be kell állítani a megfelelő nyelvi környezetet a függvények használata előtt, lásd: setlocale().

Figyelj arra, hogy minden változókat stringgé alakító függvény az átadott tömb első elemét ellenőrzi, hogy megállapítsa, hogy egy tömböt vagy egy struktúrát állítson-e elő. Ha az első elem kulcsa string, akkor struktúrát állít elő, egyébként tömböt.

Példa 1. Egyszerű értékek átalakítása

<?php
print wddx_serialize_value("PHP to WDDX packet example", "PHP packet");
?>

Ez a példa az alábbi eredményt adja:

<wddxPacket version='1.0'><header comment='PHP packet'/><data>
<string>PHP to WDDX packet example</string></data></wddxPacket>

Példa 2. Bővíthető csomagok

<?php
$pi = 3.1415926;
$packet_id = wddx_packet_start("PHP");
wddx_add_vars($packet_id, "pi");

/* A $cities képzeletben egy adatbázisból származik */
$cities = array("Austin", "Novato", "Seattle");
wddx_add_vars($packet_id, "cities");

$packet = wddx_packet_end($packet_id);
print $packet;
?>

Ez a példa az alábbi eredményt adja:

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

Tartalom
wddx_add_vars -- Hozzáad a megadott WDDX csomaghoz változókat
wddx_deserialize -- Kibont egy WDDX csomagot
wddx_packet_end -- Befejezi a megadott WDDX csomagot
wddx_packet_start -- Egy új WDDX csomagot kezd egy struktúrával
wddx_serialize_value -- Egy egyedülálló értékből WDDX csomagot állít elő
wddx_serialize_vars -- Változókat csomagol egy WDDX csomagba

wddx_add_vars

(PHP 3>= 3.0.7, PHP 4 )

wddx_add_vars -- Hozzáad a megadott WDDX csomaghoz változókat

Leírás

wddx_add_vars ( int packet_id, mixed name_var [, mixed ...])

A wddx_add_vars() az átadott változók packet_id által hivatkozott csomagba helyezésére szolgál. A változókat pontosan úgy kell megadni, mint a wddx_serialize_vars() függvény esetén.

wddx_deserialize

(PHP 3>= 3.0.7, PHP 4 )

wddx_deserialize -- Kibont egy WDDX csomagot

Leírás

mixed wddx_deserialize ( string packet)

A wddx_deserialized() a kapott packet csomagot felbontja. Visszaadja az eredményt, ami egy string, szám vagy tömb. A struktúrák asszociatív tömbökké alakulnak!

wddx_packet_end

(PHP 3>= 3.0.7, PHP 4 )

wddx_packet_end -- Befejezi a megadott WDDX csomagot

Leírás

string wddx_packet_end ( int packet_id)

A wddx_packet_end() befejezi a packet_id paraméterrel megadott WDDX csomagot és visszatér a stringgel, ami a csomagot tartalmazza.

wddx_packet_start

(PHP 3>= 3.0.7, PHP 4 )

wddx_packet_start -- Egy új WDDX csomagot kezd egy struktúrával

Leírás

int wddx_packet_start ( [string comment])

A wddx_packet_start() egy új WDDX csomagot kezd, amibe később újabb változók helyezhetőek. Van egy elhagyható comment string paramétere, és későbbi használat céljára egy csomag azonosítóval tér vissza. Automatikusan egy struktúra definíciót kezd a csomagban.

wddx_serialize_value

(PHP 3>= 3.0.7, PHP 4 )

wddx_serialize_value -- Egy egyedülálló értékből WDDX csomagot állít elő

Leírás

string wddx_serialize_value ( mixed var [, string comment])

A wddx_serialize_value() egy addott értékből állít elő egy WDDX csomagot. Veszi a var értékét, és az elhagyható comment stringet ami a csomag fejlécében jelenik meg, és visszaadja a WDDX csomagot.

wddx_serialize_vars

(PHP 3>= 3.0.7, PHP 4 )

wddx_serialize_vars -- Változókat csomagol egy WDDX csomagba

Leírás

string wddx_serialize_vars ( mixed var_name [, mixed ...])

A wddx_serialize_vars() az átadott változók WDDX csomaggá alakítására használható.

A wddx_serialize_vars() tetszőleges számú paramétert elfogad, amelyek közül bármelyik lehet egy string, ami egy változó nevét adja, vagy egy tömb, ami változónevek tömbjét adja.

Példa 1. wddx_serialize_vars() példa

<?php
$a = 1;
$b = 5.5;
$c = array("blue", "orange", "violet");
$d = "colors";

$clvars = array("c", "d");
print wddx_serialize_vars("a", "b", $clvars);
?>

Ez a példa az alábbi eredményt adja:
<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>

CXIII. XML értelmező függvények

Bevezetés

Az XML (eXtensible Markup Language) olyan adatformátum, amit a Weben keresztüli adatcserére terveztek. Ezt az ajánlást a World Wide Web Consortium (W3C) dolgozta ki és gondozza. További információk az XML-ről és a kapcsolódó technológiákról a http://www.w3.org/XML/ címen található.

Ez a kiterjesztés James Clark expat könyvtárát használja, amely a http://www.jclark.com/xml/expat.html címen beszerezhető. Ez lehető teszi XML dokumentumok beolvasását, ún. elemzését, de nemazok érvényesítését. Három különböző PHP által is támogatott forrás-karakterkódolást támogat: US-ASCII, ISO-8859-1 és UTF-8. UTF-16 nincs támogatva.

Ez a kiterjesztés lehetőséget nyújt arra, hogy XML elemzőket hozzunk létre és azokhoz saját kezelőfüggvényeket rendeljünk hozzá, amelyek más és más események esetén futnak le. Minden XML elemzőnek néhány paramétere beállítható, ami a működését befolyásolja.


Követelmények

Ez a kiterjesztés az expat könyvtárat használja, amely a http://www.jclark.com/xml/expat.html címen beszerezhető. A Makefile, amely ezzel a csomaggal jön alapértelmezés szerint nem telepíti a nekünk szükséges eljáráskönyvtárat, ehhez a következő sorokat kell beleírni:
libexpat.a: $(OBJS)
    ar -rc $@ $(OBJS)
    ranlib $@
Elérhető forrás RPM csomag is a következő helyen: http://sourceforge.net/projects/expat/, ha nem akarsz kínlódni a fordítással ;)


Telepítés

Az Apache 1.3.7 vagy későbbi verziójával már együtt jár az expat könyvtár. Ekkor a PHP-t csak egyszerűen a --with-xml opcióval kell fordítani - minden kiegészítő elérési útvonal nélkül - és ekkor az Apacheüba épített expat könyvtárat használja majd.

Az UNIX rendszereken a configure parancsot kell a --with-xml kapcsolóval. Az expat könyvtárnak olyan helyen kell installálva lennie, ahol a fordító el tudja érni. Ha a PHP-t modulként Apache 1.3.9 (ennek vagy későbbi verziójú) alá installálod, akkor a PHP automatikusan az Apache beépített expat eljáráskönyvtárat fogja használni. Szükség lehet CPPFLAGS és a LDFLAGS környezeti változók beállítására a rendszeren, mielőtt elindítod a configure parancsot, ha az expat-ot valamilyen egzotikus helyre installálták.

A PHP telepítése.... Tada! Ezt kell(ene) látnod!


Futásidejű beállítások

Ez a kiterjesztés semmilyen konfigurációs beállításokat nem definiál a php.ini állományban.


Erőforrás típusok

Ez a kiterjesztés semmilyen erőforrás típust nem definiál.


Előre definiált állandók

Az itt listázott állandókat ez a kiterjesztés definiálja, és csak akkor elérhetőek, ha az adott kiterjesztés be van fordítva a PHP-be, vagy dinamikusan betöltött.

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)


Eseménykezelők

A definiálható XML eseménykezelők:

Táblázat 1. A támogatott XML eseménykezelők:

PHP függvány ,amely regisztrálja a kezelőtesemény leírása
xml_set_element_handler() Elem esemény akkor történik, amikor az XML elemző egy elem kezdő vagy zárócímkéjével találkozik. A nyító és zárócímkékhez külön eseménykezelők rendelhetők.
xml_set_character_data_handler() (Elemzett) szöveges adatnak tekinthető durván minden, ami az XML dokumentumban nem a jelölésekhez tartozó tartalom, beleértve a jelölések közti térközöket is. Az XML elemző nem ad és nem vesz el semmilyen térkökaraktert az elemzés során a dokumentumból, ez teljes mértékben a feldolgozó alkalmazás feladata, illetve annak eldöntése, hogy ezek a karakterek értékes információt jelentenek vagy sem.
xml_set_processing_instruction_handler() PHP programozók számára ismerős lehet a feldolgozó utasítás (proccesing instructions: PI) fogalma. A <?php ?> maga is ilyen, ahol a php a feldolgozó utasítás "célpontja", magyarán a megcélzott feldolgozó. Ezek mind az alkalmazásfüggő elemek, kivéve az XML jelölésűeket, amely lefoglalt ebben az esetben is.
xml_set_default_handler() Azok az adatok, amelyek semmilyen más kezelő nem kezel le, ehhez a függvényhez kerülnek, pl.: XML és dokumentumtípus deklaráció.
xml_set_unparsed_entity_decl_handler() Ezt a kezelőt hívja meg az elemző, ha jelölés deklarációs egyedet (unparsed, NDATA entity). kell feldolgozni.
xml_set_notation_decl_handler() Ez a kezelő felelős a jelölések deklarációjáért.
xml_set_external_entity_ref_handler() Ezt az kezelőt hívja meg az elemző, ha egy külső egyedhivatkozást talál. Ez lehet állományra vagy URL-re történő hivatkozás. Lásd a Példák külső egyedek kezelésére c. fejezetet!


Betű egységesítés (case-folding)

Az elemek nevei kisbetűket és nagybetűket vegyesen tartalmazhatnak. Az elemkezelő fügvények szempontjából ez nem mindegy, ezért az XML szabvány definiált egy betűkezelő szabályt, mely szerint "ha kisbetűt, nagybetűt vegyesen tartalmazó karaktersorozatot kell feldolgozni, akkor a karaktersorozatban a kisbetűket ki kell cserélni a nekik megfelelő nagybetűkre". Más szavakkal, amikor egy karaktersorozat érkezik az XML értelmezőhöz, a betűkezelés egyszerűen a teljes nagybetűre váltást jelenti.

Alapértelmezés szerint az XML kezelők már nagybetűre váltott formában kapják meg a neveket az értelmezőtől. Ez a viselkedés azonban lekérdezhető ill. megváltoztatható az XML elemző következő két függvényével: xml_parser_get_option() (lekérdezés) és a xml_parser_set_option() (beállítás) függvényekkel.


Hibaüzenetek

A következő hibaüzeneteket definálták (az xml_parse() függvény visszatérési értékei lehetnek):

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


Karakterkódolások

A PHP XML kiterjesztése támogatja az Unicode karakterkészeletet különböző karakterkódolások által. Kétféle karakterkódolás különböztetünk meg, az ún. forrás kódolást és a cél kódolást. A PHP belső, értelmezési célokra a dokumentumokat mindig UTF-8 karakterkódolás szerint kódolja.

A forrás-kódolás az XML dokumentum értelmezése, elemzése során használja. Az XML értelmezőt létrehozásakor meg lehet határozni az elemző forrás kódolását, amit később már nem lehet megváltoztatni. A támogatott karakterkészletek a forrás kódolás számára a következők: ISO-8859-1, US-ASCII és az UTF-8. Az első kettő egybájtos kódolás, ami annyit tesz, hogy minden karaktert egyetlen bájton ábrázolnak. Az UTF-8 egy és négy bájt között különböző hosszúságú bitláncon (21 hosszúig) tudja ábrázolja a karaktereket. A forrás kódolás alapértelmezett karakterkészlete a PHP-ben a ISO-8859-1.

A cél-kódolás akkor készül el, amikor a PHP átadja az adatokat az XML kezelő függvényeknek. Amikor egy XML elemző létrejön, a cél-kódolás a forrás-kódolásához igazodik, de ezt meg lehet változtatni a későbbiek során. A cél-kódolás hatással lesz a karakteres adatra, XML elemek címkéire és a feldolgozó utasításokban definiált célpontokra is!

Ha az XML elemző olyan karaktert talál, mely nincs definiálva a forrás-kódolás karakterkészletében, akkor ez hibát okoz.

Ha az értelmezett XML dokumentumban találkozik a PHP egy olyan karakterrel, amit nem nem tud megjeleníteni a cél-kódolás karakterkészlete, akkor a problémás karaktert "lefokozza". Ez annyit jelent, hogy kérdőjelet rak a helyébe.


Példák

Here are some example PHP scripts parsing XML documents.


XML Element Structure Example

This first example displays the stucture of the start elements in a document with indentation.

Példa 1. Show XML Element Structure

<?php
$file = "data.xml";
$depth = array();

function startElement($parser, $name, $attrs) {
    global $depth;
    for ($i = 0; $i < $depth[$parser]; $i++) {
        print "  ";
    }
    print "$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);


XML Tag Mapping Example

Példa 2. 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.
$file = "data.xml";
$map_array = array(
    "BOLD"     => "B",
    "EMPHASIS" => "I",
    "LITERAL"  => "TT"
);

function startElement($parser, $name, $attrs) {
    global $map_array;
    if ($htmltag = $map_array[$name]) {
        print "<$htmltag>";
    }
}

function endElement($parser, $name) {
    global $map_array;
    if ($htmltag = $map_array[$name]) {
        print "</$htmltag>";
    }
}

function characterData($parser, $data) {
    print $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 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.)

Példa 3. External Entity Example

$file = "xmltest.xml";

function trustedFile($file) {
    // only trust local files owned by ourselves
    if (!eregi("^([a-z]+)://", $file)
        && fileowner($file) == getmyuid()) {
            return true;
    }
    return false;
}

function startElement($parser, $name, $attribs) {
    print "&lt;<font color=\"#0000cc\">$name</font>";
    if (sizeof($attribs)) {
        while (list($k, $v) = each($attribs)) {
            print " <font color=\"#009900\">$k</font>=\"<font
                   color=\"#990000\">$v</font>\"";
        }
    }
    print "&gt;";
}

function endElement($parser, $name) {
    print "&lt;/<font color=\"#0000cc\">$name</font>&gt;";
}

function characterData($parser, $data) {
    print "<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");
}

print "<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)));
    }
}
print "</pre>";
print "parse complete\n";
xml_parser_free($xml_parser);

?>

Példa 4. 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 print 'Hi!  This is PHP version '.phpversion(); ?>
  </para>
 </section>
</chapter>

This file is included from xmltest.xml:

Példa 5. xmltest2.xml

<?xml version="1.0"?>
<!DOCTYPE foo [
<!ENTITY testEnt "test entity">
]>
<foo>
   <element attrib="value"/>
   &testEnt;
   <?php print "This is some more PHP code being executed."; ?>
</foo>

Tartalom
utf8_decode --  UTF-8 kódolt sztring ISO-8859-1 karaktereit egybájtos ISO-8859-1 karakterekre cseréli
utf8_encode -- ISO-8859-1 szöveget UTF-8 szerint kódol át
xml_error_string -- visszaadja az XML elemző egy tipikus hibájához tartozó szöveget
xml_get_current_byte_index --  visszaadja az XML elemző aktuális bájtindexét
xml_get_current_column_number --  visszaadja az XML elemző aktuális oszlop számát
xml_get_current_line_number -- visszaadja az XML elemző aktuális sorindexét
xml_get_error_code -- visszadja az elemzés hibakódját
xml_parse_into_struct -- XML adatot tömbökbe pakol
xml_parse -- elemez egy XML dokumentumot
xml_parser_create_ns --  XML elemzőt hoz létre
xml_parser_create -- XML elemzőt hoz létre
xml_parser_free -- megszünteti az XML elemzőt
xml_parser_get_option -- információt ad az XML elemzőről
xml_parser_set_option -- beállítja az XML elemző paramétereit
xml_set_character_data_handler -- szövegkezelő függvényt rendel az elemzőhöz
xml_set_default_handler -- alap sztringkezelő függvényt rendel az elemzőhöz
xml_set_element_handler -- nyitó és záró jelöléseket kezelő függvényt rendel az elemzőhöz
xml_set_end_namespace_decl_handler --  névtérkezelő függvényt rendel az elemzőhöz
xml_set_external_entity_ref_handler -- külső egyedek kezelésére rendel függvényt az elemzőhöz
xml_set_notation_decl_handler -- jelölések kezelésére rendel függvényt az elemzőhöz
xml_set_object -- objektumon belüli XML elemző használatához
xml_set_processing_instruction_handler --  PI kezelőt rendel az elemzőhöz
xml_set_start_namespace_decl_handler --  névtérkezelő függvényt rendel az elemzőhöz
xml_set_unparsed_entity_decl_handler --  "nem elemzendő egyedek" kezelőfüggvényét állítja be az elemző számára

utf8_decode

(PHP 3>= 3.0.6, PHP 4 )

utf8_decode --  UTF-8 kódolt sztring ISO-8859-1 karaktereit egybájtos ISO-8859-1 karakterekre cseréli

Leírás

string utf8_decode ( string data)

Ez a függvény a data-ban kapott sztringet UTF-8 kódolásúnak tekinti, és ISO-8859-1 kódolásúvá alakítja át.

Lásd az utf8_encode()-t az UTF-8 kódolásról szóló leírásért!

utf8_encode

(PHP 3>= 3.0.6, PHP 4 )

utf8_encode -- ISO-8859-1 szöveget UTF-8 szerint kódol át

Leírás

string utf8_encode ( string data)

Ez a függvény a data paraméterben átadott sztringet UTF-8 szerint kódolja, és ezt a kódolt alakot adja vissza. Az UTF-8 az Unicode szabványos módszere a hosszú karakterek értékének bájtfolyamba kódolására. Az UTF-8 átlátszó megoldás a sima ASCII karakterek esetén, ön-szinkronizáló tulajdonsággal bír (azaz a programok meg tudják határozni, hogy hol kezdődnek a karakterek a bájtfolyamon belül) és a hagyományos összehasonlító-függvényekkel és egyebekkel együtt is használhatók. PHP az UTF-8 karaktereket 4 bájtos hosszig az alábbiak szerint kódolja:

Táblázat 1. UTF-8 kódolás

bájtokbitekábrázolás
170bbbbbbb
211110bbbbb 10bbbbbb
3161110bbbb 10bbbbbb 10bbbbbb
42111110bbb 10bbbbbb 10bbbbbb 10bbbbbb
Ahol minden b egy bitet jelent, amit karakter tárolásához használható.

xml_error_string

(PHP 3>= 3.0.6, PHP 4 )

xml_error_string -- visszaadja az XML elemző egy tipikus hibájához tartozó szöveget

Leírás

string xml_error_string ( int code)

code

Az xml_get_error_code() által visszaadott hiba kódja.

Visszaadja a code azonosítójú hibához tartozó szöveges magyarázatot, vagy FALSE-ot, ha nincs ilyen magyarázat.

xml_get_current_byte_index

(PHP 3>= 3.0.6, PHP 4 )

xml_get_current_byte_index --  visszaadja az XML elemző aktuális bájtindexét

Leírás

int xml_get_current_byte_index ( resource parser)

parser

hivatkozás az XML elemzőre, amelynek az aktuális bájtindexére kiváncsiak vagyunk.

xml_get_current_byte_index() visszaadja az adatpuffer aktuális bájtindexét (0-tól indítva), ami azt mutatja, hogy hol tart a feldolgozással az elemző jelenleg. Ha a parser nem egy érvényes elemzőt takar, akkor FALSE-t ad vissza.

xml_get_current_column_number

(PHP 3>= 3.0.6, PHP 4 )

xml_get_current_column_number --  visszaadja az XML elemző aktuális oszlop számát

Leírás

int xml_get_current_column_number ( resource parser)

parser

hivatkozás az XML elemzőre, amelynek az aktuális oszlopindexére kiváncsiak vagyunk.

xml_get_current_column_number() visszaadja az aktuális oszlop számát az aktuális soron belül, amit a xml_get_current_line_number()-rel lehet lekérdezni. Az aktuális annyit tesz, ahol az elemző jelenleg áll a feldolgozással. Ha a parser nem egy érvényes elemzőt takar, akkor FALSE-t ad vissza.

xml_get_current_line_number

(PHP 3>= 3.0.6, PHP 4 )

xml_get_current_line_number -- visszaadja az XML elemző aktuális sorindexét

Leírás

int xml_get_current_line_number ( resource parser)

parser

hivatkozás az XML elemzőre, amelynek az aktuális sorindexére kiváncsiak vagyunk.

xml_get_current_line_number() visszaadja az adatpuffer aktuális sorindexét, ami azt mutatja, hogy az elemző hányadik sorban tart a feldolgozással jelenleg. Ha a parser nem egy érvényes elemzőt takar, akkor FALSE-t ad vissza.

xml_get_error_code

(PHP 3>= 3.0.6, PHP 4 )

xml_get_error_code -- visszadja az elemzés hibakódját

Leírás

int xml_get_error_code ( resource parser)

parser

hivatkozás az XML elemzőre, amely az elemzés során hibát észlelt.

Ez a függvény a Hibakódok c. részben felsorolt hibák kódjával tér vissza (ha előzőleg hiba lépett fel az elemzés során). Ha a parser nem egy érvényes elemzőt takar, akkor FALSE-t ad vissza.

xml_parse_into_struct

(PHP 3>= 3.0.8, PHP 4 )

xml_parse_into_struct -- XML adatot tömbökbe pakol

Leírás

int xml_parse_into_struct ( resource parser, string data, array &values, array &index)

Ez a függvény az XML fájlt 2 párhuzamos tömbbe rendezi, ezek közül az egyik, az index mutatókat tartalmaz a másik, a values elemeire. Ezeket a paramétereket referencia szerint kell átadni a függvény számára.

Megjegyzés: Az index tömb az XML elemek nyitó és záró tag-jeit tartalmazza az elemzés időrendiségében, azaz adott elemhez tartozó címkék (tag-ek) nem feltétlenül egymás után, héjszerűen (egymásba ágyazva) szerepelnek. Az index tömb kulcsai a megtalált címkék nevei, a hozzájuk tartozó tömbök pedig indexeket tárolnak a values tömbhöz, ahol az adott címkéhez ill. az általa jelölt elemhez tartozó részletes információkat lehet megtalálni.

Az alábbi példa megvilágítja ezeknek a függvény által visszaadott tömböknek a belső felépítését és kapcsolataikat egymással. Ebben az egyszerű példában a para elem egy note elemet foglal magában:

$xml    = "<para><note>egyszerű kis megjegyzés</note></para>";
$parser = xml_parser_create();
xml_parse_into_struct($parser, $xml, $ertek, $index);
xml_parser_free($parser);
echo "indexek\n";
print_r($index);
echo "\nertekek\n";
print_r($ertek);

Futtatás után lássuk az így előálló szerkezeteket:

indexek
Array
(
    [PARA] => Array
        (
            [0] => 0
            [1] => 2
        )

    [NOTE] => Array
        (
            [0] => 1
        )

)

ertekek
Array
(
    [0] => Array
        (
            [tag] => PARA
            [type] => open
            [level] => 1
        )

    [1] => Array
        (
            [tag] => NOTE
            [type] => complete
            [level] => 2
            [value] => egyszerű kis megjegyzés
        )

    [2] => Array
        (
            [tag] => PARA
            [type] => close
            [level] => 1
        )

)

Az epxat könyvtáron alapuló eseményvezérelt elemzés bonyolult lehet, ha az XML dokumentumnak összetett a szerkezete. Ez a függvény nem DOM stílusú objektumhierarchiát állít elő az elemzést követően, de olyan könnyen kezelhető szerkezetet ad, amit faszerűen fel lehet dolgozni. Ekképpen, könnyen lehet az XML-t ábrázoló objektumokat létrehozni. Vegyük példaként a következő XML állományt, amely az aminosavak kis információs adatbázisa:

Példa 1. moldb.xml - molekuláris adatok adatbázisa

<?xml version="1.0"?>
<moldb>

    <molecule>
        <name>Alanine</name>
        <symbol>ala</symbol>
        <code>A</code>
        <type>víztaszító?</type>
    </molecule>

    <molecule>
        <name>Lysine</name>
        <symbol>lys</symbol>
        <code>K</code>
        <type>telített</type>
    </molecule>

</moldb>
és a következő programot, amely a megfelelő objektumokat állítja elő:

Példa 2. parsemoldb.php - beolvassa a moldb.xml-t

<?php

class AminoAcid {
    var $name;   // animosav neve
    var $symbol; // 3betűs rövidítés
    var $code;   // 1betűs kód
    var $type;   // víztaszító, telített vagy semleges

    function AminoAcid ($aa) {
        foreach ($aa as $k=>$v)
            $this->$k = $aa[$k];
    }
}

function readDatabase($filename) {
    // beolvassa az aminosavak XML adatbázisát
    $adat   = 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,$adat,$ertekek,$tagek);
    xml_parser_free($parser);

    // végighalad a tömbökön
    foreach ($tagek as $key => $val) {
        if ($key == "molecule") {
            $molranges = $val;
            // minden egymással határos tömbbejegyzés-pár a molekula
            // definicójának alsó és felső határa
            for ($i=0; $i < count($molranges); $i+=2) {
                    $offset = $molranges[$i] + 1;
                $len = $molranges[$i + 1] - $offset;
                $tdb[] = parseMol(array_slice($ertekek, $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 "** Aminosavak adatbázisa:\n";
print_r($db);

?>
A parsemoldb.php futtatásával előálló $db változó fogja tárolni az AminoAcid típusú objektumok tömbjét, és a program kimenete a következő lesz:

** Aminosavak adatbázisa:
Array
(
    [0] => aminoacid Object
        (
            [name] => Alanine
            [symbol] => ala
            [code] => A
            [type] => víztaszító
        )

    [1] => aminoacid Object
        (
            [name] => Lysine
            [symbol] => lys
            [code] => K
            [type] => telített
        )

)

xml_parse

(PHP 3>= 3.0.6, PHP 4 )

xml_parse -- elemez egy XML dokumentumot

Leírás

int xml_parse ( int parser, string data [, int isFinal])

parser

hivatkozás a használni kívánt XML elemzőre.

data

Az elemzendő adat mérete. Egy dokumentum kisebb darabonként is elemezhető, ha xml_parse()-t egymás után az újabb adattöredékekkel meghívva, mindaddig amíg az isFinal paraméter be van állítva, és az utolsó darab átadásakor TRUE az értéke.

isFinal (elhagyható)

Ha be van állítva és TRUE, akkor data a jelenleg elemzett dokumentum legutolsó darabja, ami még hátravan az elemzésből.

Egy XML dokumentum elemzésekor a beállított eseménykezelők kerülnek meghívásra mindannyiszor, amikor szükség van rájuk, majd ezután a függvény visszatérési értéke TRUE vagy FALSE.

TRUE, ha az elemzés sikeres volt, és FALSE ha sikertelen, vagy ha a parser nem egy érvényes elemzőt takar, akkor FALSE-t ad vissza. Sikertelen elemzést követően a hibáról az xml_get_error_code(), xml_error_string(), xml_get_current_line_number(), xml_get_current_column_number() és xml_get_current_byte_index() függvények segítségével lehet többet megtudni.

xml_parser_create_ns

(PHP 4 >= 4.0.5)

xml_parser_create_ns --  XML elemzőt hoz létre

Leírás

resource xml_parser_create_ns ( [string encoding [, string sep]])

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

xml_parser_create

(PHP 3>= 3.0.6, PHP 4 )

xml_parser_create -- XML elemzőt hoz létre

Leírás

resource xml_parser_create ( [string encoding])

encoding (optional)

Milyen kódolást használjon az elemző. Az alábbi karakterkódolásokat támogatja:

ISO-8859-1 (alapértelmezés szerinti)
US-ASCII
UTF-8

Ez a függvény létrehoz egy XML elemzőt, és visszaad egy azonosítót hozzá, amelyet a többi XML függvényhez kell használni. Hiba esetén FALSE-t ad vissza.

xml_parser_free

(PHP 3>= 3.0.6, PHP 4 )

xml_parser_free -- megszünteti az XML elemzőt

Leírás

string xml_parser_free ( resource parser)

parser

hivatkozás a megszüntetendő XML elemzőre.

Felszabadítja a parser által azonosított elemzőt, és TRUE-val tér vissza. Ha a parser nem egy érvényes elemzőt takar, akkor FALSE-t ad vissza.

xml_parser_get_option

(PHP 3>= 3.0.6, PHP 4 )

xml_parser_get_option -- információt ad az XML elemzőről

Leírás

mixed xml_parser_get_option ( resource parser, int option)

parser

hivatkozás a lekérdezni kívánt XML elemzőre.

option

a lekérdezendő paraméter neve, lásd a xml_parser_set_option() alatt az opciók listáját!

Visszaadja a parser XML elemző aktuális option beállítását. Ha a parser nem egy érvényes elemzőt takar, vagy az option nem megfelelő, akkor FALSE-t ad vissza.

Lásd a xml_parser_set_option() alatt az opciók listáját!

xml_parser_set_option

(PHP 3>= 3.0.6, PHP 4 )

xml_parser_set_option -- beállítja az XML elemző paramétereit

Leírás

bool xml_parser_set_option ( resource parser, int option, mixed value)

parser

hivatkozás a módosítani kívánt XML elemzőre.

option

a beállítandó opció/paraméter, lásd alább a táblázatban!

value

a beállítani kívánt érték.

TRUE-t ad vissza, ha sikerült a parser XML elemző option beállításához új értéket rendelni (value). Ha a parser nem egy érvényes elemzőt takar, vagy az option nem megfelelő, akkor FALSE-t ad vissza.

Az alábbi opciók/paraméterek használhatók:

Táblázat 1. XML elemző paraméterei

állandótípusleírás
XML_OPTION_CASE_FOLDINGinteger szabályozza az XML elemző "betű-egységesítési" beállítását. Alapértelmezés szerint engedélyezett.
XML_OPTION_TARGET_ENCODINGstring beállítja az XML elemző kimeneti (cél) karakterkódolását, ami alapértelmezés szerint megegyezik a bemeneti (forrás) karakterkódolásával, amit az xml_parser_create() meghívásakor lehet megadni. A támogatott kódolások: ISO-8859-1, US-ASCII és UTF-8.

xml_set_character_data_handler

(PHP 3>= 3.0.6, PHP 4 )

xml_set_character_data_handler -- szövegkezelő függvényt rendel az elemzőhöz

Leírás

bool xml_set_character_data_handler ( resource parser, string handler)

A parser paraméterben megjelölt XML elemző karakteres adat-kezelő függvényét állítja be, amelynek a nevét a handler paraméterben kell átadni. Ennek a függvénynek már léteznie kell, amikor a parser elemzővel meghívásra kerül az xml_parse() függvény.

A handler-ben megnevezett függvénynek két paramétert kell fogadnia, a függvény prototípusa a következő: handler ( resource parser, string data)

parser

Az első paraméter, parser, hivatkozás az aktuális XML elemzőre, amely a karakterkezelőt meghívta és használja.

data

A második sztring típusú paraméter, data, maga a karakteres adat.

Ha a függvény neve helyett üres sztring vagy FALSE szerepel, akkor a kérdéses kezelőfüggvény nem elérhető, le van tiltva.

TRUE-t ad vissza, ha a kezelőt sikeresen beállította, és FALSE-t, ha a parser nem érvényes erőforrás.

Megjegyzés: A függvény neve helyett egy tömböt is átadhatsz, ami egy objektum referenciát és egy metódus nevet kell tartalmazzon.

xml_set_default_handler

(PHP 3>= 3.0.6, PHP 4 )

xml_set_default_handler -- alap sztringkezelő függvényt rendel az elemzőhöz

Leírás

bool xml_set_default_handler ( resource parser, string handler)

A parser paraméterben megjelölt XML elemző alapértelmezés szerinti kezelő függvényét állítja be, amelynek a nevét a handler paraméterben kell átadni. Ennek a függvénynek már léteznie kell, amikor a parser elemzővel meghívásra kerül az xml_parse() függvény.

A handler-ben megnevezett függvénynek két paramétert kell fogadnia, a függvény prototípusa a következő: handler ( resource parser, string data)

parser

Az első paraméter, parser, hivatkozás az aktuális XML elemzőre, amely ezt a kezelőfüggvényt meghívta és használja.

data

A második sztring típusú paraméter, data, maga a karakteres adat. Ez lehet az XML deklaráció, a dokumentumtípus deklaráció, valamilyen entitás vagy valamilyen más karakteres adat, amihez nincs külön kezelőfüggvény beállítva.

Ha a függvény neve helyett üres sztring vagy FALSE szerepel, akkor a kérdéses kezelőfüggvény nem elérhető, le van tiltva.

TRUE-t ad vissza, ha a kezelőt sikeresen beállította, és FALSE-t, ha a parser nem érvényes erőforrás.

Megjegyzés: A függvény neve helyett egy tömböt is átadhatsz, ami egy objektum referenciát és egy metódus nevet kell tartalmazzon.

xml_set_element_handler

(PHP 3>= 3.0.6, PHP 4 )

xml_set_element_handler -- nyitó és záró jelöléseket kezelő függvényt rendel az elemzőhöz

Leírás

bool xml_set_element_handler ( resource parser, string startElementHandler, string endElementHandler)

A parser paraméterben megjelölt XML elemző elemek nyitó- és zárócímkéit kezelő függvényeit állítja be, amelyeknek a nevét a start_element_handler és end_element_handler paraméterben kell átadni. Ezeknek a függvényeknek már létezniük kell, amikor a parser elemzővel meghívásra kerül az xml_parse() függvény.

A start_element_handler-ben megnevezett függvénynek három paramétert kell fogadnia, a függvény prototípusa a következő: start_element_handler ( resource parser, string name, array attribs)

parser

Az első paraméter, parser, hivatkozás az aktuális XML elemzőre, amely ezt a kezelőfüggvényt meghívta és használja.

name

A második sztring típusú paraméter, name, az elem nevét tartalmazza. Ha a betű-egységesítés (case-folding) be van kapcsolva az elemzőben, akkor az elem neve csupa nagy betűvel fog szerepelni.

attribs

A harmadik paraméter, attribs asszociatív tömbjében kerülnek átadásra az elem attribútumai, ha vannak. A tömb kulcsai az attribútumok nevei, míg a hozzájuk tartozó értékek az attribútumok értékei. Az attribútumok neveinek írásmódja az elemek nevéhez hasonlóan egységesítve (case-folded) lesznek, de az attribútum-értékek nem.

A tömb megőrzi az attribútumok eredeti sorrendjét, ezért each() függvénnyel a tömbbön végiglépkedve az első bejegyzés az előfordulás szerinti első attribútumé lesz, és így tovább.

Az end_element_handler-ben megnevezett függvénynek két paramétert kell fogadnia, a függvény prototípusa a következő: end_element_handler ( resource parser, string name)

parser

Az első paraméter, parser, hivatkozás az aktuális XML elemzőre, amely ezt a kezelőfüggvényt meghívta és használja.

name

A második sztring típusú paraméter, name, az elem nevét tartalmazza. Ha a betű-egységesítés (case-folding) be van kapcsolva az elemzőben, akkor az elem neve csupa nagy betűvel fog szerepelni.

Ha a függvény neve helyett üres sztring vagy FALSE szerepel, akkor a kérdéses kezelőfüggvény nem elérhető, le van tiltva.

TRUE-t ad vissza, ha a kezelőt sikeresen beállította, és FALSE-t, ha a parser nem érvényes erőforrás.

Megjegyzés: A függvény neve helyett egy tömböt is átadhatsz, ami egy objektum referenciát és egy metódus nevet kell tartalmazzon.

xml_set_end_namespace_decl_handler

(PHP 4 >= 4.0.5)

xml_set_end_namespace_decl_handler --  névtérkezelő függvényt rendel az elemzőhöz

Leírás

bool xml_set_end_namespace_decl_handler ( resource pind, string hdl)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

Megjegyzés: A függvény neve helyett egy tömböt is átadhatsz, ami egy objektum referenciát és egy metódus nevet kell tartalmazzon.

xml_set_external_entity_ref_handler

(PHP 3>= 3.0.6, PHP 4 )

xml_set_external_entity_ref_handler -- külső egyedek kezelésére rendel függvényt az elemzőhöz

Leírás

bool xml_set_external_entity_ref_handler ( resource parser, string handler)

A parser paraméterben megjelölt XML elemző külső egyedeket (external entity) kezelő függvényét állítja be, amelynek a nevét a handler paraméterben kell átadni. Ennek a függvénynek már léteznie kell, amikor a parser elemzővel meghívásra kerül az xml_parse() függvény.

A handler-ben megnevezett függvénynek öt paramétert kell fogadnia és integer értéket visszaadnia. Ha a kezelőfüggvény FALSE-t ad vissza (ami megegyezik azzal az esettel ha nem ad vissza semmilyen értéket), az XML elemző XML_ERROR_EXTERNAL_ENTITY_HANDLING hibával leáll, amit az xml_get_error_code() függvénnyel lehet akkor kiolvasni. A függvény prototípusa a következő: int handler ( resource parser, string open_entity_names, string base, string system_id, string public_id)

parser

Az első paraméter, parser, hivatkozás az aktuális XML elemzőre, amely ezt a kezelőfüggvényt meghívta és használja.

open_entity_names

A második paraméter, open_entity_names, szóközzel elválaszott lista az elemző számára még függőben levő összes egyed nevével, beleértve a hivatkozott egyed nevét is.

base

Ez tartalmazná azt az "alapot", amivel külső egyedek rendszerazonosítóját (system_id) fel lehetne oldani. Ez a paraméter jelenleg üres sztringet ad.

system_id

A negyedik paraméter, system_id, ami az egyed deklarációjában szereplő rendszerazonosítót tartalmazza.

public_id

Az ötödik paraméter, public_id, az egyed-deklarációban meghatározott nyilvános azonosító, vagy üres sztring, ha nincs ilyen. Az XML specifikációnak megfelelően ebben a paraméterben a szóközök normalizálva lesznek.

Ha a függvény neve helyett üres sztring vagy FALSE szerepel, akkor a kérdéses kezelőfüggvény nem elérhető, le van tiltva.

TRUE-t ad vissza, ha a kezelőt sikeresen beállította, és FALSE-t, ha a parser nem érvényes erőforrás.

Megjegyzés: A függvény neve helyett egy tömböt is átadhatsz, ami egy objektum referenciát és egy metódus nevet kell tartalmazzon.

xml_set_notation_decl_handler

(PHP 3>= 3.0.6, PHP 4 )

xml_set_notation_decl_handler -- jelölések kezelésére rendel függvényt az elemzőhöz

Leírás

bool xml_set_notation_decl_handler ( resource parser, string handler)

A parser paraméterben megjelölt XML elemző jelölés (notation) -kezelő függvényét állítja be, amelynek a nevét a handler paraméterben kell átadni. Ennek a függvénynek már léteznie kell, amikor a parser elemzővel meghívásra kerül az xml_parse() függvény.

A jelölés deklaráció a DTD része, és a következő alakot ölti:
<!NOTATION
     name {systemId |
     publicId}>
. Lásd az XML 1.0 specifikáció 4.7 fejezetét a pontos jelölésdeklaráció szintaktikájáról!

A handler-ben megnevezett függvénynek öt paramétert kell fogadnia, a függvény prototípusa a következő: handler ( resource parser, string notation_name, string base, string system_id, string public_id)

parser

Az első paraméter, parser, hivatkozás az aktuális XML elemzőre, amely ezt a kezelőfüggvényt meghívta és használja.

notation_name

A jelölés neve, ahogy name, ahogy a fenti alakból kiolvasható.

base

Ez tartalmazná azt az "alapot", amivel külső jelölések rendszerazonosítóját (system_id) fel lehetne oldani. Ez a paraméter jelenleg üres sztringet ad.

system_id

A negyedik paraméter, system_id, ami a jelölés deklarációjában szereplő rendszerazonosítót tartalmazza.

public_id

Az ötödik paraméter, public_id, a jelölés-deklarációban meghatározott nyilvános azonosító.

Ha a függvény neve helyett üres sztring vagy FALSE szerepel, akkor a kérdéses kezelőfüggvény nem elérhető, le van tiltva.

TRUE-t ad vissza, ha a kezelőt sikeresen beállította, és FALSE-t, ha a parser nem érvényes erőforrás.

Megjegyzés: A függvény neve helyett egy tömböt is átadhatsz, ami egy objektum referenciát és egy metódus nevet kell tartalmazzon.

xml_set_object

(PHP 4 )

xml_set_object -- objektumon belüli XML elemző használatához

Leírás

void xml_set_object ( resource parser, object &object)

Ezzel a függvénnyel a parser elemzőt az object objektumon belül is lehet használni. Minden visszahívandó, beállítható kezelőfüggvény a megismert xml_set_element_handler() és társain keresztül állítható be. Mindegyik ilyen regisztrálást az object tagfüggvényeire (metódusaira) értelmez ezután.

<?php
class xml  {
    var $elemzo;

    function xml()
    {
        $this->elemzo = xml_parser_create();

        xml_set_object($this->elemzo, $this);
        xml_set_element_handler($this->elemzo, "nyito_cimke", "zaro_cimke");
        xml_set_character_data_handler($this->elemzo, "cdata");
    }

    function fuss_neki($adat)
    {
        xml_parse($this->elemzo, $adat);
    }

    function nyito_cimke($elemzo, $elem, $attributumok)
    {
        var_dump($elemzo, $elem, $attributumok);
    }

    function cdata($elemzo, $CDATA)
    {
        var_dump($elemzo, $CDATA);
    }

    function zaro_cimke($elemzo, $elem)
    {
        var_dump($elemzo, $elem);
    }

} // xml osztály vége

$xml_elemzo = new xml();
$xml_elemzo->fuss_neki("<A ID='hello'>PHP</A>");
?>

xml_set_processing_instruction_handler

(PHP 3>= 3.0.6, PHP 4 )

xml_set_processing_instruction_handler --  PI kezelőt rendel az elemzőhöz

Leírás

bool xml_set_processing_instruction_handler ( resource parser, string handler)

A parser paraméterben megjelölt XML elemző PI-kezelő függvényét állítja be, amelynek a nevét a handler paraméterben kell átadni. Ennek a függvénynek már léteznie kell, amikor a parser elemzővel meghívásra kerül az xml_parse() függvény.

A feldolgozó utasítás alakja az alábbi:

<?feldolgozó
       adat?>

Ezekben a feldolgozó utasításokban PHP kódot is el lehet helyezni, de vigyázni kell arra korlátozásra, hogy XML PI-n belül nem szerepelhet a PI végét jelző karaktersorozat (?>). Emiatt ez a karaktersorozat nem szerepelhet a beépített PHP kódban, mert különben az ezután álló kódot a PI-t "igazából" lezáró jelöléssel együtt sima szöveges adatnak fogja tekinteni az elemző.

A handler-ben megnevezett függvénynek három paramétert kell fogadnia, a függvény prototípusa a következő: handler ( resource parser, string target, string data)

parser

Az első paraméter, parser, hivatkozás az aktuális XML elemzőre, amely ezt a kezelőfüggvényt meghívta és használja.

target

A második paraméter, target, a PI feldolgozót jelöli.

data

A harmadik paraméter, data, a PI adatot tartalmazza.

Ha a függvény neve helyett üres sztring vagy FALSE szerepel, akkor a kérdéses kezelőfüggvény nem elérhető, le van tiltva.

TRUE-t ad vissza, ha a kezelőt sikeresen beállította, és FALSE-t, ha a parser nem érvényes erőforrás.

Megjegyzés: A függvény neve helyett egy tömböt is átadhatsz, ami egy objektum referenciát és egy metódus nevet kell tartalmazzon.

xml_set_start_namespace_decl_handler

(PHP 4 >= 4.0.5)

xml_set_start_namespace_decl_handler --  névtérkezelő függvényt rendel az elemzőhöz

Leírás

bool xml_set_start_namespace_decl_handler ( resource pind, string hdl)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

Megjegyzés: A függvény neve helyett egy tömböt is átadhatsz, ami egy objektum referenciát és egy metódus nevet kell tartalmazzon.

xml_set_unparsed_entity_decl_handler

(PHP 3>= 3.0.6, PHP 4 )

xml_set_unparsed_entity_decl_handler --  "nem elemzendő egyedek" kezelőfüggvényét állítja be az elemző számára

Leírás

bool xml_set_unparsed_entity_decl_handler ( resource parser, string handler)

A parser paraméterben megjelölt XML elemző "nem elemzendő egyedet" (unparsed entity) kezelő függvényét állítja be, amelynek a nevét a handler paraméterben kell átadni. Ennek a függvénynek már léteznie kell, amikor a parser elemzővel meghívásra kerül az xml_parse() függvény.

Ez az kezelőfüggvény akkor kerül meghívásra, ha az XML elemző az alábbi alakú, ún. külső, nem elemzendő egyed-deklarációval találkozik:
<!ENTITY name {public_id | system_id}
        NDATA notation_name>

Lásd még az XML 1.0 specifikáció 4.2.2 fejezetét a jelölésként deklarált külső egyedekről!

A handler-ben megnevezett függvénynek hat paramétert kell fogadnia, a függvény prototípusa a következő: handler ( resource parser, string entity_name, string base, string system_id, string public_id, string notation_name)

parser

Az első paraméter, parser, hivatkozás az aktuális XML elemzőre, amely ezt a kezelőfüggvényt meghívta és használja.

entity_name

A definiálandó egyed neve.

base

Ez tartalmazná azt az "alapot", amivel külső egyedek rendszerazonosítóját (system_id) fel lehetne oldani. Ez a paraméter jelenleg üres sztringet ad.

system_id

A negyedik paraméter, system_id, ami az egyed deklarációjában szereplő rendszerazonosítót tartalmazza.

public_id

Az ötödik paraméter, public_id, az egyed-deklarációban meghatározott nyilvános azonosító.

notation_name

Az egyed jelölésének (notation) a neve.(lásd: xml_set_notation_decl_handler()!)

Ha a függvény neve helyett üres sztring vagy FALSE szerepel, akkor a kérdéses kezelőfüggvény nem elérhető, le van tiltva.

TRUE-t ad vissza, ha a kezelőt sikeresen beállította, és FALSE-t, ha a parser nem érvényes erőforrás.

Megjegyzés: A függvény neve helyett egy tömböt is átadhatsz, ami egy objektum referenciát és egy metódus nevet kell tartalmazzon.

CXIV. XML-RPC functions

Bevezetés

These functions can be used to write XML-RPC servers and clients. You can find more information about XML-RPC at http://www.xmlrpc.com/, and more documentation on this extension and it's functions at http://xmlrpc-epi.sourceforge.net/.

Figyelem

Ez a kiterjesztés KÍSÉRLETI JELLEGGEL MŰKÖDIK. Ez azt jelenti, hogy minden itt dokumentált működés, beleértve a függvények nevét, működését vagy bármi más, amit a kiterjesztés kapcsán leírtunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a kiterjesztést csak a saját felelősségedre használd!


Követelmények

Az itt leírt függvények használatához semmilyen külső függvénykönyvtár megléte nem szükségeltetik.


Telepítés

XML-RPC support in PHP is not enabled by default. You will need to use the --with-xmlrpc[=DIR] configuration option when compiling PHP to enable XML-RPC support. This extension is bundled into PHP as of 4.1.0.


Futásidejű beállítások

Az alábbi függvények viselkedése befolyásolható a php.ini segítségével.

Táblázat 1. XML-RPC configuration options

NameDefaultChangeable
xmlrpc_errors"0"PHP_INI_SYSTEM
xmlrpc_error_number"0"PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().


Erőforrás típusok

Ez a kiterjesztés semmilyen erőforrás típust nem definiál.


Előre definiált állandók

Ez a kiterjesztés semmilyen konstans értéket nem definiál.

Tartalom
xmlrpc_decode_request -- Decodes XML into native PHP types
xmlrpc_decode -- Decodes XML into native PHP types
xmlrpc_encode_request -- Generates XML for a method request
xmlrpc_encode -- Generates XML for a PHP value
xmlrpc_get_type -- Gets xmlrpc type for a PHP value. Especially useful for base64 and datetime strings
xmlrpc_parse_method_descriptions -- Decodes XML into a list of method descriptions
xmlrpc_server_add_introspection_data -- Adds introspection documentation
xmlrpc_server_call_method -- Parses XML requests and call methods
xmlrpc_server_create -- Creates an xmlrpc server
xmlrpc_server_destroy -- Destroys server resources
xmlrpc_server_register_introspection_callback -- Register a PHP function to generate documentation
xmlrpc_server_register_method -- Register a PHP function to resource method matching method_name
xmlrpc_set_type -- Sets xmlrpc type, base64 or datetime, for a PHP string value

xmlrpc_decode_request

(PHP 4 >= 4.1.0)

xmlrpc_decode_request -- Decodes XML into native PHP types

Description

array xmlrpc_decode_request ( string xml, string &method [, string encoding])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

xmlrpc_decode

(PHP 4 >= 4.1.0)

xmlrpc_decode -- Decodes XML into native PHP types

Description

array xmlrpc_decode ( string xml [, string encoding])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

xmlrpc_encode_request

(PHP 4 >= 4.1.0)

xmlrpc_encode_request -- Generates XML for a method request

Description

string xmlrpc_encode_request ( string method, mixed params)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

xmlrpc_encode

(PHP 4 >= 4.1.0)

xmlrpc_encode -- Generates XML for a PHP value

Description

string xmlrpc_encode ( mixed value)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

xmlrpc_get_type

(PHP 4 >= 4.1.0)

xmlrpc_get_type -- Gets xmlrpc type for a PHP value. Especially useful for base64 and datetime strings

Description

string xmlrpc_get_type ( mixed value)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

xmlrpc_parse_method_descriptions

(PHP 4 >= 4.1.0)

xmlrpc_parse_method_descriptions -- Decodes XML into a list of method descriptions

Description

array xmlrpc_parse_method_descriptions ( string xml)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

xmlrpc_server_add_introspection_data

(PHP 4 >= 4.1.0)

xmlrpc_server_add_introspection_data -- Adds introspection documentation

Description

int xmlrpc_server_add_introspection_data ( resource server, array desc)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

xmlrpc_server_call_method

(PHP 4 >= 4.1.0)

xmlrpc_server_call_method -- Parses XML requests and call methods

Description

mixed xmlrpc_server_call_method ( resource server, string xml, mixed user_data [, array output_options])

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

xmlrpc_server_create

(PHP 4 >= 4.1.0)

xmlrpc_server_create -- Creates an xmlrpc server

Description

resource xmlrpc_server_create ( void )

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

xmlrpc_server_destroy

(PHP 4 >= 4.1.0)

xmlrpc_server_destroy -- Destroys server resources

Description

int xmlrpc_server_destroy ( resource server)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

xmlrpc_server_register_introspection_callback

(PHP 4 >= 4.1.0)

xmlrpc_server_register_introspection_callback -- Register a PHP function to generate documentation

Description

bool xmlrpc_server_register_introspection_callback ( resource server, string function)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

xmlrpc_server_register_method

(PHP 4 >= 4.1.0)

xmlrpc_server_register_method -- Register a PHP function to resource method matching method_name

Description

bool xmlrpc_server_register_method ( resource server, string method_name, string function)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

xmlrpc_set_type

(PHP 4 >= 4.1.0)

xmlrpc_set_type -- Sets xmlrpc type, base64 or datetime, for a PHP string value

Description

bool xmlrpc_set_type ( string value, string type)

Figyelem

Ez a függvény KÍSÉRLETI JELLEGGEL MŰKÖDIK. A függvény működése, neve, bármi amit a függévénnyel kapcsolatban dokumentáltunk megváltozhat egy későbbi PHP kiadásban minden figyelmeztetés nélkül. Ezt a függvényt csak a saját felelősségedre használd!

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

CXV. XSLT függvények

Bevezetés

Ez a PHP kiterjesztés a használt motortól független API (programozási felületet) biztosít XSLT transzformációk elvégzéhez, ám jelenleg csak a Ginger Alliance Sablotron motorját támogatja. Más XSLT könyvtárak támogatása is tervbe van véve, mint például Xalan vagy libxslt.

Az XSLT (Extensible Stylesheet Language (XSL) Transformations) XML dokumentumok más szerkezetű XML dokumentumokká alakítását végző nyelv. A World Wide Web consortium (W3C) igazgatja ezt a szabványt. Az XSLT-ről és a kapcsolodó technológiákról a http://www.w3.org/TR/xslt címen találsz több olvasnivalót.

Megjegyzés: Ez a kiterjesztés különbözik a PHP 4.1.x előtti verziókban meglevőtől, és az új kiterjesztés csak a PHP 4.1.x verzióiban használható. A régi kiterjesztéssel kapcsolatos kérdéseket a php-general@lists.php.net levelező listán teheted fel.


Követelmények

Ez a kiterjesztés a Sablotron és expat csomagokat használja, amelyeknek forrásai és fordított változata is megtalálhatók a http://www.gingerall.com/ címen.


Telepítés

UNIX rendszeren a configure szkriptet az --enable-xslt --with-xslt-sablot kapcsolókkal kell futtatni. A Sablotron csomagot előzőleg olyan helyre kell telepíteni, ahol a fordító megtalálja.


Futásidejű beállítások

Ez a kiterjesztés semmilyen konfigurációs beállításokat nem definiál a php.ini állományban.


Erőforrás típusok

Ez a kiterjesztés semmilyen erőforrás típust nem definiál.


Előre definiált állandók

Ez a kiterjesztés semmilyen konstans értéket nem definiál.

Tartalom
xslt_create -- új XSLT feldolgozó indítása
xslt_errno -- visszaadja a hibakódot
xslt_error -- visszaadja a hibaüzenetet
xslt_free -- megszünteti az XSLT feldolgozó erőforrás
xslt_process -- végrehajtja az XSLT transzformációt
xslt_set_base -- beállítja az alap URI-t mindegyik XSLT feldolgozáshoz
xslt_set_encoding -- beállítja az XML dokumentumok kódolását
xslt_set_error_handler -- beállítja az XSLT feldolgozó hibakezelőjét
xslt_set_log -- beállítja a naplófájl nevét
xslt_set_sax_handler -- beállítja az XSLT feldolgozó SAX kezelőjét
xslt_set_sax_handlers --  beállítja az XML dokumentumok feldolgozásakor meghívandó SAX kezelőt
xslt_set_scheme_handler -- beállítja az XSLT feldolgozó scheme kezelőjét
xslt_set_scheme_handlers --  beállítja az XSLT feldolgozó scheme kezelőit

xslt_create

(PHP 4 >= 4.0.3)

xslt_create -- új XSLT feldolgozó indítása

Leírás

resource xslt_create ( void )

Létrehoz az XSLT feldolgozó erőforrást, amellyel a többi XSLT függvény dolgozik. Ezt az erőforrást adja vissza.

xslt_errno

(PHP 4 >= 4.0.3)

xslt_errno -- visszaadja a hibakódot

Leírás

int xslt_errno ( resource xh)

Visszaadja az xh XSLT feldolgozó kibocsátotta legutolsó hiba kódját.

xslt_error

(PHP 4 >= 4.0.3)

xslt_error -- visszaadja a hibaüzenetet

Leírás

mixed xslt_error ( resource xh)

Visszaadja az xh XSLT feldolgozó kibocsátotta legutolsó hiba szövegét.

Példa 1. Hibakezelés az xslt_error() és xslt_errno() függvényekkel.

<?php

$xh = xslt_create();
$result = xslt_process($xh, 'kutya.xml', 'kedvencek.xsl');
if (!$result) {
    die(sprintf("Nem lehet az XSLT dokumentumot feldolgozni [%d]: %s",
                xslt_errno($xh), xslt_error($xh)));
}

print($result);

xslt_free($xh);
?>

xslt_free

(PHP 4 >= 4.0.3)

xslt_free -- megszünteti az XSLT feldolgozó erőforrás

Leírás

void xslt_free ( resource xh)

Az xh paraméterben megadott XSLT feldolgozó erőforrást felszabadítja.

xslt_process

(PHP 4 >= 4.0.3)

xslt_process -- végrehajtja az XSLT transzformációt

Leírás

mixed xslt_process ( resource xh, string xml, string xsl [, string result [, array arguments [, array parameters]]])

Az új XSLT kiterjesztés magva a xslt_process() függvény. Ezzel lehet XSLT transzformációkat végezni szinte mindenféle forrású adaton - az argumentum puffer koncepiójára építve. Az argumentum puffer elképzelése a Sablotron XSLT feldolgozótól származik, amely jelenleg az egyetlen támogatott XSLT feldolgozó ehhez a kiterjesztéshez.

A legegyszerűbb transzformáció, ha az xslt_process() fájlokon dolgozik: a megadott XML fájlt egy XSLT fájl alapján transzformál és a végeredményt egy harmadikba írja. Ez Sablotronnal tényleg elég egyszerű...

Példa 1. Az xslt_process() használata XML fájl XSLT transzformációjára. A végeredmény is fájlba kerül

<?php

// új XSLT feldolgozó lefoglalása
$xh = xslt_create();

// dokumentum feldolgozása
if (xslt_process($xh, 'minta.xml', 'minta.xsl', 'eredmeny.xml')) {
    print "SIKER, a minta.xml a minta.xsl alapján feldolgozásra került,";
    print " az eredmeny.xml tartalmazza a muvelet vegeredmenyet, ami:<br />\n";
    print "<pre>\n";
    readfile('eredmeny.xml');
    print "</pre>\n";
}
else {
    print "Sajnálom, a minta.xml-t nem lehet a minta.xsl alapján feldolgozni,";
    print "amelynek az oka: " . xslt_error($xh);
    print " és a hibakódja: " . xslt_errno($xh);
}

xslt_free($xh);

?>

Bár nagyon hasznos ez a müködési elv, sokszor, főképp webes környezetben a kimenetet közvetlenül ki kell iratni, nem pedig fájlba menteni; ezért a harmadik paraméter elhagyása vagy NULL értéke esetén, az xslt_process() automatikusan az XSLT transzformáció eredményével tér vissza.

Példa 2. Az xslt_process() XML fájl XSL fájl alapú transzformációjának eredménye változóba kerül elmentésre

<?php

// új XSLT feldolgozó lefoglalása
$xh = xslt_create();

// dokumentum feldolgozása
$result = xslt_process($xh, 'minta.xml', 'minta.xsl');
if ($result) {
    print "SIKER, a minta.xml a minta.xsl alapján feldolgozásra került,";
    print " amelynek az eredménye a \$result változóba került: <br />\n";
    print "<pre>\n";
    print $result;
    print "</pre>\n";
}
else {
    print "Sajnálom, a minta.xml-t nem lehet a minta.xsl alapján feldolgozni,";
    print "amelynek az oka: " . xslt_error($xh);
    print " és a hibakódja: " . xslt_errno($xh);
}

xslt_free($xh);

?>

A két fenti eset a XSLT transzformáció két legegyszerűbb esete, ám merem állítani a leggyakoribb módjai is ennek. Vannak olyan helyzetek azonban, amikor az XML és az XSLT fájlok nem állnak rendelkezésre, hanem azok külső forrásból - pl. adatbázisból vagy hálózaton keresztül érkeznek. Ekkor az XML és XSLT adatok csak változók formájában hozzáférhetők, és piaci alkalmazások esetén a fájlba másolás okozta veszteség nem megengedhető. Ebben segít az XSLT "argument" szintaxisa. XML és XSLT fájlok helyett ún. "argumentum helyfoglalókat" lehet definiálni, amelyek helyett az arguments (5.) paraméterben megadott tartalmat fogja használni az XSLT feldolgozó. A következő példa egyetlen fájlt sem használ.

Példa 3. Using the xslt_process() to transform a variable containing XML data and a variable containing XSL data into a variable containing the resulting XML data

<?php
// $xml és $xsl tartalmazza az XML és XSL adatokat

$arguments = array(
     '/_xml' => $xml,
     '/_xsl' => $xsl
);

// új XSLT feldolgozó allokálása
$xh = xslt_create();

// a dokumentum feldolgozása
$result = xslt_process($xh, 'arg:/_xml', 'arg:/_xsl', NULL, $arguments);
if ($result) {
    print "SIKER, a minta.xml a minta.xsl alapján feldolgozásra került,";
    print " amelynek az eredménye a \$result változóba került: <br />\n";
    print "<pre>\n";
    print $result;
    print "</pre>\n";
}
else {
    print "Sajnálom, a minta.xml-t nem lehet a minta.xsl alapján feldolgozni,";
    print "amelynek az oka: " . xslt_error($xh);
    print " és a hibakódja: " . xslt_errno($xh);
}

xslt_free($xh);
?>

Végezetül, az xslt_process() utolsó, parameters paraméterében bármlyen adat átadható az XSLT feldolgozónak az XSL dokumentumhoz. Ezeket a paramétereket az XSL-en belül <xsl:param name="parameter_name"> utasítással érhetők el.

xslt_set_base

(PHP 4 >= 4.0.5)

xslt_set_base -- beállítja az alap URI-t mindegyik XSLT feldolgozáshoz

Leírás

void xslt_set_base ( resource xh, string uri)

Beállítja azt az alap URI-t mindegyik XSLT feldolgozáshoz, amely az Xpath kifejezésekben előforduló document() és egyéb külső forrást használó parancsok kezeléséhez szükséges.

xslt_set_encoding

(PHP 4 >= 4.0.5)

xslt_set_encoding -- beállítja az XML dokumentumok kódolását

Leírás

void xslt_set_encoding ( resource xh, string encoding)

Beállítja az XSLT transzformáció kimenetén használt kódolást. Csak akkor használható, ha a Sablotron kiszolgáló encoding támogatással lett fordítva.

xslt_set_error_handler

(PHP 4 >= 4.0.4)

xslt_set_error_handler -- beállítja az XSLT feldolgozó hibakezelőjét

Leírás

void xslt_set_error_handler ( resource xh, mixed handler)

Beállítja az xh-ban megadott XSLT feldolgozó hibakezelőjét. Ez a hibakezelő kerül meghívásra mindannyiszor, ha hiba történik az XSLT transzformáció során. Ugyanez a függvény kezeli a megjegyzéseket (notice).

xslt_set_log

(PHP 4 >= 4.0.6)

xslt_set_log -- beállítja a naplófájl nevét

Leírás

void xslt_set_log ( resource xh, mixed log)

xh

Hivatkozás az XSLT elemzőre.

log

Ez a paraméter lehet egy logikai érték, ami ki-bekapcsolja a naplózást, vagy lehet egy sztring is, amely a naplófájl nevét tartalmazza.

Ezzel a függvénnyel beállítható, hogy melyik fájlba kerüljenek az XSLT üzenetek. Ezek az üzenetek abban különböznek a hibaüzenetektől, hogy nem tényleges hibákról értesítnek, hanem inkább az XSLT feldolgozó állapotáról, ezért hibakereséskor hasznosak, ha valami nem jól működik az XSLT körül.

Alapértelmezés szerint a naplózás inaktív, így az engedélyezéshez először logikai paraméterrel kell meghívni az xslt_set_log()-ot, és ha a naplózást fájlba szeretnéd átirányítani, akkor egy sztring paraméterrel is meg kell hívni.

Példa 1. XSLT naplózás használata

<?php

$xh = xslt_create();
xslt_set_log($xh, TRUE);
xslt_set_log($xh, getcwd() . 'xslt.log');

$result = xslt_process($xh, 'kutya.xml', 'kedvencek.xsl');
print($result);

xslt_free($xh);
?>

xslt_set_sax_handler

(4.0.3 - 4.0.6 only)

xslt_set_sax_handler -- beállítja az XSLT feldolgozó SAX kezelőjét

Leírás

void xslt_set_sax_handler ( resource xh, array handlers)

Beállítja a SAX kezelőt az xh-ban megadott XSLT feldolgozó számára. A SAX kezelőket a handlers kétdimenziós tömbben kell megadni a következők szerint (bármelyik legfelső szintű elem elhagyható):

array(
[document] =>
    array(
        start document handler,
        end document handler
    ),
[element] =>
    array(
        start element handler,
        end element handler
    ),
[namespace] =>
    array(
        start namespace handler,
        end namespace handler
    ),
[comment] => comment handler,
[pi] => processing instruction handler,
[character] => character data handler
)

xslt_set_sax_handlers

(PHP 4 >= 4.0.6)

xslt_set_sax_handlers --  beállítja az XML dokumentumok feldolgozásakor meghívandó SAX kezelőt

Leírás

void xslt_set_sax_handlers ( resource processor, array handlers)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

xslt_set_scheme_handler

(4.0.5 - 4.0.6 only)

xslt_set_scheme_handler -- beállítja az XSLT feldolgozó scheme kezelőjét

Leírás

void xslt_set_scheme_handler ( resource xh, array handlers)

Beállítja az xh-ban megadott XSLT feldolgozó scheme kezelőjét. A scheme kezelőket a handlers tömbben kell megadni a következők szerint (bármelyik elem elhagyható):

array(
[get_all] => get all handler,
[open] => open handler,
[get] => get handler,
[put] => put handler,
[close] => close handler
)

xslt_set_scheme_handlers

(PHP 4 >= 4.0.6)

xslt_set_scheme_handlers --  beállítja az XSLT feldolgozó scheme kezelőit

Leírás

void xslt_set_scheme_handlers ( resource processor, array handlers)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

CXVI. YAZ functions

Bevezetés

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


Telepítés

Compile YAZ (ANSI/NISO Z39.50 support) and install it. Build PHP with your favourite modules and add option --with-yaz[=DIR]. Your task is roughly the following:

Példa 1. YAZ compilation

gunzip -c php-4.3.X.tar.gz|tar xf -
gunzip -c yaz-2.0.tar.gz|tar xf -
cd yaz-2.0
./configure --prefix=/usr
make
make install
cd ../php-4.3.X.
./configure --with-yaz=/usr/bin
make
make install

If you are using YAZ as a shared extension, add (or uncomment) the following line in php.ini on Unix:
extension=php_yaz.so
And for Windows:
extension=php_yaz.dll

On Windows, php_yaz.dll depend on yaz.dll. You'll find yaz.dll in sub directory dlls in the Win32 zip archive. Copy yaz.dll to a directory in your PATH environment (c:\winnt\system32 or c:\windows\system32).

Figyelem

Az IMAP kiterjesztés nem használható együtt a recode és YAZ kiterjesztésekkel. Ennek oka az, hogy C forrás szinten ugyanazt a beépített szimbólumot használják.

Megjegyzés: The above problem is solved in version 2.0 of YAZ.


Futásidejű beállítások

Az alábbi függvények viselkedése befolyásolható a php.ini segítségével.

Táblázat 1. YAZ configuration options

NameDefaultChangeable
yaz.max_links"100"PHP_INI_ALL
yaz.log_file""PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().


Erőforrás típusok

Ez a kiterjesztés semmilyen erőforrás típust nem definiál.


Előre definiált állandók

Ez a kiterjesztés semmilyen konstans értéket nem definiál.


Példák

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.

Példa 2. Parallel searching using Yaz

<?php
$num_hosts = count($host);
if (empty($term) || 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="term" />
    <input type="submit" name="action" value="Search" />
    </form>
    ';        
} else {
    echo 'You searched for ' . htmlspecialchars($term) . '<br />';
    for ($i = 0; $i < $num_hosts; $i++) {
        $id[] = yaz_connect($host[$i]);
        yaz_range($id[$i], 1, 10);
        yaz_search($id[$i], "rpn", $term);
    }
    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>';
    }
}
?>

Tartalom
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_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 the maximum number 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

yaz_addinfo

(PHP 4 >= 4.0.1)

yaz_addinfo -- Returns additional error information

Description

string yaz_addinfo ( resource id)

Returns additional error message for server (last request), identified by parameter id. An empty string is returned if the last operation was successful or if no additional information was provided by the server.

See also yaz_error().

yaz_ccl_conf

(PHP 4 >= 4.0.5)

yaz_ccl_conf -- Configure CCL parser

Description

int 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. Each index of the array config 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.

Példa 1. CCL configuration

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.

<?php
$fields["ti"] = "1=4";
$fields["au"] = "1=1";
$fields["isbn"] = "1=7";
yaz_ccl_conf($id, $fields);
?>

yaz_ccl_parse

(PHP 4 >= 4.0.5)

yaz_ccl_parse -- Invoke CCL Parser

Description

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. If the supplied query was successfully converted to RPN, this function returns TRUE, and the index rpn of the supplied array result holds a valid RPN query. If the query could not be converted (because of invalid syntax, unknown field, etc.) this function returns FALSE and three indexes are set in the resulting array to indicate the cause of failure: errorcode CCL error code (integer), errorstring CCL error string, and errorpos approximate position in query of failure (integer is character position).

Példa 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_close

(PHP 4 >= 4.0.1)

yaz_close -- Close YAZ connection

Description

bool yaz_close ( resource id)

Closes the connection given by parameter id. The id is a connection resource as returned by a previous call to yaz_connect().

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

yaz_connect

(PHP 4 >= 4.0.1)

yaz_connect --  Prepares for a connection to a Z39.50 server.

Description

resource 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. The zurl argument takes the form host[:port][/database]. If port is omitted, port 210 is used. If database is omitted Default is used. 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.

If the second argument, options, is given as a string it is treated as the Z39.50 V2 authentication string (OpenAuth).

If options is given as an array the contents of the array serves as options. Note that array options are only supported for PHP 4.1.0 and later.

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

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.

Megjegyzés: The use of a proxy often improves performance. A Z39.50 proxy is part of the free YAZ++ package.

yaz_database

(PHP 4 >= 4.0.6)

yaz_database --  Specifies the databases within a session

Description

bool yaz_database ( resource id, string databases)

This function specifies one or more databases to be used in search, retrieval, etc. - overriding databases specified in call to yaz_connect(). Multiple databases are separated by a plus sign +.

This function allows you to use different sets of databases within a session.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

yaz_element

(PHP 4 >= 4.0.1)

yaz_element --  Specifies Element-Set Name for retrieval

Description

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. Most servers support F (for full records) and B (for brief records).

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

yaz_errno

(PHP 4 >= 4.0.1)

yaz_errno -- Returns error number

Description

int yaz_errno ( resource id)

Returns an errornumber for the server (last request) identified by id. 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.

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). To get a text description of the error, call yaz_error().

yaz_error

(PHP 4 >= 4.0.1)

yaz_error -- Returns error description

Description

string yaz_error ( resource id)

Returns an error text message for server (last request), identified by parameter id. An empty string is returned if the last operation was successful.

yaz_error() returns an English text message corresponding to the last error number as returned by yaz_errno().

yaz_es_result

(PHP 4 >= 4.2.0)

yaz_es_result --  Inspects Extended Services Result

Description

array yaz_es_result ( resource id)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

yaz_get_option

(PHP 5 CVS only)

yaz_get_option -- Returns value of option for connection

Description

string yaz_get_option ( resource id, string name)

Returns the value of the option specified with name. If an option is not set, an empty string is returned.

See the description of yaz_set_option() for available options.

yaz_hits

(PHP 4 >= 4.0.1)

yaz_hits -- Returns number of hits for last search

Description

int yaz_hits ( resource id)

yaz_hits() returns the number of hits for the last search.

yaz_itemorder

(PHP 4 >= 4.0.5)

yaz_itemorder --  Prepares for Z39.50 Item Order with an ILL-Request package

Description

int 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. The args parameter must be a hash 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
    

yaz_present

(PHP 4 >= 4.0.5)

yaz_present --  Prepares for retrieval (Z39.50 present).

Description

bool yaz_present ( resource id)

This function prepares for retrieval of records after a successful search. The yaz_range() should be called prior to this function to specify the range of records to be retrieved.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

yaz_range

(PHP 4 >= 4.0.1)

yaz_range --  Specifies the maximum number of records to retrieve

Description

bool yaz_range ( resource id, int start, int number)

This function should be called before either yaz_search() or yaz_present() to specify a range of records to be retrieved. The parameter start specifies the position of the first record to be retrieved and parameter number is the number of records. Records in a result set are numbered 1, 2, ... $hits where $hits is the count returned by yaz_hits().

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

yaz_record

(PHP 4 >= 4.0.1)

yaz_record -- Returns a record

Description

string yaz_record ( resource id, int pos, string type)

Returns the record at position pos or an empty string if no record exists at the given position.

The yaz_record() function inspects a record in the current result set at the position specified by parameter pos. If no database record exists at the given position an empty string is returned. The type specifies the form of the returned record.

If type is "string" the record is returned in a string representation suitable for printing (for XML and SUTRS). If type is "array" the record is returned as an array representation (for structured records). If type is "raw" the record is returned in its original raw form.

Records in a result set are numbered 1, 2, ... $hits where $hits is the count returned by yaz_hits().

yaz_scan_result

(PHP 4 >= 4.0.5)

yaz_scan_result -- Returns Scan Response result

Description

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(). This function 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. If the optional parameter result is given it 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).

yaz_scan

(PHP 4 >= 4.0.5)

yaz_scan -- Prepares for a scan

Description

int yaz_scan ( resource id, string type, string startterm [, array flags])

This function prepares for a Z39.50 Scan Request, where parameter id specifies connection. Starting term point for the scan is given by startterm. The form in which the starting term is specified is given by parameter type. Currently only type rpn is supported. The optional parameter flags specifies additional information to control the behaviour of the scan request. Three indexes are currently read from the flags: number (number of terms requested), position (preferred position of term) and stepSize (preferred step size). 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.

The syntax of startterm is similar to the RPN query as described in yaz_search(). The startterm consists of zero or more @attr-operator specifications, then followed by exactly one token.

Példa 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; ';
    while (list($key, $val) = each($options)) {
      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_schema

(PHP 4 >= 4.2.0)

yaz_schema --  Specifies schema for retrieval.

Description

int yaz_schema ( resource id, string schema)

The 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, ... This function should be called before yaz_search() or yaz_present().

yaz_search

(PHP 4 >= 4.0.1)

yaz_search -- Prepares for a search

Description

int yaz_search ( resource id, string type, string query)

yaz_search() prepares for a search on the connection given by parameter id. The parameter type represents the query type - only "rpn" is supported now in which case the third argument specifies a Type-1 query in prefix query notation. Like yaz_connect() this function is non-blocking and only prepares for a search to be executed later when yaz_wait() is called.

The RPN 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 operater 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.

Táblázat 1. RPN Operators

ConstructDescription
@and query1 query2intersection of query1 and query2
@or query1 query2union of query1 and query2
@not query1 query2query1 and not query2
@set nameresult set reference
@attrset set queryspecifies attribute-set for query. This construction is only allowed once - in the beginning of the whole query
@attr [set] type=value queryapplies 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.

Példa 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.

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

You can find information about attributes at the Z39.50 Maintenance Agency site.

Megjegyzés: If you would like to use a more friendly notation, use the CCL parser - functions yaz_ccl_conf() and yaz_ccl_parse().

yaz_set_option

(PHP 5 CVS only)

yaz_set_option -- Sets one or more options for connection

Description

string yaz_set_option ( resource id, string name, string value)

Sets option name to value.

Táblázat 1. PYP/YAZ Connection Options

NameDescription
implementationNameimplementation name of server
implementationVersionimplementation version of server
implementationIdimplementation ID of server
schemaschema for retrieval. By default, no schema is used. Setting this option is equivalent to using function yaz_schema()
preferredRecordSyntaxrecord syntax for retrieval. By default, no syntax is used. Setting this option is equivalent to using function yaz_syntax()
startoffset 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()
countmaximum number of records to be retrieved via yaz_search() or yaz_present().
elementSetNameelement-set-name for retrieval. Setting this option is equivalent to calling yaz_element().

yaz_sort

(PHP 4 >= 4.1.0)

yaz_sort -- Sets sorting criteria

Description

int 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(). The parameter criteria 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

Példa 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_syntax

(PHP 4 >= 4.0.1)

yaz_syntax --  Specifies the preferred record syntax for retrieval.

Description

int yaz_syntax ( resource id, string 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.). This function should be called before yaz_search() or yaz_present().

yaz_wait

(PHP 4 >= 4.0.1)

yaz_wait -- Wait for Z39.50 requests to complete

Description

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

If the options array is given that holds options that change the behaviour of yaz_wait().

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.

CXVII. YP/NIS Functions

Bevezetés

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.

Megjegyzés: Ez a kiterjesztés nem működik Windows operációs rendszereken!


Követelmények

None besides functions from standard Unix libraries which are always available (either libc or libnsl, configure will detect which one to use).


Telepítés

To get these functions to work, you have to configure PHP with --enable-yp.


Futásidejű beállítások

Ez a kiterjesztés semmilyen konfigurációs beállításokat nem definiál a php.ini állományban.


Előre definiált állandók

Az itt listázott állandókat ez a kiterjesztés definiálja, és csak akkor elérhetőek, ha az adott kiterjesztés be van fordítva a PHP-be, vagy dinamikusan betöltött.

YPERR_BADARGS (integer)

YPERR_BADDB (integer)

YPERR_BUSY (integer)

YPERR_DOMAIN (integer)

YPERR_KEY (integer)

YPERR_MAP (integer)

YPERR_NODOM (integer)

YPERR_NOMORE (integer)

YPERR_PMAP (integer)

YPERR_RESRC (integer)

YPERR_RPC (integer)

YPERR_YPBIND (integer)

YPERR_YPERR (integer)

YPERR_YPSERV (integer)

YPERR_VERS (integer)

Tartalom
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

yp_all

(PHP 4 >= 4.0.6)

yp_all --  Traverse the map and call a function on each entry

Description

void yp_all ( string domain, string map, string callback)

Figyelem

Ez a függvény jelenleg nincs dokumentálva, csak a paraméterek listája található itt.

yp_cat

(PHP 4 >= 4.0.6)

yp_cat --  Return an array containing the entire map

Description

array yp_cat ( string domain, string map)

yp_cat() returns all map entries as an array with the maps key values as array indices and the maps entries as array data.

yp_err_string

(PHP 4 >= 4.0.6)

yp_err_string --  Returns the error string associated with the given error code

Description

string yp_err_string ( int errorcode)

yp_err_string() returns the error message associated with the given error code. Useful to indicate what exactly went wrong.

Példa 1. Example for NIS errors

<?php
    echo "Error: " . yp_err_string(yp_errno());
?>

See also yp_errno().

yp_errno

(PHP 4 >= 4.0.6)

yp_errno --  Returns the error code of the previous operation

Description

int yp_errno ( void )

yp_errno() returns the error code of the previous operation.

Possible errors are:

1 args to function are bad
2 RPC failure - domain has been unbound
3 can't bind to server on this domain
4 no such map in server's domain
5 no such key in map
6 internal yp server or client error
7 resource allocation failure
8 no more records in map database
9 can't communicate with portmapper
10 can't communicate with ypbind
11 can't communicate with ypserv
12 local domain name not set
13 yp database is bad
14 yp version mismatch
15 access violation
16 database busy

See also yp_err_string().

yp_first

(PHP 3>= 3.0.7, PHP 4 )

yp_first --  Returns the first key-value pair from the named map

Description

array yp_first ( string domain, string map)

yp_first() returns the first key-value pair from the named map in the named domain, otherwise FALSE.

Példa 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;
?>

See also yp_next() and yp_get_default_domain().

yp_get_default_domain

(PHP 3>= 3.0.7, PHP 4 )

yp_get_default_domain -- Fetches the machine's default NIS domain

Description

int yp_get_default_domain ( void )

yp_get_default_domain() returns the default domain of the node or FALSE. 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.

Példa 1. Example for the default domain

<?php
$domain = yp_get_default_domain();
echo "Default NIS domain is: " . $domain;
?>

yp_master

(PHP 3>= 3.0.7, PHP 4 )

yp_master --  Returns the machine name of the master NIS server for a map

Description

string yp_master ( string domain, string map)

yp_master() returns the machine name of the master NIS server for a map.

Példa 1. Example for the NIS master

<?php
$number = yp_master($domain, $mapname);
echo "Master for this map is: " . $master;
?>

See also yp_get_default_domain().

yp_match

(PHP 3>= 3.0.7, PHP 4 )

yp_match -- Returns the matched line

Description

string yp_match ( string domain, string map, string key)

yp_match() returns the value associated with the passed key out of the specified map or FALSE. This key must be exact.

Példa 1. Example for NIS match

<?php
$entry = yp_match($domain, "passwd.byname", "joe");
echo "Matched entry is: " . $entry;
?>

The above code will produce :

joe:##joe:11111:100:Joe User:/home/j/joe:/usr/local/bin/bash

See also yp_get_default_domain().

yp_next

(PHP 3>= 3.0.7, PHP 4 )

yp_next -- Returns the next key-value pair in the named map.

Description

array yp_next ( string domain, string map, string key)

yp_next() returns the next key-value pair in the named map after the specified key or FALSE.

Példa 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];
?>

See also yp_first() and yp_get_default_domain().

yp_order

(PHP 3>= 3.0.7, PHP 4 )

yp_order -- Returns the order number for a map

Description

int yp_order ( string domain, string map)

yp_order() returns the order number for a map or FALSE.

Példa 1. Example for the NIS order

<?php
    $number = yp_order($domain, $mapname);
    echo "Order number for this map is: " . $number;
?>

See also yp_get_default_domain().

CXVIII. Zip Fájl függvények (csak olvasáshoz)

Ez a modul a ZZIPlib könyvtár függvényeit használja, a zip eljárással tömörített állományok és a bennük levő fájlok olvasásához. A ZZIPlib-et Guido Draheimnek köszönhetjük.

Vedd figyelembe, hogy a ZZIPlib csak a teljes zip imlementációnak megfelelő tömörített zip fájlokat kezeli. A zip programkészletre is szükség van ahhoz, hogy zip fájlokat olvasson a modul.

A zip támogatás nincs beépítve a PHP-ben, a --with-zip opcióval kell fordítanod, hogy használhasd. Szükség van még a ZZIPlib 0.10.6 vagy későbbi kiadására is.

Megjegyzés: A zip támogatás a PHP 4.1.0-nál régebbi verziókban csak kísérleti jellegű, tehát ezekben nem működik megbízhatóan. Ez a dokumentum a 4.1.0 és az újabb PHP verziók zip modulját mutatja be.


Példa

Az alábbi példa megnyit egy zip állományt, beolvassa a benne található fájlokat és kinyomtatja tartalmukat. A példában felhasznált test2.zip állomány a ZZIPlib csomag egyik "beépített" próba állománya.

Példa 1. Példaprogram

<?php

$zip = zip_open("/tmp/test2.zip");

if ($zip) {

    while ($zip_entry = zip_read($zip)) {
        echo "Név:                " . zip_entry_name($zip_entry) . "\n";
        echo "Tömörítetlen méret: " . zip_entry_filesize($zip_entry) . "\n";
        echo "Tömörített méret:   " . zip_entry_compressedsize($zip_entry) . "\n";
        echo "Tömörítési metódus: " . zip_entry_compressionmethod($zip_entry) . "\n";

        if (zip_entry_open($zip, $zip_entry, "r")) {
            echo "A fájl tartalma:\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);

}

?>

A program először megnyitja a megadott útvonalon található test2.zip fájlt. A ciklust addig végzi, amíg a a zip_read() egy érvényes $zip_entry (vagyis a zip állományban létező fájl vagy könyvtár) értékkel tér vissza. A zip_read() tulajdonképpen egy tömb eléréseként képzelhető, amely tömbbe a zip_open() betölti a megnyitott zip állományban lévő fájlok neveit. Minden egyes ciklusnál a program automatikusan előre lépteti a tömböt eggyel.

Tartalom
zip_close -- Lezár egy megnyitott ZIP állományt
zip_entry_close -- Lezár egy ZIP állományban található objektumot
zip_entry_compressedsize -- Egy zip-ben lévő objektum tömörített méretét adja vissza
zip_entry_compressionmethod --  A megadott zip objektum tömörítési típusával tér vissza
zip_entry_filesize --  Az adott zip objektum tömörítetlen fájlméretét adja vissza
zip_entry_name -- A zip objektum nevével tér vissza
zip_entry_open -- Olvasásra megnyit egy zip objektumot
zip_entry_read -- Olvas egy megnyitott zip objektumból
zip_open -- Megnyit egy zip állományt
zip_read -- Beolvassa a soron következő zip objektumot egy zip állományban

zip_close

(4.1.0 - 4.3.2 only)

zip_close -- Lezár egy megnyitott ZIP állományt

Leírás

void zip_close ( resource zip)

Lezár egy megnyitott ZIP állományt. Ez csak akkor működik, ha a zip forrásfájlt előzőleg a zip_open() függvénnyel nyitottuk meg.

Ennek a függvénynek nincs visszatérési értéke.

Lásd még: zip_open() és zip_read().

zip_entry_close

(4.1.0 - 4.3.2 only)

zip_entry_close -- Lezár egy ZIP állományban található objektumot

Leírás

void zip_entry_close ( resource zip_entry)

Lezárja a zip állományban lévő zip_entry objektumot. A zip_entry paraméter egy létező objektum a zip fájlban, amit a zip_entry_open() függvénnyel nyitottunk meg.

Ennek a függvénynek nincs visszatérési értéke.

Lásd még: zip_entry_open() és zip_entry_read().

zip_entry_compressedsize

(4.1.0 - 4.3.2 only)

zip_entry_compressedsize -- Egy zip-ben lévő objektum tömörített méretét adja vissza

Leírás

int zip_entry_compressedsize ( resource zip_entry)

Az adott zip_entry objektum tömörített méretével tér vissza. A zip_entry egy létező zip állománybeli objektumra mutat, amihez a zip_read() függvény segítségével jutunk.

Lásd még: zip_open() és zip_read().

zip_entry_compressionmethod

(4.1.0 - 4.3.2 only)

zip_entry_compressionmethod --  A megadott zip objektum tömörítési típusával tér vissza

Leírás

string zip_entry_compressionmethod ( resource zip_entry)

A megadott zip_entry objektum tömörítési metódusának típusával tér vissza. A paraméter egy létező zip állománybeli objektumra mutat, amihez a zip_read() függvény segítségével jutottunk.

Lásd még: zip_open() és zip_read().

zip_entry_filesize

(4.1.0 - 4.3.2 only)

zip_entry_filesize --  Az adott zip objektum tömörítetlen fájlméretét adja vissza

Leírás

int zip_entry_filesize ( resource zip_entry)

Visszatér az adott zip_entry objektum tömörítetlen fájlméretének értékével. Ez a zip_entry paraméter egy létező zip objektum ami a zip_read() függvény visszatérési értéke.

Lásd még: zip_open() és zip_read().

zip_entry_name

(4.1.0 - 4.3.2 only)

zip_entry_name -- A zip objektum nevével tér vissza

Leírás

string zip_entry_name ( resource zip_entry)

A zip_entry paraméterrel megadott zip objektum nevével tér vissza. A zip_entry paraméter egy létező zip objektum, amit a zip_read() függvénnyel olvashatunk ki a zip állományból.

Lásd még: zip_open() és zip_read().

zip_entry_open

(4.1.0 - 4.3.2 only)

zip_entry_open -- Olvasásra megnyit egy zip objektumot

Leírás

bool zip_entry_open ( resource zip, resource zip_entry [, string mode])

Olvasásra megnyit egy létező zip objektumot egy zip állományból. A zip paraméter egy létező zip fájl, amit a zip_open() függvénnyel nyitottunk meg. Az olvasni kívánt objektumot a zip_entry definiálja, ami a zip_read() függvény visszatérési értéke. A mode nem kötelező paraméter, lásd az fopen() dokumentációját a lehetséges értékekért.

Megjegyzés: Jelenleg a mode paramétert nem veszi figyelembe a PHP, csak az "rb" alapértelmezett értékkel dolgozik. Emiatt a PHP-ben csak olvasási hozzáférést kapunk a zip állományokhoz. Az fopen() dokumentációja részletesen magyarázza a különböző fájl kapcsolókat, köztük az "rb"-t is.

Ez a függvény siker esetén logikai IGAZ (TRUE), kudarcnál logikai HAMIS (FALSE) értékeket vesz fel.

Megjegyzés: Ellentétben az fopen() és más hasonló függvényekkel, a zip_entry_open() függvény visszatérési értéke csak a művelet eredményességét mutatja és nincs szükség a vizsgált zip objektum olvasására vagy lezárására.

Lásd még: zip_entry_read() és zip_entry_close().

zip_entry_read

(4.1.0 - 4.3.2 only)

zip_entry_read -- Olvas egy megnyitott zip objektumból

Leírás

string zip_entry_read ( resource zip_entry [, int length])

A length paraméterben megadott bájt hosszúságú részt olvas be egy megnyitott zip objektumból. Ha a length paraméter nincs megadva, az alapértelmezés 1024 bájt. A zip_entry paraméter egy létező zip objektum, ami a zip_read() függvény visszatérési értéke.

Megjegyzés: A length paramétert tömörítetlen méretben kell érteni!

Az olvasott adattal vagy (pl. hibás adatok esetén) logikai HAMIS (FALSE) értékkel tér vissza, ha elérte a fájl végét.

Lásd még: zip_entry_open(), zip_entry_close() és zip_entry_filesize().

zip_open

(4.1.0 - 4.3.2 only)

zip_open -- Megnyit egy zip állományt

Leírás

resource zip_open ( string filename)

Olvasásra megnyit egy zip állományt. A filename az olvasni kívánt zip állomány neve.

Ezzel a függvénnyel nyitjuk meg a zip állományokat további feldolgozásra. Miután megnyitottuk, a zip_read() függvénnyel olvashatjuk ill. a zip_close() függvénnyel zárhatjuk le az állományt. A zip_open() logikai HAMIS (FALSE) értékkel tér vissza, ha a filename paraméterben megadott fájl nem létezik.

Lásd még: zip_read() és zip_close().

zip_read

(4.1.0 - 4.3.2 only)

zip_read -- Beolvassa a soron következő zip objektumot egy zip állományban

Leírás

resource zip_read ( resource zip)

Beolvassa a soron következő zip objektumot egy zip állományból. A zip paraméter egy létező zip állomány, amit előzőleg megnyitottunk a zip_open() függvénnyel.

Ez a függvény az aktuális zip objektumot adja vissza, mely a zip_entry_...() függvények segítségével dolgozható fel. Ha nincs több olvasnivaló, FALSE értékkel tér vissza.

Lásd még: zip_open(), zip_close(), zip_entry_open(), és zip_entry_read().

CXIX. Zlib Compression Functions

Bevezetés

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

Megjegyzés: 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 prepend the filename or path with a 'zlib:' prefix when calling fopen().

In version 4.3.0, this special prefix has been changed to 'zlib://' to prevent ambiguities with filenames containing ':'.

This feature requires a C runtime library that provides the fopencookie() function. To my current knowledge the GNU libc is the only library that provides this feature.


Követelmények

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.


Telepítés

Zlib support in PHP is not enabled by default. You will need to configure PHP --with-zlib[=DIR]

A PHP Windowsos változata beépített támogatással rendelkezik eme kiterjesztéshez. nincs szükség semmilyen kiterjesztés betöltésére, hogy az itt felsorolt függvnyeket használhasd.

Megjegyzés: Builtin support for zlib on Windows is available with PHP 4.3.0.


Futásidejű beállítások

Az alábbi függvények viselkedése befolyásolható a php.ini segítségével.

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.

Táblázat 1. Zlib Configuration Options

NameDefaultChangeable
zlib.output_compression"Off"PHP_INI_ALL
zlib.output_compression_level"-1"PHP_INI_ALL
zlib.output_handler""PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().

Here's a short explanation of the configuration directives.

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.

You can use ini_set() to disable this in your script if the headers aren't already sent. If you output a "Content-Type: image/" header the compression is disabled, too (in order to circumvent a Netscape bug). You can reenable it, if you add "ini_set('zlib.output_compression', 'On')" after the header call which added the image content-type.

This option also accepts integer values instead of boolean "On"/"Off", using this you can set the output buffer size (default is 4KB).

Megjegyzés: 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.

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.


Erőforrás típusok

Ez a kiterjesztés semmilyen erőforrás típust nem definiál.


Előre definiált állandók

Az itt listázott állandókat ez a kiterjesztés definiálja, és csak akkor elérhetőek, ha az adott kiterjesztés be van fordítva a PHP-be, vagy dinamikusan betöltött.

FORCE_GZIP (integer)

FORCE_DEFLATE (integer)


Példák

This example opens a temporary file and writes a test string to it, then it prints out the content of this file twice.

Példa 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</h1></body>\n</html>\n";

?>
Tartalom
gzclose -- Close an open gz-file pointer
gzcompress -- Compress a string
gzdeflate -- Deflate a string
gzencode -- Create a gzip compressed string
gzeof -- Test for end-of-file on a gz-file pointer
gzfile -- Read entire gz-file into an array
gzgetc -- Get character from gz-file pointer
gzgets -- Get line from file pointer
gzgetss --  Get line from gz-file pointer and strip HTML tags
gzinflate -- Inflate a deflated string
gzopen -- Open gz-file
gzpassthru --  Output all remaining data on a gz-file pointer
gzputs -- Alias for 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 deflated string
gzwrite -- Binary-safe gz-file write
readgzfile -- Output a gz-file
zlib_get_coding_type -- Returns the coding type used for output compression

gzclose

(PHP 3, PHP 4 )

gzclose -- Close an open gz-file pointer

Description

int gzclose ( resource zp)

The gz-file pointed to by zp is closed.

Siker esetén TRUE értékkel tér vissza, ellenkező esetben FALSE értéket ad.

The gz-file pointer must be valid, and must point to a file successfully opened by gzopen().

gzcompress

(PHP 4 >= 4.0.1)

gzcompress -- Compress a string

Description

string gzcompress ( string data [, int level])

This function returns a compressed version of the input data using the ZLIB data format, or FALSE if an error is encountered. The optional parameter level can be given as 0 for no compression up to 9 for maximum compression.

For details on the ZLIB compression algorithm see the document "ZLIB Compressed Data Format Specification version 3.3" (RFC 1950).

Megjegyzés: This is not the same as gzip compression, which includes some header data. See gzencode() for gzip compression.

See also gzdeflate(), gzinflate(), gzuncompress(), gzencode().

gzdeflate

(PHP 4 >= 4.0.4)

gzdeflate -- Deflate a string

Description

string gzdeflate ( string data [, int level])

This function returns a compressed version of the input data using the DEFLATE data format, or FALSE if an error is encountered. The optional parameter level can be given as 0 for no compression up to 9 for maximum compression.

For details on the DEFLATE compression algorithm see the document "DEFLATE Compressed Data Format Specification version 1.3" (RFC 1951).

See also gzinflate(), gzcompress(), gzuncompress(), gzencode().

gzencode

(PHP 4 >= 4.0.4)

gzencode -- Create a gzip compressed string

Description

string gzencode ( string data [, int level [, int encoding_mode]])

This function returns a compressed version of the input data compatible with the output of the gzip program, or FALSE if an error is encountered. The optional parameter level 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.

You can also give FORCE_GZIP (the default) or FORCE_DEFLATE as optional third parameter encoding_mode. If you use FORCE_DEFLATE, you get a standard zlib deflated string (inclusive zlib headers) after the gzip file header but without the trailing crc32 checksum.

Megjegyzés: level was added in PHP 4.2, before PHP 4.2 gzencode() only had the data and (optional) encoding_mode parameters..

The resulting data contains the appropriate headers and data structure to make a standard .gz file, e.g.:

Példa 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);
?>

For more information on the GZIP file format, see the document: GZIP file format specification version 4.3 (RFC 1952).

See also gzcompress(). gzuncompress(), gzdeflate(), gzinflate().

gzeof

(PHP 3, PHP 4 )

gzeof -- Test for end-of-file on a gz-file pointer

Description

int gzeof ( resource zp)

Returns TRUE if the gz-file pointer is at EOF or an error occurs; otherwise returns FALSE.

The gz-file pointer must be valid, and must point to a file successfully opened by gzopen().

gzfile

(PHP 3, PHP 4 )

gzfile -- Read entire gz-file into an array

Description

array gzfile ( string filename [, int use_include_path])

Identical to readgzfile(), except that gzfile() returns the file in an array.

You can use the optional second parameter and set it to "1", if you want to search for the file in the include_path, too.

See also readgzfile(), and gzopen().

gzgetc

(PHP 3, PHP 4 )

gzgetc -- Get character from gz-file pointer

Description

string gzgetc ( resource zp)

Returns a string containing a single (uncompressed) character read from the file pointed to by zp. Returns FALSE on EOF (unlike gzeof()).

The gz-file pointer must be valid, and must point to a file successfully opened by gzopen().

See also gzopen(), and gzgets().

gzgets

(PHP 3, PHP 4 )

gzgets -- Get line from file pointer

Description

string gzgets ( resource zp, int length)

Returns a (uncompressed) string of up to length - 1 bytes read from the file pointed to by fp. Reading ends when length - 1 bytes have been read, on a newline, or on EOF (whichever comes first).

If an error occurs, returns FALSE.

The file pointer must be valid, and must point to a file successfully opened by gzopen().

See also gzopen(), gzgetc(), and fgets().

gzgetss

(PHP 3, PHP 4 )

gzgetss --  Get line from gz-file pointer and strip HTML tags

Description

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.

You can use the optional third parameter to specify tags which should not be stripped.

Megjegyzés: Allowable_tags was added in PHP 3.0.13, PHP 4.0b3.

See also gzgets(), gzopen(), and strip_tags().

gzinflate

(PHP 4 >= 4.0.4)

gzinflate -- Inflate a deflated string

Description

string gzinflate ( string data [, int length])

This function takes data compressed by gzdeflate() and returns 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.

See also gzcompress(). gzuncompress(), gzdeflate(), gzencode().

gzopen

(PHP 3, PHP 4 )

gzopen -- Open gz-file

Description

resource gzopen ( string filename, string mode [, int use_include_path])

Opens a gzip (.gz) file for reading or writing. The mode parameter is 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.)

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.

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

You can use the optional third parameter and set it to "1", if you want to search for the file in the include_path, too.

Példa 1. gzopen() Example

<?php
$fp = gzopen("/tmp/file.gz", "r");
?>

See also gzclose().

gzpassthru

(PHP 3, PHP 4 )

gzpassthru --  Output all remaining data on a gz-file pointer

Description

int gzpassthru ( resource zp)

Reads to EOF on the given gz-file pointer and writes the (uncompressed) results to standard output.

If an error occurs, returns FALSE.

The file pointer must be valid, and must point to a file successfully opened by gzopen().

gzputs

gzputs -- Alias for gzwrite()

Description

This function is an alias of gzwrite().

gzread

(PHP 3, PHP 4 )

gzread -- Binary-safe gz-file read

Description

string gzread ( resource zp, int length)

gzread() reads up to length bytes from the gz-file pointer referenced by zp. Reading stops when length (uncompressed) bytes have been read or EOF is reached, whichever comes first.

Példa 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);
?>

See also gzwrite(), gzopen(), gzgets(), gzgetss(), gzfile(), and gzpassthru().

gzrewind

(PHP 3, PHP 4 )

gzrewind -- Rewind the position of a gz-file pointer

Description

int gzrewind ( resource zp)

Sets the file position indicator for zp to the beginning of the file stream.

If an error occurs, returns 0.

The file pointer must be valid, and must point to a file successfully opened by gzopen().

See also gzseek() and gztell().

gzseek

(PHP 3, PHP 4 )

gzseek -- Seek on a gz-file pointer

Description

int gzseek ( resource zp, int offset)

Sets the file position indicator for the file referenced by zp to offset bytes 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.

Upon success, returns 0; otherwise, returns -1. Note that seeking past EOF is not considered an error.

See also gztell() and gzrewind().

gztell

(PHP 3, PHP 4 )

gztell -- Tell gz-file pointer read/write position

Description

int gztell ( resource zp)

Returns the position of the file pointer referenced by zp; i.e., its offset into the file stream.

If an error occurs, returns FALSE.

The file pointer must be valid, and must point to a file successfully opened by gzopen().

See also gzopen(), gzseek() and gzrewind().

gzuncompress

(PHP 4 >= 4.0.1)

gzuncompress -- Uncompress a deflated string

Description

string gzuncompress ( string data [, int length])

This function takes data compressed by gzcompress() and returns 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.

See also gzdeflate(), gzinflate(), gzcompress(), gzencode().

gzwrite

(PHP 3, PHP 4 )

gzwrite -- Binary-safe gz-file write

Description

int gzwrite ( resource zp, string string [, int length])

gzwrite() writes the contents of string to the gz-file stream pointed to by zp. If the length argument is given, writing will stop after length (uncompressed) bytes have been written or the end of string is reached, whichever comes first.

gzwrite() returns the number of (uncompressed) bytes written to the gz-file stream pointed to by zp.

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.

See also gzread(), gzopen(), and gzputs().

readgzfile

(PHP 3, PHP 4 )

readgzfile -- Output a gz-file

Description

int readgzfile ( string filename [, int use_include_path])

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.

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.

The file filename will be opened from the filesystem and its contents written to standard output.

You can use the optional second parameter and set it to "1", if you want to search for the file in the include_path, too.

See also gzpassthru(), gzfile(), and gzopen().

zlib_get_coding_type

(PHP 4 >= 4.3.2)

zlib_get_coding_type -- Returns the coding type used for output compression

Description

string zlib_get_coding_type ( void )

Returns the coding type used for output compression. Possible return values are gzip, deflate, or FALSE

See also the zlib.output_compression directive.

VI. Zend API

Hacking the Core of PHP

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.

Hacking the Core of PHP

24. Fejezet. 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 24-1 Ábra). 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.

Ábra 24-1. The internal structure of PHP.

The following sections discuss where PHP can be extended and how it's done.


25. Fejezet. Extension Possibilities

As shown in 24-1 Ábra 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:

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

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


26. Fejezet. Source Layout

Megjegyzés: 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://www.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.

DirectoryContents
php4 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.
php4/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).
php4/main This directory contains the main php macros and definitions. (important)
php4/pear Directory for the PHP Extension and Application Repository. This directory contains core PEAR files.
php4/sapi Contains the code for the different server abstraction layers.
php4/TSRM Location of the "Thread Safe Resource Manager" (TSRM) for Zend and PHP.
php4/Zend 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:

  • php4/main/php.h, located in the main PHP directory. This file contains most of PHP's macro and API definitions.

  • php4/Zend/zend.h, located in the main Zend directory. This file contains most of Zend's macros and definitions.

  • php4/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:

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

Figyelem

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

Megjegyzés: 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.


27. Fejezet. 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/manual/m4/html_mono/m4.html)

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 27-1 Példa is a bit more complex:

Példa 27-1. The default config.m4.

dnl $Id: Extending_Zend_Build.xml,v 1.8 2002/10/10 18:13:11 imajes Exp $
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.


28. Fejezet. 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. 28-1 Példa shows the source.

Példa 28-1. A simple extension.

/* include standard header */
#include "php.h"

/* declaration of functions to be exported */
ZEND_FUNCTION(first_module);

/* compiled function list so Zend knows what's in this module */
zend_function_entry firstmod_functions[] =
{
    ZEND_FE(first_module, NULL)
    {NULL, NULL, NULL}
};

/* compiled module information */
zend_module_entry firstmod_module_entry =
{
    STANDARD_MODULE_HEADER,
    "First Module",
    firstmod_functions,
    NULL, 
    NULL, 
    NULL, 
    NULL, 
    NULL,
    NO_VERSION_YET,
    STANDARD_MODULE_PROPERTIES
};

/* implement standard "stub" routine to introduce ourselves to Zend */
#if COMPILE_DL_FIRST_MODULE
ZEND_GET_MODULE(firstmod)
#endif

/* implement function that is meant to be made available to PHP */
ZEND_FUNCTION(first_module)
{
    long parameter;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &parameter) == FAILURE) {
        return;
    }

    RETURN_LONG(parameter);
}

This code contains a complete PHP module. We'll explain the source code in detail shortly, but first we'd like to discuss the build process. (This will allow the impatient to experiment before we dive into API discussions.)

Megjegyzés: 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 28-1 Példa can be enabled with --enable-first_module or --enable-first_module=yes.

Compiling Manually. To compile your modules manually, you need the following commands:

ActionCommand
Compilingcc -fpic -DCOMPILE_DL=1 -I/usr/local/include -I. -I.. -I../Zend -c -o <your_object_file> <your_c_file>
Linkingcc -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 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.)


29. Fejezet. 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 29-1 Példa. If you compiled it into the PHP binary, omit the call to dl(), as the module's functionality is instantly available to your scripts.

Figyelem

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.

Példa 29-1. 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 in your Web browser should give you the output shown in 29-1 Ábra.

Ábra 29-1. Output of first_module.php.

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.


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


31. Fejezet. 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 31-1 Táblázat for descriptions).

Táblázat 31-1. Zend's Parameters to Functions Called from PHP

ParameterDescription
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 31-1 Példa.

Példa 31-1. 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;

EntryDescription
fname Denotes the function name as seen in PHP (for example, fopen, mysql_connect, or, in our example, first_module).
handler Pointer to the C function responsible for handling calls to this function. For example, see the standard macro INTERNAL_FUNCTION_PARAMETERS discussed earlier.
func_arg_types Allows you to mark certain parameters so that they're forced to be passed by reference. You usually should set this to NULL.

In the example above, the declaration looks like this:
zend_function_entry firstmod_functions[] =
{
    ZEND_FE(first_module, NULL)
    {NULL, NULL, NULL}
};
You can see that the last entry in the list always has to be {NULL, NULL, NULL}. This marker has to be set for Zend to know when the end of the list of exported functions is reached.

Megjegyzés: You cannot use the predefined macros for the end marker, as these would try to refer to a function named "NULL"!

The macro ZEND_FE (short for 'Zend Function Entry') simply expands to a structure entry in zend_function_entry. Note that these macros introduce a special naming scheme to your functions - your C functions will be prefixed with zif_, meaning that ZEND_FE(first_module) will refer to a C function zif_first_module(). If you want to mix macro usage with hand-coded entries (not a good practice), keep this in mind.

Tip: Compilation errors that refer to functions named zif_*() relate to functions defined with ZEND_FE.

31-2 Táblázat shows a list of all the macros that you can use to define functions.

Táblázat 31-2. Macros for Defining Functions

Macro NameDescription
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 31-2 Példa.

Példa 31-2. 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 ]

};

EntryDescription
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 31-3 Táblázat. 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.

Táblázat 31-3. Macros to Declare Startup and Shutdown Functions

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


32. Fejezet. 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 (see 32-1 Ábra).

Ábra 32-1. WRONG_PARAM_COUNT in action.

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

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

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 > 5)
    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 32-1 Példa. Don't worry if you don't know all the functions used in this source yet; we'll get to them shortly.

Példa 32-1. 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_P(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 32-1 Táblázat).

Note: All conversion functions expect a **zval as parameter.

Táblázat 32-1. Argument Conversion Functions

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

Megjegyzés: You can find a demonstration of the behavior in cross_conversion.php on the accompanying CD-ROM. 32-2 Ábra shows the output.

Ábra 32-2. 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 32-2 Példa.

Példa 32-2. 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 32-2 Táblázat, 32-3 Táblázat and 32-4 Táblázat.

Táblázat 32-2. Zend zval Structure

EntryDescription
value Union containing this variable's contents. See 32-3 Táblázat for a description.
type Contains this variable's type. For a list of available types, see 32-4 Táblázat.
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.

Táblázat 32-3. Zend zvalue_value Structure

EntryDescription
lvalUse this property if the variable is of the type IS_LONG, IS_BOOLEAN, or IS_RESOURCE.
dvalUse 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.
htThis entry points to the variable's hash table entry if the variable is an array.
objUse this property if the variable is of the type IS_OBJECT.

Táblázat 32-4. Zend Variable Type Constants

ConstantDescription
IS_NULLDenotes a NULL (empty) value.
IS_LONGA long (integer) value.
IS_DOUBLEA double (floating point) value.
IS_STRINGA string.
IS_ARRAYDenotes an array.
IS_OBJECTAn object.
IS_BOOLA Boolean value.
IS_RESOURCEA resource (for a discussion of resources, see the appropriate section below).
IS_CONSTANTA 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 32-3 Példa.

Példa 32-3. 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);


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.


33. Fejezet. 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
);
33-1 Példa 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.

Példa 33-1. 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();

}


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 33-2 Példa).

Példa 33-2. Creation of a long.

zval *new_long;

MAKE_STD_ZVAL(new_long);

new_long->type = IS_LONG;
new_long->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->type = IS_DOUBLE;
new_double->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->type = IS_STRING;
new_string->value.str.len = strlen(string_contents);
new_string->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->type = IS_STRING;
new_string->value.str.len = 0;
new_string->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->type = IS_BOOL;
new_bool->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. 33-1 Táblázat, 33-2 Táblázat and 33-3 Táblázat describe these functions. All functions return FAILURE on failure and SUCCESS on success.

Táblázat 33-1. Zend's API for Associative Arrays

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

Táblázat 33-2. Zend's API for Indexed Arrays, Part 1

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

Táblázat 33-3. Zend's API for Indexed Arrays, Part 2

FunctionDescription
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 33-3 Példa) and zend_hash_index_update() for indexed arrays (see 33-4 Példa):

Példa 33-3. 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->value.ht, key, strlen(key) + 1, (void *)&new_element, sizeof(zval *), NULL) == FAILURE)
{
    // do error handling here
}

Példa 33-4. 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->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 33-4 Táblázat to add members to your object.

Táblázat 33-4. Zend's API for Object Creation

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

Megjegyzés: 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:

ldNormal resource destruction handler callback
pldPesistent resource destruction handler callback
type_nameA string specifying the name of your resource. It's always a good thing to specify an 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_numberThe module_number is automatically available in your PHP_MINIT_FUNCTION function and therefore you just pass it over.

The return value is an 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);
}

Megjegyzés: 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_resource_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_resultThis is an already initialized zval * container.
rsrc_pointerYour resource pointer you want to store.
rsrc_typeThe 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 an 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 uniquly identifies the newly registered resource. You can use the macro RETURN_RESOURE to return it to the user:
RETURN_RESOURCE(rsrc_id)

Megjegyzés: It is common practice that if you want to return the resource immidiately 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)

rsrcThis is your pointer which will point to your previously registered resource.
rsrc_typeThis is the typecast argument for your pointer, e.g. myresource *.
rsrc_idThis 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_idThis integer specifies the default resource ID if no resource could be fetched or -1.
resource_type_nameThis 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_typeThe 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 33-5 Táblázat describes macros that do exactly this task. They don't need any zval allocation; you simply have to supply a variable name and value.

Táblázat 33-5. Macros for Global Variable Creation

MacroDescription
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 33-6 Táblázat. 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.

Táblázat 33-6. Macros for Creating Constants

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

34. Fejezet. 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 lvalue (result of the evaluation of the left side of the operator) to the rvalue (same for the right 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.


35. Fejezet. 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 35-1 Táblázat and 35-2 Táblázat.

Megjegyzés: The macros in 35-1 Táblázat automatically return from your function, those in 35-2 Táblázat only set the return value; they don't return from your function.

Táblázat 35-1. Predefined Macros for Returning Values from a Function

MacroDescription
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_FALSEReturns Boolean false.
RETURN_TRUEReturns Boolean true.

Táblázat 35-2. Predefined Macros for Setting the Return Value of a Function

MacroDescription
RETVAL_RESOURCE(resource)Sets the return value to the specified resource.
RETVAL_BOOL(bool)Sets the return value to the specified Boolean value.
RETVAL_NULLSets 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.


36. Fejezet. 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");
36-1 Táblázat shows a list of possible values (see 36-1 Ábra). These values are also referred to in php.ini. Depending on which error type you choose, your messages will be logged.

Táblázat 36-1. Zend's Predefined Error Messages.

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

Ábra 36-1. 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). 36-1 Példa shows a source example and its output. To print the table footer, use php_info_print_table_end().

Példa 36-1. 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();


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 36-2 Példa.

Példa 36-2. Printing execution information.

zend_printf("The name of the current function is %s<br>", get_active_function_name(TSRMLS_C));
zend_printf("The file currently executed is %s<br>", zend_get_executed_filename(TSRMLS_C));
zend_printf("The current line being executed is %i<br>", zend_get_executed_lineno(TSRMLS_C));


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


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

38-1 Példa 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.

Példa 38-1. 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<br>", retval->type);

*return_value = *retval;
zval_copy_ctor(return_value);
zval_ptr_dtor(&retval);

<?php

dl("call_userland.so");

function test_function()
{

    print("We are in the test function!<br>");

    return("hello");

}

$return_value = call_userland("test_function");

print("Return value: \"$return_value\"<br>");
?>


39. Fejezet. 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<br>", 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 39-1 Táblázat.

Táblázat 39-1. Macros to Access Initialization Entries in PHP

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

}


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


41. Fejezet. 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 41-1 Táblázat.

Táblázat 41-1. M4 Macros for config.m4

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

42. Fejezet. API Macros

A set of macros was introduced into Zend's API that simplify access to zval containers (see 42-1 Táblázat).

Táblázat 42-1. API Macros for Accessing zval Containers

MacroRefers 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

VII. PHP API: Felület, kiegészítések írásához


43. Fejezet. Streams API for PHP Extension Authors

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!

Megjegyzés: The functions in this chapter are for use in the PHP source code and are not PHP functions. Userland stream functions can be found in the Stream Reference.


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:

Példa 43-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.

Táblázat 43-1. ANSI stdio equivalent functions in the Streams API

ANSI Stdio FunctionPHP Streams FunctionNotes
fopenphp_stream_open_wrapperStreams includes additional parameters
fclosephp_stream_close 
fgetsphp_stream_gets 
freadphp_stream_readThe nmemb parameter is assumed to have a value of 1, so the prototype looks more like read(2)
fwritephp_stream_writeThe nmemb parameter is assumed to have a value of 1, so the prototype looks more like write(2)
fseekphp_stream_seek 
ftellphp_stream_tell 
rewindphp_stream_rewind 
feofphp_stream_eof 
fgetcphp_stream_getc 
fputcphp_stream_putc 
fflushphp_stream_flush 
putsphp_stream_putsSame semantics as puts, NOT fputs
fstatphp_stream_statStreams 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:

Példa 43-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();
}

Példa 43-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.

Megjegyzés: 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 Common API Reference

Tartalom
php_stream_stat_path -- Gets the status for a file or URL
php_stream_stat -- Gets the status for the underlying storage associated with a stream
php_stream_open_wrapper -- Opens a stream on a file or URL
php_stream_read -- Read a number of bytes from a stream into a buffer
php_stream_write -- Write a number of bytes from a buffer to a stream
php_stream_eof -- Check for an end-of-file condition on a stream
php_stream_getc -- Read a single byte from a stream
php_stream_gets -- Read a line of data from a stream into a buffer
php_stream_close -- Close a stream
php_stream_flush -- Flush stream buffers to storage
php_stream_seek -- Reposition a stream
php_stream_tell -- Determine the position of a stream
php_stream_copy_to_stream -- Copy data from one stream to another
php_stream_copy_to_mem -- Copy data from stream and into an allocated buffer
php_stream_make_seekable -- Convert a stream into a stream is seekable
php_stream_cast -- Convert a stream into another form, such as a FILE* or socket
php_stream_can_cast -- Determines if a stream can be converted into another form, such as a FILE* or socket
php_stream_is_persistent -- Determines if a stream is a persistent stream
php_stream_is -- Determines if a stream is of a particular type
php_stream_passthru -- Outputs all remaining data from a stream
php_register_url_stream_wrapper -- Registers a wrapper with the Streams API
php_unregister_url_stream_wrapper -- Unregisters a wrapper from the Streams API
php_stream_open_wrapper_ex -- Opens a stream on a file or URL, specifying context
php_stream_open_wrapper_as_file -- Opens a stream on a file or URL, and converts to a FILE*
php_stream_filter_register_factory -- Registers a filter factory with the Streams API
php_stream_filter_unregister_factory -- Deregisters a filter factory with the Streams API

php_stream_stat_path

(no version information, might be only in CVS)

php_stream_stat_path -- Gets the status for a file or URL

Description

int php_stream_stat_path ( char * path, php_stream_statbuf * ssb)

php_stream_stat_path() examines the file or URL specified by path and returns information such as file size, access and creation times and so on. The return value is 0 on success, -1 on error. For more information about the information returned, see php_stream_statbuf.

php_stream_stat

(no version information, might be only in CVS)

php_stream_stat -- Gets the status for the underlying storage associated with a stream

Description

int php_stream_stat ( php_stream * stream, php_stream_statbuf * ssb)

php_stream_stat() examines the storage to which stream is bound, and returns information such as file size, access and creation times and so on. The return value is 0 on success, -1 on error. For more information about the information returned, see php_stream_statbuf.

php_stream_open_wrapper

(no version information, might be only in CVS)

php_stream_open_wrapper -- Opens a stream on a file or URL

Description

php_stream * php_stream_open_wrapper ( char * path, char * mode, int options, char ** opened)

php_stream_open_wrapper() opens a stream on the file, URL or other wrapped resource specified by path. Depending on the value of mode, the stream may be opened for reading, writing, appending or combinations of those. See the table below for the different modes that can be used; in addition to the characters listed below, you may include the character 'b' either as the second or last character in the mode string. The presence of the 'b' character informs the relevant stream implementation to open the stream in a binary safe mode.

The 'b' character is ignored on all POSIX conforming systems which treat binary and text files in the same way. It is a good idea to specify the 'b' character whenever your stream is accessing data where the full 8 bits are important, so that your code will work when compiled on a system where the 'b' flag is important.

Any local files created by the streams API will have their initial permissions set according to the operating system defaults - under Unix based systems this means that the umask of the process will be used. Under Windows, the file will be owned by the creating process. Any remote files will be created according to the URL wrapper that was used to open the file, and the credentials supplied to the remote server.

r

Open text file for reading. The stream is positioned at the beginning of the file.

r+

Open text file for reading and writing. The stream is positioned at the beginning of the file.

w

Truncate the file to zero length or create text file for writing. The stream is positioned at the beginning of the file.

w+

Open text file for reading and writing. The file is created if it does not exist, otherwise it is truncated. The stream is positioned at the beginning of the file.

a

Open for writing. The file is created if it does not exist. The stream is positioned at the end of the file.

a+

Open text file for reading and writing. The file is created if it does not exist. The stream is positioned at the end of the file.

options affects how the path/URL of the stream is interpreted, safe mode checks and actions taken if there is an error during opening of the stream. See Stream open options for more information about options.

If opened is not NULL, it will be set to a string containing the name of the actual file/resource that was opened. This is important when the options include USE_PATH, which causes the include_path to be searched for the file. You, the caller, are responsible for calling efree() on the filename returned in this parameter.

Megjegyzés: If you specified STREAM_MUST_SEEK in options, the path returned in opened may not be the name of the actual stream that was returned to you. It will, however, be the name of the original resource from which the seekable stream was manufactured.

php_stream_read

(no version information, might be only in CVS)

php_stream_read -- Read a number of bytes from a stream into a buffer

Description

size_t php_stream_read ( php_stream * stream, char * buf, size_t count)

php_stream_read() reads up to count bytes of data from stream and copies them into the buffer buf.

php_stream_read() returns the number of bytes that were read successfully. There is no distinction between a failed read or an end-of-file condition - use php_stream_eof() to test for an EOF.

The internal position of the stream is advanced by the number of bytes that were read, so that subsequent reads will continue reading from that point.

If less than count bytes are available to be read, this call will block (or wait) until the required number are available, depending on the blocking status of the stream. By default, a stream is opened in blocking mode. When reading from regular files, the blocking mode will not usually make any difference: when the stream reaches the EOF php_stream_read() will return a value less than count, and 0 on subsequent reads.

php_stream_write

(no version information, might be only in CVS)

php_stream_write -- Write a number of bytes from a buffer to a stream

Description

size_t php_stream_write ( php_stream * stream, const char * buf, size_t count)

php_stream_write() writes count bytes of data from buf into stream.

php_stream_write() returns the number of bytes that were written successfully. If there was an error, the number of bytes written will be less than count.

The internal position of the stream is advanced by the number of bytes that were written, so that subsequent writes will continue writing from that point.

php_stream_eof

(no version information, might be only in CVS)

php_stream_eof -- Check for an end-of-file condition on a stream

Description

int php_stream_eof ( php_stream * stream)

php_stream_eof() checks for an end-of-file condition on stream.

php_stream_eof() returns the 1 to indicate EOF, 0 if there is no EOF and -1 to indicate an error.

php_stream_getc

(no version information, might be only in CVS)

php_stream_getc -- Read a single byte from a stream

Description

int php_stream_getc ( php_stream * stream)

php_stream_getc() reads a single character from stream and returns it as an unsigned char cast as an int, or EOF if the end-of-file is reached, or an error occurred.

php_stream_getc() may block in the same way as php_stream_read() blocks.

The internal position of the stream is advanced by 1 if successful.

php_stream_gets

(no version information, might be only in CVS)

php_stream_gets -- Read a line of data from a stream into a buffer

Description

char * php_stream_gets ( php_stream * stream, char * buf, size_t maxlen)

php_stream_gets() reads up to count-1 bytes of data from stream and copies them into the buffer buf. Reading stops after an EOF or a newline. If a newline is read, it is stored in buf as part of the returned data. A NUL terminating character is stored as the last character in the buffer.

php_stream_read() returns buf when successful or NULL otherwise.

The internal position of the stream is advanced by the number of bytes that were read, so that subsequent reads will continue reading from that point.

This function may block in the same way as php_stream_read().

php_stream_close

(no version information, might be only in CVS)

php_stream_close -- Close a stream

Description

int php_stream_close ( php_stream * stream)

php_stream_close() safely closes stream and releases the resources associated with it. After stream has been closed, it's value is undefined and should not be used.

php_stream_close() returns 0 if the stream was closed or EOF to indicate an error. Regardless of the success of the call, stream is undefined and should not be used after a call to this function.

php_stream_flush

(no version information, might be only in CVS)

php_stream_flush -- Flush stream buffers to storage

Description

int php_stream_flush ( php_stream * stream)

php_stream_flush() causes any data held in write buffers in stream to be committed to the underlying storage.

php_stream_flush() returns 0 if the buffers were flushed, or if the buffers did not need to be flushed, but returns EOF to indicate an error.

php_stream_seek

(no version information, might be only in CVS)

php_stream_seek -- Reposition a stream

Description

int php_stream_seek ( php_stream * stream, off_t offset, int whence)

php_stream_seek() repositions the internal position of stream. The new position is determined by adding the offset to the position indicated by whence. If whence is set to SEEK_SET, SEEK_CUR or SEEK_END the offset is relative to the start of the stream, the current position or the end of the stream, respectively.

php_stream_seek() returns 0 on success, but -1 if there was an error.

Megjegyzés: Not all streams support seeking, although the streams API will emulate a seek if whence is set to SEEK_CUR and offset is positive, by calling php_stream_read() to read (and discard) offset bytes.

The emulation is only applied when the underlying stream implementation does not support seeking. If the stream is (for example) a file based stream that is wrapping a non-seekable pipe, the streams api will not apply emulation because the file based stream implements a seek operation; the seek will fail and an error result will be returned to the caller.

php_stream_tell

(no version information, might be only in CVS)

php_stream_tell -- Determine the position of a stream

Description

off_t php_stream_tell ( php_stream * stream)

php_stream_tell() returns the internal position of stream, relative to the start of the stream. If there is an error, -1 is returned.

php_stream_copy_to_stream

(no version information, might be only in CVS)

php_stream_copy_to_stream -- Copy data from one stream to another

Description

size_t php_stream_copy_to_stream ( php_stream * src, php_stream * dest, size_t maxlen)

php_stream_copy_to_stream() attempts to read up to maxlen bytes of data from src and write them to dest, and returns the number of bytes that were successfully copied.

If you want to copy all remaining data from the src stream, pass the constant PHP_STREAM_COPY_ALL as the value of maxlen.

Megjegyzés: This function will attempt to copy the data in the most efficient manner, using memory mapped files when possible.

php_stream_copy_to_mem

(no version information, might be only in CVS)

php_stream_copy_to_mem -- Copy data from stream and into an allocated buffer

Description

size_t php_stream_copy_to_mem ( php_stream * src, char ** buf, size_t maxlen, int persistent)

php_stream_copy_to_mem() allocates a buffer maxlen+1 bytes in length using pemalloc() (passing persistent). It then reads maxlen bytes from src and stores them in the allocated buffer.

The allocated buffer is returned in buf, and the number of bytes successfully read. You, the caller, are responsible for freeing the buffer by passing it and persistent to pefree().

If you want to copy all remaining data from the src stream, pass the constant PHP_STREAM_COPY_ALL as the value of maxlen.

Megjegyzés: This function will attempt to copy the data in the most efficient manner, using memory mapped files when possible.

php_stream_make_seekable

(no version information, might be only in CVS)

php_stream_make_seekable -- Convert a stream into a stream is seekable

Description

int php_stream_make_seekable ( php_stream * origstream, php_stream ** newstream, int flags)

php_stream_make_seekable() checks if origstream is seekable. If it is not, it will copy the data into a new temporary stream. If successful, newstream is always set to the stream that is valid to use, even if the original stream was seekable.

flags allows you to specify your preference for the seekable stream that is returned: use PHP_STREAM_NO_PREFERENCE to use the default seekable stream (which uses a dynamically expanding memory buffer, but switches to temporary file backed storage when the stream size becomes large), or use PHP_STREAM_PREFER_STDIO to use "regular" temporary file backed storage.

Táblázat 43-1. php_stream_make_seekable() return values

ValueMeaning
PHP_STREAM_UNCHANGEDOriginal stream was seekable anyway. newstream is set to the value of origstream.
PHP_STREAM_RELEASEDOriginal stream was not seekable and has been released. newstream is set to the new seekable stream. You should not access origstream anymore.
PHP_STREAM_FAILEDAn error occurred while attempting conversion. newstream is set to NULL; origstream is still valid.
PHP_STREAM_CRITICALAn error occurred while attempting conversion that has left origstream in an indeterminate state. newstream is set to NULL and it is highly recommended that you close origstream.

Megjegyzés: If you need to seek and write to the stream, it does not make sense to use this function, because the stream it returns is not guaranteed to be bound to the same resource as the original stream.

Megjegyzés: If you only need to seek forwards, there is no need to call this function, as the streams API will emulate forward seeks when the whence parameter is SEEK_CUR.

Megjegyzés: If origstream is network based, this function will block until the whole contents have been downloaded.

Megjegyzés: NEVER call this function with an origstream that is reference by a file pointer in a PHP script! This function may cause the underlying stream to be closed which could cause a crash when the script next accesses the file pointer!

Megjegyzés: In many cases, this function can only succeed when origstream is a newly opened stream with no data buffered in the stream layer. For that reason, and because this function is complicated to use correctly, it is recommended that you use php_stream_open_wrapper() and pass in PHP_STREAM_MUST_SEEK in your options instead of calling this function directly.

php_stream_cast

(no version information, might be only in CVS)

php_stream_cast -- Convert a stream into another form, such as a FILE* or socket

Description

int php_stream_cast ( php_stream * stream, int castas, void ** ret, int flags)

php_stream_cast() attempts to convert stream into a resource indicated by castas. If ret is NULL, the stream is queried to find out if such a conversion is possible, without actually performing the conversion (however, some internal stream state *might* be changed in this case). If flags is set to REPORT_ERRORS, an error message will be displayed is there is an error during conversion.

Megjegyzés: This function returns SUCCESS for success or FAILURE for failure. Be warned that you must explicitly compare the return value with SUCCESS or FAILURE because of the underlying values of those constants. A simple boolean expression will not be interpreted as you intended.

Táblázat 43-1. Resource types for castas

ValueMeaning
PHP_STREAM_AS_STDIORequests an ANSI FILE* that represents the stream
PHP_STREAM_AS_FDRequests a POSIX file descriptor that represents the stream
PHP_STREAM_AS_SOCKETDRequests a network socket descriptor that represents the stream

In addition to the basic resource types above, the conversion process can be altered by using the following flags by using the OR operator to combine the resource type with one or more of the following values:

Táblázat 43-2. Resource types for castas

ValueMeaning
PHP_STREAM_CAST_TRY_HARDTries as hard as possible, at the expense of additional resources, to ensure that the conversion succeeds
PHP_STREAM_CAST_RELEASEInforms the streams API that some other code (possibly a third party library) will be responsible for closing the underlying handle/resource. This causes the stream to be closed in such a way the underlying handle is preserved and returned in ret. If this function succeeds, stream should be considered closed and should no longer be used.

Megjegyzés: If your system supports fopencookie() (systems using glibc 2 or later), the streams API will always be able to synthesize an ANSI FILE* pointer over any stream. While this is tremendously useful for passing any PHP stream to any third-party libraries, such behaviour is not portable. You are requested to consider the portability implications before distributing you extension. If the fopencookie synthesis is not desirable, you should query the stream to see if it naturally supports FILE* by using php_stream_is()

Megjegyzés: If you ask a socket based stream for a FILE*, the streams API will use fdopen() to create it for you. Be warned that doing so may cause data that was buffered in the streams layer to be lost if you intermix streams API calls with ANSI stdio calls.

See also php_stream_is() and php_stream_can_cast().

php_stream_can_cast

(no version information, might be only in CVS)

php_stream_can_cast -- Determines if a stream can be converted into another form, such as a FILE* or socket

Description

int php_stream_can_cast ( php_stream * stream, int castas)

This function is equivalent to calling php_stream_cast() with ret set to NULL and flags set to 0. It returns SUCCESS if the stream can be converted into the form requested, or FAILURE if the conversion cannot be performed.

Megjegyzés: Although this function will not perform the conversion, some internal stream state *might* be changed by this call.

Megjegyzés: You must explicitly compare the return value of this function with one of the constants, as described in php_stream_cast().

See also php_stream_cast() and php_stream_is().

php_stream_is_persistent

(no version information, might be only in CVS)

php_stream_is_persistent -- Determines if a stream is a persistent stream

Description

int php_stream_is_persistent ( php_stream * stream)

php_stream_is_persistent() returns 1 if the stream is a persistent stream, 0 otherwise.

php_stream_is

(no version information, might be only in CVS)

php_stream_is -- Determines if a stream is of a particular type

Description

int php_stream_is ( php_stream * stream, int istype)

php_stream_is() returns 1 if stream is of the type specified by istype, or 0 otherwise.

Táblázat 43-1. Values for istype

ValueMeaning
PHP_STREAM_IS_STDIOThe stream is implemented using the stdio implementation
PHP_STREAM_IS_SOCKETThe stream is implemented using the network socket implementation
PHP_STREAM_IS_USERSPACEThe stream is implemented using the userspace object implementation
PHP_STREAM_IS_MEMORYThe stream is implemented using the grow-on-demand memory stream implementation

Megjegyzés: The PHP_STREAM_IS_XXX "constants" are actually defined as pointers to the underlying stream operations structure. If your extension (or some other extension) defines additional streams, it should also declare a PHP_STREAM_IS_XXX constant in it's header file that you can use as the basis of this comparison.

Megjegyzés: This function is implemented as a simple (and fast) pointer comparison, and does not change the stream state in any way.

See also php_stream_cast() and php_stream_can_cast().

php_stream_passthru

(no version information, might be only in CVS)

php_stream_passthru -- Outputs all remaining data from a stream

Description

size_t php_stream_passthru ( php_stream * stream)

php_stream_passthru() outputs all remaining data from stream to the active output buffer and returns the number of bytes output. If buffering is disabled, the data is written straight to the output, which is the browser making the request in the case of PHP on a web server, or stdout for CLI based PHP. This function will use memory mapped files if possible to help improve performance.

php_register_url_stream_wrapper

(no version information, might be only in CVS)

php_register_url_stream_wrapper -- Registers a wrapper with the Streams API

Description

int php_register_url_stream_wrapper ( char * protocol, php_stream_wrapper * wrapper, TSRMLS_DC )

php_register_url_stream_wrapper() registers wrapper as the handler for the protocol specified by protocol.

Megjegyzés: If you call this function from a loadable module, you *MUST* call php_unregister_url_stream_wrapper() in your module shutdown function, otherwise PHP will crash.

php_unregister_url_stream_wrapper

(no version information, might be only in CVS)

php_unregister_url_stream_wrapper -- Unregisters a wrapper from the Streams API

Description

int php_unregister_url_stream_wrapper ( char * protocol, TSRMLS_DC )

php_unregister_url_stream_wrapper() unregisters the wrapper associated with protocol.

php_stream_open_wrapper_ex

(no version information, might be only in CVS)

php_stream_open_wrapper_ex -- Opens a stream on a file or URL, specifying context

Description

php_stream * php_stream_open_wrapper_ex ( char * path, char * mode, int options, char ** opened, php_stream_context * context)

php_stream_open_wrapper_ex() is exactly like php_stream_open_wrapper(), but allows you to specify a php_stream_context object using context. To find out more about stream contexts, see XXX

php_stream_open_wrapper_as_file

(no version information, might be only in CVS)

php_stream_open_wrapper_as_file -- Opens a stream on a file or URL, and converts to a FILE*

Description

FILE * php_stream_open_wrapper_as_file ( char * path, char * mode, int options, char ** opened)

php_stream_open_wrapper_as_file() is exactly like php_stream_open_wrapper(), but converts the stream into an ANSI stdio FILE* and returns that instead of the stream. This is a convenient shortcut for extensions that pass FILE* to third-party libraries.

php_stream_filter_register_factory

(no version information, might be only in CVS)

php_stream_filter_register_factory -- Registers a filter factory with the Streams API

Description

int php_stream_filter_register_factory ( const char * filterpattern, php_stream_filter_factory * factory)

Use this function to register a filter factory with the name given by filterpattern. filterpattern can be either a normal string name (i.e. myfilter) or a global pattern (i.e. myfilterclass.*) to allow a single filter to perform different operations depending on the exact name of the filter invoked (i.e. myfilterclass.foo, myfilterclass.bar, etc...)

Megjegyzés: Filters registered by a loadable extension must be certain to call php_stream_filter_unregister_factory() during MSHUTDOWN.

php_stream_filter_unregister_factory

(no version information, might be only in CVS)

php_stream_filter_unregister_factory -- Deregisters a filter factory with the Streams API

Description

int php_stream_filter_unregister_factory ( const char * filterpattern)

Deregisters the filterfactory specified by the filterpattern making it no longer available for use.

Megjegyzés: Filters registered by a loadable extension must be certain to call php_stream_filter_unregister_factory() during MSHUTDOWN.


Streams Dir API Reference

Tartalom
php_stream_opendir -- Open a directory for file enumeration
php_stream_readdir -- Fetch the next directory entry from an opened dir
php_stream_rewinddir -- Rewind a directory stream to the first entry
php_stream_closedir -- Close a directory stream and release resources

The functions listed in this section work on local files, as well as remote files (provided that the wrapper supports this functionality!).

php_stream_opendir

(no version information, might be only in CVS)

php_stream_opendir -- Open a directory for file enumeration

Description

php_stream * php_stream_opendir ( char * path, php_stream_context * context)

php_stream_opendir() returns a stream that can be used to list the files that are contained in the directory specified by path. This function is functionally equivalent to POSIX opendir(). Although this function returns a php_stream object, it is not recommended to try to use the functions from the common API on these streams.

php_stream_readdir

(no version information, might be only in CVS)

php_stream_readdir -- Fetch the next directory entry from an opened dir

Description

php_stream_dirent * php_stream_readdir ( php_stream * dirstream, php_stream_dirent * ent)

php_stream_readdir() reads the next directory entry from dirstream and stores it into ent. If the function succeeds, the return value is ent. If the function fails, the return value is NULL. See php_stream_dirent for more details about the information returned for each directory entry.

php_stream_rewinddir

(no version information, might be only in CVS)

php_stream_rewinddir -- Rewind a directory stream to the first entry

Description

int php_stream_rewinddir ( php_stream * dirstream)

php_stream_rewinddir() rewinds a directory stream to the first entry. Returns 0 on success, but -1 on failure.

php_stream_closedir

(no version information, might be only in CVS)

php_stream_closedir -- Close a directory stream and release resources

Description

int php_stream_closedir ( php_stream * dirstream)

php_stream_closedir() closes a directory stream and releases resources associated with it. Returns 0 on success, but -1 on failure.


Streams File API Reference

Tartalom
php_stream_fopen_from_file -- Convert an ANSI FILE* into a stream
php_stream_fopen_tmpfile -- Open a FILE* with tmpfile() and convert into a stream
php_stream_fopen_temporary_file -- Generate a temporary file name and open a stream on it

php_stream_fopen_from_file

(no version information, might be only in CVS)

php_stream_fopen_from_file -- Convert an ANSI FILE* into a stream

Description

php_stream * php_stream_fopen_from_file ( FILE * file, char * mode)

php_stream_fopen_from_file() returns a stream based on the file. mode must be the same as the mode used to open file, otherwise strange errors may occur when trying to write when the mode of the stream is different from the mode on the file.

php_stream_fopen_tmpfile

(no version information, might be only in CVS)

php_stream_fopen_tmpfile -- Open a FILE* with tmpfile() and convert into a stream

Description

php_stream * php_stream_fopen_tmpfile ( void )

php_stream_fopen_from_file() returns a stream based on a temporary file opened with a mode of "w+b". The temporary file will be deleted automatically when the stream is closed or the process terminates.

php_stream_fopen_temporary_file

(no version information, might be only in CVS)

php_stream_fopen_temporary_file -- Generate a temporary file name and open a stream on it

Description

php_stream * php_stream_fopen_temporary_file ( const char * dir, const char * pfx, char ** opened)

php_stream_fopen_temporary_file() generates a temporary file name in the directory specified by dir and with a prefix of pfx. The generated file name is returns in the opened parameter, which you are responsible for cleaning up using efree(). A stream is opened on that generated filename in "w+b" mode. The file is NOT automatically deleted; you are responsible for unlinking or moving the file when you have finished with it.


Streams Socket API Reference

Tartalom
php_stream_sock_open_from_socket -- Convert a socket descriptor into a stream
php_stream_sock_open_host -- Open a connection to a host and return a stream
php_stream_sock_open_unix -- Open a Unix domain socket and convert into a stream

php_stream_sock_open_from_socket

(no version information, might be only in CVS)

php_stream_sock_open_from_socket -- Convert a socket descriptor into a stream

Description

php_stream * php_stream_sock_open_from_socket ( int socket, int persistent)

php_stream_sock_open_from_socket() returns a stream based on the socket. persistent is a flag that controls whether the stream is opened as a persistent stream. Generally speaking, this parameter will usually be 0.

php_stream_sock_open_host

(no version information, might be only in CVS)

php_stream_sock_open_host -- Open a connection to a host and return a stream

Description

php_stream * php_stream_sock_open_host ( const char * host, unsigned short port, int socktype, struct timeval * timeout, int persistent)

php_stream_sock_open_host() establishes a connect to the specified host and port. socktype specifies the connection semantics that should apply to the connection. Values for socktype are system dependent, but will usually include (at a minimum) SOCK_STREAM for sequenced, reliable, two-way connection based streams (TCP), or SOCK_DGRAM for connectionless, unreliable messages of a fixed maximum length (UDP).

persistent is a flag the controls whether the stream is opened as a persistent stream. Generally speaking, this parameter will usually be 0.

If not NULL, timeout specifies a maximum time to allow for the connection to be made. If the connection attempt takes longer than the timeout value, the connection attempt is aborted and NULL is returned to indicate that the stream could not be opened.

Megjegyzés: The timeout value does not include the time taken to perform a DNS lookup. The reason for this is because there is no portable way to implement a non-blocking DNS lookup.

The timeout only applies to the connection phase; if you need to set timeouts for subsequent read or write operations, you should use php_stream_sock_set_timeout() to configure the timeout duration for your stream once it has been opened.

The streams API places no restrictions on the values you use for socktype, but encourages you to consider the portability of values you choose before you release your extension.

php_stream_sock_open_unix

(no version information, might be only in CVS)

php_stream_sock_open_unix -- Open a Unix domain socket and convert into a stream

Description

php_stream * php_stream_sock_open_unix ( const char * path, int pathlen, int persistent, struct timeval * timeout)

php_stream_sock_open_unix() attempts to open the Unix domain socket specified by path. pathlen specifies the length of path. If timeout is not NULL, it specifies a timeout period for the connection attempt. persistent indicates if the stream should be opened as a persistent stream. Generally speaking, this parameter will usually be 0.

Megjegyzés: This function will not work under Windows, which does not implement Unix domain sockets. A possible exception to this rule is if your PHP binary was built using cygwin. You are encouraged to consider this aspect of the portability of your extension before it's release.

Megjegyzés: This function treats path in a binary safe manner, suitable for use on systems with an abstract namespace (such as Linux), where the first character of path is a NUL character.


Streams Structures

Tartalom
struct php_stream_statbuf -- Holds information about a file or URL
struct php_stream_dirent -- Holds information about a single file during dir scanning
struct php_stream_ops -- Holds member functions for a stream implementation
struct php_stream_wrapper -- Holds wrapper properties and pointer to operations
struct php_stream_wrapper_ops -- Holds member functions for a stream wrapper implementation
struct php_stream_filter -- Holds filter properties and pointer to operations
struct php_stream_filter_ops -- Holds member functions for a stream filter implementation

struct php_stream_statbuf

struct php_stream_statbuf -- Holds information about a file or URL

Description

php_stream_statbuf
     struct stat sb

sb is a regular, system defined, struct stat.

struct php_stream_dirent

struct php_stream_dirent -- Holds information about a single file during dir scanning

Description

php_stream_dirent
     char d_name[MAXPATHLEN]

d_name holds the name of the file, relative to the directory being scanned.

struct php_stream_ops

struct php_stream_ops -- Holds member functions for a stream implementation

Description

typedef struct _php_stream_ops {
             /* all streams MUST implement these operations */
             size_t (*write)(php_stream *stream, const char *buf, size_t count TSRMLS_DC);
             size_t (*read)(php_stream *stream, char *buf, size_t count TSRMLS_DC);
             int (*close)(php_stream *stream, int close_handle TSRMLS_DC);
             int (*flush)(php_stream *stream TSRMLS_DC);
             
             const char *label; /* name describing this class of stream */
             
             /* these operations are optional, and may be set to NULL if the stream does not
              * support a particular operation */
            int (*seek)(php_stream *stream, off_t offset, int whence TSRMLS_DC);
            char *(*gets)(php_stream *stream, char *buf, size_t size TSRMLS_DC);
            int (*cast)(php_stream *stream, int castas, void **ret TSRMLS_DC);
            int (*stat)(php_stream *stream, php_stream_statbuf *ssb TSRMLS_DC);
        } php_stream_ops;

struct php_stream_wrapper

struct php_stream_wrapper -- Holds wrapper properties and pointer to operations

Description

struct _php_stream_wrapper  {
            php_stream_wrapper_ops *wops;   /* operations the wrapper can perform */
            void *abstract;                 /* context for the wrapper */
            int is_url;                     /* so that PG(allow_url_fopen) can be respected */

            /* support for wrappers to return (multiple) error messages to the stream opener */
            int err_count;
            char **err_stack;
        } php_stream_wrapper;

struct php_stream_wrapper_ops

struct php_stream_wrapper_ops -- Holds member functions for a stream wrapper implementation

Description

typedef struct _php_stream_wrapper_ops {
            /* open/create a wrapped stream */
            php_stream *(*stream_opener)(php_stream_wrapper *wrapper, char *filename, char *mode,
                    int options, char **opened_path, php_stream_context *context STREAMS_DC TSRMLS_DC);
            /* close/destroy a wrapped stream */
            int (*stream_closer)(php_stream_wrapper *wrapper, php_stream *stream TSRMLS_DC);
            /* stat a wrapped stream */
            int (*stream_stat)(php_stream_wrapper *wrapper, php_stream *stream, php_stream_statbuf *ssb TSR$
            /* stat a URL */
            int (*url_stat)(php_stream_wrapper *wrapper, char *url, php_stream_statbuf *ssb TSRMLS_DC);
            /* open a "directory" stream */
            php_stream *(*dir_opener)(php_stream_wrapper *wrapper, char *filename, char *mode,
                    int options, char **opened_path, php_stream_context *context STREAMS_DC TSRMLS_DC);

            const char *label;

            /* Delete/Unlink a file */
            int (*unlink)(php_stream_wrapper *wrapper, char *url, int options, php_stream_context *context TSRMLS_DC);
        } php_stream_wrapper_ops;

struct php_stream_filter

struct php_stream_filter -- Holds filter properties and pointer to operations

Description

struct _php_stream_filter {
            php_stream_filter_ops *fops;
            void *abstract; /* for use by filter implementation */
            php_stream_filter *next;
            php_stream_filter *prev;
            int is_persistent;

            /* link into stream and chain */
            php_stream_filter_chain *chain;

            /* buffered buckets */
            php_stream_bucket_brigade buffer;
        } php_stream_filter;

struct php_stream_filter_ops

struct php_stream_filter_ops -- Holds member functions for a stream filter implementation

Description

typedef struct _php_stream_filter_ops {
            php_stream_filter_status_t (*filter)(
                    php_stream *stream,
                    php_stream_filter *thisfilter,
                    php_stream_bucket_brigade *buckets_in,
                    php_stream_bucket_brigade *buckets_out,
                    size_t *bytes_consumed,
                    int flags
                    TSRMLS_DC);

            void (*dtor)(php_stream_filter *thisfilter TSRMLS_DC);

            const char *label;
} php_stream_filter_ops;

Streams Constants

Tartalom
Stream open options -- Affects the operation of stream factory functions

Stream open options

Stream open options -- Affects the operation of stream factory functions

Description

One or more of these values can be combined using the OR operator.

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.

Megjegyzés: 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.


44. Fejezet. General Information

This section holds the most general questions about PHP: what it is and what it does.

1. What is PHP?
2. What does PHP stand for?
3. What is the relation between the versions?
4. Can I run several versions of PHP at the same time?
5. What are the differences between PHP 3 and PHP 4?
6. I think I found a bug! Who should I tell?

1. What is PHP?

From the preface of the manual:

PHP is an HTML-embedded scripting language. Much of its syntax is borrowed from C, Java and Perl with a couple of unique PHP-specific features thrown in. The goal of the language is to allow web developers to write dynamically generated pages quickly.

A nice introduction to PHP by Stig Sæther Bakken can be found at http://www.zend.com/zend/art/intro.php on the Zend website. Also, much of the PHP Conference Material is freely available.

2. What does PHP stand for?

PHP stands for PHP: Hypertext Preprocessor. This confuses many people because the first word of the acronym is the acronym. This type of acronym is called a recursive acronym. The curious can visit Free On-Line Dictionary of Computing for more information on recursive acronyms.

3. What is the relation between the versions?

PHP/FI 2.0 is an early and no longer supported version of PHP. PHP 3 is the successor to PHP/FI 2.0 and is a lot nicer. PHP 4 is the current generation of PHP, which uses the Zend engine under the hood. PHP 5 uses Zend engine 2 which, among other things, offers many additional OOP features. PHP 5 is experimental.

4. Can I run several versions of PHP at the same time?

Yes. See the INSTALL file that is included in the PHP 4 source distribution. Also, read the related appendix.

5. What are the differences between PHP 3 and PHP 4?

There are a couple of articles written on this by the authors of PHP 4. Here's a list of some of the more important new features:

  • Extended API module

  • Generalized build process under Unix

  • Generic web server interface that also supports multi-threaded web servers

  • Improved syntax highlighter

  • Native HTTP session support

  • Output buffering support

  • More powerful configuration system

  • Reference counting

Please see the What's new in PHP 4 overview for a detailed explanation of these features and more. If you're migrating from PHP 3 to PHP 4, also read the related appendix.

6. I think I found a bug! Who should I tell?

You should go to the PHP Bug Database and make sure the bug isn't a known bug. If you don't see it in the database, use the reporting form to report the bug. It is important to use the bug database instead of just sending an email to one of the mailing lists because the bug will have a tracking number assigned and it will then be possible for you to go back later and check on the status of the bug. The bug database can be found at http://bugs.php.net/.


45. Fejezet. 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. Help! I can't seem to subscribe/unsubscribe to/from one of the mailing lists!
4. Is there an archive of the mailing lists anywhere?
5. What can I ask the mailing list?
6. What information should I include when posting to the mailing list?

1. Are there any PHP mailing lists?

Of course! There are many mailing lists for several subjects. A whole list of mailing lists can be found on our Support page.

The most general mailing list is php-general. To subscribe, send mail to php-general-subscribe@lists.php.net. You don't need to include anything special in the subject or body of the message. To unsubscribe, send mail to php-general-unsubscribe@lists.php.net.

You can also subscribe and unsubscribe using the web interface on our Support page.

2. Are there any other communities?

There are countless of them around the world. We have links for example to some IRC servers and foreign language mailing lists on our Support page.

3. Help! I can't seem to subscribe/unsubscribe to/from one of the mailing lists!

If you have problems subscribing to or unsubscribing from the php-general mailing list, it may be because the mailing list software can't figure out the correct mailing address to use. If your email address was joeblow@example.com, 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.

4. Is there an archive of the mailing lists anywhere?

Yes, you will find a list of archive sites on the Support page. The 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/

5. What can I ask the mailing list?

Since PHP is growing more and more popular by the day the traffic has increased on the php-general mailing list and as of now the list gets about 150 to 200 posts a day. Because of this it is in everyones interest that you use the list as a last resort when you have looked everywhere else.

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

6. 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 what operating system you are running on, what version of PHP you're trying to set up, how you got it (pre-compiled, CVS, RPMs and so on), what you have done so far, where you got stuck and the exact error message.

This goes for any other problem as well. You have to include information on what you have done, where you got stuck, what you're trying to do and, if applicable, exact error messages. If you're having problems with your source code you need to include the part of the code that isn't working. Do not include more code than necessary though! It makes the post hard to read and a lot of people might just skip it all together because of this. If you're unsure about how much information to include in the mail it's better that you include to much than to little.

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.


46. Fejezet. 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 CVS repository on my Windows machine, what do I need to compile it?
6. Where do I find the Browser Capabilities File?

1. 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 CVS to get the absolute latest version of the source. For more information, go to http://www.php.net/anoncvs.php.

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

3. Where can I get libraries needed to compile some of the optional PHP extensions?

Megjegyzés: Those marked with * are not thread-safe libraries, and should not be used with PHP as a server module in the multi-threaded Windows web servers (IIS, Netscape). This does not matter in Unix environments, yet.

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

5. I got the latest version of the PHP source code from the CVS repository on my Windows machine, what do I need to compile it?

First, you will need Microsoft Visual C++ v6 (v5 may do it also, but we do it with v6), and you will need some support files. See the manual section about building PHP from source on Windows.

6. Where do I find the Browser Capabilities File?

You can find a browscap.ini file at http://www.garykeith.com/browsers/downloads.asp.


47. Fejezet. 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. I upgraded to PHP 4, and now mysql keeps telling me "Warning: MySQL: Unable to save result set in ...". What's up?
4. PHP 5 no longer bundles MySQL client libraries, what does this mean to me? Can I still use MySQL with PHP? I try to use MySQL and get "function undefined" errors, what gives?
5. After installing shared MySQL support, Apache dumps core as soon as libphp4.so is loaded. Can this be fixed?
6. 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>?

1. I heard it's possible to access Microsoft SQL Server from PHP. How?

On Windows machines, you can simply use the included ODBC support and the correct ODBC driver.

On Unix machines, you can use the Sybase-CT driver to access Microsoft SQL Servers because they are (at least mostly) protocol-compatible. Sybase has made a free version of the necessary libraries for Linux systems. For other Unix operating systems, you need to contact Sybase for the correct libraries. Also see the answer to the next question.

2. 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. There is a free pilot program where you can download an evaluation copy that doesn't expire and prices start at $675 for the commercial supported version.

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 www.mysql.com (get it from your mirror!). 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. Latest release is myodbc-2_50_19-win95.zip (NT available too, as well as source code). 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.

3. I upgraded to PHP 4, and now mysql keeps telling me "Warning: MySQL: Unable to save result set in ...". What's up?

Most likely what has happened is, PHP 4 was compiled with the '--with-mysql' option, without specifying the path to MySQL. This means PHP is using its built-in MySQL client library. If your system is running applications, such as PHP 3 as a concurrent Apache module, or auth-mysql, that use other versions of MySQL clients, then there is a conflict between the two differing versions of those clients.

Recompiling PHP 4, and adding the path to MySQL to the flag, '--with-mysql=/your/path/to/mysql' usually solves the problem.

4. PHP 5 no longer bundles MySQL client libraries, what does this mean to me? Can I still use MySQL with PHP? I try to use MySQL and get "function undefined" errors, what gives?

Yes. There will always be MySQL support in PHP of one kind or another. The only change in PHP 5 is that we are no longer bundling the client library itself. Some reasons in no particular order:

  • Most systems these days already have the client library installed.

  • Given the above, having multiple versions of the library can get messy. For example, if you link mod_auth_mysql against one version and PHP against another, and then enable both in Apache, you get a nice fat crash. Also, the bundled library didn't always play well with the installed server version. The most obvious symptom of this being disagreement over where to find the mysql.socket Unix domain socket file.

  • Maintenance was somewhat lax and it was falling further and further behind the released version.

  • Future versions of the library are under the GPL and thus we don't have an upgrade path since we cannot bundle a GPL'ed library in a BSD/Apache-style licensed project. A clean break in PHP 5 seemed like the best option.

This won't actually affect that many people. Unix users, at least the ones who know what they are doing, tend to always build PHP against their system's libmyqlclient library simply by doing --with-mysql=/usr when building PHP. Windows users may enable the extension php_mysql.dll inside php.ini. Also, copy libmySQL.dll into the appropriate %SYSTEMROOT% directory, just like you do with every other bundled DLL from the dll directory.

5. After installing shared MySQL support, Apache dumps core as soon as libphp4.so is loaded. Can this be fixed?

If your MySQL libs are linked against pthreads this will happen. Check using ldd. If they are, grab the MySQL tarball and compile from source, or recompile from the source rpm and remove the switch in the spec file that turns on the threaded client code. Either of these suggestions will fix this. Then recompile PHP with the new MySQL libs.

6. 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:
$result = mysql_query("SELECT * FROM tables_priv");
if (!$result) {
    echo mysql_error();
    exit;
}
or
$result = mysql_query("SELECT * FROM tables_priv")
    or die("Bad query: ".mysql_error());


48. Fejezet. Installation

This section holds common questions about the way to install PHP. PHP is available for almost any OS (except maybe for MacOS before OSX), and almost any web server.

To install PHP, follow the instructions in the INSTALL file located in the distribution. Windows users should also read the install.txt file. There are also some helpful hints for Windows users here.

1. Unix/Windows: Where should my php.ini file be located?
2. Unix: I installed PHP, but every time I load a document, I get the message 'Document Contains No Data'! What's going on here?
3. Unix: I installed PHP using RPMS, but Apache isn't processing the PHP pages! What's going on here?
4. Unix: I installed PHP 3 using RPMS, but it doesn't compile with the database support I need! 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/php4] root# apachectl configtest
 apachectl: /usr/local/apache/bin/httpd Undefined symbols:
  _compress
  _uncompress
9. Windows: I have installed PHP, but when I 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.

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

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

3. 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_php3.c
AddModule mod_perl.c

# Extra Modules
LoadModule php_module         modules/mod_php.so
LoadModule php3_module        modules/libphp3.so     /* for PHP 3 */
LoadModule php4_module        modules/libphp4.so     /* for PHP 4 */
LoadModule perl_module        modules/libperl.so
And add:
AddType application/x-httpd-php3 .php3    /* for PHP 3 */
AddType application/x-httpd-php .php      /* for PHP 4 */
... to the global properties, or to the properties of the VirtualDomain you want to have PHP support added to.

4. Unix: I installed PHP 3 using RPMS, but it doesn't compile with the database support I need! What's going on here?

Due to the way PHP 3 built, it is not easy to build a complete flexible PHP RPM. This issue is addressed in PHP 4. For PHP 3, we currently suggest you use the mechanism described in the INSTALL.REDHAT file in the PHP distribution. If you insist on using an RPM version of PHP 3, read on...

The RPM packagers are setting up the RPMS to install without database support to simplify installations and because RPMS use /usr/ instead of the standard /usr/local/ directory for files. You need to tell the RPM spec file which databases to support and the location of the top-level of your database server.

This example will explain the process of adding support for the popular MySQL database server, using the mod installation for Apache.

Of course all of this information can be adjusted for any database server that PHP supports. We will assume you installed MySQL and Apache completely with RPMS for this example as well.

  • First remove mod_php3 :
    rpm -e mod_php3

  • Then get the source rpm and INSTALL it, NOT --rebuild
    rpm -Uvh mod_php3-3.0.5-2.src.rpm

  • Then edit the /usr/src/redhat/SPECS/mod_php3.spec file

    In the %build section add the database support you want, and the path.

    For MySQL you would add
    --with-mysql=/usr \
    The %build section will look something like this:
    ./configure --prefix=/usr \
    	--with-apxs=/usr/sbin/apxs \
    	--with-config-file-path=/usr/lib \
    	--enable-debug=no \
    	--enable-safe-mode \
    	--with-exec-dir=/usr/bin \
    	--with-mysql=/usr \
    	--with-system-regex

  • Once this modification is made then build the binary rpm as follows:
    rpm -bb /usr/src/redhat/SPECS/mod_php3.spec

  • Then install the rpm
    rpm -ivh /usr/src/redhat/RPMS/i386/mod_php3-3.0.5-2.i386.rpm

Make sure you restart Apache, and you now have PHP 3 with MySQL support using RPM's. Note that it is probably much easier to just build from the distribution tarball of PHP 3 and follow the instructions in INSTALL.REDHAT found in that distribution.

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

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.

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.

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.

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.

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

9. Windows: I have installed PHP, but when I 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, php4ts.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.

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

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

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.

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.

To be sure your php.ini is being read by PHP, make a call to phpinfo() and near the top 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 than it's not being read and you should put your php.ini in that directory. If php.ini is included within the PATH than 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


49. Fejezet. Build Problems

This section gathers most common errors that occur at build time.

1. I got the latest version of PHP using the anonymous CVS 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:
4. When I try to start Apache, I get the following message:
5. When I run configure, it says that it can't find the include files or library for GD, gdbm, or some other package!
6. When it is compiling the file language-parser.tab.c, it gives me errors that say yytname undeclared.
7. When I run make, it seems to run fine but then fails when it tries to link the final application complaining that it can't find some files.
8. When linking PHP, it complains about a number of undefined references.
9. I can't figure out how to build PHP with Apache 1.3.
10. I have followed all the steps to install the Apache module version on Unix, and my PHP scripts show up in my browser or I am being asked to save the file.
11. It says to use: --activate-module=src/modules/php4/libphp4.a, but that file doesn't exist, so I changed it to --activate-module=src/modules/php4/libmodphp4.a and it doesn't work!? What's going on?
12. When I try to build Apache with PHP as a static module using --activate-module=src/modules/php4/libphp4.a it tells me that my compiler is not ANSI compliant.
13. When I try to build PHP using --with-apxs I get strange error messages.
14. During make, I get errors in microtime, and a lot of RUSAGE_ stuff.
15. When compiling PHP with MySQL, configure runs fine but during make I get an error similar to the following: ext/mysql/libmysql/my_tempnam.o(.text+0x46): In function my_tempnam': /php4/ext/mysql/libmysql/my_tempnam.c:103: the use of tempnam' is dangerous, better use mkstemp', what's wrong?
16. I want to upgrade my PHP. Where can I find the ./configure line that was used to build my current PHP installation?
17. When building PHP with the GD library it either gives strange compile errors or segfaults on execution.
18. When compiling PHP I seemingly get random errors, like it hangs. I'm using Solaris if that matters.

1. I got the latest version of PHP using the anonymous CVS 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 CVS 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.)

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!

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.

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

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.

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

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.

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

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

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.

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.

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

If you're linking with Apache 1.2.x, did you remember to add the appropriate information to the EXTRA_LIBS line of the Configuration file and re-rerun Apache's Configure script? See the INSTALL file that comes with the distribution for more information.

Some people have also reported that they had to add '-ldl' immediately following libphp4.a when linking with Apache.

9. 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://www.apache.org/dist/httpd/.

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

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.

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-php3 .php3 (for PHP 3)

    or AddType application/x-httpd-php .php (for PHP 4)

    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.

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?

Note that the libphp4.a file is not supposed to exist. The apache process will create it!

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.

This is a misleading error message from Apache that has been fixed in more recent versions.

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

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

15. When compiling PHP with MySQL, configure runs fine but during make I get an error similar to the following: ext/mysql/libmysql/my_tempnam.o(.text+0x46): In function my_tempnam': /php4/ext/mysql/libmysql/my_tempnam.c:103: the use of tempnam' is dangerous, better use mkstemp', what's wrong?

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.

Megjegyzés: 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).

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

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

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


50. Fejezet. Using PHP

This section gathers many common errors that you may face while writing PHP scripts.

1. 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?
2. 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 \\.
3. 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?
4. 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?
5. 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>
6. I get the message 'Warning: Cannot send session cookie - headers already sent...' or 'Cannot add header information - headers already sent...'.
7. I need to access information in the request header directly. How can I do this?
8. When I try to use authentication with IIS I get 'No Input file specified'.
9. My PHP script works on IE and Lynx, but on Netscape some of my output is missing. When I do a "View Source" I see the content in IE but not in Netscape.
10. How am I supposed to mix XML and PHP? It complains about my <?xml tags!
11. How can I use PHP with FrontPage or some other HTML editor that insists on moving my code around?
12. Where can I find a complete list of variables are available to me in PHP?
13. How can I generate PDF files without using the non-free and commercial libraries ClibPDF and PDFLib? I'd like something that's free and doesn't require external PDF libraries.
14. 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?

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

Superglobals: availability note: Since PHP 4.1.0, superglobal arrays such as $_GET , $_POST, and $_SERVER, etc. have been available. For more information, read the manual section on superglobals

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

The function addslashes() will do this. See also mysql_escape_string(). You may also strip backslashes with stripslashes().

directive note: magic_quotes_gpc: The PHP directive magic_quotes_gpc defaults to on. It essentially runs addslashes() on all your GET, POST, and COOKIE data. You may use stripslashes() to strip them.

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

The PHP function stripslashes() will strip those backslashes from your string. Most likely the backslashes magically exist because the PHP directive magic_quotes_gpc is on.

directive note: magic_quotes_gpc: The PHP directive magic_quotes_gpc defaults to on. It essentially runs addslashes() on all your GET, POST, and COOKIE data. You may use stripslashes() to strip them.

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

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

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

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

8. When I try to use authentication with IIS I get 'No Input file specified'.

The security model of IIS is at fault here. This is a problem common to all CGI programs running under IIS. A workaround is to create a plain HTML file (not parsed by PHP) as the entry page into an authenticated directory. Then use a META tag to redirect to the PHP page, or have a link to the PHP page. PHP will then recognize the authentication correctly. With the ISAPI module, this is not a problem. This should not effect other NT web servers. For more information, see: http://support.microsoft.com/support/kb/articles/q160/4/22.asp and the manual section on HTTP Authentication .

9. My PHP script works on IE and Lynx, but on Netscape some of my output is missing. When I do a "View Source" I see the content in IE but not in Netscape.

Netscape is more strict regarding HTML tags (such as tables) then IE. Running your HTML output through a HTML validator, such as validator.w3.org, might be helpful. For example, a missing </table> might cause this.

Also, both IE and Lynx ignore any NULs (\0) in the HTML stream, Netscape does not. The best way to check for this is to compile the command line version of PHP (also known as the CGI version) and run your script from the command line. In *nix, pipe it through od -c and look for any \0 characters. If you are on Windows you need to find an editor or some other program that lets you look at binary files. When Netscape sees a NUL in a file it will typically not output anything else on that line whereas both IE and Lynx will.

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

11. How can I use PHP with FrontPage or some other HTML editor that insists on moving my code around?

One of the easiest things to do is to enable using ASP tags in your PHP code. This allows you to use the ASP-style <% and %> code delimiters. Some of the popular HTML editors handle those more intelligently (for now). To enable the ASP-style tags, you need to set the asp_tags php.ini variable, or use the appropriate Apache directive.

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

register_globals: important note: Since PHP 4.2.0, the default value for the PHP directive register_globals is off. The PHP community encourages all to not rely on this directive but instead use other means, such as the superglobals.

13. How can I generate PDF files without using the non-free and commercial libraries ClibPDF and 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 http://www.ros.co.nz/pdf/, http://www.fpdf.org/, http://www.gnuvox.com/pdf4php/, and http://www.potentialtech.com/ppl.php. There is also the Panda module.

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

Superglobals: availability note: Since PHP 4.1.0, superglobal arrays such as $_GET , $_POST, and $_SERVER, etc. have been available. For more information, read the manual section on superglobals


51. Fejezet. 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 outside of PHP. The manual page on this topic includes many examples as well. Pay close attention to what register_globals means to you too.

1. What encoding/decoding do I need when I pass a value through a form/URL?
2. I'm trying to use an <input type="image"> tag, but the $foo.x and $foo.y variables aren't available. $_GET['foo.x'] isn't existing either. Where are they?
3. How do I create arrays in a HTML <form>?
4. How do I get all the results from a select multiple HTML tag?
5. How can I pass a variable from Javascript to PHP?

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

Példa 51-1. A hidden HTML form element

<?php
    echo "<input type='hidden' value='" . htmlspecialchars($data) . "' />\n";
?>

Megjegyzés: 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.

Példa 51-2. Data to be edited by the user

<?php
    echo "<textarea name='mydata'>\n";
    echo htmlspecialchars($data)."\n";
    echo "</textarea>";
?>

Megjegyzés: 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.

Példa 51-3. In a URL

<?php
    echo "<a href='" . htmlspecialchars("/nextpage.php?stage=23&data=" .
        urlencode($data)) . "'>\n";
?>

Megjegyzés: In fact you are faking a HTML GET request, therefore it's necessary to manually urlencode() the data.

Megjegyzés: 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 urlencoded() 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.

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?

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 outside of PHP. For example, $_GET['foo_x'].

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

Megjegyzés: Specifying an arrays key is optional in HTML. If you do not specify the keys, the array gets filled in the order the elements appear in the form. Our first example will contain keys 0, 1, 2 and 3.

See also Array Functions and Variables from outside PHP.

4. How do I get all the results from a select multiple HTML tag?

The select multiple tag in an HTML construct allows users to select multiple items from a list. These items are then passed to the action handler for the form. The problem is that they are all passed with the same widget name. I.e.
<select name="var" multiple="yes">
Each selected option will arrive at the action handler as:
var=option1
var=option2
var=option3
Each option will overwrite the contents of the previous $var variable. The solution is to use PHP's "array from form element" feature. The following should be used:
<select name="var[]" multiple="yes">
This tells PHP to treat $var as an array and each assignment of a value to var[] adds an item to the array. The first item becomes $var[0], the next $var[1], etc. The count() function can be used to determine how many options were selected, and the sort() function can be used to sort the option array if necessary.

Note that if you are using JavaScript the [] on the element name might cause you problems when you try to refer to the element by name. Use it's numerical form element ID instead, or enclose the variable name in single quotes and use that as the index to the elements array, for example:
variable = documents.forms[0].elements['var[]'];

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

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


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

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

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

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

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

5. How can I trap COM errors ?

Currently it's not possible to trap COM errors beside the ways provided by PHP itself (@, track_errors, ..), but we are thinking of a way to implement this.

6. Can I generate DLL files from PHP scripts like i can in Perl ?

No, unfortunately there is no such tool available for PHP.

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

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

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

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

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

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

12. Is there a way to handle an event sent from COM object ?

Starting in PHP 4.3.0, you can define an event sink and bind it as shown in the example below. You can use com_print_typeinfo() to have PHP generate a skeleton for the event sink class.

Példa 52-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");
$sink =& new IEEventSinker();
com_event_sink($ie, $sink, "DWebBrowserEvents2");
$ie->Visible = true;
$ie->Navigate("http://www.php.net");
while(!$sink->terminated) {
  com_message_pump(4000);
}
$ie = null;
?>

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 ?

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

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

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


53. Fejezet. PHP and other languages

PHP is the best language for web programing, but what about other languages?

1. PHP vs. ASP?
2. Is there an ASP to PHP converter?
3. PHP vs. Cold Fusion?
4. PHP vs. Perl?

1. PHP vs. ASP?

ASP is not really a language in itself, it's an acronym for Active Server Pages, the actual language used to program ASP with is Visual Basic Script or JScript. The biggest drawback of ASP is that it's a proprietary system that is natively used only on Microsoft Internet Information Server (IIS). This limits it's availability to Win32 based servers. There are a couple of projects in the works that allows ASP to run in other environments and webservers: InstantASP from Halcyon (commercial), Chili!Soft ASP from Chili!Soft (commercial). ASP is said to be a slower and more cumbersome language than PHP, less stable as well. Some of the pros of ASP is that since it primarily uses VBScript it's relatively easy to pick up the language if you're already know how to program in Visual Basic. ASP support is also enabled by default in the IIS server making it easy to get up and running. The components built in ASP are really limited, so if you need to use "advanced" features like interacting with FTP servers, you need to buy additional components.

2. Is there an ASP to PHP converter?

Yes, the server-side asp2php is the one most often referred to as well as this client-side option.

3. PHP vs. Cold Fusion?

PHP is commonly said to be faster and more efficient for complex programming tasks and trying out new ideas. PHP is generally referred to as more stable and less resource intensive as well. Cold Fusion has better error handling, database abstraction and date parsing although database abstraction is addressed in PHP 4. Another thing that is listed as one of Cold Fusion's strengths is its excellent search engine, but it has been mentioned that a search engine is not something that should be included in a web scripting language. PHP runs on almost every platform there is; Cold Fusion is only available on Win32, Solaris, Linux and HP/UX. Cold Fusion has a good IDE and is generally easier to get started with, whereas PHP initially requires more programming knowledge. Cold Fusion is designed with non-programmers in mind, while PHP is focused on programmers.

A great summary by Michael J Sheldon on this topic has been posted to the PHP mailing list. A copy can be found at http://marc.theaimsgroup.com/?l=php-general&m=95602167412542&w=1.

4. PHP vs. Perl?

The biggest advantage of PHP over Perl is that PHP was designed for scripting for the web where Perl was designed to do a lot more and can because of this get very complicated. The flexibility / complexity of Perl makes it easier to write code that another author / coder has a hard time reading. PHP has a less confusing and stricter format without losing flexibility. PHP is easier to integrate into existing HTML than Perl. PHP has pretty much all the 'good' functionality of Perl: constructs, syntax and so on, without making it as complicated as Perl can be. Perl is a very tried and true language, it's been around since the late eighties, but PHP is maturing very quickly.


54. Fejezet. Migrating from PHP 2 to PHP 3

PHP has already a long history behind him: Legendary PHP 1.0, PHP/FI, PHP 3.0 and PHP 4.0.

1. Migrating from PHP 2 to PHP 3?

1. Migrating from PHP 2 to PHP 3?

PHP/FI 2.0 is no longer supported. Please see appropriate manual section for information about migration from PHP/FI 2.0.

If you are still working with PHP 2, we strongly recommend you to upgrade straight to PHP 4.


55. Fejezet. Migrating from PHP 3 to PHP 4

PHP has already a long history behind him : Legendary PHP 1.0, PHP/FI, PHP 3.0 and PHP 4.0.

1. Migrating from PHP 3 to PHP 4
2. Do sessions work in PHP 3?
3. Incompatible functions?

1. Migrating from PHP 3 to PHP 4

PHP 4 was designed to be as compatible with earlier versions of PHP as possible and very little functionality was broken in the process. If you're really unsure about compatibility you should install PHP 4 in a test environment and run your scripts there.

Also see the appropriate migration appendix of this manual.

2. Do sessions work in PHP 3?

Although native session support didn't exist in PHP 3, there are third-party applications that did (and still do) offer session functionality. The most common method was by using PHPLIB.

3. Incompatible functions?

Since PHP 4 is basically a rewrite of the entire PHP engine there was very few functions that were altered and only then some of the more exotic ones.


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

1. How can I handle the bz2 compressed manuals on Windows?

If you don't have an archiver-tool to handle bz2 files download the commandline 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 Windows Commander, a bz2 plugin for that program is available freely from the Windows Commander site.

The bzip2 commandline 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.


A. Függelék. History of PHP and related projects

PHP has come a long way in the last few years. Growing to be one of the most prominent languages powering the Web was not an easy task. Those of you interested in briefly seeing how PHP grew out to what it is today, read on. Old PHP releases can be found at the PHP Museum.


History of PHP

PHP/FI

PHP succeeds an older product, named PHP/FI. PHP/FI was created by Rasmus Lerdorf in 1995, initially as a simple set of Perl scripts for tracking accesses to his online resume. He named this set of scripts 'Personal Home Page Tools'. As more functionality was required, Rasmus wrote a much larger C implementation, which was able to communicate with databases, and enabled users to develop simple dynamic Web applications. Rasmus chose to release the source code for PHP/FI for everybody to see, so that anybody can use it, as well as fix bugs in it and improve the code.

PHP/FI, which stood for Personal Home Page / Forms Interpreter, included some of the basic functionality of PHP as we know it today. It had Perl-like variables, automatic interpretation of form variables and HTML embedded syntax. The syntax itself was similar to that of Perl, albeit much more limited, simple, and somewhat inconsistent.

By 1997, PHP/FI 2.0, the second write-up of the C implementation, had a cult of several thousand users around the world (estimated), with approximately 50,000 domains reporting as having it installed, accounting for about 1% of the domains on the Internet. While there were several people contributing bits of code to this project, it was still at large a one-man project.

PHP/FI 2.0 was officially released only in November 1997, after spending most of its life in beta releases. It was shortly afterwards succeeded by the first alphas of PHP 3.0.


PHP 3

PHP 3.0 was the first version that closely resembles PHP as we know it today. It was created by Andi Gutmans and Zeev Suraski in 1997 as a complete rewrite, after they found PHP/FI 2.0 severely underpowered for developing an eCommerce application they were working on for a University project. In an effort to cooperate and start building upon PHP/FI's existing user-base, Andi, Rasmus and Zeev decided to cooperate and announce PHP 3.0 as the official successor of PHP/FI 2.0, and development of PHP/FI 2.0 was mostly halted.

One of the biggest strengths of PHP 3.0 was its strong extensibility features. In addition to providing end users with a solid infrastructure for lots of different databases, protocols and APIs, PHP 3.0's extensibility features attracted dozens of developers to join in and submit new extension modules. Arguably, this was the key to PHP 3.0's tremendous success. Other key features introduced in PHP 3.0 were the object oriented syntax support and the much more powerful and consistent language syntax.

The whole new language was released under a new name, that removed the implication of limited personal use that the PHP/FI 2.0 name held. It was named plain 'PHP', with the meaning being a recursive acronym - PHP: Hypertext Preprocessor.

By the end of 1998, PHP grew to an install base of tens of thousands of users (estimated) and hundreds of thousands of Web sites reporting it installed. At its peak, PHP 3.0 was installed on approximately 10% of the Web servers on the Internet.

PHP 3.0 was officially released in June 1998, after having spent about 9 months in public testing.


PHP 4

By the winter of 1998, shortly after PHP 3.0 was officially released, Andi Gutmans and Zeev Suraski had begun working on a rewrite of PHP's core. The design goals were to improve performance of complex applications, and improve the modularity of PHP's code base. Such applications were made possible by PHP 3.0's new features and support for a wide variety of third party databases and APIs, but PHP 3.0 was not designed to handle such complex applications efficiently.

The new engine, dubbed 'Zend Engine' (comprised of their first names, Zeev and Andi), met these design goals successfully, and was first introduced in mid 1999. PHP 4.0, based on this engine, and coupled with a wide range of additional new features, was officially released in May 2000, almost two years after its predecessor, PHP 3.0. In addition to the highly improved performance of this version, PHP 4.0 included other key features such as support for many more Web servers, HTTP sessions, output buffering, more secure ways of handling user input and several new language constructs.

PHP 4 is currently the latest released version of PHP. Work has already begun on modifying and improving the Zend Engine to integrate the features which were designed for PHP 5.0.

Today, PHP is being used by hundreds of thousands of developers (estimated), and several million sites report as having it installed, which accounts for over 20% of the domains on the Internet.

PHP's development team includes dozens of developers, as well as dozens others working on PHP-related projects such as PEAR and the documentation project.


PHP 5

The future of PHP is mainly driven by its core, the Zend Engine. PHP 5 will include the new Zend Engine 2.0. To get more information on this engine, see its webpage.


History of PHP related projects

PEAR

PEAR, the PHP Extension and Application Repository (originally, PHP Extension and Add-on Repository) is PHP's version of foundation classes, and may grow in the future to be one of the key ways to distribute both PHP and C-based PHP extensions among developers.

PEAR was born in discussions held in the PHP Developers' Meeting (PDM) held in January 2000 in Tel Aviv. It was created by Stig S. Bakken, and is dedicated to his first-born daughter, Malin Bakken.

Since early 2000, PEAR has grown to be a big, significant project with a large number of developers working on implementing common, reusable functionality for the benefit of the entire PHP community. PEAR today includes a wide variety of infrastructure foundation classes for database access, content caching, mathematical calculations, eCommerce and much more.

More information about PEAR can be found in the manual.


PHP Quality Assurance Initiative

The PHP Quality Assurance Initiative was set up in the summer of 2000 in response to criticism that PHP releases were not being tested well enough for production environments. The team now consists of a core group of developers with a good understanding of the PHP code base. These developers spend a lot of their time localizing and fixing bugs within PHP. In addition there are many other team members who test and provide feedback on these fixes using a wide variety of platforms.


PHP-GTK

PHP-GTK is the PHP solution for writing client side GUI applications. Andrei Zmievski remembers the planing and creation process of PHP-GTK:

GUI programming has always been of my interests, and I found that Gtk+ is a very nice toolkit, except that programming with it in C is somewhat tedious. After witnessing PyGtk and GTK-Perl implementations, I decided to see if PHP could be made to interface with Gtk+, even minimally. Starting in August of 2000, I began to have a bit more free time so that is when I started experimenting. My main guideline was the PyGtk implementation as it was fairly feature complete and had a nice object-oriented interface. James Henstridge, the author of PyGtk, provided very helpful advice during those initial stages.

Hand-writing the interfaces to all the Gtk+ functions was out of the question, so I seized upon the idea of code-generator, similar to how PyGtk did it. The code generator is a PHP program that reads a set of .defs file containing the Gtk+ classes, constants, and methods information and generates C code that interfaces PHP with them. What cannot be generated automatically can be written by hand in .overrides file.

Working on the code generator and the infrastructure took some time, because I could spend little time on PHP-GTK during the fall of 2000. After I showed PHP-GTK to Frank Kromann, he got interested and started helping me out with code generator work and Win32 implementation. When we wrote the first Hello World program and fired it up, it was extremely exciting. It took a couple more months to get the project to a presentable condition and the initial version was released on March 1, 2001. The story promptly hit SlashDot.

Sensing that PHP-GTK might be extensive, I set up separate mailing lists and CVS repositories for it, as well as the gtk.php.net website with the help of Colin Viebrock. The documentation would also need to be done and James Moore came in to help with that.

Since its release PHP-GTK has been gaining popularity. We have our own documentation team, the manual keeps improving, people start writing extensions for PHP-GTK, and more and more exciting applications with it.


Books about PHP

As PHP grew, it began to be recognized as a world-wide popular development platform. One of the most interesting ways of seeing this trend was by observing the books about PHP that came out throughout the years.

To the best of our knowledge, the first book dedicated to PHP was 'PHP - tvorba interaktivních internetových aplikací' - a Czech book published in April 1999, authored by Jirka Kosek. Next month followed a German book authored by Egon Schmid, Christian Cartus and Richard Blume. The first book in English about PHP was published shortly afterwards, and was 'Core PHP Programming' by Leon Atkinson. Both of these books covered PHP 3.0.

While these books were the first of their kind - they were followed by a large number of books from a host of authors and publishers. There are over 40 books in English, 50 books in German, and over 20 books in French! In addition, you can find books about PHP in many other languages, including Spanish, Korean, Japanese and Hebrew.

Clearly, this large number of books, written by different authors, published by many publishers, and their availability in so many languages - are a strong testimony for PHP's world-wide success.


Publications about PHP

To the best of our knowledge, the first article about PHP in a hard-copy magazine was published in the Czech mutation of Computerworld in the spring of 1998, and covered PHP 3.0. As with books, this was the first in a series of many articles published about PHP in various prominent magazines.

Articles about PHP appeared in Dr. Dobbs, Linux Enterprise, Linux Magazine and many more. Articles about migrating ASP-based applications to PHP under Windows even appear on Microsoft's very own MSDN!


B. Függelék. Migrating from PHP 4 to PHP 5

What has changed in PHP 5

PHP 5 and the integrated Zend Engine 2 have greatly improved PHP's performance and capabilities, but great care has been taken to break as little existing code as possible. So migrating your code from PHP 4 to 5 should be very easy. Most existing PHP 4 code should be ready to run without changes, but you should still know about the few differences and take care to test your code before switching versions in production environments.


Backward Incompatible Changes

Although most existing PHP 4 code should work without changes, you shoud pay attention to this backward imcompatible changes:


C. Függelék. Migrating from PHP 3 to PHP 4

What has changed in PHP 4

PHP 4 and the integrated Zend engine have greatly improved PHP's performance and capabilities, but great care has been taken to break as little existing code as possible. So migrating your code from PHP 3 to 4 should be much easier than migrating from PHP/FI 2 to PHP 3. A lot of existing PHP 3 code should be ready to run without changes, but you should still know about the few differences and take care to test your code before switching versions in production environments. The following should give you some hints about what to look for.


Running PHP 3 and PHP 4 concurrently

Recent operating systems provide the ability to perform versioning and scoping. This features make it possible to let PHP 3 and PHP 4 run as concurrent modules in one Apache server.

This feature is known to work on the following platforms:

  • Linux with recent binutils (binutils 2.9.1.0.25 tested)

  • Solaris 2.5 or better

  • FreeBSD (3.2, 4.0 tested)

To enable it, configure PHP 3 and PHP 4 to use APXS (--with-apxs) and the necessary link extensions (--enable-versioning). Otherwise, all standard installations instructions apply. For example:

$ ./configure \
  --with-apxs=/apache/bin/apxs \
  --enable-versioning \
  --with-mysql \
  --enable-track-vars


Migrating Configuration Files

The global configuration file, php3.ini, has changed its name to php.ini.

For the Apache configuration file, there are slightly more changes. The MIME types recognized by the PHP module have changed.

application/x-httpd-php3        -->    application/x-httpd-php
application/x-httpd-php3-source -->    application/x-httpd-php-source

You can make your configuration files work with both versions of PHP (depending on which one is currently compiled into the server), using the following syntax:

AddType  application/x-httpd-php3        .php3
AddType  application/x-httpd-php3-source .php3s

AddType  application/x-httpd-php         .php
AddType  application/x-httpd-php-source  .phps

In addition, the PHP directive names for Apache have changed.

Starting with PHP 4.0, there are only four Apache directives that relate to PHP:

php_value [PHP directive name] [value]
php_flag [PHP directive name] [On|Off]
php_admin_value [PHP directive name] [value]
php_admin_flag [PHP directive name] [On|Off]

There are two differences between the Admin values and the non admin values:

  • Admin values (or flags) can only appear in the server-wide Apache configuration files (e.g., httpd.conf).

  • Standard values (or flags) cannot control certain PHP directives, for example: safe mode (if you could override safe mode settings in .htaccess files, it would defeat safe mode's purpose). In contrast, Admin values can modify the value of any PHP directive.

To make the transition process easier, PHP 4 is bundled with scripts that automatically convert your Apache configuration and .htaccess files to work with both PHP 3 and PHP 4. These scripts do NOT convert the mime type lines! You have to convert these yourself.

To convert your Apache configuration files, run the apconf-conv.sh script (available in the scripts/apache/ directory). For example:

~/php4/scripts/apache:#  ./apconf-conv.sh /usr/local/apache/conf/httpd.conf

Your original configuration file will be saved in httpd.conf.orig.

To convert your .htaccess files, run the aphtaccess-conv.sh script (available in the scripts/apache/ directory as well):

~/php4/scripts/apache:#  find / -name .htaccess -exec ./aphtaccess-conv.sh {} \;

Likewise, your old .htaccess files will be saved with an .orig prefix.

The conversion scripts require awk to be installed.


Parser behavior

Parsing and execution are now two completely separated steps, no execution of a files code will happen until the complete file and everything it requires has completely and successfully been parsed.

One of the new requirements introduced with this split is that required and included files now have to be syntactically complete. You can no longer spread the different controlling parts of a control structure across file boundaries. That is you cannot start a for or while loop, an if statement or a switch block in one file and have the end of loop, else, endif, case or break statements in a different file.

It still perfectly legal to include additional code within loops or other control structures, only the controlling keywords and corresponding curly braces {...} have to be within the same compile unit (file or eval()ed string).

This should not harm too much as spreading code like this should be considered as very bad style anyway.

Another thing no longer possible, though rarely seen in PHP 3 code is returning values from a required file. Returning a value from an included file is still possible.


Error reporting

Configuration changes

With PHP 3 the error reporting level was set as a simple numeric value formed by summing up the numbers related to different error levels. Usual values were 15 for reporting all errors and warnings or 7 for reporting everything but simple notice messages reporting bad style and things like that.

PHP 4 has a larger set of error and warning levels and comes with a configuration parser that now allows for symbolic constants to be used for setting the intended behavior.

Error reporting level should now be configured by explicitly taking away the warning levels you do not want to generate error messages by x-oring them from the symbolic constant E_ALL. Sounds complicated? Well, lets say you want the error reporting system to report all but the simple style warnings that are categorized by the symbolic constant E_NOTICE. Then you'll put the following into your php.ini: error_reporting = E_ALL & ~ ( E_NOTICE ). If you want to suppress warnings too you add up the appropriate constant within the braces using the binary or operator '|': error_reporting= E_ALL & ~ ( E_NOTICE | E_WARNING ).

Figyelem

When upgrading code or servers from PHP 3 to PHP 4 you should check these settings and calls to error_reporting() or you might disable reporting the new error types, especially E_COMPILE_ERROR. This may lead to empty documents without any feedback of what happened or where to look for the problem.

Figyelem

Using the old values 7 and 15 for setting up error reporting is a very bad idea as this suppresses some of the newly added error classes including parse errors. This may lead to very strange behavior as scripts might no longer work without error messages showing up anywhere.

This has lead to a lot of unreproducible bug reports in the past where people reported script engine problems they were not capable to track down while the TRUE case was usually some missing '}' in a required file that the parser was not able to report due to a misconfigured error reporting system.

So checking your error reporting setup should be the first thing to do whenever your scripts silently die. The Zend engine can be considered mature enough nowadays to not cause this kind of strange behavior.


Additional warning messages

A lot of existing PHP 3 code uses language constructs that should be considered as very bad style as this code, while doing the intended thing now, could easily be broken by changes in other places. PHP 4 will output a lot of notice messages in such situations where PHP 3 didn't. The easy fix is to just turn off E_NOTICE messages, but it is usually a good idea to fix the code instead.

The most common case that will now produce notice messages is the use of unquoted string constants as array indices. Both PHP 3 and 4 will fall back to interpret these as strings if no keyword or constant is known by that name, but whenever a constant by that name had been defined anywhere else in the code it might break your script. This can even become a security risk if some intruder manages to redefine string constants in a way that makes your script give him access rights he wasn't intended to have. So PHP 4 will now warn you whenever you use unquoted string constants as for example in $_SERVER[REQUEST_METHOD]. Changing it to $_SERVER['REQUEST_METHOD'] will make the parser happy and greatly improve the style and security of your code.

Another thing PHP 4 will now tell you about is the use of uninitialized variables or array elements.


Initializers

Static variable and class member initializers only accept scalar values while in PHP 3 they accepted any valid expression. This is, once again, due to the split between parsing and execution as no code has yet been executed when the parser sees the initializer.

For classes you should use constructors to initialize member variables instead. For static variables anything but a simple static value rarely makes sense anyway.


empty("0")

The perhaps most controversial change in behavior has happened to the behavior of the empty(). A String containing only the character '0' (zero) is now considered empty while it wasn't in PHP 3.

This new behavior makes sense in web applications, with all input fields returning strings even if numeric input is requested, and with PHP's capabilities of automatic type conversion. But on the other hand it might break your code in a rather subtle way, leading to misbehavior that is hard to track down if you do not know about what to look for.


Missing functions

While PHP 4 comes with a lot of new features, functions and extensions, you may still find some functions from version 3 missing. A small number of core functions has vanished because they do not work with the new scheme of splitting parsing and execution as introduced into 4 with the Zend engine. Other functions and even complete extensions have become obsolete as newer functions and extensions serve the same task better and/or in a more general way. Some functions just simply haven't been ported yet and finally some functions or extensions may be missing due to license conflicts.


Functions missing due to conceptual changes

As PHP 4 now separates parsing from execution it is no longer possible to change the behavior of the parser (now embedded in the Zend engine) at runtime as parsing already happened by then. So the function short_tags() no longer exists. You can still change the parsers behavior by setting appropriate values in the php.ini file.

Another feature of PHP 3 that is not a part of PHP 4 is the bundled debugging interface. There are third-party add-ons for the Zend engine which add similar functionality.


Deprecate functions and extensions

The Adabas and Solid database extensions are no more. Long live the unified ODBC extension instead.


Changed status for unset()

unset(), although still available, is implemented as a language construct rather than a function.

This does not have any consequences on the behavior of unset(), but testing for "unset" using function_exists() will return FALSE as it would with other language constructs that look like functions such as echo().

Another more practical change is that it is no longer possible to call unset() indirectly, that is $func="unset"; $func($somevar) won't work anymore.


PHP 3 extension

Extensions written for PHP 3 will not work with PHP 4, neither as binaries nor at the source level. It is not difficult to port extensions to PHP 4 if you have access to the original source. A detailed description of the actual porting process is not part of this text.


Variable substitution in strings

PHP 4 adds a new mechanism to variable substitution in strings. You can now finally access object member variables and elements from multidimensional arrays within strings.

To do so you have to enclose your variables with curly braces with the dollar sign immediately following the opening brace: {$...}

To embed the value of an object member variable into a string you simply write "text {$obj->member} text" while in PHP 3 you had to use something like "text ".$obj->member." text".

This should lead to more readable code, while it may break existing scripts written for PHP 3. But you can easily check for this kind of problem by checking for the character combination {$ in your code and by replacing it with \{$ with your favorite search-and-replace tool.


Cookies

PHP 3 had the bad habit of setting cookies in the reverse order of the setcookie() calls in your code. PHP 4 breaks with this habit and creates the cookie header lines in exactly the same order as you set the cookies in the code.

This might break some existing code, but the old behaviour was so strange to understand that it deserved a change to prevent further problems in the future.


Handling of global variables

While handling of global variables had the focus on to be easy in PHP 3 and early versions of PHP 4, the focus has changed to be more secure. While in PHP 3 the following example worked fine, in PHP 4 it has to be unset($GLOBALS["id"]);. This is only one issue of global variable handling. You should always have used $GLOBALS, with newer versions of PHP 4 you are forced to do so in most cases. Read more on this subject in the global references section.

Példa C-1. Migration of global variables

<?php
$id = 1;
function test()
{
    global $id;
    unset($id);
}
test();
echo($id); // This will print out 1 in PHP 4
?>

D. Függelék. Migrating from PHP/FI 2 to PHP 3

About the incompatibilities in 3.0

PHP 3.0 is rewritten from the ground up. It has a proper parser that is much more robust and consistent than 2.0's. 3.0 is also significantly faster, and uses less memory. However, some of these improvements have not been possible without compatibility changes, both in syntax and functionality.

In addition, PHP's developers have tried to clean up both PHP's syntax and semantics in version 3.0, and this has also caused some incompatibilities. In the long run, we believe that these changes are for the better.

This chapter will try to guide you through the incompatibilities you might run into when going from PHP/FI 2.0 to PHP 3.0 and help you resolve them. New features are not mentioned here unless necessary.

A conversion program that can automatically convert your old PHP/FI 2.0 scripts exists. It can be found in the convertor subdirectory of the PHP 3.0 distribution. This program only catches the syntax changes though, so you should read this chapter carefully anyway.


old_function

The old_function statement allows you to declare a function using a syntax identical to PHP/FI2 (except you must replace 'function' with 'old_function'.

This is a deprecated feature, and should only be used by the PHP/FI2->PHP 3 convertor.

Figyelem

Functions declared as old_function cannot be called from PHP's internal code. Among other things, this means you can't use them in functions such as usort(), array_walk(), and register_shutdown_function(). You can get around this limitation by writing a wrapper function (in normal PHP 3 form) to call the old_function.


Start/end tags

The first thing you probably will notice is that PHP's start and end tags have changed. The old <? > form has been replaced by three new possible forms:

Példa D-1. Migration: old start/end tags

<? echo "This is PHP/FI 2.0 code.\n"; >
As of version 2.0, PHP/FI also supports this variation:

Példa D-2. Migration: first new start/end tags

<? echo "This is PHP 3.0 code!\n"; ?>
Notice that the end tag now consists of a question mark and a greater-than character instead of just greater-than. However, if you plan on using XML on your server, you will get problems with the first new variant, because PHP may try to execute the XML markup in XML documents as PHP code. Because of this, the following variation was introduced:

Példa D-3. Migration: second new start/end tags

<?php echo "This is PHP 3.0 code!\n"; ?>
Some people have had problems with editors that don't understand the processing instruction tags at all. Microsoft FrontPage is one such editor, and as a workaround for these, the following variation was introduced as well:

Példa D-4. Migration: third new start/end tags

<script language="php">

  echo "This is PHP 3.0 code!\n";

</script>


if..endif syntax

The `alternative' way to write if/elseif/else statements, using if(); elseif(); else; endif; cannot be efficiently implemented without adding a large amount of complexity to the 3.0 parser. Because of this, the syntax has been changed:

Példa D-5. Migration: old if..endif syntax

if ($foo);
    echo "yep\n";
elseif ($bar);
    echo "almost\n";
else;
    echo "nope\n";
endif;

Példa D-6. Migration: new if..endif syntax

if ($foo):
    echo "yep\n";
elseif ($bar):
    echo "almost\n";
else:
    echo "nope\n";
endif;
Notice that the semicolons have been replaced by colons in all statements but the one terminating the expression (endif).


while syntax

Just like with if..endif, the syntax of while..endwhile has changed as well:

Példa D-7. Migration: old while..endwhile syntax

while ($more_to_come);
    ...
endwhile;

Példa D-8. Migration: new while..endwhile syntax

while ($more_to_come):
    ...
endwhile;

Figyelem

If you use the old while..endwhile syntax in PHP 3.0, you will get a never-ending loop.


Expression types

PHP/FI 2.0 used the left side of expressions to determine what type the result should be. PHP 3.0 takes both sides into account when determining result types, and this may cause 2.0 scripts to behave unexpectedly in 3.0.

Consider this example:

$a[0]=5;
$a[1]=7;

$key = key($a);
while ("" != $key) {
    echo "$keyn";
    next($a);
}

In PHP/FI 2.0, this would display both of $a's indices. In PHP 3.0, it wouldn't display anything. The reason is that in PHP 2.0, because the left argument's type was string, a string comparison was made, and indeed "" does not equal "0", and the loop went through. In PHP 3.0, when a string is compared with an integer, an integer comparison is made (the string is converted to an integer). This results in comparing atoi("") which is 0, and variablelist which is also 0, and since 0==0, the loop doesn't go through even once.

The fix for this is simple. Replace the while statement with:

while ((string)$key != "") {


Error messages have changed

PHP 3.0's error messages are usually more accurate than 2.0's were, but you no longer get to see the code fragment causing the error. You will be supplied with a file name and a line number for the error, though.


Short-circuited boolean evaluation

In PHP 3.0 boolean evaluation is short-circuited. This means that in an expression like (1 || test_me()), the function test_me() would not be executed since nothing can change the result of the expression after the 1.

This is a minor compatibility issue, but may cause unexpected side-effects.


Function TRUE/FALSE return values

Most internal functions have been rewritten so they return TRUE when successful and FALSE when failing, as opposed to 0 and -1 in PHP/FI 2.0, respectively. The new behaviour allows for more logical code, like $fp = fopen("/your/file") or fail("darn!");. Because PHP/FI 2.0 had no clear rules for what functions should return when they failed, most such scripts will probably have to be checked manually after using the 2.0 to 3.0 convertor.

Példa D-9. Migration from 2.0: return values, old code

$fp = fopen($file, "r");
if ($fp == -1);
    echo("Could not open $file for reading<br />\n");
endif;

Példa D-10. Migration from 2.0: return values, new code

$fp = @fopen($file, "r") or print("Could not open $file for reading<br />\n");


Other incompatibilities

  • The PHP 3.0 Apache module no longer supports Apache versions prior to 1.2. Apache 1.2 or later is required.

  • echo() no longer supports a format string. Use the printf() function instead.

  • In PHP/FI 2.0, an implementation side-effect caused $foo[0] to have the same effect as $foo. This is not true for PHP 3.0.

  • Reading arrays with $array[] is no longer supported

    That is, you cannot traverse an array by having a loop that does $data = $array[]. Use current() and next() instead.

    Also, $array1[] = $array2 does not append the values of $array2 to $array1, but appends $array2 as the last entry of $array1. See also multidimensional array support.

  • "+" is no longer overloaded as a concatenation operator for strings, instead it converts it's arguments to numbers and performs numeric addition. Use "." instead.

Példa D-11. Migration from 2.0: concatenation for strings

echo "1" + "1";

In PHP 2.0 this would echo 11, in PHP 3.0 it would echo 2. Instead use:
echo "1"."1";
$a = 1;
$b = 1;
echo $a + $b;

This would echo 2 in both PHP 2.0 and 3.0.
$a = 1;
$b = 1;
echo $a.$b;
This will echo 11 in PHP 3.0.


E. Függelék. A PHP debuggere

A debuggerről

A PHP 3 tartalmaz hálózat-alapú debugger támogatást.

PHP 4 nem nyújt beépített támogatást a hibák követésére, bár külső debuggerek rendelkezésre állnak. A Zend IDE termék tartalmaz egy debuggert, és ingyenes debuggerek is elérhetőek, mint a a DBG vagy az Advanced PHP Debugger (APD).


A debugger használata

A PHP 3 belső debuggere hasznos rejtőzködő hibák keresésekor. Minden alkalommal, amikor a PHP 3 elindul a debugger egy TCP portra csatlakozik. Ettől kezdve minden hibaüzenet erre a TCP csatlakozásra kerül elküldésre. Ezt az információt egy debug szervernek szánja, ami egy IDE-ben, vagy egy programozható szerkesztőben fut (mint például az Emacs).

A következőképpen kell beállítani a debuggert:

  1. Meg kell adni a TCP portot a debugger számára a konfigurációs fájlban a debugger.port beállítással, és engedélyezni kell a debugger.enabled beállítással.

  2. Egy TCP port figyelőt kell irányítani a megfelelő port számra (például socket -l -s 1400 UNIX rendszeren).

  3. A kódba írd be: debugger_on(host), ahol host a TCP figyelő neve vagy IP címe.

Ettől kezdve minden figyelmeztetés, hiba, stb. a figyelőnél meg fog jelenni, akkor is, ha kikapcsolod az error_reporting()-al.


A debugger protokoll

A PHP 3 debugger protokollja sor-alapú. Ez azt jelenti, hogy minden sornak van egy típus eleme, és több sor alkot egy üzenetet. Minden üzenet a start típussal kezdődik, és az end típussal végződik. A PHP 3 esetleg párhuzamosan küldhet sorokat más-más üzenetekkel.

Egy sor a következő formát mutatja:


dátum idő
host(pid)
típus:
üzenet adata
     

dátum

ISO 8601 formátumú dátum (éééé-hh-nn)

idő

Időpont, beleértve a mikroszekundumokat is: óó:pp:uuuuuu

host

Domain név vagy IP cím, ahonnan a szkript hiba érkezett.

pid

PID (process id). A host-on futó process azonosítója, ami a PHP 3 szkriptet futtatja.

típus

A sor típusa. Megadja a fogadó programnak, hogy hogyan kell kezelni az utána következő adatot.

Táblázat E-1. Debugger sor típusok

NévJelentés
start Közli, hogy egy üzenet itt kezdődik el. Az adat tartalma a hiba típusa, ami "Debugger hiba típusok" táblázatban találhatóak egyike.
messageA PHP 3 hibaüzenet.
location Fájlnév és sorszám, ahol a hiba felmerült. Az első location sor mindig a legfelső szintű fájlt mutatja. Az adat tartalma fájlnév:sorszám lesz. Mindig található egy location sor a message és function sorok után.
frames A frame-ek száma a következő stack kiírásban. Ha négy frame van, az azt jelenti, hogy négy mélységben hívott függvényben volt hiba. Ha nincs "frames" rész, akkor az érték 0 (a hiba a legfelső szinten történt).
function A függvény neve, ahol a hiba kelezkezett. Minden frame-nél megjelenik az ahhoz tartozó függvénynévvel.
end Közli a debugger programmal, hogy az üzenet végetért.

adat

A sorhoz tartozó adat.

Táblázat E-2. Debugger hiba típusok

DebuggerPHP 3 hiba
warningE_WARNING
errorE_ERROR
parseE_PARSE
noticeE_NOTICE
core-errorE_CORE_ERROR
core-warningE_CORE_WARNING
unknown(bármi más)

Példa E-1. Pálda debugger üzenetre


1998-04-05 23:27:400966 lucifer.guardian.no(20481) start: notice
1998-04-05 23:27:400966 lucifer.guardian.no(20481) message: Uninitialized variable
1998-04-05 23:27:400966 lucifer.guardian.no(20481) location: (NULL):7
1998-04-05 23:27:400966 lucifer.guardian.no(20481) frames: 1
1998-04-05 23:27:400966 lucifer.guardian.no(20481) function: display
1998-04-05 23:27:400966 lucifer.guardian.no(20481) location: /home/ssb/public_html/test.php3:10
1998-04-05 23:27:400966 lucifer.guardian.no(20481) end: notice
     


F. Függelék. Extending PHP 3

This section is rather outdated and demonstrates how to extend PHP 3. If you're interested in PHP 4, please read the section on the Zend API. Also, you'll want to read various files found in the PHP source, files such as README.SELF-CONTAINED-EXTENSIONS and README.EXT_SKEL.


Adding functions to PHP

Function Prototype

All functions look like this:
void php3_foo(INTERNAL_FUNCTION_PARAMETERS) {
     
}
Even if your function doesn't take any arguments, this is how it is called.


Function Arguments

Arguments are always of type pval. This type contains a union which has the actual type of the argument. So, if your function takes two arguments, you would do something like the following at the top of your function:

Példa F-1. Fetching function arguments

pval *arg1, *arg2;
if (ARG_COUNT(ht) != 2 || getParameters(ht,2,&arg1,&arg2)==FAILURE) {
   WRONG_PARAM_COUNT;
}
NOTE: Arguments can be passed either by value or by reference. In both cases you will need to pass &(pval *) to getParameters. If you want to check if the n'th parameter was sent to you by reference or not, you can use the function, ParameterPassedByReference(ht,n). It will return either 1 or 0.

When you change any of the passed parameters, whether they are sent by reference or by value, you can either start over with the parameter by calling pval_destructor on it, or if it's an ARRAY you want to add to, you can use functions similar to the ones in internal_functions.h which manipulate return_value as an ARRAY.

Also if you change a parameter to IS_STRING make sure you first assign the new estrdup()'ed string and the string length, and only later change the type to IS_STRING. If you change the string of a parameter which already IS_STRING or IS_ARRAY you should run pval_destructor on it first.


Variable Function Arguments

A function can take a variable number of arguments. If your function can take either 2 or 3 arguments, use the following:

Példa F-2. Variable function arguments

pval *arg1, *arg2, *arg3;
int arg_count = ARG_COUNT(ht);

if (arg_count < 2 || arg_count > 3 ||
    getParameters(ht,arg_count,&arg1,&arg2,&arg3)==FAILURE) {
    WRONG_PARAM_COUNT;
}


Using the Function Arguments

The type of each argument is stored in the pval type field. This type can be any of the following:

Táblázat F-1. PHP Internal Types

IS_STRINGString
IS_DOUBLEDouble-precision floating point
IS_LONGLong integer
IS_ARRAYArray
IS_EMPTYNone
IS_USER_FUNCTION??
IS_INTERNAL_FUNCTION?? (if some of these cannot be passed to a function - delete)
IS_CLASS??
IS_OBJECT??

If you get an argument of one type and would like to use it as another, or if you just want to force the argument to be of a certain type, you can use one of the following conversion functions:
convert_to_long(arg1);
convert_to_double(arg1);
convert_to_string(arg1); 
convert_to_boolean_long(arg1); /* If the string is "" or "0" it becomes 0, 1 otherwise */
convert_string_to_number(arg1);  /* Converts string to either LONG or DOUBLE depending on string */

These function all do in-place conversion. They do not return anything.

The actual argument is stored in a union; the members are:

  • IS_STRING: arg1->value.str.val

  • IS_LONG: arg1->value.lval

  • IS_DOUBLE: arg1->value.dval


Memory Management in Functions

Any memory needed by a function should be allocated with either emalloc() or estrdup(). These are memory handling abstraction functions that look and smell like the normal malloc() and strdup() functions. Memory should be freed with efree().

There are two kinds of memory in this program: memory which is returned to the parser in a variable, and memory which you need for temporary storage in your internal function. When you assign a string to a variable which is returned to the parser you need to make sure you first allocate the memory with either emalloc() or estrdup(). This memory should NEVER be freed by you, unless you later in the same function overwrite your original assignment (this kind of programming practice is not good though).

For any temporary/permanent memory you need in your functions/library you should use the three emalloc(), estrdup(), and efree() functions. They behave EXACTLY like their counterpart functions. Anything you emalloc() or estrdup() you have to efree() at some point or another, unless it's supposed to stick around until the end of the program; otherwise, there will be a memory leak. The meaning of "the functions behave exactly like their counterparts" is: if you efree() something which was not emalloc()'ed nor estrdup()'ed you might get a segmentation fault. So please take care and free all of your wasted memory.

If you compile with "-DDEBUG", PHP will print out a list of all memory that was allocated using emalloc() and estrdup() but never freed with efree() when it is done running the specified script.


Setting Variables in the Symbol Table

A number of macros are available which make it easier to set a variable in the symbol table:

  • SET_VAR_STRING(name,value)

  • SET_VAR_DOUBLE(name,value)

  • SET_VAR_LONG(name,value)

Figyelem

Be careful with SET_VAR_STRING. The value part must be malloc'ed manually because the memory management code will try to free this pointer later. Do not pass statically allocated memory into a SET_VAR_STRING.

Symbol tables in PHP are implemented as hash tables. At any given time, &symbol_table is a pointer to the 'main' symbol table, and active_symbol_table points to the currently active symbol table (these may be identical like in startup, or different, if you're inside a function).

The following examples use 'active_symbol_table'. You should replace it with &symbol_table if you specifically want to work with the 'main' symbol table. Also, the same functions may be applied to arrays, as explained below.

Példa F-3. Checking whether $foo exists in a symbol table

if (hash_exists(active_symbol_table,"foo",sizeof("foo"))) { exists... }
else { doesn't exist }

Példa F-4. Finding a variable's size in a symbol table

hash_find(active_symbol_table,"foo",sizeof("foo"),&pvalue);
check(pvalue.type);
Arrays in PHP are implemented using the same hashtables as symbol tables. This means the two above functions can also be used to check variables inside arrays.

If you want to define a new array in a symbol table, you should do the following.

First, you may want to check whether it exists and abort appropriately, using hash_exists() or hash_find().

Next, initialize the array:

Példa F-5. Initializing a new array

pval arr;
  
if (array_init(&arr) == FAILURE) { failed... };
hash_update(active_symbol_table,"foo",sizeof("foo"),&arr,sizeof(pval),NULL);
This code declares a new array, named $foo, in the active symbol table. This array is empty.

Here's how to add new entries to it:

Példa F-6. Adding entries to a new array

pval entry;
  
entry.type = IS_LONG;
entry.value.lval = 5;
  
/* defines $foo["bar"] = 5 */
hash_update(arr.value.ht,"bar",sizeof("bar"),&entry,sizeof(pval),NULL); 

/* defines $foo[7] = 5 */
hash_index_update(arr.value.ht,7,&entry,sizeof(pval),NULL); 

/* defines the next free place in $foo[],
 * $foo[8], to be 5 (works like php2)
 */
hash_next_index_insert(arr.value.ht,&entry,sizeof(pval),NULL);
If you'd like to modify a value that you inserted to a hash, you must first retrieve it from the hash. To prevent that overhead, you can supply a pval ** to the hash add function, and it'll be updated with the pval * address of the inserted element inside the hash. If that value is NULL (like in all of the above examples) - that parameter is ignored.

hash_next_index_insert() uses more or less the same logic as "$foo[] = bar;" in PHP 2.0.

If you are building an array to return from a function, you can initialize the array just like above by doing:

if (array_init(return_value) == FAILURE) { failed...; }

...and then adding values with the helper functions:

add_next_index_long(return_value,long_value);
add_next_index_double(return_value,double_value);
add_next_index_string(return_value,estrdup(string_value));

Of course, if the adding isn't done right after the array initialization, you'd probably have to look for the array first:
pval *arr;
  
if (hash_find(active_symbol_table,"foo",sizeof("foo"),(void **)&arr)==FAILURE) { can't find... }
else { use arr->value.ht... }

Note that hash_find receives a pointer to a pval pointer, and not a pval pointer.

Just about any hash function returns SUCCESS or FAILURE (except for hash_exists(), which returns a boolean truth value).


Returning simple values

A number of macros are available to make returning values from a function easier.

The RETURN_* macros all set the return value and return from the function:

  • RETURN

  • RETURN_FALSE

  • RETURN_TRUE

  • RETURN_LONG(l)

  • RETURN_STRING(s,dup) If dup is TRUE, duplicates the string

  • RETURN_STRINGL(s,l,dup) Return string (s) specifying length (l).

  • RETURN_DOUBLE(d)

The RETVAL_* macros set the return value, but do not return.

  • RETVAL_FALSE

  • RETVAL_TRUE

  • RETVAL_LONG(l)

  • RETVAL_STRING(s,dup) If dup is TRUE, duplicates the string

  • RETVAL_STRINGL(s,l,dup) Return string (s) specifying length (l).

  • RETVAL_DOUBLE(d)

The string macros above will all estrdup() the passed 's' argument, so you can safely free the argument after calling the macro, or alternatively use statically allocated memory.

If your function returns boolean success/error responses, always use RETURN_TRUE and RETURN_FALSE respectively.


Returning complex values

Your function can also return a complex data type such as an object or an array.

Returning an object:

  1. Call object_init(return_value).

  2. Fill it up with values. The functions available for this purpose are listed below.

  3. Possibly, register functions for this object. In order to obtain values from the object, the function would have to fetch "this" from the active_symbol_table. Its type should be IS_OBJECT, and it's basically a regular hash table (i.e., you can use regular hash functions on .value.ht). The actual registration of the function can be done using:
    add_method( return_value, function_name, function_ptr );

The functions used to populate an object are:

  • add_property_long( return_value, property_name, l ) - Add a property named 'property_name', of type long, equal to 'l'

  • add_property_double( return_value, property_name, d ) - Same, only adds a double

  • add_property_string( return_value, property_name, str ) - Same, only adds a string

  • add_property_stringl( return_value, property_name, str, l ) - Same, only adds a string of length 'l'

Returning an array:

  1. Call array_init(return_value).

  2. Fill it up with values. The functions available for this purpose are listed below.

The functions used to populate an array are:

  • add_assoc_long(return_value,key,l) - add associative entry with key 'key' and long value 'l'

  • add_assoc_double(return_value,key,d)

  • add_assoc_string(return_value,key,str,duplicate)

  • add_assoc_stringl(return_value,key,str,length,duplicate) specify the string length

  • add_index_long(return_value,index,l) - add entry in index 'index' with long value 'l'

  • add_index_double(return_value,index,d)

  • add_index_string(return_value,index,str)

  • add_index_stringl(return_value,index,str,length) - specify the string length

  • add_next_index_long(return_value,l) - add an array entry in the next free offset with long value 'l'

  • add_next_index_double(return_value,d)

  • add_next_index_string(return_value,str)

  • add_next_index_stringl(return_value,str,length) - specify the string length


Using the resource list

PHP has a standard way of dealing with various types of resources. This replaces all of the local linked lists in PHP 2.0.

Available functions:

  • php3_list_insert(ptr, type) - returns the 'id' of the newly inserted resource

  • php3_list_delete(id) - delete the resource with the specified id

  • php3_list_find(id,*type) - returns the pointer of the resource with the specified id, updates 'type' to the resource's type

Typically, these functions are used for SQL drivers but they can be used for anything else; for instance, maintaining file descriptors.

Typical list code would look like this:

Példa F-7. Adding a new resource

RESOURCE *resource;

/* ...allocate memory for resource and acquire resource... */
/* add a new resource to the list */
return_value->value.lval = php3_list_insert((void *) resource, LE_RESOURCE_TYPE);
return_value->type = IS_LONG;

Példa F-8. Using an existing resource

pval *resource_id;
RESOURCE *resource;
int type;

convert_to_long(resource_id);
resource = php3_list_find(resource_id->value.lval, &type);
if (type != LE_RESOURCE_TYPE) {
	php3_error(E_WARNING,"resource index %d has the wrong type",resource_id->value.lval);
	RETURN_FALSE;
}
/* ...use resource... */

Példa F-9. Deleting an existing resource

pval *resource_id;
RESOURCE *resource;
int type;

convert_to_long(resource_id);
php3_list_delete(resource_id->value.lval);
The resource types should be registered in php3_list.h, in enum list_entry_type. In addition, one should add shutdown code for any new resource type defined, in list.c's list_entry_destructor() (even if you don't have anything to do on shutdown, you must add an empty case).


Using the persistent resource table

PHP has a standard way of storing persistent resources (i.e., resources that are kept in between hits). The first module to use this feature was the MySQL module, and mSQL followed it, so one can get the general impression of how a persistent resource should be used by reading mysql.c. The functions you should look at are:

php3_mysql_do_connect
php3_mysql_connect()
php3_mysql_pconnect()

The general idea of persistence modules is this:

  1. Code all of your module to work with the regular resource list mentioned in section (9).

  2. Code extra connect functions that check if the resource already exists in the persistent resource list. If it does, register it as in the regular resource list as a pointer to the persistent resource list (because of 1., the rest of the code should work immediately). If it doesn't, then create it, add it to the persistent resource list AND add a pointer to it from the regular resource list, so all of the code would work since it's in the regular resource list, but on the next connect, the resource would be found in the persistent resource list and be used without having to recreate it. You should register these resources with a different type (e.g. LE_MYSQL_LINK for non-persistent link and LE_MYSQL_PLINK for a persistent link).

If you read mysql.c, you'll notice that except for the more complex connect function, nothing in the rest of the module has to be changed.

The very same interface exists for the regular resource list and the persistent resource list, only 'list' is replaced with 'plist':

  • php3_plist_insert(ptr, type) - returns the 'id' of the newly inserted resource

  • php3_plist_delete(id) - delete the resource with the specified id

  • php3_plist_find(id,*type) - returns the pointer of the resource with the specified id, updates 'type' to the resource's type

However, it's more than likely that these functions would prove to be useless for you when trying to implement a persistent module. Typically, one would want to use the fact that the persistent resource list is really a hash table. For instance, in the MySQL/mSQL modules, when there's a pconnect() call (persistent connect), the function builds a string out of the host/user/passwd that were passed to the function, and hashes the SQL link with this string as a key. The next time someone calls a pconnect() with the same host/user/passwd, the same key would be generated, and the function would find the SQL link in the persistent list.

Until further documented, you should look at mysql.c or msql.c to see how one should use the plist's hash table abilities.

One important thing to note: resources going into the persistent resource list must *NOT* be allocated with PHP's memory manager, i.e., they should NOT be created with emalloc(), estrdup(), etc. Rather, one should use the regular malloc(), strdup(), etc. The reason for this is simple - at the end of the request (end of the hit), every memory chunk that was allocated using PHP's memory manager is deleted. Since the persistent list isn't supposed to be erased at the end of a request, one mustn't use PHP's memory manager for allocating resources that go to it.

When you register a resource that's going to be in the persistent list, you should add destructors to it both in the non-persistent list and in the persistent list. The destructor in the non-persistent list destructor shouldn't do anything. The one in the persistent list destructor should properly free any resources obtained by that type (e.g. memory, SQL links, etc). Just like with the non-persistent resources, you *MUST* add destructors for every resource, even it requires no destruction and the destructor would be empty. Remember, since emalloc() and friends aren't to be used in conjunction with the persistent list, you mustn't use efree() here either.


Adding runtime configuration directives

Many of the features of PHP can be configured at runtime. These configuration directives can appear in either the designated php3.ini file, or in the case of the Apache module version in the Apache .conf files. The advantage of having them in the Apache .conf files is that they can be configured on a per-directory basis. This means that one directory may have a certain safemodeexecdir for example, while another directory may have another. This configuration granularity is especially handy when a server supports multiple virtual hosts.

The steps required to add a new directive:

  1. Add directive to php3_ini_structure struct in mod_php3.h.

  2. In main.c, edit the php3_module_startup function and add the appropriate cfg_get_string() or cfg_get_long() call.

  3. Add the directive, restrictions and a comment to the php3_commands structure in mod_php3.c. Note the restrictions part. RSRC_CONF are directives that can only be present in the actual Apache .conf files. Any OR_OPTIONS directives can be present anywhere, include normal .htaccess files.

  4. In either php3take1handler() or php3flaghandler() add the appropriate entry for your directive.

  5. In the configuration section of the _php3_info() function in functions/info.c you need to add your new directive.

  6. And last, you of course have to use your new directive somewhere. It will be addressable as php3_ini.directive.


Calling User Functions

To call user functions from an internal function, you should use the call_user_function() function.

call_user_function() returns SUCCESS on success, and FAILURE in case the function cannot be found. You should check that return value! If it returns SUCCESS, you are responsible for destroying the retval pval yourself (or return it as the return value of your function). If it returns FAILURE, the value of retval is undefined, and you mustn't touch it.

All internal functions that call user functions must be reentrant. Among other things, this means they must not use globals or static variables.

call_user_function() takes six arguments:


HashTable *function_table

This is the hash table in which the function is to be looked up.


pval *object

This is a pointer to an object on which the function is invoked. This should be NULL if a global function is called. If it's not NULL (i.e. it points to an object), the function_table argument is ignored, and instead taken from the object's hash. The object *may* be modified by the function that is invoked on it (that function will have access to it via $this). If for some reason you don't want that to happen, send a copy of the object instead.


pval *function_name

The name of the function to call. Must be a pval of type IS_STRING with function_name.str.val and function_name.str.len set to the appropriate values. The function_name is modified by call_user_function() - it's converted to lowercase. If you need to preserve the case, send a copy of the function name instead.


pval *retval

A pointer to a pval structure, into which the return value of the invoked function is saved. The structure must be previously allocated - call_user_function() does NOT allocate it by itself.


int param_count

The number of parameters being passed to the function.


pval *params[]

An array of pointers to values that will be passed as arguments to the function, the first argument being in offset 0, the second in offset 1, etc. The array is an array of pointers to pval's; The pointers are sent as-is to the function, which means if the function modifies its arguments, the original values are changed (passing by reference). If you don't want that behavior, pass a copy instead.


Reporting Errors

To report errors from an internal function, you should call the php3_error() function. This takes at least two parameters -- the first is the level of the error, the second is the format string for the error message (as in a standard printf() call), and any following arguments are the parameters for the format string. The error levels are:


E_NOTICE

Notices are not printed by default, and indicate that the script encountered something that could indicate an error, but could also happen in the normal course of running a script. For example, trying to access the value of a variable which has not been set, or calling stat() on a file that doesn't exist.


E_WARNING

Warnings are printed by default, but do not interrupt script execution. These indicate a problem that should have been trapped by the script before the call was made. For example, calling ereg() with an invalid regular expression.


E_ERROR

Errors are also printed by default, and execution of the script is halted after the function returns. These indicate errors that can not be recovered from, such as a memory allocation problem.


E_PARSE

Parse errors should only be generated by the parser. The code is listed here only for the sake of completeness.


E_CORE_ERROR

This is like an E_ERROR, except it is generated by the core of PHP. Functions should not generate this type of error.


E_CORE_WARNING

This is like an E_WARNING, except it is generated by the core of PHP. Functions should not generate this type of error.


E_COMPILE_ERROR

This is like an E_ERROR, except it is generated by the Zend Scripting Engine. Functions should not generate this type of error.


E_COMPILE_WARNING

This is like an E_WARNING, except it is generated by the Zend Scripting Engine. Functions should not generate this type of error.


E_USER_ERROR

This is like an E_ERROR, except it is generated in PHP code by using the PHP function trigger_error(). Functions should not generate this type of error.


E_USER_WARNING

This is like an E_WARNING, except it is generated by using the PHP function trigger_error(). Functions should not generate this type of error.


E_USER_NOTICE

This is like an E_NOTICE, except it is generated by using the PHP function trigger_error(). Functions should not generate this type of error.


E_ALL

All of the above. Using this error_reporting level will show all error types.


G. Függelék. Álnevek listája

Ez a PHP-ben használt álnevek listája. Minden álnév megtalálható itt. Legtöbbször rossz ötlet az álneveket használni a függvények igazi neve helyett, mivel ezeket gyakran törlik, vagy átnevezik. Ez a lista azok számára készült, akik a régi programjaikat frissíteni szeretnék az új függvénynevek használatával.

Meg kell azonban jegyezni, hogy néhány függvénynek egyszerűen két neve van, és egyik sem álneve a másiknak. Ilyen például az is_int() és az is_integer(), mindkettő eppen ugyanúgy használható.

Ez a lista a PHP 4.0.6-os változatnak felel meg. Naponta frissülő álnév-listát itt találsz.

Táblázat G-1. Álnevek

ÁlnévFő függvény neveKiterjesztés
_gettext()Gettext
addswfmovie_add()Ming (flash)
addswfsprite_add()Ming (flash)
add_rootdomxml_add_root()DOM XML
addactionswfbutton_addAction()Ming (flash)
addcolorswfdisplayitem_addColor()Ming (flash)
addentryswfgradient_addEntry()Ming (flash)
addfillswfshape_addfill()Ming (flash)
addshapeswfbutton_addShape()Ming (flash)
addstringswftext_addString()Ming (flash)
addstringswftextfield_addString()Ming (flash)
alignswftextfield_align()Ming (flash)
attributesdomxml_attributes()DOM XML
childrendomxml_children()DOM XML
choprtrim()Beépített
closeclosedir()Beépített
com_getcom_propget()COM
com_propsetcom_propput()COM
com_setcom_propput()COM
cv_addccvs_add()CCVS
cv_authccvs_auth()CCVS
cv_commandccvs_command()CCVS
cv_countccvs_count()CCVS
cv_deleteccvs_delete()CCVS
cv_doneccvs_done()CCVS
cv_initccvs_init()CCVS
cv_lookupccvs_lookup()CCVS
cv_newccvs_new()CCVS
cv_reportccvs_report()CCVS
cv_returnccvs_return()CCVS
cv_reverseccvs_reverse()CCVS
cv_saleccvs_sale()CCVS
cv_statusccvs_status()CCVS
cv_textvalueccvs_textvalue()CCVS
cv_voidccvs_void()CCVS
dieexit()Egyéb függvény
dirgetdir()Beépített
diskfreespacedisk_free_space()Állományrendszer
domxml_getattrdomxml_get_attribute()DOM XML
domxml_setattrdomxml_set_attribute()DOM XML
doublevalfloatval()Beépített
drawarcswfshape_drawarc()Ming (flash)
drawcircleswfshape_drawcircle()Ming (flash)
drawcubicswfshape_drawcubic()Ming (flash)
drawcubictoswfshape_drawcubicto()Ming (flash)
drawcurveswfshape_drawcurve()Ming (flash)
drawcurvetoswfshape_drawcurveto()Ming (flash)
drawglyphswfshape_drawglyph()Ming (flash)
drawlineswfshape_drawline()Ming (flash)
drawlinetoswfshape_drawlineto()Ming (flash)
dtddomxml_intdtd()DOM XML
dumpmemdomxml_dumpmem()DOM XML
fbsqlfbsql_db_query()FrontBase
fputsfwrite()Beépített
get_attributedomxml_get_attribute()DOM XML
getascentswffont_getAscent()Ming (flash)
getascentswftext_getAscent()Ming (flash)
getattrdomxml_get_attribute()DOM XML
getdescentswffont_getDescent()Ming (flash)
getdescentswftext_getDescent()Ming (flash)
getheightswfbitmap_getHeight()Ming (flash)
getleadingswffont_getLeading()Ming (flash)
getleadingswftext_getLeading()Ming (flash)
getshape1swfmorph_getShape1()Ming (flash)
getshape2swfmorph_getShape2()Ming (flash)
getwidthswfbitmap_getWidth()Ming (flash)
getwidthswffont_getWidth()Ming (flash)
getwidthswftext_getWidth()Ming (flash)
gzputsgzwrite()Zlib
i18n_convertmb_convert_encoding()Több bájtos karakter alapú karakterláncok
i18n_discover_encodingmb_detect_encoding()Több bájtos karakter alapú karakterláncok
i18n_http_inputmb_http_input()Több bájtos karakter alapú karakterláncok
i18n_http_outputmb_http_output()Több bájtos karakter alapú karakterláncok
i18n_internal_encodingmb_internal_encoding()Több bájtos karakter alapú karakterláncok
i18n_ja_jp_hantozenmb_convert_kana()Több bájtos karakter alapú karakterláncok
i18n_mime_header_decodemb_decode_mimeheader()Több bájtos karakter alapú karakterláncok
i18n_mime_header_encodemb_encode_mimeheader()Több bájtos karakter alapú karakterláncok
imap_createimap_createmailbox()IMAP
imap_fetchtextimap_body()IMAP
imap_getmailboxesimap_list_full()IMAP
imap_getsubscribedimap_lsub_full()IMAP
imap_headerimap_headerinfo()IMAP
imap_listmailboximap_list()IMAP
imap_listsubscribedimap_lsub()IMAP
imap_renameimap_renamemailbox()IMAP
imap_scanimap_listscan()IMAP
imap_scanmailboximap_listscan()IMAP
ini_alterini_set()Beépített
is_doubleis_float()Beépített
is_integeris_int()Beépített
is_longis_int()Beépített
is_realis_float()Beépített
is_writeableis_writable()Beépített
joinimplode()Beépített
labelframeswfmovie_labelFrame()Ming (flash)
labelframeswfsprite_labelFrame()Ming (flash)
last_childdomxml_last_child()DOM XML
lastchilddomxml_last_child()DOM XML
ldap_closeldap_unbind()LDAP
magic_quotes_runtimeset_magic_quotes_runtime()Beépített
mbstrcutmb_strcut()Több bájtos karakter alapú karakterláncok
mbstrlenmb_strlen()Több bájtos karakter alapú karakterláncok
mbstrposmb_strpos()Több bájtos karakter alapú karakterláncok
mbstrrposmb_strrpos()Több bájtos karakter alapú karakterláncok
mbsubstrmb_substr()Több bájtos karakter alapú karakterláncok
ming_setcubicthresholdming_setCubicThreshold()Ming (flash)
ming_setscaleming_setScale()Ming (flash)
moveswfdisplayitem_move()Ming (flash)
movepenswfshape_movepen()Ming (flash)
movepentoswfshape_movepento()Ming (flash)
movetoswfdisplayitem_moveTo()Ming (flash)
movetoswffill_moveTo()Ming (flash)
movetoswftext_moveTo()Ming (flash)
msqlmsql_db_query()mSQL
msql_createdbmsql_create_db()mSQL
msql_dbnamemsql_result()mSQL
msql_dropdbmsql_drop_db()mSQL
msql_fieldflagsmsql_field_flags()mSQL
msql_fieldlenmsql_field_len()mSQL
msql_fieldnamemsql_field_name()mSQL
msql_fieldtablemsql_field_table()mSQL
msql_fieldtypemsql_field_type()mSQL
msql_freeresultmsql_free_result()mSQL
msql_listdbsmsql_list_dbs()mSQL
msql_listfieldsmsql_list_fields()mSQL
msql_listtablesmsql_list_tables()mSQL
msql_numfieldsmsql_num_fields()mSQL
msql_numrowsmsql_num_rows()mSQL
msql_regcasesql_regcase()mSQL
msql_selectdbmsql_select_db()mSQL
msql_tablenamemsql_result()mSQL
mssql_affected_rowssybase_affected_rows()Sybase
mssql_affected_rowssybase_affected_rows()Sybase
mssql_closesybase_close()Sybase
mssql_closesybase_close()Sybase
mssql_connectsybase_connect()Sybase
mssql_connectsybase_connect()Sybase
mssql_data_seeksybase_data_seek()Sybase
mssql_data_seeksybase_data_seek()Sybase
mssql_fetch_arraysybase_fetch_array()Sybase
mssql_fetch_arraysybase_fetch_array()Sybase
mssql_fetch_fieldsybase_fetch_field()Sybase
mssql_fetch_fieldsybase_fetch_field()Sybase
mssql_fetch_objectsybase_fetch_object()Sybase
mssql_fetch_objectsybase_fetch_object()Sybase
mssql_fetch_rowsybase_fetch_row()Sybase
mssql_fetch_rowsybase_fetch_row()Sybase
mssql_field_seeksybase_field_seek()Sybase
mssql_field_seeksybase_field_seek()Sybase
mssql_free_resultsybase_free_result()Sybase
mssql_free_resultsybase_free_result()Sybase
mssql_get_last_messagesybase_get_last_message()Sybase
mssql_get_last_messagesybase_get_last_message()Sybase
mssql_min_client_severitysybase_min_client_severity()Sybase
mssql_min_error_severitysybase_min_error_severity()Sybase
mssql_min_message_severitysybase_min_message_severity()Sybase
mssql_min_server_severitysybase_min_server_severity()Sybase
mssql_num_fieldssybase_num_fields()Sybase
mssql_num_fieldssybase_num_fields()Sybase
mssql_num_rowssybase_num_rows()Sybase
mssql_num_rowssybase_num_rows()Sybase
mssql_pconnectsybase_pconnect()Sybase
mssql_pconnectsybase_pconnect()Sybase
mssql_querysybase_query()Sybase
mssql_querysybase_query()Sybase
mssql_resultsybase_result()Sybase
mssql_resultsybase_result()Sybase
mssql_select_dbsybase_select_db()Sybase
mssql_select_dbsybase_select_db()Sybase
multcolorswfdisplayitem_multColor()Ming (flash)
mysqlmysql_db_query()MySQL
mysql_createdbmysql_create_db()MySQL
mysql_db_namemysql_result()MySQL
mysql_dbnamemysql_result()MySQL
mysql_dropdbmysql_drop_db()MySQL
mysql_fieldflagsmysql_field_flags()MySQL
mysql_fieldlenmysql_field_len()MySQL
mysql_fieldnamemysql_field_name()MySQL
mysql_fieldtablemysql_field_table()MySQL
mysql_fieldtypemysql_field_type()MySQL
mysql_freeresultmysql_free_result()MySQL
mysql_listdbsmysql_list_dbs()MySQL
mysql_listfieldsmysql_list_fields()MySQL
mysql_listtablesmysql_list_tables()MySQL
mysql_numfieldsmysql_num_fields()MySQL
mysql_numrowsmysql_num_rows()MySQL
mysql_selectdbmysql_select_db()MySQL
mysql_tablenamemysql_result()MySQL
namedomxml_attrname()DOM XML
new_childdomxml_new_child()DOM XML
new_xmldocdomxml_new_xmldoc()DOM XML
nextframeswfmovie_nextFrame()Ming (flash)
nextframeswfsprite_nextFrame()Ming (flash)
nodedomxml_node()DOM XML
oci8appendocicollappend()OCI8
oci8assignocicollassign()OCI8
oci8assignelemocicollassignelem()OCI8
oci8closeocicloselob()OCI8
oci8freeocifreecoll()OCI8
oci8freeocifreedesc()OCI8
oci8getelemocicollgetelem()OCI8
oci8loadociloadlob()OCI8
oci8maxocicollmax()OCI8
oci8ocifreecursorocifreestatement()OCI8
oci8saveocisavelob()OCI8
oci8savefileocisavelobfile()OCI8
oci8sizeocicollsize()OCI8
oci8trimocicolltrim()OCI8
oci8writetemporaryociwritetemporarylob()OCI8
oci8writetofileociwritelobtofile()OCI8
odbc_doodbc_exec()OCI8
odbc_field_precisionodbc_field_len()OCI8
outputswfmovie_output()Ming (flash)
parentdomxml_parent()DOM XML
pdf_add_outlinepdf_add_bookmark()PDF
pg_clientencodingpg_client_encoding()PostgreSQL
pg_setclientencodingpg_set_client_encoding()PostgreSQL
poscurrent()Beépített
recoderecode_string()Recode
removeswfmovie_remove()Ming (flash)
removeswfsprite_remove()Ming (flash)
rewindrewinddir()Beépített
rootdomxml_root()DOM XML
rotateswfdisplayitem_rotate()Ming (flash)
rotatetoswfdisplayitem_rotateTo()Ming (flash)
rotatetoswffill_rotateTo()Ming (flash)
saveswfmovie_save()Ming (flash)
savetofileswfmovie_saveToFile()Ming (flash)
scaleswfdisplayitem_scale()Ming (flash)
scaletoswfdisplayitem_scaleTo()Ming (flash)
scaletoswffill_scaleTo()Ming (flash)
set_attributedomxml_set_attribute()DOM XML
set_contentdomxml_set_content()DOM XML
setactionswfbutton_setAction()Ming (flash)
setattrdomxml_set_attribute()DOM XML
setbackgroundswfmovie_setBackground()Ming (flash)
setboundsswftextfield_setBounds()Ming (flash)
setcolorswftext_setColor()Ming (flash)
setcolorswftextfield_setColor()Ming (flash)
setdepthswfdisplayitem_setDepth()Ming (flash)
setdimensionswfmovie_setDimension()Ming (flash)
setdownswfbutton_setDown()Ming (flash)
setfontswftext_setFont()Ming (flash)
setfontswftextfield_setFont()Ming (flash)
setframesswfmovie_setFrames()Ming (flash)
setframesswfsprite_setFrames()Ming (flash)
setheightswftext_setHeight()Ming (flash)
setheightswftextfield_setHeight()Ming (flash)
sethitswfbutton_setHit()Ming (flash)
setindentationswftextfield_setIndentation()Ming (flash)
setleftfillswfshape_setleftfill()Ming (flash)
setleftmarginswftextfield_setLeftMargin()Ming (flash)
setlineswfshape_setline()Ming (flash)
setlinespacingswftextfield_setLineSpacing()Ming (flash)
setmarginsswftextfield_setMargins()Ming (flash)
setmatrixswfdisplayitem_setMatrix()Ming (flash)
setnameswfdisplayitem_setName()Ming (flash)
setnameswftextfield_setName()Ming (flash)
setoverswfbutton_setOver()Ming (flash)
setrateswfmovie_setRate()Ming (flash)
setratioswfdisplayitem_setRatio()Ming (flash)
setrightfillswfshape_setrightfill()Ming (flash)
setrightmarginswftextfield_setRightMargin()Ming (flash)
setspacingswftext_setSpacing()Ming (flash)
setupswfbutton_setUp()Ming (flash)
show_sourcehighlight_file ()Beépített
sizeofcount()Beépített
skewxswfdisplayitem_skewX()Ming (flash)
skewxtoswfdisplayitem_skewXTo()Ming (flash)
skewxtoswffill_skewXTo()Ming (flash)
skewyswfdisplayitem_skewY()Ming (flash)
skewytoswfdisplayitem_skewYTo()Ming (flash)
skewytoswffill_skewYTo()Ming (flash)
snmpwalkoidsnmprealwalk()SNMP
strchrstrstr()Beépített
streammp3swfmovie_streamMp3()Ming (flash)
swfactionswfaction_init()Ming (flash)
swfbitmapswfbitmap_init()Ming (flash)
swfbuttonswfbutton_init()Ming (flash)
swffillswffill_init()Ming (flash)
swffontswffont_init()Ming (flash)
swfgradientswfgradient_init()Ming (flash)
swfmorphswfmorph_init()Ming (flash)
swfmovieswfmovie_init()Ming (flash)
swfshapeswfshape_init()Ming (flash)
swfspriteswfsprite_init()Ming (flash)
swftextswftext_init()Ming (flash)
swftextfieldswftextfield_init()Ming (flash)
unlinkdomxml_unlink_node()DOM XML
xptr_new_contextxpath_new_context()DOM XML


H. Függelék. List of Reserved Words

The following is a listing of predefined identifiers in PHP. None of the identifiers listed here should be used as identifiers in a your scripts. These lists include keywords and predefined variable, constant, and class names. These lists are neither exhaustive or complete.


List of Keywords

These words have special meaning in PHP. Some of them represent things which look like functions, some look like constants, and so on--but they're not, really: they are language constructs. You cannot use any of the following words as constants, class names, or function names. Using them as variable names is generally OK, but could lead to confusion.


Predefined Variables

Since PHP 4.1.0, the preferred method for retrieving external variables is with the superglobals mentioned below. Before this time, people relied on either register_globals or the long predefined PHP arrays ($HTTP_*_VARS). As of PHP 5.0.0, the long PHP predefined variable arrays may be disabled with the register_long_arrays directive.


Server variables: $_SERVER

Megjegyzés: Introduced in 4.1.0. In earlier versions, use $HTTP_SERVER_VARS.

$_SERVER is an array containing information such as headers, paths, and script locations. The entries in this array are created by the webserver. There is no guarantee that every webserver 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.

This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. You don't need to do a global $_SERVER; to access it within functions or methods, as you do with $HTTP_SERVER_VARS.

$HTTP_SERVER_VARS contains the same initial information, but is not an autoglobal. (Note that $HTTP_SERVER_VARS and $_SERVER are different variables and that PHP handles them as such)

If the register_globals directive is set, then these variables will also be made available in the global scope of the script; i.e., separate from the $_SERVER and $HTTP_SERVER_VARS arrays. For related information, see the security chapter titled Using Register Globals. These individual globals are not autoglobals.

You may or may not find any of the following elements in $_SERVER. Note that few, if any, of these will be available (or indeed have any meaning) if running PHP on the command line.

'PHP_SELF'

The filename of the currently executing script, relative to the document root. For instance, $_SERVER['PHP_SELF'] in a script at the address http://example.com/test.php/foo.bar would be /test.php/foo.bar.

If PHP is running as a command-line processor, this variable is 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_NAME'

The name of the server host under which the current script is executing. If the script is running on a virtual host, this will be the value defined for that virtual host.

'SERVER_SOFTWARE'

Server identification string, given in the headers when responding to requests.

'SERVER_PROTOCOL'

Name and revision of the information protocol via which the page was requested; i.e. 'HTTP/1.0';

'REQUEST_METHOD'

Which request method was used to access the page; i.e. 'GET', 'HEAD', 'POST', 'PUT'.

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

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

Megjegyzés: Your web server must be configured to create this variable. For example in Apache you'll need HostnameLookups On inside httpd.conf for it to exist. See also gethostbyaddr().

'REMOTE_PORT'

The port being used on the user's machine to communicate with the web server.

'SCRIPT_FILENAME'

The absolute pathname of the currently executing script.

Megjegyzés: If a script is executed with the CLI, as a relative path, such as file.php or ../file.php, $_SERVER['SCRIPT_FILENAME'] will contain the relative path specified by the user.

'SERVER_ADMIN'

The value given to the SERVER_ADMIN (for Apache) directive in the web server configuration file. If the script is running on a virtual host, this will be the value defined for that virtual host.

'SERVER_PORT'

The port on the server machine being used by the web server for communication. For default setups, this will be '80'; using SSL, for instance, will change this to whatever your defined secure HTTP port is.

'SERVER_SIGNATURE'

String containing the server version and virtual host name which are added to server-generated pages, if enabled.

'PATH_TRANSLATED'

Filesystem- (not document root-) based path to the current script, after the server has done any virtual-to-real mapping.

'SCRIPT_NAME'

Contains the current script's path. This is useful for pages which need to point to themselves.

'REQUEST_URI'

The URI which was given in order to access this page; for instance, '/index.html'.

'PHP_AUTH_USER'

When running under Apache as module doing HTTP authentication this variable is set to the username provided by the user.

'PHP_AUTH_PW'

When running under Apache as module doing HTTP authentication this variable is set to the password provided by the user.

'AUTH_TYPE'

When running under Apache as module doing HTTP authenticated this variable is set to the authentication type.


Environment variables: $_ENV

Megjegyzés: Introduced in 4.1.0. In earlier versions, use $HTTP_ENV_VARS.

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.

This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. You don't need to do a global $_ENV; to access it within functions or methods, as you do with $HTTP_ENV_VARS.

$HTTP_ENV_VARS contains the same initial information, but is not an autoglobal. (Note that HTTP_ENV_VARS and $_ENV are different variables and that PHP handles them as such)

If the register_globals directive is set, then these variables will also be made available in the global scope of the script; i.e., separate from the $_ENV and $HTTP_ENV_VARS arrays. For related information, see the security chapter titled Using Register Globals. These individual globals are not autoglobals.


HTTP Cookies: $_COOKIE

Megjegyzés: Introduced in 4.1.0. In earlier versions, use $HTTP_COOKIE_VARS.

An associative array of variables passed to the current script via HTTP cookies. Automatically global in any scope.

This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. You don't need to do a global $_COOKIE; to access it within functions or methods, as you do with $HTTP_COOKIE_VARS.

$HTTP_COOKIE_VARS contains the same initial information, but is not an autoglobal. (Note that HTTP_COOKIE_VARS and $_COOKIE are different variables and that PHP handles them as such)

If the register_globals directive is set, then these variables will also be made available in the global scope of the script; i.e., separate from the $_COOKIE and $HTTP_COOKIE_VARS arrays. For related information, see the security chapter titled Using Register Globals. These individual globals are not autoglobals.


HTTP GET variables: $_GET

Megjegyzés: Introduced in 4.1.0. In earlier versions, use $HTTP_GET_VARS.

An associative array of variables passed to the current script via the HTTP GET method. Automatically global in any scope.

This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. You don't need to do a global $_GET; to access it within functions or methods, as you do with $HTTP_GET_VARS.

$HTTP_GET_VARS contains the same initial information, but is not an autoglobal. (Note that HTTP_GET_VARS and $_GET are different variables and that PHP handles them as such)

If the register_globals directive is set, then these variables will also be made available in the global scope of the script; i.e., separate from the $_GET and $HTTP_GET_VARS arrays. For related information, see the security chapter titled Using Register Globals. These individual globals are not autoglobals.


HTTP POST variables: $_POST

Megjegyzés: Introduced in 4.1.0. In earlier versions, use $HTTP_POST_VARS.

An associative array of variables passed to the current script via the HTTP POST method. Automatically global in any scope.

This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. You don't need to do a global $_POST; to access it within functions or methods, as you do with $HTTP_POST_VARS.

$HTTP_POST_VARS contains the same initial information, but is not an autoglobal. (Note that HTTP_POST_VARS and $_POST are different variables and that PHP handles them as such)

If the register_globals directive is set, then these variables will also be made available in the global scope of the script; i.e., separate from the $_POST and $HTTP_POST_VARS arrays. For related information, see the security chapter titled Using Register Globals. These individual globals are not autoglobals.


HTTP File upload variables: $_FILES

Megjegyzés: Introduced in 4.1.0. In earlier versions, use $HTTP_POST_FILES.

An associative array of items uploaded to the current script via the HTTP POST method. Automatically global in any scope.

This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. You don't need to do a global $_FILES; to access it within functions or methods, as you do with $HTTP_POST_FILES.

$HTTP_POST_FILES contains the same information, but is not an autoglobal.

If the register_globals directive is set, then these variables will also be made available in the global scope of the script; i.e., separate from the $_FILES and $HTTP_POST_FILES arrays. For related information, see the security chapter titled Using Register Globals. These individual globals are not autoglobals.


Request variables: $_REQUEST

Megjegyzés: Introduced in 4.1.0. There is no equivalent array in earlier versions.

Megjegyzés: Prior to PHP 4.3.0, $_FILES information was also included into $_REQUEST.

An associative array consisting of the contents of $_GET, $_POST, and $_COOKIE.

This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. You don't need to do a global $_REQUEST; to access it within functions or methods.

If the register_globals directive is set, then these variables will also be made available in the global scope of the script; i.e., separate from the $_REQUEST array. For related information, see the security chapter titled Using Register Globals. These individual globals are not autoglobals.


Session variables: $_SESSION

Megjegyzés: Introduced in 4.1.0. In earlier versions, use $HTTP_SESSION_VARS.

An associative array containing session variables available to the current script. See the Session functions documentation for more information on how this is used.

This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. You don't need to do a global $_SESSION; to access it within functions or methods, as you do with $HTTP_SESSION_VARS.

$HTTP_SESSION_VARS contains the same information, but is not an autoglobal.

If the register_globals directive is set, then these variables will also be made available in the global scope of the script; i.e., separate from the $_SESSION and $HTTP_SESSION_VARS arrays. For related information, see the security chapter titled Using Register Globals. These individual globals are not autoglobals.


Global variables: $GLOBALS

Megjegyzés: $GLOBALS has been available since PHP 3.0.0.

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.

This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. You don't need to do a global $GLOBALS; to access it within functions or methods.


The previous error message: $php_errormsg

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


Predefined Classes

Standard Defined Classes

These classes are defined in the standard set of functions included in the PHP build.

Directory

The class from which dir is instantiated.

stdClass

__PHP_Incomplete_Class


Predefined classes as of PHP 5

These additional predefined classes were introduced in PHP 5.0.0

exception

php_user_filter


Ming Defined Classes

These classes are defined in the Ming extension, and will only be available when that extension has either been compiled into PHP or dynamically loaded at runtime.

swfshape

swffill

swfgradient

swfbitmap

swftext

swftextfield

swffont

swfdisplayitem

swfmovie

swfbutton

swfaction

swfmorph

swfsprite


Oracle 8 Defined Classes

These classes are defined in the Oracle 8 extension, and will only be available when that extension has either been compiled into PHP or dynamically loaded at runtime.

OCI-Lob

OCI-Collection


qtdom Defined Classes

These classes are defined in the qtdom extension, and will only be available when that extension has either been compiled into PHP or dynamically loaded at runtime.

QDomDocument

QDomNode


Előre definiált konstansok

Tartalom
Core Predefined Constants -- Constants defined in the PHP core, Zend, and SAPI modules
Standard Predefined Constants -- Constants defined in PHP by default

Core Predefined Constants

Core Predefined Constants -- Constants defined in the PHP core, Zend, and SAPI modules

Description

These constants are defined by the PHP core. This includes PHP, the Zend engine, and SAPI modules.

PHP_VERSION (string)

PHP_OS (string)

DEFAULT_INCLUDE_PATH (string)

PEAR_INSTALL_DIR (string)

PEAR_EXTENSION_DIR (string)

PHP_EXTENSION_DIR (string)

PHP_BINDIR (string)

PHP_LIBDIR (string)

PHP_DATADIR (string)

PHP_SYSCONFDIR (string)

PHP_LOCALSTATEDIR (string)

PHP_CONFIG_FILE_PATH (string)

PHP_OUTPUT_HANDLER_START (integer)

PHP_OUTPUT_HANDLER_CONT (integer)

PHP_OUTPUT_HANDLER_END (integer)

E_ERROR (integer)

E_WARNING (integer)

E_PARSE (integer)

E_NOTICE (integer)

E_CORE_ERROR (integer)

E_CORE_WARNING (integer)

E_COMPILE_ERROR (integer)

E_COMPILE_WARNING (integer)

E_USER_ERROR (integer)

E_USER_WARNING (integer)

E_USER_NOTICE (integer)

E_ALL (integer)

Standard Predefined Constants

Standard Predefined Constants -- Constants defined in PHP by default

Description

These constants are defined in PHP by default.

EXTR_OVERWRITE (integer)

EXTR_SKIP (integer)

EXTR_PREFIX_SAME (integer)

EXTR_PREFIX_ALL (integer)

EXTR_PREFIX_INVALID (integer)

EXTR_PREFIX_IF_EXISTS (integer)

EXTR_IF_EXISTS (integer)

SORT_ASC (integer)

SORT_DESC (integer)

SORT_REGULAR (integer)

SORT_NUMERIC (integer)

SORT_STRING (integer)

CASE_LOWER (integer)

CASE_UPPER (integer)

COUNT_NORMAL (integer)

COUNT_RECURSIVE (integer)

ASSERT_ACTIVE (integer)

ASSERT_CALLBACK (integer)

ASSERT_BAIL (integer)

ASSERT_WARNING (integer)

ASSERT_QUIET_EVAL (integer)

CONNECTION_ABORTED (integer)

CONNECTION_NORMAL (integer)

CONNECTION_TIMEOUT (integer)

INI_USER (integer)

INI_PERDIR (integer)

INI_SYSTEM (integer)

INI_ALL (integer)

M_E (float)

M_LOG2E (float)

M_LOG10E (float)

M_LN2 (float)

M_LN10 (float)

M_PI (float)

M_PI_2 (float)

M_PI_4 (float)

M_1_PI (float)

M_2_PI (float)

M_2_SQRTPI (float)

M_SQRT2 (float)

M_SQRT1_2 (float)

CRYPT_SALT_LENGTH (integer)

CRYPT_STD_DES (integer)

CRYPT_EXT_DES (integer)

CRYPT_MD5 (integer)

CRYPT_BLOWFISH (integer)

DIRECTORY_SEPARATOR (string)

SEEK_SET (integer)

SEEK_CUR (integer)

SEEK_END (integer)

LOCK_SH (integer)

LOCK_EX (integer)

LOCK_UN (integer)

LOCK_NB (integer)

HTML_SPECIALCHARS (integer)

HTML_ENTITIES (integer)

ENT_COMPAT (integer)

ENT_QUOTES (integer)

ENT_NOQUOTES (integer)

INFO_GENERAL (integer)

INFO_CREDITS (integer)

INFO_CONFIGURATION (integer)

INFO_MODULES (integer)

INFO_ENVIRONMENT (integer)

INFO_VARIABLES (integer)

INFO_LICENSE (integer)

INFO_ALL (integer)

CREDITS_GROUP (integer)

CREDITS_GENERAL (integer)

CREDITS_SAPI (integer)

CREDITS_MODULES (integer)

CREDITS_DOCS (integer)

CREDITS_FULLPAGE (integer)

CREDITS_QA (integer)

CREDITS_ALL (integer)

STR_PAD_LEFT (integer)

STR_PAD_RIGHT (integer)

STR_PAD_BOTH (integer)

PATHINFO_DIRNAME (integer)

PATHINFO_BASENAME (integer)

PATHINFO_EXTENSION (integer)

CHAR_MAX (integer)

LC_CTYPE (integer)

LC_NUMERIC (integer)

LC_TIME (integer)

LC_COLLATE (integer)

LC_MONETARY (integer)

LC_ALL (integer)

LC_MESSAGES (integer)

ABDAY_1 (integer)

ABDAY_2 (integer)

ABDAY_3 (integer)

ABDAY_4 (integer)

ABDAY_5 (integer)

ABDAY_6 (integer)

ABDAY_7 (integer)

DAY_1 (integer)

DAY_2 (integer)

DAY_3 (integer)

DAY_4 (integer)

DAY_5 (integer)

DAY_6 (integer)

DAY_7 (integer)

ABMON_1 (integer)

ABMON_2 (integer)

ABMON_3 (integer)

ABMON_4 (integer)

ABMON_5 (integer)

ABMON_6 (integer)

ABMON_7 (integer)

ABMON_8 (integer)

ABMON_9 (integer)

ABMON_10 (integer)

ABMON_11 (integer)

ABMON_12 (integer)

MON_1 (integer)

MON_2 (integer)

MON_3 (integer)

MON_4 (integer)

MON_5 (integer)

MON_6 (integer)

MON_7 (integer)

MON_8 (integer)

MON_9 (integer)

MON_10 (integer)

MON_11 (integer)

MON_12 (integer)

AM_STR (integer)

PM_STR (integer)

D_T_FMT (integer)

D_FMT (integer)

T_FMT (integer)

T_FMT_AMPM (integer)

ERA (integer)

ERA_YEAR (integer)

ERA_D_T_FMT (integer)

ERA_D_FMT (integer)

ERA_T_FMT (integer)

ALT_DIGITS (integer)

INT_CURR_SYMBOL (integer)

CURRENCY_SYMBOL (integer)

CRNCYSTR (integer)

MON_DECIMAL_POINT (integer)

MON_THOUSANDS_SEP (integer)

MON_GROUPING (integer)

POSITIVE_SIGN (integer)

NEGATIVE_SIGN (integer)

INT_FRAC_DIGITS (integer)

FRAC_DIGITS (integer)

P_CS_PRECEDES (integer)

P_SEP_BY_SPACE (integer)

N_CS_PRECEDES (integer)

N_SEP_BY_SPACE (integer)

P_SIGN_POSN (integer)

N_SIGN_POSN (integer)

DECIMAL_POINT (integer)

RADIXCHAR (integer)

THOUSANDS_SEP (integer)

THOUSEP (integer)

GROUPING (integer)

YESEXPR (integer)

NOEXPR (integer)

YESSTR (integer)

NOSTR (integer)

CODESET (integer)

LOG_EMERG (integer)

LOG_ALERT (integer)

LOG_CRIT (integer)

LOG_ERR (integer)

LOG_WARNING (integer)

LOG_NOTICE (integer)

LOG_INFO (integer)

LOG_DEBUG (integer)

LOG_KERN (integer)

LOG_USER (integer)

LOG_MAIL (integer)

LOG_DAEMON (integer)

LOG_AUTH (integer)

LOG_SYSLOG (integer)

LOG_LPR (integer)

LOG_NEWS (integer)

LOG_UUCP (integer)

LOG_CRON (integer)

LOG_AUTHPRIV (integer)

LOG_LOCAL0 (integer)

LOG_LOCAL1 (integer)

LOG_LOCAL2 (integer)

LOG_LOCAL3 (integer)

LOG_LOCAL4 (integer)

LOG_LOCAL5 (integer)

LOG_LOCAL6 (integer)

LOG_LOCAL7 (integer)

LOG_PID (integer)

LOG_CONS (integer)

LOG_ODELAY (integer)

LOG_NDELAY (integer)

LOG_NOWAIT (integer)

LOG_PERROR (integer)


I. Függelék. Erőforrás típusok listája

Az alábbiakban PHP erőforrásokat előállító, használó és megszüntető függvények neveinek listája látható. Az is_resource() függvény használható az erőforrás típusok ellenőrzésére. A get_resource_type() adja vissza, hogy pontosan milyen típusú az adott erőforrás.

Táblázat I-1. Erőforrás típusok

Erőforrás típus neveLéterhozzaHasználjaMegszüntetiLeírás
aspell aspell_new() aspell_check(), aspell_check_raw(), aspell_suggest() Nincs Aspell szótár
bzip2 bzopen() bzerrno(), bzerror(), bzerrstr(), bzflush(), bzread(), bzwrite() bzclose() Bzip2 állomány
COM com_load() com_invoke(), com_propget(), com_get(), com_propput(), com_set(), com_propput() Nincs COM objektum referencia
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() PDF dokumentum a CPDF függvényekkel
cpdf outline    
curl curl_init() curl_init(), curl_exec() curl_close() Curl session
dbm dbmopen() dbmexists(), dbmfetch(), dbminsert(), dbmreplace(), dbmdelete(), dbmfirstkey(), dbmnextkey() dbmclose() DBM adatbázis kapcsolat
dba dba_open() dba_delete(), dba_exists(), dba_fetch(), dba_firstkey(), dba_insert(), dba_nextkey(), dba_optimize(), dba_replace(), dba_sync() dba_close() DBA adatbázis kapcsolat
dba persistent dba_popen() dba_delete(), dba_exists(), dba_fetch(), dba_firstkey(), dba_insert(), dba_nextkey(), dba_optimize(), dba_replace(), dba_sync() Nincs Állandó DBA adatbázis kapcsolat
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() Dbase adatbázis kapcsolat
dbx_link_object dbx_connect() dbx_query() dbx_close() dbx kapcsolat
dbx_result_object dbx_query()   Nincs dbx eredmény
domxml attribute    
domxml document    
domxml node    
xpath context    
xpath object    
fbsql database fbsql_select_db()   Nincs fbsql adatbázis
fbsql link fbsql_change_user(), fbsql_connect() 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() fbsql_close() fbsql adatbázis kapcsolat
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() Nincs Állandó fbsql adatbázis kapcsolat
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() fbsql eredmény
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() FDF állomány
ftp ftp_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_quit() FTP stream
gd imagecreate(), imagecreatefromgif(), imagecreatefromjpeg(), imagecreatefrompng(), imagecreatefromwbmp(), imagecreatefromstring(), imagecreatetruecolor() 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(), imagesetpixel(), imagestring(), imagestringup(), imagesx(), imagesy(), imagettftext(), imagefilledarc(), imageellipse(), imagefilledellipse(), imagecolorclosestalpha(), imagecolorexactalpha(), imagecolorresolvealpha(), imagecopymerge(), imagecopymergegray(), imagecopyresampled(), imagetruecolortopalette(), imagesetbrush(), imagesettile(), imagesetthickness() imagedestroy() GD kép
gd font imageloadfont() imagechar(), imagecharup(), imagefontheight() Nincs GD betűtípus
gd PS encoding    
gd PS font imagepsloadfont() imagepstext(), imagepsslantfont(), imagepsextendfont(), imagepsencodefont(), imagepsbbox() imagepsfreefont() GD PS betűtípus
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() Nincs GMP szám
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() Hyperwave objektum
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() Hyperwave szerver kapcsolat
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() Nincs Állandó Hyperwave szerver kapcsolat
icap icap_open() icap_fetch_event(), icap_list_events(), icap_store_event(), icap_snooze(), icap_list_alarms(), icap_delete_event() icap_close() icap szerver kapcsolat
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() IMAP, POP3 szerver kapcsolat
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() ingresII adatbázis kapcsolat
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() Nincs Állandó ingresII adatbázis kapcsolat
interbase blob    
interbase link ibase_connect() ibase_query(), ibase_prepare(), ibase_trans() ibase_close() Interbase adatbázis kapcsolat
interbase link persistent ibase_pconnect() ibase_query(), ibase_prepare(), ibase_trans() Nincs Állandó Interbase adatbázis kapcsolat
interbase query ibase_prepare() ibase_execute() ibase_free_query() Interbase lekérdezés
interbase result ibase_query() ibase_fetch_row(), ibase_fetch_object(), ibase_field_info(), ibase_num_fields() ibase_free_result() Interbase eredmény
interbase transaction ibase_trans() ibase_commit() ibase_rollback() Interbase tranzakció
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() ldap kapcsolat
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() ldap keresés eredménye
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() Naptár szerver kapcsolat
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() mSQL adatbázis kapcsolat
msql link persistent msql_pconnect() msql(), msql_create_db(), msql_createdb(), msql_drop_db(), msql_drop_db(), msql_select_db(), msql_select_db() Nincs Állandó mSQL adatbázis kapcsolat
msql query msql_query() msql(), msql_affected_rows(), msql_data_seek(), msql_dbname(), msql_fetch_array(), msql_fetch_field(), msql_fetch_object(), msql_fetch_row(), msql_fieldname(), msql_field_seek(), msql_fieldtable(), msql_fieldtype(), msql_fieldflags(), msql_fieldlen(), msql_num_fields(), msql_num_rows(), msql_numfields(), msql_numrows(), msql_result() msql_free_result(), msql_free_result() mSQL eredmény
mssql link mssql_connect() mssql_query(), mssql_select_db() mssql_close() Microsft SQL Server adatbázis kapcsolat
mssql link persistent mssql_pconnect() mssql_query(), mssql_select_db() Nincs Állandó Microsft SQL Server adatbázis kapcsolat
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() Microsft SQL Server eredmény
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() MySQL adatbázis kapcsolat
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() Nincs Állandó MySQL adatbázis kapcsolat
mysql result mysql_db_query(), mysql_list_dbs(), mysql_list_fields(), mysql_list_tables(), mysql_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() MySQL eredmény
oci8 collection    
oci8 connection ocilogon(), ociplogon(), ocinlogon() ocicommit(), ociserverversion(), ocinewcursor(), ociparse(), ocierror() ocilogoff() Oracle adatbázis kapcsolat
oci8 descriptor    
oci8 server    
oci8 session    
oci8 statement ocinewdescriptor() ocirollback(), ocinewdescriptor(), ocirowcount(), ocidefinebyname(), ocibindbyname(), ociexecute(), ocinumcols(), ociresult(), ocifetch(), ocifetchinto(), ocifetchstatement(), ocicolumnisnull(), ocicolumnname(), ocicolumnsize(), ocicolumntype(), ocistatementtype(), ocierror() ocifreestatement() Oracle Cursor
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() ODBC adatbázis kapcsolat
odbc link persistent 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() Nincs Állandó ODBC adatbázis kapcsolat
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() ODBC eredmény
birdstep link    
birdstep result    
OpenSSL key openssl_get_privatekey(), openssl_get_publickey() openssl_sign(), openssl_seal(), openssl_open(), openssl_verify() openssl_free_key() OpenSSL kulcs
OpenSSL X.509 openssl_x509_read() openssl_x509_parse(), openssl_x509_checkpurpose() openssl_x509_free() Nyilvános kulcs
oracle cursor ora_open() ora_bind(), ora_columnname(), ora_columnsize(), ora_columntype(), ora_error(), ora_errorcode(), ora_exec(), ora_fetch(), ora_fetch_into(), ora_getcolumn(), ora_numcols(), ora_numrows(), ora_parse() ora_close() Oracle Cursor
oracle link ora_logon() ora_do(), ora_error(), ora_errorcode(), ora_rollback(), ora_commitoff(), ora_commiton(), ora_open(), ora_commit() ora_logoff() oracle adatbázis kapcsolat
oracle link persistent ora_plogon() ora_do(), ora_error(), ora_errorcode(), ora_rollback(), ora_commitoff(), ora_commiton(), ora_open(), ora_commit() Nincs Állandó oracle adatbázis kapcsolat
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_open_memory_image() pdf_close(), pdf_delete() PDF dokumentum
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() Kép PDF állományban
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() PostGreSQL adatbázis kapcsolat
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() Nincs Állandó PostGreSQL adatbázis kapcsolat
pgsql result pg_query(), 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() PostgreSQL eredmény
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() Nincs pspell szótár
pspell config pspell_config_create() pspell_new_config() Nincs pspell configuration
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() XSLT elemző
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() Foglalat
sockets i/o vector    
dir dir() readdir(), rewinddir() closedir() Könytvár kezelő
file fopen() feof(), fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), flock(), fpassthru(), fputs(), fwrite(), fread(), fseek(), ftell(), fstat(), ftruncate(), set_file_buffer(), rewind() fclose() Állomány kezelő
pipe popen() feof(), fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), fpassthru(), fputs(), fwrite(), fread() pclose() Processz kezelő
socket fsockopen() fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), fpassthru(), fputs(), fwrite(), fread() fclose() Foglalat kezelő
stream    
sybase-db link sybase_connect() sybase_query(), sybase_select_db() sybase_close() Sybase adatbázis kapcsolat a DB könyvtárral
sybase-db link persistent sybase_pconnect() sybase_query(), sybase_select_db() Nincs Állandó Sybase adatbázis kapcsolat a DB könyvtárral
sybase-db 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() Sybase eredmény a DB könyvtárral
sybase-ct link sybase_connect() sybase_affected_rows(), sybase_query(), sybase_select_db() sybase_close() Sybase adatbázis kapcsolat a CT könyvtárral
sybase-ct link persistent sybase_pconnect() sybase_affected_rows(), sybase_query(), sybase_select_db() Nincs Állandó Sybase adatbázis kapcsolat a CT könyvtárral
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() Sybase eredmény a CT könyvtárral
sysvsem sem_get() sem_acquire() sem_release() System V szemafor
sysvshm shm_attach() shm_remove(), shm_put_var(), shm_get_var(), shm_remove_var() shm_detach() System V megosztott memória
wddx wddx_packet_start() wddx_add_vars() wddx_packet_end() WDDX csomag
xml xml_parser_create() 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() XML elemző
zlib gzopen() gzeof(), gzgetc(), gzgets(), gzgetss(), gzpassthru(), gzputs(), gzread(), gzrewind(), gzseek(), gztell(), gzwrite() gzclose() gz-tömörített file


J. Függelék. List of Supported Protocols/Wrappers

The following is a list of the various URL style protocols that PHP has built-in for use with the filesystem functions such as fopen() and copy(). In addition to these wrappers, as of PHP 4.3.0, you can write your own wrappers using PHP script and stream_wrapper_register().


Filesystem

All versions of PHP. Explicitly using file:// since PHP 4.3.0

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

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

Táblázat J-1. Wrapper Summary

AttributeSupported
Restricted by allow_url_fopen.No
Allows ReadingYes
Allows WritingYes
Allows AppendingYes
Allows Simultaneous Reading and WritingYes
Supports stat()Yes
Supports unlink()Yes
Supports rename()Yes
Supports mkdir()Yes
Supports rmdir()Yes


HTTP and HTTPS

PHP 3, PHP 4. https:// since PHP 4.3.0

  • http://example.com

  • http://user:password@example.com

  • https://example.com

  • https://user:password@example.com

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 ini file or the stream context, it will also be included in the request.

Redirects have been supported since PHP 4.0.5; if you are using an earlier version you will need to include trailing slashes in your URLs. 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.

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

$fp = fopen($url, 'r');

/* Prior to PHP 4.3.0 use $http_response_header 
   instead of stream_get_meta_data() */
foreach(stream_get_meta_data($fp) as $response) {

  /* Were we redirected? */
  if (substr(strtolower($response), 0, 10) == 'location: ') {
    /* update $url with where we were redirected to */
    $url = substr($response, 10);
  }

}

?>

The stream allows access to the body of the resource; the headers are stored in the $http_response_header variable. Since PHP 4.3.0, the headers are available using stream_get_meta_data().

HTTP connections are read-only; you cannot write data or copy files to an HTTP resource.

Megjegyzés: HTTPS is supported starting from PHP 4.3.0, if you have compiled in support for OpenSSL.

Táblázat J-2. Wrapper Summary

AttributeSupported
Restricted by allow_url_fopen.Yes
Allows ReadingYes
Allows WritingNo
Allows AppendingNo
Allows Simultaneous Reading and WritingN/A
Supports stat()No
Supports unlink()No
Supports rename()No
Supports mkdir()No
Supports rmdir()No

Táblázat J-3. Context options (as of PHP 5.0.0)

NameUsageDefault
method GET, POST, or any other HTTP method supported by the remote server. GET
headerAdditional headers to be sent during request. Values in this option will override other values (such as User-agent:, Host:, and Authentication:).  
user_agentValue to send with User-Agent: header. This value will only be used if user-agent is not specified in the header context option above. php.ini setting: user_agent
content Additional data to be sent after the headers. Typically used with POST or PUT requests.  
proxy URI specifying address of proxy server. (e.g. tcp://proxy.example.com:5100 ).  
request_fulluri 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. FALSE

Underlying socket stream context options: Additional context options may be supported by the underlying transport For http:// streams, refer to context options for the tcp:// transport. For https:// streams, refer to context options for the ssl:// transport.


FTP and FTPS

PHP 3, PHP 4. ftps:// since PHP 4.3.0

  • 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

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.

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.

ftps:// was introduced in PHP 4.3.0. It is the same as ftp://, but attempts to negotiate a secure connection with the ftp server. If the server does not support SSL, then the connection falls back to regular unencrypted ftp.

Megjegyzés: FTPS is supported starting from PHP 4.3.0, if you have compiled in support for OpenSSL.

Táblázat J-4. Wrapper Summary

AttributePHP 4PHP 5
Restricted by allow_url_fopen.YesYes
Allows ReadingYesYes
Allows WritingYes (new files only)Yes (new files/existing files with overwrite)
Allows AppendingNoYes
Allows Simultaneous Reading and WritingNoNo
Supports stat()No filesize(), filetype(), file_exists(), is_file(), and is_dir() elements only.
Supports unlink()NoYes
Supports rename()NoYes
Supports mkdir()NoYes
Supports rmdir()NoYes

Táblázat J-5. Context options (as of PHP 5.0.0)

NameUsageDefault
overwrite Allow overwriting of already existing files on remote server. Applies to write mode (uploading) only. FALSE (Disabled)
resume_pos File offset at which to begin transfer. Applies to read mode (downloading) only. 0 (Beginning of File)

Underlying socket stream context options: Additional context options may be supported by the underlying transport For ftp:// streams, refer to context options for the tcp:// transport. For ftps:// streams, refer to context options for the ssl:// transport.


PHP input/output streams

PHP 3.0.13 and up, php://output and php://input since PHP 4.3.0, php://filter since PHP 5.0.0

  • php://stdin

  • php://stdout

  • php://stderr

  • php://output

  • php://input

  • php://filter

php://stdin, php://stdout and php://stderr allow access to the corresponding input or output stream of the PHP process.

php://output allows you to write to the output buffer mechanism in the same way as print() and echo().

php://input allows you to read raw POST data. It is a less memory intensive alternative to $HTTP_RAW_POST_DATA and does not need any special php.ini directives.

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

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 parts of its 'path'.

  • /resource=<stream to be filtered> (required) 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");
    ?>

  • /read=<filter list to apply to read chain> (optional) 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");
    ?>

  • /write=<filter list to apply to write chain> (optional) 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_set_contents("php://filter/write=string.rot13/resource=example.txt","Hello World");
    ?>

  • /<filter list to apply to both chains> (optional) Any filter lists which are not prefixed specifically by read= or write= will be applied to both the read and write chains (as appropriate).

Táblázat J-6. Wrapper Summary (For php://filter, refer to summary of wrapper being filtered.)

AttributeSupported
Restricted by allow_url_fopen.No
Allows Reading php://stdin and php://input only.
Allows Writing php://stdout, php://stderr, and php://output only.
Allows Appending php://stdout, php://stderr, and php://output only. (Equivalent to writing)
Allows Simultaneous Reading and WritingNo. These wrappers are unidirectional.
Supports stat()No
Supports unlink()No
Supports rename()No
Supports mkdir()No
Supports rmdir()No


Compression Streams

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:

  • compress.zlib://

  • compress.bzip2://

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.

Táblázat J-7. Wrapper Summary

AttributeSupported
Restricted by allow_url_fopen.No
Allows ReadingYes
Allows WritingYes
Allows AppendingYes
Allows Simultaneous Reading and WritingNo
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


K. Függelék. List of Supported Socket Transports

The following is a list of the various URL style socket transports that PHP has built-in for use with the streams based socket functions such as fsockopen(), and stream_socket_client(). These transports do not apply to the Sockets Extension.

For a list of transports installed in your version of PHP use stream_get_transports().


Internet Domain: TCP, UDP, SSL, and TLS

PHP 3, PHP 4. ssl:// & tls:// since PHP 4.3

Megjegyzés: If no transport is specified, tcp:// will be assumed.

  • 127.0.0.1

  • fe80::1

  • www.example.com

  • tcp://127.0.0.1

  • tcp://fe80::1

  • tcp://www.example.com

  • udp://www.example.com

  • ssl://www.example.com

  • tls://www.example.com

Internet Domain sockets expect a port number in addition to a target address. In the case of fsockopen() this is specified in a second parameter and therefore does not impact the formatting of transport URL. With stream_socket_client() and related functions as with traditional URLs however, the port number is specified as a suffix of the transport URL delimited by a colon.

  • tcp://127.0.0.1:80

  • tcp://[fe80::1]:80

  • tcp://www.example.com:80

IPv6 numeric addresses with port numbers: In the second example above, while the IPv4 and hostname examples are left untouched apart from the addition of their colon and portnumber, the IPv6 address is wrapped in square brackets: [fe80::1]. This is to distinguish between the colons used in an IPv6 address and the colon used to delimit the portnumber.

The ssl:// and tls:// transports (available only when openssl support is compiled into PHP) are extensions of the tcp:// transport which includes SSL encryption. Since PHP 4.3.0 OpenSSL support must be statically compiled into PHP, since PHP 5.0.0 it may be compiled as a module or statically.

Táblázat K-1. Context options for ssl:// and tls:// transports (since PHP 4.3.2)

NameUsageDefault 
verify_peer TRUE or FALSE. Require verification of SSL certificate used. FALSE 
allow_self_signed TRUE or FALSE. Allow self-signed certificates. FALSE 
cafile 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 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 Path to local certificate file on filesystem. It must be a PEM encoded file which contains your certificate and private key. It can optionally contain the certificate chain of issuers.   
passphrase Passphrase with which your local_cert file was encoded.   
CN_match Common Name we are expecting. PHP will perform limited wildcard matching. If the Common Name does not match this, the connection attempt will fail.   

Megjegyzés: 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://.


Unix Domain: Unix and UDG

unix:// since PHP 3, udg:// since PHP 5

  • unix:///tmp/mysock

  • udg:///tmp/mysock

unix:// provides access to a socket stream connection in the Unix domain. udg:// provides an alternate transport to a Unix domain socket using the user datagram protocol.

Unix domain sockets, unlike Internet domain sockets, do not expect a port number. In the case of fsockopen() the portno parameter should be set to 0.


L. Függelék. PHP type comparison tables

The following tables demonstrate behaviors for PHP types and comparison operators, for both loose and strict comparisons. This supplemental is also related to the manual section on type juggling. Inspiration was provided by various user comments and by the work over at BlueShoes.

Before utilizing these tables, it's important to understand types and their meanings. For example, "42" is a string while 42 is an integer. FALSE is a boolean while "false" is a string.

Megjegyzés: HTML Forms do not pass integers, floats, or booleans, they pass strings. To find out of a string is numeric, you may use is_numeric().

Megjegyzés: Simply doing if ($x) while $x is undefined will generate an error of level E_NOTICE. Instead, consider using empty() or isset() and/or initialize your variables.

Táblázat L-1. Comparisons of $x with PHP functions

Expressiongettype()empty()is_null()isset()boolean : if($x)
$x = "";stringTRUEFALSETRUEFALSE
$x = NULLNULLTRUETRUEFALSEFALSE
var $x;NULLTRUETRUEFALSEFALSE
$x is undefinedNULLTRUETRUEFALSEFALSE
$x = array();arrayTRUEFALSETRUEFALSE
$x = false;booleanTRUEFALSETRUEFALSE
$x = true;booleanFALSEFALSETRUETRUE
$x = 1;integerFALSEFALSETRUETRUE
$x = 42;integerFALSEFALSETRUETRUE
$x = 0;integerTRUEFALSETRUEFALSE
$x = -1;integerFALSEFALSETRUETRUE
$x = "1";stringFALSEFALSETRUETRUE
$x = "0";stringTRUEFALSETRUEFALSE
$x = "-1";stringFALSEFALSETRUETRUE
$x = "php";stringFALSEFALSETRUETRUE
$x = "true";stringFALSEFALSETRUETRUE
$x = "false";stringFALSEFALSETRUETRUE

Táblázat L-2. Loose comparisons with ==

 TRUEFALSE10-1"1""0""-1"NULLarray()"php"
TRUETRUEFALSETRUEFALSETRUETRUEFALSETRUEFALSEFALSETRUE
FALSEFALSETRUEFALSETRUEFALSEFALSETRUEFALSETRUETRUEFALSE
1TRUEFALSETRUEFALSEFALSETRUEFALSEFALSEFALSEFALSEFALSE
0FALSETRUEFALSETRUEFALSEFALSETRUEFALSETRUEFALSETRUE
-1TRUEFALSEFALSEFALSETRUEFALSEFALSETRUEFALSEFALSEFALSE
"1"TRUEFALSETRUEFALSEFALSETRUEFALSEFALSEFALSEFALSEFALSE
"0"FALSETRUEFALSETRUEFALSEFALSETRUEFALSEFALSEFALSEFALSE
"-1"TRUEFALSEFALSEFALSETRUEFALSEFALSETRUEFALSEFALSEFALSE
NULLFALSETRUEFALSETRUEFALSEFALSEFALSEFALSETRUETRUEFALSE
array()FALSETRUEFALSEFALSEFALSEFALSEFALSEFALSEFALSETRUEFALSE
"php"TRUEFALSEFALSETRUEFALSEFALSEFALSEFALSEFALSEFALSETRUE

Táblázat L-3. Strict comparisons with ===

 TRUEFALSE10-1"1""0""-1"NULLarray()"php"
TRUETRUEFALSEFALSEFALSEFALSEFALSEFALSEFALSEFALSEFALSEFALSE
FALSEFALSETRUEFALSEFALSEFALSEFALSEFALSEFALSEFALSEFALSEFALSE
1FALSEFALSETRUEFALSEFALSEFALSEFALSEFALSEFALSEFALSEFALSE
0FALSEFALSEFALSETRUEFALSEFALSEFALSEFALSEFALSEFALSEFALSE
-1FALSEFALSEFALSEFALSETRUEFALSEFALSEFALSEFALSEFALSEFALSE
"1"FALSEFALSEFALSEFALSEFALSETRUEFALSEFALSEFALSEFALSEFALSE
"0"FALSEFALSEFALSEFALSEFALSEFALSETRUEFALSEFALSEFALSEFALSE
"-1"FALSEFALSEFALSEFALSEFALSEFALSEFALSETRUEFALSEFALSEFALSE
NULLFALSEFALSEFALSEFALSEFALSEFALSEFALSEFALSETRUEFALSEFALSE
array()FALSEFALSEFALSEFALSEFALSEFALSEFALSEFALSEFALSETRUEFALSE
"php"FALSEFALSEFALSEFALSEFALSEFALSEFALSEFALSEFALSEFALSETRUE

PHP 3.0 note: The string value "0" was considered non-empty in PHP 3, this behavior changed in PHP 4 where it's now seen as empty.


M. Függelék. List of Parser Tokens

Various parts of the PHP language are represented internally by types like T_SR. PHP outputs identifiers like this one in parse errors, like "Parse error: unexpected T_SR, expecting ',' or ';' in script.php on line 10."

You're supposed to know what T_SR means. For everybody who doesn't know that, here is a table with those identifiers, PHP-syntax and references to the appropriate places in the manual.

Táblázat M-1. Tokens

TokenSyntaxReference
T_AND_EQUAL&=assignment operators
T_ARRAYarray()array(), array syntax
T_ARRAY_CAST(array)type-casting
T_ASasforeach
T_BAD_CHARACTER anything below ASCII 32 except \t (0x09), \n (0x0a) and \r (0x0d)
T_BOOLEAN_AND&&logical operators
T_BOOLEAN_OR||logical operators
T_BOOL_CAST(bool) or (boolean)type-casting
T_BREAKbreakbreak
T_CASEcaseswitch
T_CHARACTER  
T_CLASSclassclasses and objects
T_CLOSE_TAG?> or %> 
T_COMMENT// or #comments
T_CONCAT_EQUAL.=assignment operators
T_CONSTconst 
T_CONSTANT_ENCAPSED_STRING"foo" or 'bar'string syntax
T_CONTINUEcontinue 
T_CURLY_OPEN  
T_DEC--incrementing/decrementing operators
T_DECLAREdeclaredeclare
T_DEFAULTdefaultswitch
T_DIV_EQUAL/=assignment operators
T_DNUMBER0.12, etcfloating point numbers
T_DOdodo..while
T_DOLLAR_OPEN_CURLY_BRACES${complex variable parsed syntax
T_DOUBLE_ARROW=>array syntax
T_DOUBLE_CAST(real), (double) or (float)type-casting
T_ECHOechoecho()
T_ELSEelseelse
T_ELSEIFelseifelseif
T_EMPTYemptyempty()
T_ENCAPSED_AND_WHITESPACE  
T_ENDDECLAREenddeclaredeclare, alternative syntax
T_ENDFORendforfor, alternative syntax
T_ENDFOREACHendforeachforeach, alternative syntax
T_ENDIFendifif, alternative syntax
T_ENDSWITCHendswitchswitch, alternative syntax
T_ENDWHILEendwhilewhile, alternative syntax
T_END_HEREDOC heredoc syntax
T_EVALeval()eval()
T_EXITexit or dieexit(), die()
T_EXTENDSextendsextends, classes and objects
T_FILE__FILE__constants
T_FORforfor
T_FOREACHforeachforeach
T_FUNCTIONfunction or cfunctionfunctions
T_GLOBALglobalvariable scope
T_IFifif
T_INC++incrementing/decrementing operators
T_INCLUDEinclude()include()
T_INCLUDE_ONCEinclude_once()include_once()
T_INLINE_HTML  
T_INT_CAST(int) or (integer)type-casting
T_ISSETisset()isset()
T_IS_EQUAL==comparison operators
T_IS_GREATER_OR_EQUAL>=comparison operators
T_IS_IDENTICAL===comparison operators
T_IS_NOT_EQUAL!= or <>comparison operators
T_IS_NOT_IDENTICAL!==comparison operators
T_SMALLER_OR_EQUAL<=comparison operators
T_LINE__LINE__constants
T_LISTlist()list()
T_LNUMBER123, 012, 0x1ac, etcintegers
T_LOGICAL_ANDandlogical operators
T_LOGICAL_ORorlogical operators
T_LOGICAL_XORxorlogical operators
T_MINUS_EQUAL-=assignment operators
T_ML_COMMENT/* and */comments
T_MOD_EQUAL%=assignment operators
T_MUL_EQUAL*=assignment operators
T_NEWnewclasses and objects
T_NUM_STRING  
T_OBJECT_CAST(object)type-casting
T_OBJECT_OPERATOR->classes and objects
T_OLD_FUNCTIONold_functionold_function
T_OPEN_TAG<?php, <? or <%escaping from HTML
T_OPEN_TAG_WITH_ECHO<?= or <%=escaping from HTML
T_OR_EQUAL|=assignment operators
T_PAAMAYIM_NEKUDOTAYIM::::
T_PLUS_EQUAL+=assignment operators
T_PRINTprint()print()
T_REQUIRErequire()require()
T_REQUIRE_ONCErequire_once()require_once()
T_RETURNreturnreturning values
T_SL<<bitwise operators
T_SL_EQUAL<<=assignment operators
T_SR>>bitwise operators
T_SR_EQUAL>>=assignment operators
T_START_HEREDOC<<<heredoc syntax
T_STATICstaticvariable scope
T_STRING  
T_STRING_CAST(string)type-casting
T_STRING_VARNAME  
T_SWITCHswitchswitch
T_UNSETunset()unset()
T_UNSET_CAST(unset)(not documented; casts to NULL)
T_USEuse(not implemented)
T_VARvarclasses and objects
T_VARIABLE$foovariables
T_WHILEwhilewhile, do..while
T_WHITESPACE  
T_XOR_EQUAL^=assignment operators
T_FUNC_C__FUNCTION__constants, since PHP 4.3.0
T_CLASS_C__CLASS__constants, since PHP 4.3.0

N. Függelék. About the manual

Formats

The PHP manual is provided in several formats. These formats can be divided into two groups: online readable formats, and downloadable packages.

Megjegyzés: Some publishers have made available printed versions of this manual. We cannot recommend any of those, as they tend to become out-of-date very quickly.

You can read the manual online at http://www.php.net/ and on the numerous mirror sites. For best performance, you should choose the mirror site closest to you. You can view the manual in either its plain (print-friendly) HTML format or an HTML format that integrates the manual into the look and feel of the PHP website itself.

An advantage of the online manual over most of the offline formats is the integration of user-contributed notes. An obvious disadvantage is that you have to be online to view the manual in the online formats.

There are several offline formats of the manual, and the most appropriate format for you depends on what operating system you use and your personal reading style. For information on how the manual is generated in so many formats, read the 'How we generate the formats' section of this appendix.

The most cross-platform formats of the manual are the HTML and plain-text versions. The HTML format is provided both as a single HTML file and as a package of individual files for each section (which results in a collection of several thousand files). The HTML and plaintext formats are provided as tar files compressed using the bzip2 archiver.

Another popular cross-platform format, and the format most suited to printing, is PDF (also known as Adobe Acrobat). But before you rush to download this format and hit the Print button, be warned that the manual is nearly 2000 pages long, and constantly being revised.

Megjegyzés: If you do not already have a program capable of viewing PDF format files, you may need to download Adobe Acrobat Reader.

For owners of Palm-compatible handhelds, the Palm document and iSilo formats are ideal for this platform. You can bring your handheld with you on your daily commute and use a DOC or iSilo reader to brush up on your PHP knowledge, or just use it as a quick reference.

For Windows platforms, the Windows HTML Help version of the manual soups up the HTML format for use with the Windows HTML Help application. This version provides full-text search, a full index, and bookmarking. Many popular Windows PHP development environments also integrate with this version of the documentation to provide easy access.


About user notes

The user-contributed notes play an important role in the development of this manual. By allowing readers of the manual to contribute examples, caveats, and further clarifications from their browser, we are able to incorporate that feedback into the main text of the manual. And until the notes have been incorporated, they can be viewed in their submitted form online and in some of the offline formats.

Megjegyzés: The user-contributed notes are not moderated before they appear online, so the quality of the writing or code examples, and even the veracity of the contribution, cannot be guaranteed. (Not that there is any guarantee of the quality or accuracy of the manual text itself.)

Megjegyzés: For the purposes of license coverage the user-contributed notes are considered part of the PHP manual, and are therefore covered by the same license that covers this documentation (Open Publication License at the moment). For more details see the Manual's Copyright page.


How to read a function definition (prototype)

Each function is documented for quick reference. Knowing how to read and understand the manual will make using PHP much easier. Rather than relying on examples or cut/paste, you will want to know how to read function definitions (prototypes). Let's begin:

Prerequisite: Basic understanding of types: Although PHP is a loosely typed language, it's important to have a basic understanding of types as they have important meaning.

Function definitions tell us what type of value is returned. Let's use the definition for strlen() as our first example:

strlen

(PHP 3, PHP 4 >= 4.0.0)
strlen -- Get string length

Description
int strlen ( string str )

Returns the length of string.

Táblázat N-1. Explanation of a function definition

PartDescription
strlen The function name.
(PHP 3, PHP 4 >= 4.0.0) strlen() has been around in both all of PHP 3 and PHP 4
int Type of value this function returns, which is an integer (i.e. The length of a string is measured in numbers).
( string str ) The first (and in this case the only) parameter/argument for the function strlen() is named str, and it's a string.

We could rewrite the above function definition in a generic way:

returned type    function name    ( parameter type   parameter name )

Many functions take on multiple parameters, such as in_array(). Its prototype is as follows:

bool in_array ( mixed needle, array haystack [, bool strict])

What does this mean? in_array() returns a boolean value, TRUE on success (if the needle was found in the haystack) or FALSE on failure (if the needle was not found in the haystack). The first parameter is named needle and it can be of many different types, so we call it "mixed". This mixed needle (what we're looking for) can be either a scalar value (string, integer, or float), or an array. haystack (the array we're searching in) is the second parameter. The third optional parameter is named strict. All optional parameters are seen in [ brackets ]. The manual states that the strict parameter defaults to boolean FALSE. See the manual page on each function for details on how they work.


PHP versions documented in this manual

This documentation contains information about PHP 4, with some added migration and compatibility notes regarding PHP 3. Behaviour, parameter, return value and other changes between different PHP versions are documented in notes and inline text in the manual.

You may find documentation pieces for the CVS version of PHP, which always means the very latest development version available through the CVS version handling system. If you are not a developer of PHP itself, and you are not keen on using the very latest development version of PHP, features marked with the "available in CVS" wording are not accessible to you. These features, though, will probably be available in the next stable version of PHP. If you would like to download the CVS version, see the anonymous CVS access page.

You may also encounter documentation for a PHP version which is not released (something like PHP 5.0.0 as the latest stable version is 4.3.x). Most of the time, this is not an error in the documentation. Explanation is often added for features not available in the current PHP release, but which will be available in a known future PHP version.


How to find more information about PHP

This manual does not attempt to provide instruction about general programming practices. If you are a first-time, or even just a beginning, programmer, you may find it difficult to learn how to program in PHP using just this manual. You may want to seek out a text more oriented towards beginners. You can find a list of PHP-related books at http://www.php.net/books.php.

There are a number of active mailing lists for discussion of all aspects of programming with PHP. If you find yourself stuck on a problem for which you can't find your own solution, you may be able to get help from someone on these lists. You can find a list of the mailing lists at http://www.php.net/support.php, as well as links to the mailing list archives and other online support resources. Furthermore, at http://www.php.net/links.php there is a list of websites devoted to PHP articles, forums, and code galleries.


How to help improve the documentation

There are three ways you can help to improve this documentation.

If you find errors in this manual, in any language, please report them using the bug system at http://bugs.php.net/. Classify the bug as "Documentation Problem". You can also submit problems related to specific manual formats here.

Megjegyzés: Please don't abuse the bug system by submitting requests for help. Use the mailing lists or community sites mentioned earlier, instead.

By contributing notes, you can provide additional examples, caveats, and clarifications for other readers. But please do not submit bug reports using the annotation system. You can read more about annotations in the 'About user notes' section of this appendix.

If you know English and some foreign language, you may also help out in the translations. If you would like to start a new translation, or help in a translation project, please read http://cvs.php.net/co.php/phpdoc/howto/howto.html.tar.gz.


How we generate the formats

This manual is written in XML using the DocBook XML DTD, using DSSSL (Document Style and Semantics Specification Language) for formatting, and experimentally the XSLT (Extensible Stylesheet Language Transformations) for maintenance and formatting.

Using XML as a source format gives us the ability to generate many output formats from the source files, while only maintaining one source document for all formats. The tools used for formatting HTML and TeX versions are Jade, written by James Clark; and The Modular DocBook Stylesheets, written by Norman Walsh. We use Microsoft HTML Help Workshop to generate the Windows HTML Help format of the manual, and of course PHP itself to do some additional conversions and formatting.

You can download the manual in various languages and formats, including plain text, plain HTML, PDF, PalmPilot DOC, PalmPilot iSilo, and Windows HTML Help, from http://www.php.net/docs.php. The manuals are updated periodically as the text is updated.

You can find more information about downloading the XML source code of this documentation at http://cvs.php.net/. The documentation is stored in the phpdoc module.


Translations

The PHP manual is available not only in various formats, but also in various languages. The text of the manual is first written in English, then teams of people across the world take care of translating it to their native languages. If a translation for a specified function or chapter has not yet been made, the manual's build system falls back to the English version of it.

People involved in the translations start from the XML source code available from http://cvs.php.net/ and from it they translate to their mother language. They do not use the HTML, the plain text, or the PDF version. It is the build system which takes care of the conversions from XML to human readable formats.

Megjegyzés: If you would like to help translate the documentation to your native language, please get in touch with the translation/documentation team by subscribing to the phpdoc mailing list: send an empty mail to phpdoc-subscribe@lists.php.net. The mailing list address is phpdoc@lists.php.net. State in the message that you are interested in translating the manual to a language and someone will get back to you, helping you start a new language translation or reach the already active documentation team for your language.

At the moment the manual is available, partly or not, in the following languages: Brazilian Portuguese, Chinese (Simplified), Chinese (Hong Kong Cantonese), Chinese (Traditional), Czech, Dutch, Finnish, French, German, Hebrew, Hungarian, Italian, Japanese, Korean, Polish, Romanian, Russian, Slovak, Slovenian, Spanish, Swedish, and Turkish.

They can all be downloaded here: http://www.php.net/docs.php.


O. Függelék. Open Publication License

v1.0, 8 June 1999


I. REQUIREMENTS ON BOTH UNMODIFIED AND MODIFIED VERSIONS

The Open Publication works may be reproduced and distributed in whole or in part, in any medium physical or electronic, provided that the terms of this license are adhered to, and that this license or an incorporation of it by reference (with any options elected by the author(s) and/or publisher) is displayed in the reproduction.

Proper form for an incorporation by reference is as follows:

Copyright (c) <year> by <author's name or designee>. This material may be distributed only subject to the terms and conditions set forth in the Open Publication License, vX.Y or later (the latest version is presently available at http://www.opencontent.org/openpub/

The reference must be immediately followed with any options elected by the author(s) and/or publisher of the document (see section VI). Commercial redistribution of Open Publication-licensed material is permitted. Any publication in standard (paper) book form shall require the citation of the original publisher and author. The publisher and author's names shall appear on all outer surfaces of the book. On all outer surfaces of the book the original publisher's name shall be as large as the title of the work and cited as possessive with respect to the title.


II. COPYRIGHT

The copyright to each Open Publication is owned by its author(s) or designee.


III. SCOPE OF LICENSE

The following license terms apply to all Open Publication works, unless otherwise explicitly stated in the document.

Mere aggregation of Open Publication works or a portion of an Open Publication work with other works or programs on the same media shall not cause this license to apply to those other works. The aggregate work shall contain a notice specifying the inclusion of the Open Publication material and appropriate copyright notice.

SEVERABILITY. If any part of this license is found to be unenforceable in any jurisdiction, the remaining portions of the license remain in force.

NO WARRANTY. Open Publication works are licensed and provided "as is" without warranty of any kind, express or implied, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose or a warranty of non-infringement.


IV. REQUIREMENTS ON MODIFIED WORKS

All modified versions of documents covered by this license, including translations, anthologies, compilations and partial documents, must meet the following requirements:

  1. The modified version must be labeled as such.

  2. The person making the modifications must be identified and the modifications dated.

  3. Acknowledgement of the original author and publisher if applicable must be retained according to normal academic citation practices.

  4. The location of the original unmodified document must be identified.

  5. The original author's (or authors') name(s) may not be used to assert or imply endorsement of the resulting document without the original author's (or authors') permission.


V. GOOD-PRACTICE RECOMMENDATIONS

In addition to the requirements of this license, it is requested from and strongly recommended of redistributors that:

  1. If you are distributing Open Publication works on hardcopy or CD-ROM, you provide email notification to the authors of your intent to redistribute at least thirty days before your manuscript or media freeze, to give the authors time to provide updated documents. This notification should describe modifications, if any, made to the document.

  2. All substantive modifications (including deletions) be either clearly marked up in the document or else described in an attachment to the document.

  3. Finally, while it is not mandatory under this license, it is considered good form to offer a free copy of any hardcopy and CD-ROM expression of an Open Publication-licensed work to its author(s).


VI. LICENSE OPTIONS

The author(s) and/or publisher of an Open Publication-licensed document may elect certain options by appending language to the reference to or copy of the license. These options are considered part of the license instance and must be included with the license (or its incorporation by reference) in derived works.

A. To prohibit distribution of substantively modified versions without the explicit permission of the author(s). "Substantive modification" is defined as a change to the semantic content of the document, and excludes mere changes in format or typographical corrections.

To accomplish this, add the phrase `Distribution of substantively modified versions of this document is prohibited without the explicit permission of the copyright holder.' to the license reference or copy.

B. To prohibit any publication of this work or derivative works in whole or in part in standard (paper) book form for commercial purposes is prohibited unless prior permission is obtained from the copyright holder.

To accomplish this, add the phrase 'Distribution of the work or derivative of the work in any standard (paper) book form is prohibited unless prior permission is obtained from the copyright holder.' to the license reference or copy.


P. Függelék. Függvények listája


Függvények listája


C

cal_days_in_month()
cal_from_jd()
cal_info()
cal_to_jd()
call_user_func()
call_user_func_array()
call_user_method()
call_user_method_array()
ccvs_add()
ccvs_auth()
ccvs_command()
ccvs_count()
ccvs_delete()
ccvs_done()
ccvs_init()
ccvs_lookup()
ccvs_new()
ccvs_report()
ccvs_return()
ccvs_reverse()
ccvs_sale()
ccvs_status()
ccvs_textvalue()
ccvs_void()
ceil()
chdir()
checkdate()
checkdnsrr()
chgrp()
chmod()
chop()
chown()
chr()
chroot()
chunk_split()
class_exists()
clearstatcache()
closedir()
closelog()
com()
com_addref()
com_get()
com_invoke()
com_isenum()
com_load()
com_load_typelib()
com_propget()
com_propput()
com_propset()
com_release()
com_set()
compact()
connection_aborted()
connection_status()
connection_timeout()
constant()
convert_cyr_string()
copy()
cos()
cosh()
count()
count_chars()
cpdf_add_annotation()
cpdf_add_outline()
cpdf_arc()
cpdf_begin_text()
cpdf_circle()
cpdf_clip()
cpdf_close()
cpdf_closepath()
cpdf_closepath_fill_stroke()
cpdf_closepath_stroke()
cpdf_continue_text()
cpdf_curveto()
cpdf_end_text()
cpdf_fill()
cpdf_fill_stroke()
cpdf_finalize()
cpdf_finalize_page()
cpdf_global_set_document_limits()
cpdf_import_jpeg()
cpdf_lineto()
cpdf_moveto()
cpdf_newpath()
cpdf_open()
cpdf_output_buffer()
cpdf_page_init()
cpdf_place_inline_image()
cpdf_rect()
cpdf_restore()
cpdf_rlineto()
cpdf_rmoveto()
cpdf_rotate()
cpdf_rotate_text()
cpdf_save()
cpdf_save_to_file()
cpdf_scale()
cpdf_set_action_url()
cpdf_set_char_spacing()
cpdf_set_creator()
cpdf_set_current_page()
cpdf_set_font()
cpdf_set_font_directories()
cpdf_set_font_map_file()
cpdf_set_horiz_scaling()
cpdf_set_keywords()
cpdf_set_leading()
cpdf_set_page_animation()
cpdf_set_subject()
cpdf_set_text_matrix()
cpdf_set_text_pos()
cpdf_set_text_rendering()
cpdf_set_text_rise()
cpdf_set_title()
cpdf_set_viewer_preferences()
cpdf_set_word_spacing()
cpdf_setdash()
cpdf_setflat()
cpdf_setgray()
cpdf_setgray_fill()
cpdf_setgray_stroke()
cpdf_setlinecap()
cpdf_setlinejoin()
cpdf_setlinewidth()
cpdf_setmiterlimit()
cpdf_setrgbcolor()
cpdf_setrgbcolor_fill()
cpdf_setrgbcolor_stroke()
cpdf_show()
cpdf_show_xy()
cpdf_stringwidth()
cpdf_stroke()
cpdf_text()
cpdf_translate()
crack_check()
crack_closedict()
crack_getlastmessage()
crack_opendict()
crc32()
create_function()
crypt()
ctype_alnum()
ctype_alpha()
ctype_cntrl()
ctype_digit()
ctype_graph()
ctype_lower()
ctype_print()
ctype_punct()
ctype_space()
ctype_upper()
ctype_xdigit()
curl_close()
curl_errno()
curl_error()
curl_exec()
curl_getinfo()
curl_init()
curl_multi_add_handle()
curl_multi_close()
curl_multi_exec()
curl_multi_getcontent()
curl_multi_info_read()
curl_multi_init()
curl_multi_remove_handle()
curl_multi_select()
curl_setopt()
curl_version()
current()
cybercash_base64_decode()
cybercash_base64_encode()
cybercash_decr()
cybercash_encr()
cyrus_authenticate()
cyrus_bind()
cyrus_close()
cyrus_connect()
cyrus_query()
cyrus_unbind()

D

date()
dba_close()
dba_delete()
dba_exists()
dba_fetch()
dba_firstkey()
dba_handlers()
dba_insert()
dba_key_split()
dba_list()
dba_nextkey()
dba_open()
dba_optimize()
dba_popen()
dba_replace()
dba_sync()
dbase_add_record()
dbase_close()
dbase_create()
dbase_delete_record()
dbase_get_header_info()
dbase_get_record()
dbase_get_record_with_names()
dbase_numfields()
dbase_numrecords()
dbase_open()
dbase_pack()
dbase_replace_record()
dblist()
dbmclose()
dbmdelete()
dbmexists()
dbmfetch()
dbmfirstkey()
dbminsert()
dbmnextkey()
dbmopen()
dbmreplace()
dbplus_add()
dbplus_aql()
dbplus_chdir()
dbplus_close()
dbplus_curr()
dbplus_errcode()
dbplus_errno()
dbplus_find()
dbplus_first()
dbplus_flush()
dbplus_freealllocks()
dbplus_freelock()
dbplus_freerlocks()
dbplus_getlock()
dbplus_getunique()
dbplus_info()
dbplus_last()
dbplus_lockrel()
dbplus_next()
dbplus_open()
dbplus_prev()
dbplus_rchperm()
dbplus_rcreate()
dbplus_rcrtexact()
dbplus_rcrtlike()
dbplus_resolve()
dbplus_restorepos()
dbplus_rkeys()
dbplus_ropen()
dbplus_rquery()
dbplus_rrename()
dbplus_rsecindex()
dbplus_runlink()
dbplus_rzap()
dbplus_savepos()
dbplus_setindex()
dbplus_setindexbynumber()
dbplus_sql()
dbplus_tcl()
dbplus_tremove()
dbplus_undo()
dbplus_undoprepare()
dbplus_unlockrel()
dbplus_unselect()
dbplus_update()
dbplus_xlockrel()
dbplus_xunlockrel()
dbx_close()
dbx_compare()
dbx_connect()
dbx_error()
dbx_escape_string()
dbx_fetch_row()
dbx_query()
dbx_sort()
dcgettext()
dcngettext()
deaggregate()
debug_backtrace()
debug_print_backtrace()
debugger_off()
debugger_on()
decbin()
dechex()
decoct()
define()
define_syslog_variables()
defined()
deg2rad()
delete()
dgettext()
die()
dio_close()
dio_fcntl()
dio_open()
dio_read()
dio_seek()
dio_stat()
dio_tcsetattr()
dio_truncate()
dio_write()
dir()
dirname()
disk_free_space()
disk_total_space()
diskfreespace()
dl()
dngettext()
dns_check_record()
dns_get_mx()
dns_get_record()
domattribute->name()
domattribute->specified()
domattribute->value()
domdocument->add_root [deprecated]()
domdocument->create_attribute()
domdocument->create_cdata_section()
domdocument->create_comment()
domdocument->create_element()
domdocument->create_element_ns()
domdocument->create_entity_reference()
domdocument->create_processing_instruction()
domdocument->create_text_node()
domdocument->doctype()
domdocument->document_element()
domdocument->dump_file()
domdocument->dump_mem()
domdocument->get_element_by_id()
domdocument->get_elements_by_tagname()
domdocument->html_dump_mem()
domdocument->xinclude()
domdocumenttype->entities()
domdocumenttype->internal_subset()
domdocumenttype->name()
domdocumenttype->notations()
domdocumenttype->public_id()
domdocumenttype->system_id()
domelement->get_attribute()
domelement->get_attribute_node()
domelement->get_elements_by_tagname()
domelement->has_attribute()
domelement->remove_attribute()
domelement->set_attribute()
domelement->tagname()
domnode->add_namespace()
domnode->append_child()
domnode->append_sibling()
domnode->attributes()
domnode->child_nodes()
domnode->clone_node()
domnode->dump_node()
domnode->first_child()
domnode->get_content()
domnode->has_attributes()
domnode->has_child_nodes()
domnode->insert_before()
domnode->is_blank_node()
domnode->last_child()
domnode->next_sibling()
domnode->node_name()
domnode->node_type()
domnode->node_value()
domnode->owner_document()
domnode->parent_node()
domnode->prefix()
domnode->previous_sibling()
domnode->remove_child()
domnode->replace_child()
domnode->replace_node()
domnode->set_content()
domnode->set_name()
domnode->set_namespace()
domnode->unlink_node()
domprocessinginstruction->data()
domprocessinginstruction->target()
domxml_new_doc()
domxml_open_file()
domxml_open_mem()
domxml_version()
domxml_xmltree()
domxml_xslt_stylesheet()
domxml_xslt_stylesheet_doc()
domxml_xslt_stylesheet_file()
domxsltstylesheet->process()
domxsltstylesheet->result_dump_file()
domxsltstylesheet->result_dump_mem()
dotnet_load()
doubleval()

F

fam_cancel_monitor()
fam_close()
fam_monitor_collection()
fam_monitor_directory()
fam_monitor_file()
fam_next_event()
fam_open()
fam_pending()
fam_resume_monitor()
fam_suspend_monitor()
fbsql_affected_rows()
fbsql_autocommit()
fbsql_change_user()
fbsql_close()
fbsql_commit()
fbsql_connect()
fbsql_create_blob()
fbsql_create_clob()
fbsql_create_db()
fbsql_data_seek()
fbsql_database()
fbsql_database_password()
fbsql_db_query()
fbsql_db_status()
fbsql_drop_db()
fbsql_errno()
fbsql_error()
fbsql_fetch_array()
fbsql_fetch_assoc()
fbsql_fetch_field()
fbsql_fetch_lengths()
fbsql_fetch_object()
fbsql_fetch_row()
fbsql_field_flags()
fbsql_field_len()
fbsql_field_name()
fbsql_field_seek()
fbsql_field_table()
fbsql_field_type()
fbsql_free_result()
fbsql_get_autostart_info()
fbsql_hostname()
fbsql_insert_id()
fbsql_list_dbs()
fbsql_list_fields()
fbsql_list_tables()
fbsql_next_result()
fbsql_num_fields()
fbsql_num_rows()
fbsql_password()
fbsql_pconnect()
fbsql_query()
fbsql_read_blob()
fbsql_read_clob()
fbsql_result()
fbsql_rollback()
fbsql_select_db()
fbsql_set_lob_mode()
fbsql_set_transaction()
fbsql_start_db()
fbsql_stop_db()
fbsql_tablename()
fbsql_username()
fbsql_warnings()
fclose()
fdf_add_doc_javascript()
fdf_add_template()
fdf_close()
fdf_create()
fdf_enum_values()
fdf_errno()
fdf_error()
fdf_get_ap()
fdf_get_attachment()
fdf_get_encoding()
fdf_get_file()
fdf_get_flags()
fdf_get_opt()
fdf_get_status()
fdf_get_value()
fdf_get_version()
fdf_header()
fdf_next_field_name()
fdf_open()
fdf_open_string()
fdf_remove_item()
fdf_save()
fdf_save_string()
fdf_set_ap()
fdf_set_encoding()
fdf_set_file()
fdf_set_flags()
fdf_set_javascript_action()
fdf_set_opt()
fdf_set_status()
fdf_set_submit_form_action()
fdf_set_target_frame()
fdf_set_value()
fdf_set_version()
feof()
fflush()
fgetc()
fgetcsv()
fgets()
fgetss()
file()
file_exists()
file_get_contents()
file_put_contents()
fileatime()
filectime()
filegroup()
fileinode()
filemtime()
fileowner()
fileperms()
filepro()
filepro_fieldcount()
filepro_fieldname()
filepro_fieldtype()
filepro_fieldwidth()
filepro_retrieve()
filepro_rowcount()
filesize()
filetype()
floatval()
flock()
floor()
flush()
fmod()
fnmatch()
fopen()
fpassthru()
fprintf()
fputs()
fread()
frenchtojd()
fribidi_log2vis()
fscanf()
fseek()
fsockopen()
fstat()
ftell()
ftok()
ftp_alloc()
ftp_cdup()
ftp_chdir()
ftp_chmod()
ftp_close()
ftp_connect()
ftp_delete()
ftp_exec()
ftp_fget()
ftp_fput()
ftp_get()
ftp_get_option()
ftp_login()
ftp_mdtm()
ftp_mkdir()
ftp_nb_continue()
ftp_nb_fget()
ftp_nb_fput()
ftp_nb_get()
ftp_nb_put()
ftp_nlist()
ftp_pasv()
ftp_put()
ftp_pwd()
ftp_quit()
ftp_raw()
ftp_rawlist()
ftp_rename()
ftp_rmdir()
ftp_set_option()
ftp_site()
ftp_size()
ftp_ssl_connect()
ftp_systype()
ftruncate()
func_get_arg()
func_get_args()
func_num_args()
function_exists()
fwrite()

H

header()
headers_list()
headers_sent()
hebrev()
hebrevc()
hexdec()
highlight_file()
highlight_string()
html_entity_decode()
htmlentities()
htmlspecialchars()
http_build_query()
hw_api->checkin()
hw_api->checkout()
hw_api->children()
hw_api->content()
hw_api->copy()
hw_api->dbstat()
hw_api->dcstat()
hw_api->dstanchors()
hw_api->dstofsrcanchors()
hw_api->find()
hw_api->ftstat()
hw_api->hwstat()
hw_api->identify()
hw_api->info()
hw_api->insert()
hw_api->insertanchor()
hw_api->insertcollection()
hw_api->insertdocument()
hw_api->link()
hw_api->lock()
hw_api->move()
hw_api->object()
hw_api->objectbyanchor()
hw_api->parents()
hw_api->remove()
hw_api->replace()
hw_api->setcommitedversion()
hw_api->srcanchors()
hw_api->srcsofdst()
hw_api->unlock()
hw_api->user()
hw_api->userlist()
hw_api_attribute()
hw_api_attribute->key()
hw_api_attribute->langdepvalue()
hw_api_attribute->value()
hw_api_attribute->values()
hw_api_content()
hw_api_content->mimetype()
hw_api_content->read()
hw_api_error->count()
hw_api_error->reason()
hw_api_object()
hw_api_object->assign()
hw_api_object->attreditable()
hw_api_object->count()
hw_api_object->insert()
hw_api_object->remove()
hw_api_object->title()
hw_api_object->value()
hw_api_reason->description()
hw_api_reason->type()
hw_array2objrec()
hw_changeobject()
hw_children()
hw_childrenobj()
hw_close()
hw_connect()
hw_connection_info()
hw_cp()
hw_deleteobject()
hw_docbyanchor()
hw_docbyanchorobj()
hw_document_attributes()
hw_document_bodytag()
hw_document_content()
hw_document_setcontent()
hw_document_size()
hw_dummy()
hw_edittext()
hw_error()
hw_errormsg()
hw_free_document()
hw_getanchors()
hw_getanchorsobj()
hw_getandlock()
hw_getchildcoll()
hw_getchildcollobj()
hw_getchilddoccoll()
hw_getchilddoccollobj()
hw_getobject()
hw_getobjectbyquery()
hw_getobjectbyquerycoll()
hw_getobjectbyquerycollobj()
hw_getobjectbyqueryobj()
hw_getparents()
hw_getparentsobj()
hw_getrellink()
hw_getremote()
hw_getremotechildren()
hw_getsrcbydestobj()
hw_gettext()
hw_getusername()
hw_identify()
hw_incollections()
hw_info()
hw_inscoll()
hw_insdoc()
hw_insertanchors()
hw_insertdocument()
hw_insertobject()
hw_mapid()
hw_modifyobject()
hw_mv()
hw_new_document()
hw_objrec2array()
hw_output_document()
hw_pconnect()
hw_pipedocument()
hw_root()
hw_setlinkroot()
hw_stat()
hw_unlock()
hw_who()
hwapi_hgcsp()
hypot()

I

ibase_add_user()
ibase_affected_rows()
ibase_blob_add()
ibase_blob_cancel()
ibase_blob_close()
ibase_blob_create()
ibase_blob_echo()
ibase_blob_get()
ibase_blob_import()
ibase_blob_info()
ibase_blob_open()
ibase_close()
ibase_commit()
ibase_commit_ret()
ibase_connect()
ibase_delete_user()
ibase_drop_db()
ibase_errcode()
ibase_errmsg()
ibase_execute()
ibase_fetch_assoc()
ibase_fetch_object()
ibase_fetch_row()
ibase_field_info()
ibase_free_event_handler()
ibase_free_query()
ibase_free_result()
ibase_gen_id()
ibase_modify_user()
ibase_name_result()
ibase_num_fields()
ibase_num_params()
ibase_param_info()
ibase_pconnect()
ibase_prepare()
ibase_query()
ibase_rollback()
ibase_rollback_ret()
ibase_set_event_handler()
ibase_timefmt()
ibase_trans()
ibase_wait_event()
iconv()
iconv_get_encoding()
iconv_mime_decode()
iconv_mime_decode_headers()
iconv_mime_encode()
iconv_set_encoding()
iconv_strlen()
iconv_strpos()
iconv_strrpos()
iconv_substr()
ifx_affected_rows()
ifx_blobinfile_mode()
ifx_byteasvarchar()
ifx_close()
ifx_connect()
ifx_copy_blob()
ifx_create_blob()
ifx_create_char()
ifx_do()
ifx_error()
ifx_errormsg()
ifx_fetch_row()
ifx_fieldproperties()
ifx_fieldtypes()
ifx_free_blob()
ifx_free_char()
ifx_free_result()
ifx_get_blob()
ifx_get_char()
ifx_getsqlca()
ifx_htmltbl_result()
ifx_nullformat()
ifx_num_fields()
ifx_num_rows()
ifx_pconnect()
ifx_prepare()
ifx_query()
ifx_textasvarchar()
ifx_update_blob()
ifx_update_char()
ifxus_close_slob()
ifxus_create_slob()
ifxus_free_slob()
ifxus_open_slob()
ifxus_read_slob()
ifxus_seek_slob()
ifxus_tell_slob()
ifxus_write_slob()
ignore_user_abort()
image2wbmp()
image_type_to_mime_type()
imagealphablending()
imageantialias()
imagearc()
imagechar()
imagecharup()
imagecolorallocate()
imagecolorallocatealpha()
imagecolorat()
imagecolorclosest()
imagecolorclosestalpha()
imagecolorclosesthwb()
imagecolordeallocate()
imagecolorexact()
imagecolorexactalpha()
imagecolormatch()
imagecolorresolve()
imagecolorresolvealpha()
imagecolorset()
imagecolorsforindex()
imagecolorstotal()
imagecolortransparent()
imagecopy()
imagecopymerge()
imagecopymergegray()
imagecopyresampled()
imagecopyresized()
imagecreate()
imagecreatefromgd()
imagecreatefromgd2()
imagecreatefromgd2part()
imagecreatefromgif()
imagecreatefromjpeg()
imagecreatefrompng()
imagecreatefromstring()
imagecreatefromwbmp()
imagecreatefromxbm()
imagecreatefromxpm()
imagecreatetruecolor()
imagedashedline()
imagedestroy()
imageellipse()
imagefill()
imagefilledarc()
imagefilledellipse()
imagefilledpolygon()
imagefilledrectangle()
imagefilltoborder()
imagefontheight()
imagefontwidth()
imageftbbox()
imagefttext()
imagegammacorrect()
imagegd()
imagegd2()
imagegif()
imageinterlace()
imageistruecolor()
imagejpeg()
imageline()
imageloadfont()
imagepalettecopy()
imagepng()
imagepolygon()
imagepsbbox()
imagepscopyfont()
imagepsencodefont()
imagepsextendfont()
imagepsfreefont()
imagepsloadfont()
imagepsslantfont()
imagepstext()
imagerectangle()
imagerotate()
imagesavealpha()
imagesetbrush()
imagesetpixel()
imagesetstyle()
imagesetthickness()
imagesettile()
imagestring()
imagestringup()
imagesx()
imagesy()
imagetruecolortopalette()
imagettfbbox()
imagettftext()
imagetypes()
imagewbmp()
imap_8bit()
imap_alerts()
imap_append()
imap_base64()
imap_binary()
imap_body()
imap_bodystruct()
imap_check()
imap_clearflag_full()
imap_close()
imap_createmailbox()
imap_delete()
imap_deletemailbox()
imap_errors()
imap_expunge()
imap_fetch_overview()
imap_fetchbody()
imap_fetchheader()
imap_fetchstructure()
imap_get_quota()
imap_get_quotaroot()
imap_getacl()
imap_getmailboxes()
imap_getsubscribed()
imap_header()
imap_headerinfo()
imap_headers()
imap_last_error()
imap_list()
imap_listmailbox()
imap_listscan()
imap_listsubscribed()
imap_lsub()
imap_mail()
imap_mail_compose()
imap_mail_copy()
imap_mail_move()
imap_mailboxmsginfo()
imap_mime_header_decode()
imap_msgno()
imap_num_msg()
imap_num_recent()
imap_open()
imap_ping()
imap_qprint()
imap_renamemailbox()
imap_reopen()
imap_rfc822_parse_adrlist()
imap_rfc822_parse_headers()
imap_rfc822_write_address()
imap_scanmailbox()
imap_search()
imap_set_quota()
imap_setacl()
imap_setflag_full()
imap_sort()
imap_status()
imap_subscribe()
imap_thread()
imap_timeout()
imap_uid()
imap_undelete()
imap_unsubscribe()
imap_utf7_decode()
imap_utf7_encode()
imap_utf8()
implode()
import_request_variables()
in_array()
ingres_autocommit()
ingres_close()
ingres_commit()
ingres_connect()
ingres_fetch_array()
ingres_fetch_object()
ingres_fetch_row()
ingres_field_length()
ingres_field_name()
ingres_field_nullable()
ingres_field_precision()
ingres_field_scale()
ingres_field_type()
ingres_num_fields()
ingres_num_rows()
ingres_pconnect()
ingres_query()
ingres_rollback()
ini_alter()
ini_get()
ini_get_all()
ini_restore()
ini_set()
intval()
ip2long()
iptcembed()
iptcparse()
ircg_channel_mode()
ircg_disconnect()
ircg_fetch_error_msg()
ircg_get_username()
ircg_html_encode()
ircg_ignore_add()
ircg_ignore_del()
ircg_is_conn_alive()
ircg_join()
ircg_kick()
ircg_lookup_format_messages()
ircg_msg()
ircg_nick()
ircg_nickname_escape()
ircg_nickname_unescape()
ircg_notice()
ircg_part()
ircg_pconnect()
ircg_register_format_messages()
ircg_set_current()
ircg_set_file()
ircg_set_on_die()
ircg_topic()
ircg_whois()
is_a()
is_array()
is_bool()
is_callable()
is_dir()
is_double()
is_executable()
is_file()
is_finite()
is_float()
is_infinite()
is_int()
is_integer()
is_link()
is_long()
is_nan()
is_null()
is_numeric()
is_object()
is_readable()
is_real()
is_resource()
is_scalar()
is_string()
is_subclass_of()
is_uploaded_file()
is_writable()
is_writeable()
isset()

M

mail()
mailparse_determine_best_xfer_encoding()
mailparse_msg_create()
mailparse_msg_extract_part()
mailparse_msg_extract_part_file()
mailparse_msg_free()
mailparse_msg_get_part()
mailparse_msg_get_part_data()
mailparse_msg_get_structure()
mailparse_msg_parse()
mailparse_msg_parse_file()
mailparse_rfc822_parse_addresses()
mailparse_stream_encode()
mailparse_uudecode_all()
main()
max()
mb_convert_case()
mb_convert_encoding()
mb_convert_kana()
mb_convert_variables()
mb_decode_mimeheader()
mb_decode_numericentity()
mb_detect_encoding()
mb_detect_order()
mb_encode_mimeheader()
mb_encode_numericentity()
mb_ereg()
mb_ereg_match()
mb_ereg_replace()
mb_ereg_search()
mb_ereg_search_getpos()
mb_ereg_search_getregs()
mb_ereg_search_init()
mb_ereg_search_pos()
mb_ereg_search_regs()
mb_ereg_search_setpos()
mb_eregi()
mb_eregi_replace()
mb_get_info()
mb_http_input()
mb_http_output()
mb_internal_encoding()
mb_language()
mb_output_handler()
mb_parse_str()
mb_preferred_mime_name()
mb_regex_encoding()
mb_regex_set_options()
mb_send_mail()
mb_split()
mb_strcut()
mb_strimwidth()
mb_strlen()
mb_strpos()
mb_strrpos()
mb_strtolower()
mb_strtoupper()
mb_strwidth()
mb_substitute_character()
mb_substr()
mb_substr_count()
mcal_append_event()
mcal_close()
mcal_create_calendar()
mcal_date_compare()
mcal_date_valid()
mcal_day_of_week()
mcal_day_of_year()
mcal_days_in_month()
mcal_delete_calendar()
mcal_delete_event()
mcal_event_add_attribute()
mcal_event_init()
mcal_event_set_alarm()
mcal_event_set_category()
mcal_event_set_class()
mcal_event_set_description()
mcal_event_set_end()
mcal_event_set_recur_daily()
mcal_event_set_recur_monthly_mday()
mcal_event_set_recur_monthly_wday()
mcal_event_set_recur_none()
mcal_event_set_recur_weekly()
mcal_event_set_recur_yearly()
mcal_event_set_start()
mcal_event_set_title()
mcal_expunge()
mcal_fetch_current_stream_event()
mcal_fetch_event()
mcal_is_leap_year()
mcal_list_alarms()
mcal_list_events()
mcal_next_recurrence()
mcal_open()
mcal_popen()
mcal_rename_calendar()
mcal_reopen()
mcal_snooze()
mcal_store_event()
mcal_time_valid()
mcal_week_of_year()
mcrypt_cbc()
mcrypt_cfb()
mcrypt_create_iv()
mcrypt_decrypt()
mcrypt_ecb()
mcrypt_enc_get_algorithms_name()
mcrypt_enc_get_block_size()
mcrypt_enc_get_iv_size()
mcrypt_enc_get_key_size()
mcrypt_enc_get_modes_name()
mcrypt_enc_get_supported_key_sizes()
mcrypt_enc_is_block_algorithm()
mcrypt_enc_is_block_algorithm_mode()
mcrypt_enc_is_block_mode()
mcrypt_enc_self_test()
mcrypt_encrypt()
mcrypt_generic()
mcrypt_generic_deinit()
mcrypt_generic_end()
mcrypt_generic_init()
mcrypt_get_block_size()
mcrypt_get_cipher_name()
mcrypt_get_iv_size()
mcrypt_get_key_size()
mcrypt_list_algorithms()
mcrypt_list_modes()
mcrypt_module_close()
mcrypt_module_get_algo_block_size()
mcrypt_module_get_algo_key_size()
mcrypt_module_get_supported_key_sizes()
mcrypt_module_is_block_algorithm()
mcrypt_module_is_block_algorithm_mode()
mcrypt_module_is_block_mode()
mcrypt_module_open()
mcrypt_module_self_test()
mcrypt_ofb()
mcve_adduser()
mcve_adduserarg()
mcve_bt()
mcve_checkstatus()
mcve_chkpwd()
mcve_chngpwd()
mcve_completeauthorizations()
mcve_connect()
mcve_connectionerror()
mcve_deleteresponse()
mcve_deletetrans()
mcve_deleteusersetup()
mcve_deluser()
mcve_destroyconn()
mcve_destroyengine()
mcve_disableuser()
mcve_edituser()
mcve_enableuser()
mcve_force()
mcve_getcell()
mcve_getcellbynum()
mcve_getcommadelimited()
mcve_getheader()
mcve_getuserarg()
mcve_getuserparam()
mcve_gft()
mcve_gl()
mcve_gut()
mcve_initconn()
mcve_initengine()
mcve_initusersetup()
mcve_iscommadelimited()
mcve_liststats()
mcve_listusers()
mcve_maxconntimeout()
mcve_monitor()
mcve_numcolumns()
mcve_numrows()
mcve_override()
mcve_parsecommadelimited()
mcve_ping()
mcve_preauth()
mcve_preauthcompletion()
mcve_qc()
mcve_responseparam()
mcve_return()
mcve_returncode()
mcve_returnstatus()
mcve_sale()
mcve_setblocking()
mcve_setdropfile()
mcve_setip()
mcve_setssl()
mcve_setssl_files()
mcve_settimeout()
mcve_settle()
mcve_text_avs()
mcve_text_code()
mcve_text_cv()
mcve_transactionauth()
mcve_transactionavs()
mcve_transactionbatch()
mcve_transactioncv()
mcve_transactionid()
mcve_transactionitem()
mcve_transactionssent()
mcve_transactiontext()
mcve_transinqueue()
mcve_transnew()
mcve_transparam()
mcve_transsend()
mcve_ub()
mcve_uwait()
mcve_verifyconnection()
mcve_verifysslcert()
mcve_void()
md5()
md5_file()
mdecrypt_generic()
memory_get_usage()
metaphone()
method_exists()
mhash()
mhash_count()
mhash_get_block_size()
mhash_get_hash_name()
mhash_keygen_s2k()
microtime()
mime_content_type()
min()
ming_setcubicthreshold()
ming_setscale()
ming_useswfversion()
mkdir()
mktime()
money_format()
move_uploaded_file()
msession_connect()
msession_count()
msession_create()
msession_destroy()
msession_disconnect()
msession_find()
msession_get()
msession_get_array()
msession_getdata()
msession_inc()
msession_list()
msession_listvar()
msession_lock()
msession_plugin()
msession_randstr()
msession_set()
msession_set_array()
msession_setdata()
msession_timeout()
msession_uniq()
msession_unlock()
msg_get_queue()
msg_receive()
msg_remove_queue()
msg_send()
msg_set_queue()
msg_stat_queue()
msql()
msql_affected_rows()
msql_close()
msql_connect()
msql_create_db()
msql_createdb()
msql_data_seek()
msql_dbname()
msql_drop_db()
msql_dropdb()
msql_error()
msql_fetch_array()
msql_fetch_field()
msql_fetch_object()
msql_fetch_row()
msql_field_seek()
msql_fieldflags()
msql_fieldlen()
msql_fieldname()
msql_fieldtable()
msql_fieldtype()
msql_free_result()
msql_freeresult()
msql_list_dbs()
msql_list_fields()
msql_list_tables()
msql_listdbs()
msql_listfields()
msql_listtables()
msql_num_fields()
msql_num_rows()
msql_numfields()
msql_numrows()
msql_pconnect()
msql_query()
msql_regcase()
msql_result()
msql_select_db()
msql_selectdb()
msql_tablename()
mssql_bind()
mssql_close()
mssql_connect()
mssql_data_seek()
mssql_execute()
mssql_fetch_array()
mssql_fetch_assoc()
mssql_fetch_batch()
mssql_fetch_field()
mssql_fetch_object()
mssql_fetch_row()
mssql_field_length()
mssql_field_name()
mssql_field_seek()
mssql_field_type()
mssql_free_result()
mssql_free_statement()
mssql_get_last_message()
mssql_guid_string()
mssql_init()
mssql_min_error_severity()
mssql_min_message_severity()
mssql_next_result()
mssql_num_fields()
mssql_num_rows()
mssql_pconnect()
mssql_query()
mssql_result()
mssql_rows_affected()
mssql_select_db()
mt_getrandmax()
mt_rand()
mt_srand()
muscat_close()
muscat_get()
muscat_give()
muscat_setup()
muscat_setup_net()
mysql_affected_rows()
mysql_change_user()
mysql_client_encoding()
mysql_close()
mysql_connect()
mysql_create_db()
mysql_data_seek()
mysql_db_name()
mysql_db_query()
mysql_drop_db()
mysql_errno()
mysql_error()
mysql_escape_string()
mysql_fetch_array()
mysql_fetch_assoc()
mysql_fetch_field()
mysql_fetch_lengths()
mysql_fetch_object()
mysql_fetch_row()
mysql_field_flags()
mysql_field_len()
mysql_field_name()
mysql_field_seek()
mysql_field_table()
mysql_field_type()
mysql_free_result()
mysql_get_client_info()
mysql_get_host_info()
mysql_get_proto_info()
mysql_get_server_info()
mysql_info()
mysql_insert_id()
mysql_list_dbs()
mysql_list_fields()
mysql_list_processes()
mysql_list_tables()
mysql_num_fields()
mysql_num_rows()
mysql_pconnect()
mysql_ping()
mysql_query()
mysql_real_escape_string()
mysql_result()
mysql_select_db()
mysql_stat()
mysql_tablename()
mysql_thread_id()
mysql_unbuffered_query()
mysqli_affected_rows()
mysqli_autocommit()
mysqli_bind_param()
mysqli_bind_result()
mysqli_change_user()
mysqli_character_set_name()
mysqli_close()
mysqli_commit()
mysqli_connect()
mysqli_data_seek()
mysqli_debug()
mysqli_disable_reads_from_master()
mysqli_disable_rpl_parse()
mysqli_dump_debug_info()
mysqli_enable_reads_from_master()
mysqli_enable_rpl_parse()
mysqli_errno()
mysqli_error()
mysqli_execute()
mysqli_fetch()
mysqli_fetch_array()
mysqli_fetch_assoc()
mysqli_fetch_field()
mysqli_fetch_field_direct()
mysqli_fetch_fields()
mysqli_fetch_lengths()
mysqli_fetch_object()
mysqli_fetch_row()
mysqli_field_count()
mysqli_field_seek()
mysqli_field_tell()
mysqli_free_result()
mysqli_get_client_info()
mysqli_get_host_info()
mysqli_get_proto_info()
mysqli_get_server_info()
mysqli_get_server_version()
mysqli_info()
mysqli_init()
mysqli_insert_id()
mysqli_kill()
mysqli_master_query()
mysqli_num_fields()
mysqli_num_rows()
mysqli_options()
mysqli_param_count()
mysqli_ping()
mysqli_prepare()
mysqli_prepare_result()
mysqli_profiler()
mysqli_query()
mysqli_read_query_result()
mysqli_real_connect()
mysqli_real_escape_string()
mysqli_real_query()
mysqli_reload()
mysqli_rollback()
mysqli_rpl_parse_enabled()
mysqli_rpl_probe()
mysqli_rpl_query_type()
mysqli_select_db()
mysqli_send_long_data()
mysqli_send_query()
mysqli_slave_query()
mysqli_ssl_set()
mysqli_stat()
mysqli_stmt_affected_rows()
mysqli_stmt_close()
mysqli_stmt_errno()
mysqli_stmt_error()
mysqli_stmt_store_result()
mysqli_store_result()
mysqli_thread_id()
mysqli_thread_safe()
mysqli_use_result()
mysqli_warning_count()

N

natcasesort()
natsort()
ncurses_addch()
ncurses_addchnstr()
ncurses_addchstr()
ncurses_addnstr()
ncurses_addstr()
ncurses_assume_default_colors()
ncurses_attroff()
ncurses_attron()
ncurses_attrset()
ncurses_baudrate()
ncurses_beep()
ncurses_bkgd()
ncurses_bkgdset()
ncurses_border()
ncurses_bottom_panel()
ncurses_can_change_color()
ncurses_cbreak()
ncurses_clear()
ncurses_clrtobot()
ncurses_clrtoeol()
ncurses_color_content()
ncurses_color_set()
ncurses_curs_set()
ncurses_def_prog_mode()
ncurses_def_shell_mode()
ncurses_define_key()
ncurses_del_panel()
ncurses_delay_output()
ncurses_delch()
ncurses_deleteln()
ncurses_delwin()
ncurses_doupdate()
ncurses_echo()
ncurses_echochar()
ncurses_end()
ncurses_erase()
ncurses_erasechar()
ncurses_filter()
ncurses_flash()
ncurses_flushinp()
ncurses_getch()
ncurses_getmaxyx()
ncurses_getmouse()
ncurses_getyx()
ncurses_halfdelay()
ncurses_has_colors()
ncurses_has_ic()
ncurses_has_il()
ncurses_has_key()
ncurses_hide_panel()
ncurses_hline()
ncurses_inch()
ncurses_init()
ncurses_init_color()
ncurses_init_pair()
ncurses_insch()
ncurses_insdelln()
ncurses_insertln()
ncurses_insstr()
ncurses_instr()
ncurses_isendwin()
ncurses_keyok()
ncurses_keypad()
ncurses_killchar()
ncurses_longname()
ncurses_meta()
ncurses_mouse_trafo()
ncurses_mouseinterval()
ncurses_mousemask()
ncurses_move()
ncurses_move_panel()
ncurses_mvaddch()
ncurses_mvaddchnstr()
ncurses_mvaddchstr()
ncurses_mvaddnstr()
ncurses_mvaddstr()
ncurses_mvcur()
ncurses_mvdelch()
ncurses_mvgetch()
ncurses_mvhline()
ncurses_mvinch()
ncurses_mvvline()
ncurses_mvwaddstr()
ncurses_napms()
ncurses_new_panel()
ncurses_newpad()
ncurses_newwin()
ncurses_nl()
ncurses_nocbreak()
ncurses_noecho()
ncurses_nonl()
ncurses_noqiflush()
ncurses_noraw()
ncurses_pair_content()
ncurses_panel_above()
ncurses_panel_below()
ncurses_panel_window()
ncurses_pnoutrefresh()
ncurses_prefresh()
ncurses_putp()
ncurses_qiflush()
ncurses_raw()
ncurses_refresh()
ncurses_replace_panel()
ncurses_reset_prog_mode()
ncurses_reset_shell_mode()
ncurses_resetty()
ncurses_savetty()
ncurses_scr_dump()
ncurses_scr_init()
ncurses_scr_restore()
ncurses_scr_set()
ncurses_scrl()
ncurses_show_panel()
ncurses_slk_attr()
ncurses_slk_attroff()
ncurses_slk_attron()
ncurses_slk_attrset()
ncurses_slk_clear()
ncurses_slk_color()
ncurses_slk_init()
ncurses_slk_noutrefresh()
ncurses_slk_refresh()
ncurses_slk_restore()
ncurses_slk_set()
ncurses_slk_touch()
ncurses_standend()
ncurses_standout()
ncurses_start_color()
ncurses_termattrs()
ncurses_termname()
ncurses_timeout()
ncurses_top_panel()
ncurses_typeahead()
ncurses_ungetch()
ncurses_ungetmouse()
ncurses_update_panels()
ncurses_use_default_colors()
ncurses_use_env()
ncurses_use_extended_names()
ncurses_vidattr()
ncurses_vline()
ncurses_waddch()
ncurses_waddstr()
ncurses_wattroff()
ncurses_wattron()
ncurses_wattrset()
ncurses_wborder()
ncurses_wclear()
ncurses_wcolor_set()
ncurses_werase()
ncurses_wgetch()
ncurses_whline()
ncurses_wmouse_trafo()
ncurses_wmove()
ncurses_wnoutrefresh()
ncurses_wrefresh()
ncurses_wstandend()
ncurses_wstandout()
ncurses_wvline()
next()
ngettext()
nl2br()
nl_langinfo()
notes_body()
notes_copy_db()
notes_create_db()
notes_create_note()
notes_drop_db()
notes_find_note()
notes_header_info()
notes_list_msgs()
notes_mark_read()
notes_mark_unread()
notes_nav_create()
notes_search()
notes_unread()
notes_version()
nsapi_request_headers()
nsapi_response_headers()
nsapi_virtual()
number_format()

O

ob_clean()
ob_end_clean()
ob_end_flush()
ob_flush()
ob_get_clean()
ob_get_contents()
ob_get_flush()
ob_get_length()
ob_get_level()
ob_get_status()
ob_gzhandler()
ob_iconv_handler()
ob_implicit_flush()
ob_list_handlers()
ob_start()
ob_tidyhandler()
ocibindbyname()
ocicancel()
ocicloselob()
ocicollappend()
ocicollassign()
ocicollassignelem()
ocicollgetelem()
ocicollmax()
ocicollsize()
ocicolltrim()
ocicolumnisnull()
ocicolumnname()
ocicolumnprecision()
ocicolumnscale()
ocicolumnsize()
ocicolumntype()
ocicolumntyperaw()
ocicommit()
ocidefinebyname()
ocierror()
ociexecute()
ocifetch()
ocifetchinto()
ocifetchstatement()
ocifreecollection()
ocifreecursor()
ocifreedesc()
ocifreestatement()
ociinternaldebug()
ociloadlob()
ocilogoff()
ocilogon()
ocinewcollection()
ocinewcursor()
ocinewdescriptor()
ocinlogon()
ocinumcols()
ociparse()
ociplogon()
ociresult()
ocirollback()
ocirowcount()
ocisavelob()
ocisavelobfile()
ociserverversion()
ocisetprefetch()
ocistatementtype()
ociwritelobtofile()
ociwritetemporarylob()
octdec()
odbc_autocommit()
odbc_binmode()
odbc_close()
odbc_close_all()
odbc_columnprivileges()
odbc_columns()
odbc_commit()
odbc_connect()
odbc_cursor()
odbc_data_source()
odbc_do()
odbc_error()
odbc_errormsg()
odbc_exec()
odbc_execute()
odbc_fetch_array()
odbc_fetch_into()
odbc_fetch_object()
odbc_fetch_row()
odbc_field_len()
odbc_field_name()
odbc_field_num()
odbc_field_precision()
odbc_field_scale()
odbc_field_type()
odbc_foreignkeys()
odbc_free_result()
odbc_gettypeinfo()
odbc_longreadlen()
odbc_next_result()
odbc_num_fields()
odbc_num_rows()
odbc_pconnect()
odbc_prepare()
odbc_primarykeys()
odbc_procedurecolumns()
odbc_procedures()
odbc_result()
odbc_result_all()
odbc_rollback()
odbc_setoption()
odbc_specialcolumns()
odbc_statistics()
odbc_tableprivileges()
odbc_tables()
opendir()
openlog()
openssl_csr_export()
openssl_csr_export_to_file()
openssl_csr_new()
openssl_csr_sign()
openssl_error_string()
openssl_free_key()
openssl_get_privatekey()
openssl_get_publickey()
openssl_open()
openssl_pkcs7_decrypt()
openssl_pkcs7_encrypt()
openssl_pkcs7_sign()
openssl_pkcs7_verify()
openssl_pkey_export()
openssl_pkey_export_to_file()
openssl_pkey_get_private()
openssl_pkey_get_public()
openssl_pkey_new()
openssl_private_decrypt()
openssl_private_encrypt()
openssl_public_decrypt()
openssl_public_encrypt()
openssl_seal()
openssl_sign()
openssl_verify()
openssl_x509_check_private_key()
openssl_x509_checkpurpose()
openssl_x509_export()
openssl_x509_export_to_file()
openssl_x509_free()
openssl_x509_parse()
openssl_x509_read()
ora_bind()
ora_close()
ora_columnname()
ora_columnsize()
ora_columntype()
ora_commit()
ora_commitoff()
ora_commiton()
ora_do()
ora_error()
ora_errorcode()
ora_exec()
ora_fetch()
ora_fetch_into()
ora_getcolumn()
ora_logoff()
ora_logon()
ora_numcols()
ora_numrows()
ora_open()
ora_parse()
ora_plogon()
ora_rollback()
ord()
output_add_rewrite_var()
output_reset_rewrite_vars()
overload()
ovrimos_close()
ovrimos_commit()
ovrimos_connect()
ovrimos_cursor()
ovrimos_exec()
ovrimos_execute()
ovrimos_fetch_into()
ovrimos_fetch_row()
ovrimos_field_len()
ovrimos_field_name()
ovrimos_field_num()
ovrimos_field_type()
ovrimos_free_result()
ovrimos_longreadlen()
ovrimos_num_fields()
ovrimos_num_rows()
ovrimos_prepare()
ovrimos_result()
ovrimos_result_all()
ovrimos_rollback()

P

pack()
parse_ini_file()
parse_str()
parse_url()
passthru()
pathinfo()
pattern modifiers()
pattern syntax()
pclose()
pcntl_exec()
pcntl_fork()
pcntl_signal()
pcntl_waitpid()
pcntl_wexitstatus()
pcntl_wifexited()
pcntl_wifsignaled()
pcntl_wifstopped()
pcntl_wstopsig()
pcntl_wtermsig()
pdf_add_annotation()
pdf_add_bookmark()
pdf_add_launchlink()
pdf_add_locallink()
pdf_add_note()
pdf_add_outline()
pdf_add_pdflink()
pdf_add_thumbnail()
pdf_add_weblink()
pdf_arc()
pdf_arcn()
pdf_attach_file()
pdf_begin_page()
pdf_begin_pattern()
pdf_begin_template()
pdf_circle()
pdf_clip()
pdf_close()
pdf_close_image()
pdf_close_pdi()
pdf_close_pdi_page()
pdf_closepath()
pdf_closepath_fill_stroke()
pdf_closepath_stroke()
pdf_concat()
pdf_continue_text()
pdf_curveto()
pdf_delete()
pdf_end_page()
pdf_end_pattern()
pdf_end_template()
pdf_endpath()
pdf_fill()
pdf_fill_stroke()
pdf_findfont()
pdf_get_buffer()
pdf_get_font()
pdf_get_fontname()
pdf_get_fontsize()
pdf_get_image_height()
pdf_get_image_width()
pdf_get_majorversion()
pdf_get_minorversion()
pdf_get_parameter()
pdf_get_pdi_parameter()
pdf_get_pdi_value()
pdf_get_value()
pdf_initgraphics()
pdf_lineto()
pdf_makespotcolor()
pdf_moveto()
pdf_new()
pdf_open()
pdf_open_ccitt()
pdf_open_file()
pdf_open_gif()
pdf_open_image()
pdf_open_image_file()
pdf_open_jpeg()
pdf_open_memory_image()
pdf_open_pdi()
pdf_open_pdi_page()
pdf_open_png()
pdf_open_tiff()
pdf_place_image()
pdf_place_pdi_page()
pdf_rect()
pdf_restore()
pdf_rotate()
pdf_save()
pdf_scale()
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_info()
pdf_set_info_author()
pdf_set_info_creator()
pdf_set_info_keywords()
pdf_set_info_subject()
pdf_set_info_title()
pdf_set_leading()
pdf_set_parameter()
pdf_set_text_matrix()
pdf_set_text_pos()
pdf_set_text_rendering()
pdf_set_text_rise()
pdf_set_value()
pdf_set_word_spacing()
pdf_setcolor()
pdf_setdash()
pdf_setflat()
pdf_setfont()
pdf_setgray()
pdf_setgray_fill()
pdf_setgray_stroke()
pdf_setlinecap()
pdf_setlinejoin()
pdf_setlinewidth()
pdf_setmatrix()
pdf_setmiterlimit()
pdf_setpolydash()
pdf_setrgbcolor()
pdf_setrgbcolor_fill()
pdf_setrgbcolor_stroke()
pdf_show()
pdf_show_boxed()
pdf_show_xy()
pdf_skew()
pdf_stringwidth()
pdf_stroke()
pdf_translate()
pfpro_cleanup()
pfpro_init()
pfpro_process()
pfpro_process_raw()
pfpro_version()
pfsockopen()
pg_affected_rows()
pg_cancel_query()
pg_client_encoding()
pg_close()
pg_connect()
pg_connection_busy()
pg_connection_reset()
pg_connection_status()
pg_convert()
pg_copy_from()
pg_copy_to()
pg_dbname()
pg_delete()
pg_end_copy()
pg_escape_bytea()
pg_escape_string()
pg_fetch_all()
pg_fetch_array()
pg_fetch_assoc()
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_free_result()
pg_get_notify()
pg_get_pid()
pg_get_result()
pg_host()
pg_insert()
pg_last_error()
pg_last_notice()
pg_last_oid()
pg_lo_close()
pg_lo_create()
pg_lo_export()
pg_lo_import()
pg_lo_open()
pg_lo_read()
pg_lo_read_all()
pg_lo_seek()
pg_lo_tell()
pg_lo_unlink()
pg_lo_write()
pg_meta_data()
pg_num_fields()
pg_num_rows()
pg_options()
pg_pconnect()
pg_ping()
pg_port()
pg_put_line()
pg_query()
pg_result_error()
pg_result_seek()
pg_result_status()
pg_select()
pg_send_query()
pg_set_client_encoding()
pg_trace()
pg_tty()
pg_unescape_bytea()
pg_untrace()
pg_update()
php_ini_scanned_files()
php_logo_guid()
php_sapi_name()
php_uname()
phpcredits()
phpinfo()
phpversion()
pi()
png2wbmp()
popen()
pos()
posix_ctermid()
posix_get_last_error()
posix_getcwd()
posix_getegid()
posix_geteuid()
posix_getgid()
posix_getgrgid()
posix_getgrnam()
posix_getgroups()
posix_getlogin()
posix_getpgid()
posix_getpgrp()
posix_getpid()
posix_getppid()
posix_getpwnam()
posix_getpwuid()
posix_getrlimit()
posix_getsid()
posix_getuid()
posix_isatty()
posix_kill()
posix_mkfifo()
posix_setegid()
posix_seteuid()
posix_setgid()
posix_setpgid()
posix_setsid()
posix_setuid()
posix_strerror()
posix_times()
posix_ttyname()
posix_uname()
pow()
preg_grep()
preg_match()
preg_match_all()
preg_quote()
preg_replace()
preg_replace_callback()
preg_split()
prev()
print()
print_r()
printer_abort()
printer_close()
printer_create_brush()
printer_create_dc()
printer_create_font()
printer_create_pen()
printer_delete_brush()
printer_delete_dc()
printer_delete_font()
printer_delete_pen()
printer_draw_bmp()
printer_draw_chord()
printer_draw_elipse()
printer_draw_line()
printer_draw_pie()
printer_draw_rectangle()
printer_draw_roundrect()
printer_draw_text()
printer_end_doc()
printer_end_page()
printer_get_option()
printer_list()
printer_logical_fontheight()
printer_open()
printer_select_brush()
printer_select_font()
printer_select_pen()
printer_set_option()
printer_start_doc()
printer_start_page()
printer_write()
printf()
proc_close()
proc_get_status()
proc_nice()
proc_open()
proc_terminate()
pspell_add_to_personal()
pspell_add_to_session()
pspell_check()
pspell_clear_session()
pspell_config_create()
pspell_config_ignore()
pspell_config_mode()
pspell_config_personal()
pspell_config_repl()
pspell_config_runtogether()
pspell_config_save_repl()
pspell_new()
pspell_new_config()
pspell_new_personal()
pspell_save_wordlist()
pspell_store_replacement()
pspell_suggest()
putenv()

S

scandir()
sem_acquire()
sem_get()
sem_release()
sem_remove()
serialize()
sesam_affected_rows()
sesam_commit()
sesam_connect()
sesam_diagnostic()
sesam_disconnect()
sesam_errormsg()
sesam_execimm()
sesam_fetch_array()
sesam_fetch_result()
sesam_fetch_row()
sesam_field_array()
sesam_field_name()
sesam_free_result()
sesam_num_fields()
sesam_query()
sesam_rollback()
sesam_seek_row()
sesam_settransaction()
session_cache_expire()
session_cache_limiter()
session_decode()
session_destroy()
session_encode()
session_get_cookie_params()
session_id()
session_is_registered()
session_module_name()
session_name()
session_regenerate_id()
session_register()
session_save_path()
session_set_cookie_params()
session_set_save_handler()
session_start()
session_unregister()
session_unset()
session_write_close()
set_error_handler()
set_file_buffer()
set_include_path()
set_magic_quotes_runtime()
set_time_limit()
setcookie()
setlocale()
settype()
sha1()
sha1_file()
shell_exec()
shm_attach()
shm_detach()
shm_get_var()
shm_put_var()
shm_remove()
shm_remove_var()
shmop_close()
shmop_delete()
shmop_open()
shmop_read()
shmop_size()
shmop_write()
show_source()
shuffle()
similar_text()
simplexml_element->asxml()
simplexml_element->attributes()
simplexml_element->children()
simplexml_element->xpath()
simplexml_load_dom()
simplexml_load_file()
simplexml_load_string()
sin()
sinh()
sizeof()
sleep()
snmp_get_quick_print()
snmp_set_quick_print()
snmpget()
snmprealwalk()
snmpset()
snmpwalk()
snmpwalkoid()
socket_accept()
socket_bind()
socket_clear_error()
socket_close()
socket_connect()
socket_create()
socket_create_listen()
socket_create_pair()
socket_get_option()
socket_get_status()
socket_getpeername()
socket_getsockname()
socket_iovec_add()
socket_iovec_alloc()
socket_iovec_delete()
socket_iovec_fetch()
socket_iovec_free()
socket_iovec_set()
socket_last_error()
socket_listen()
socket_read()
socket_readv()
socket_recv()
socket_recvfrom()
socket_recvmsg()
socket_select()
socket_send()
socket_sendmsg()
socket_sendto()
socket_set_block()
socket_set_blocking()
socket_set_nonblock()
socket_set_option()
socket_set_timeout()
socket_shutdown()
socket_strerror()
socket_write()
socket_writev()
sort()
soundex()
split()
spliti()
sprintf()
sql_regcase()
sqlite_array_query()
sqlite_busy_timeout()
sqlite_changes()
sqlite_close()
sqlite_column()
sqlite_create_aggregate()
sqlite_create_function()
sqlite_current()
sqlite_error_string()
sqlite_escape_string()
sqlite_fetch_array()
sqlite_fetch_single()
sqlite_fetch_string()
sqlite_field_name()
sqlite_has_more()
sqlite_last_error()
sqlite_last_insert_rowid()
sqlite_libencoding()
sqlite_libversion()
sqlite_next()
sqlite_num_fields()
sqlite_num_rows()
sqlite_open()
sqlite_popen()
sqlite_query()
sqlite_rewind()
sqlite_seek()
sqlite_udf_decode_binary()
sqlite_udf_encode_binary()
sqlite_unbuffered_query()
sqrt()
srand()
sscanf()
stat()
str_ireplace()
str_pad()
str_repeat()
str_replace()
str_rot13()
str_shuffle()
str_split()
str_word_count()
strcasecmp()
strchr()
strcmp()
strcoll()
strcspn()
stream_context_create()
stream_context_get_options()
stream_context_set_option()
stream_context_set_params()
stream_copy_to_stream()
stream_filter_append()
stream_filter_prepend()
stream_filter_register()
stream_get_contents()
stream_get_filters()
stream_get_line()
stream_get_meta_data()
stream_get_transports()
stream_get_wrappers()
stream_register_wrapper()
stream_select()
stream_set_blocking()
stream_set_timeout()
stream_set_write_buffer()
stream_socket_accept()
stream_socket_client()
stream_socket_get_name()
stream_socket_recvfrom()
stream_socket_sendto()
stream_socket_server()
stream_wrapper_register()
strftime()
strip_tags()
stripcslashes()
stripos()
stripslashes()
stristr()
strlen()
strnatcasecmp()
strnatcmp()
strncasecmp()
strncmp()
strpos()
strrchr()
strrev()
strripos()
strrpos()
strspn()
strstr()
strtok()
strtolower()
strtotime()
strtoupper()
strtr()
strval()
substr()
substr_compare()
substr_count()
substr_replace()
swf_actiongeturl()
swf_actiongotoframe()
swf_actiongotolabel()
swf_actionnextframe()
swf_actionplay()
swf_actionprevframe()
swf_actionsettarget()
swf_actionstop()
swf_actiontogglequality()
swf_actionwaitforframe()
swf_addbuttonrecord()
swf_addcolor()
swf_closefile()
swf_definebitmap()
swf_definefont()
swf_defineline()
swf_definepoly()
swf_definerect()
swf_definetext()
swf_endbutton()
swf_enddoaction()
swf_endshape()
swf_endsymbol()
swf_fontsize()
swf_fontslant()
swf_fonttracking()
swf_getbitmapinfo()
swf_getfontinfo()
swf_getframe()
swf_labelframe()
swf_lookat()
swf_modifyobject()
swf_mulcolor()
swf_nextid()
swf_oncondition()
swf_openfile()
swf_ortho()
swf_ortho2()
swf_perspective()
swf_placeobject()
swf_polarview()
swf_popmatrix()
swf_posround()
swf_pushmatrix()
swf_removeobject()
swf_rotate()
swf_scale()
swf_setfont()
swf_setframe()
swf_shapearc()
swf_shapecurveto()
swf_shapecurveto3()
swf_shapefillbitmapclip()
swf_shapefillbitmaptile()
swf_shapefilloff()
swf_shapefillsolid()
swf_shapelinesolid()
swf_shapelineto()
swf_shapemoveto()
swf_showframe()
swf_startbutton()
swf_startdoaction()
swf_startshape()
swf_startsymbol()
swf_textwidth()
swf_translate()
swf_viewport()
swfaction()
swfbitmap()
swfbitmap->getheight()
swfbitmap->getwidth()
swfbutton()
swfbutton->addaction()
swfbutton->addshape()
swfbutton->setaction()
swfbutton->setdown()
swfbutton->sethit()
swfbutton->setover()
swfbutton->setup()
swfbutton_keypress()
swfdisplayitem()
swfdisplayitem->addcolor()
swfdisplayitem->move()
swfdisplayitem->moveto()
swfdisplayitem->multcolor()
swfdisplayitem->remove()
swfdisplayitem->rotate()
swfdisplayitem->rotateto()
swfdisplayitem->scale()
swfdisplayitem->scaleto()
swfdisplayitem->setdepth()
swfdisplayitem->setname()
swfdisplayitem->setratio()
swfdisplayitem->skewx()
swfdisplayitem->skewxto()
swfdisplayitem->skewy()
swfdisplayitem->skewyto()
swffill()
swffill->moveto()
swffill->rotateto()
swffill->scaleto()
swffill->skewxto()
swffill->skewyto()
swffont()
swffont->getwidth()
swfgradient()
swfgradient->addentry()
swfmorph()
swfmorph->getshape1()
swfmorph->getshape2()
swfmovie()
swfmovie->add()
swfmovie->nextframe()
swfmovie->output()
swfmovie->remove()
swfmovie->save()
swfmovie->setbackground()
swfmovie->setdimension()
swfmovie->setframes()
swfmovie->setrate()
swfmovie->streammp3()
swfshape()
swfshape->addfill()
swfshape->drawcurve()
swfshape->drawcurveto()
swfshape->drawline()
swfshape->drawlineto()
swfshape->movepen()
swfshape->movepento()
swfshape->setleftfill()
swfshape->setline()
swfshape->setrightfill()
swfsprite()
swfsprite->add()
swfsprite->nextframe()
swfsprite->remove()
swfsprite->setframes()
swftext()
swftext->addstring()
swftext->getwidth()
swftext->moveto()
swftext->setcolor()
swftext->setfont()
swftext->setheight()
swftext->setspacing()
swftextfield()
swftextfield->addstring()
swftextfield->align()
swftextfield->setbounds()
swftextfield->setcolor()
swftextfield->setfont()
swftextfield->setheight()
swftextfield->setindentation()
swftextfield->setleftmargin()
swftextfield->setlinespacing()
swftextfield->setmargins()
swftextfield->setname()
swftextfield->setrightmargin()
sybase_affected_rows()
sybase_close()
sybase_connect()
sybase_data_seek()
sybase_deadlock_retry_count()
sybase_fetch_array()
sybase_fetch_assoc()
sybase_fetch_field()
sybase_fetch_object()
sybase_fetch_row()
sybase_field_seek()
sybase_free_result()
sybase_get_last_message()
sybase_min_client_severity()
sybase_min_error_severity()
sybase_min_message_severity()
sybase_min_server_severity()
sybase_num_fields()
sybase_num_rows()
sybase_pconnect()
sybase_query()
sybase_result()
sybase_select_db()
sybase_set_message_handler()
sybase_unbuffered_query()
symlink()
syslog()
system()