PHP Manual Stig S¾ther Bakken Alexander Aulbach Egon Schmid Jim Winstead Lars Torben Wilson Rasmus Lerdorf Zeev Suraski Edited by Stig S¾ther Bakken Copyright © 1997, 1998, 1999 by the PHP Documentation Group Copyright This manual is © Copyright 1997, 1998, 1999 the PHP Documentation Group. The members of this group are listed on the front page of this manual. This manual can be redistributed under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. ------------------------------------------------------------------------ ------------------------------------------------------------------------ Dedication Date: 1999-08-07 Table of Contents Preface About this Manual I. Getting Started 1. Introduction 2. Installation 3. Configuration 4. Security II. Language Reference 5. Basic syntax 6. Types 7. Variables 8. Constants 9. Expressions 10. Operators 11. Control Structures 12. Functions 13. Classes and Objects III. Features 14. Error handling 15. Creating GIF images 16. HTTP authentication with PHP 17. Cookies 18. Handling file uploads 19. Using remote files 20. Connection handling 21. Persistent database connections IV. Function Reference I. Adabas D functions II. Apache-specific functions III. Array functions IV. Aspell functions V. Arbitrary precision mathematics functions VI. Calendar functions VII. ClibPDF functions VIII. Date and Time functions IX. Database (dbm-style) abstraction layer functions X. dBase functions XI. dbm functions XII. Directory functions XIII. Dynamic Loading functions XIV. Program Execution functions XV. Forms Data Format functions XVI. filePro functions XVII. Filesystem functions XVIII. HTTP functions XIX. Hyperwave functions XX. ICAP functions XXI. Image functions XXII. IMAP functions XXIII. PHP options & information XXIV. Informix functions XXV. InterBase functions XXVI. LDAP functions XXVII. Mail functions XXVIII. Mathematical functions XXIX. Encryption functions XXX. Hash functions XXXI. Miscellaneous functions XXXII. mSQL functions XXXIII. Microsoft SQL Server functions XXXIV. MySQL functions XXXV. Sybase functions XXXVI. Network functions XXXVII. NIS functions XXXVIII. ODBC functions XXXIX. Oracle 8 functions XL. Oracle functions XLI. Perl-compatible Regular Expression functions XLII. PDF functions XLIII. PostgreSQL functions XLIV. Regular expression functions XLV. Semaphore and shared memory functions XLVI. Session handling functions XLVII. Solid functions XLVIII. SNMP functions XLIX. String functions L. URL functions LI. Variable functions LII. Vmailmgr functions LIII. WDDX functions LIV. Compression functions LV. XML parser functions V. Appendixes A. Migrating from PHP/FI 2.0 to PHP 3.0 B. PHP development C. The PHP Debugger ------------------------------------------------------------------------ Preface 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. ------------------------------------------------------------------------ About this Manual This manual is written in SGML using the DocBook DTD, using DSSSL (Document Style and Semantics Specification Language) for formatting. The tools used for formatting HTML, TeX and RTF versions are Jade, written by James Clark and The Modular DocBook Stylesheets written by Norman Walsh. PHP's documentation framework was assembled by Stig S¾ther Bakken. I. Getting Started Table of Contents 1. Introduction 2. Installation 3. Configuration 4. Security ------------------------------------------------------------------------ Chapter 1. Introduction ------------------------------------------------------------------------ What is PHP? PHP is a server-side HTML-embedded scripting language. Simple answer, but what does that mean? An example: Example 1-1. An introductory example
The header above will say 'This is an example'. You should be careful not to nest 'C' style comments, which can happen when commenting out large blocks. ------------------------------------------------------------------------ Chapter 6. Types PHP supports the following types: * integer * floating-point numbers * string * array * object The type of a variable is usually not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which that variable is used. If you would like to force a variable to be converted to a certain type, you may either cast the variable or use the settype() function on it. Note that a variable may behave in different manners in certain situations, depending on what type it is a the time. For more information, see the section on Type Juggling. ------------------------------------------------------------------------ Integers Integers can be specified using any of the following syntaxes: $a = 1234; # decimal number $a = -123; # a negative number $a = 0123; # octal number (equivalent to 83 decimal) $a = 0x12; # hexadecimal number (equivalent to 18 decimal) ------------------------------------------------------------------------ Floating point numbers Floating point numbers ("doubles") can be specified using any of the following syntaxes: $a = 1.234; $a = 1.2e3; ------------------------------------------------------------------------ Strings Strings can be specified using one of two sets of delimiters. If the string is enclosed in double-quotes ("), variables within the string will be expanded (subject to some parsing limitations). As in C and Perl, the backslash ("\") character can be used in specifying special characters: Table 6-1. Escaped characters sequencemeaning \n newline \r carriage \t horizontal tab \\ backslash \$ dollar sign \" double-quote You can escape any other character, but a warning will be issued at the highest warning level. The second way to delimit a string uses the single-quote ("'") character, which does not do any variable expansion or backslash processing (except for "\\" and "\'" so you can insert backslashes and single-quotes in a singly-quoted string). ------------------------------------------------------------------------ String conversion When a string is evaluated as a numeric value, the resulting value and type are determined as follows. The string will evaluate as a double if it contains any of the characters '.', 'e', or 'E'. Otherwise, it will evaluate as an integer. The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero). Valid numeric data is an optional sign, followed by one or more digits (optionally containing a decimal point), followed by an optional exponent. The exponent is an 'e' or 'E' followed by one or more digits. When the first expression is a string, the type of the variable will depend on the second expression. $foo = 1 + "10.5"; // $foo is double (11.5) $foo = 1 + "-1.3e3"; // $foo is double (-1299) $foo = 1 + "bob-1.3e3"; // $foo is integer (1) $foo = 1 + "bob3"; // $foo is integer (1) $foo = 1 + "10 Small Pigs"; // $foo is integer (11) $foo = 1 + "10 Little Piggies"; // $foo is integer (11) $foo = "10.0 pigs " + 1; // $foo is integer (11) $foo = "10.0 pigs " + 1.0; // $foo is double (11) For more information on this conversion, see the Unix manual page for strtod(3). ------------------------------------------------------------------------ Arrays Arrays actually act like both hash tables (associative arrays) and indexed arrays (vectors). ------------------------------------------------------------------------ Single Dimension Arrays PHP supports both scalar and associative arrays. In fact, there is no difference between the two. You can create an array using the list() or array() functions, or you can explicitly set each array element value. $a[0] = "abc"; $a[1] = "def"; $b["foo"] = 13; You can also create an array by simply adding values to the array. $a[] = "hello"; // $a[2] == "hello" $a[] = "world"; // $a[3] == "world" Arrays may be sorted using the asort(), arsort(), ksort(), rsort(), sort(), uasort(), usort(), and uksort() functions depending on the type of sort you want. You can count the number of items in an array using the count() function. You can traverse an array using next() and prev() functions. Another common way to traverse an array is to use the each() function. ------------------------------------------------------------------------ Multi-Dimensional Arrays Multi-dimensional arrays are actually pretty simple. For each dimension of the array, you add another [key] value to the end: $a[1] = $f; # one dimensional examples $a["foo"] = $f; $a[1][0] = $f; # two dimensional $a["foo"][2] = $f; # (you can mix numeric and associative indices) $a[3]["bar"] = $f; # (you can mix numeric and associative indices) $a["foo"][4]["bar"][0] = $f; # four dimensional! You can "fill up" multi-dimensional arrays in many ways, but the trickiest one to understand is how to use the array() command for associative arrays. These two snippets of code fill up the one-dimensional array in the same way: # Example 1: $a["color"] = "red"; $a["taste"] = "sweet"; $a["shape"] = "round"; $a["name"] = "apple"; $a[3] = 4; # Example 2: $a = array( "color" => "red", "taste" => "sweet", "shape" => "round", "name" => "apple", 3 => 4 ); The array() function can be nested for multi-dimensional arrays: $a = array( "apple" => array( "color" => "red", "taste" => "sweet", "shape" => "round" ), "orange" => array( "color" => "orange", "taste" => "sweet", "shape" => "round" ), "banana" => array( "color" => "yellow", "taste" => "paste-y", "shape" => "banana-shaped" ) ); echo $a["apple"]["taste"]; # will output "sweet" ?> ------------------------------------------------------------------------ Objects Object Initialization To initialize an object, you use the new statement to instantiate the object to a variable. class foo { function do_foo () { echo "Doing foo."; } } $bar = new foo; $bar -> do_foo (); ------------------------------------------------------------------------ Type juggling PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which that variable is used. That is to say, if you assign a string value to variable var, var becomes a string. If you then assign an integer value to var, it becomes an integer. An example of PHP's automatic type conversion is the addition operator '+'. If any of the operands is a double, then all operands are evaluated as doubles, and the result will be a double. Otherwise, the operands will be interpreted as integers, and the result will also be an integer. Note that this does NOT change the types of the operands themselves; the only change is in how the operands are evaluated. $foo = "0"; // $foo is string (ASCII 48) $foo++; // $foo is the string "1" (ASCII 49) $foo += 1; // $foo is now an integer (2) $foo = $foo + 1.3; // $foo is now a double (3.3) $foo = 5 + "10 Little Piggies"; // $foo is integer (15) $foo = 5 + "10 Small Pigs"; // $foo is integer (15) If the last two examples above seem odd, see String conversion. If you wish to force a variable to be evaluated as a certain type, see the section on Type casting. If you wish to change the type of a variable, see settype(). ------------------------------------------------------------------------ Type casting Type casting in PHP works much as it does in C: the name of the desired type is written in parentheses before the variable which is to be cast. $foo = 10; // $foo is an integer $bar = (double) $foo; // $bar is a double The casts allowed are: * (int), (integer) - cast to integer * (real), (double), (float) - cast to double * (string) - cast to string * (array) - cast to array * (object) - cast to object Note that tabs and spaces are allowed inside the parentheses, so the following are functionally equivalent: $foo = (int) $bar; $foo = ( int ) $bar; ------------------------------------------------------------------------ Chapter 7. Variables Variable scope The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single scope. However, within user-defined functions a local function scope is introduced. Any variable used inside a function is by default limited to the local function scope. For example: $a = 1; /* global scope */ Function Test () { echo $a; /* reference to local scope variable */ } Test (); This script will not produce any output because the echo statement refers to a local version of the $a variable, and it has not been assigned a value within this scope. You may notice that this is a little bit different from the C language in that global variables in C are automatically available to functions unless specifically overridden by a local definition. This can cause some problems in that people may inadvertently change a global variable. In PHP global variables must be declared global inside a function if they are going to be used in that function. An example: $a = 1; $b = 2; Function Sum () { global $a, $b; $b = $a + $b; } Sum (); echo $b; The above script will output "3". By declaring $a and $b global within the function, all references to either variable will refer to the global version. There is no limit to the number of global variables that can be manipulated by a function. A second way to access variables from the global scope is to use the special PHP-defined $GLOBALS array. The previous example can be rewritten as: $a = 1; $b = 2; Function Sum () { $GLOBALS["b"] = $GLOBALS["a"] + $GLOBALS["b"]; } Sum (); echo $b; The $GLOBALS array is an associative array with the name of the global variable being the key and the contents of that variable being the value of the array element. Another important feature of variable scoping is the static variable. A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope. Consider the following example: Function Test () { $a = 0; echo $a; $a++; } This function is quite useless since every time it is called it sets $a to 0 and prints "0". The $a++ which increments the variable serves no purpose since as soon as the function exits the $a variable disappears. To make a useful counting function which will not lose track of the current count, the $a variable is declared static: Function Test () { static $a = 0; echo $a; $a++; } Now, every time the Test() function is called it will print the value of $a and increment it. Static variables are also essential when functions are called recursively. A recursive function is one which calls itself. Care must be taken when writing a recursive function because it is possible to make it recurse indefinitely. You must make sure you have an adequate way of terminating the recursion. The following simple function recursively counts to 10: Function Test () { static $count = 0; $count++; echo $count; if ($count < 10) { Test (); } $count--; } ------------------------------------------------------------------------ Variable variables Sometimes it is convenient to be able to have variable variable names. That is, a variable name which can be set and used dynamically. A normal variable is set with a statement such as: $a = "hello"; A variable variable takes the value of a variable and treats that as the name of a variable. In the above example, hello, can be used as the name of a variable by using two dollar signs. ie. $$a = "world"; At this point two variables have been defined and stored in the PHP symbol tree: $a with contents "hello" and $hello with contents "world". Therefore, this statement: echo "$a ${$a}"; produces the exact same output as: echo "$a $hello"; ie. they both produce: hello world. In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$a[1] then the parser needs to know if you meant to use $a[1] as a variable, or if you wanted $$a as the variable and then the [1] index from that variable. The syntax for resolving this ambiguity is: ${$a[1]} for the first case and ${$a}[1] for the second. ------------------------------------------------------------------------ Variables from outside PHP HTML Forms (GET and POST) When a form is submitted to a PHP script, any variables from that form will be automatically made available to the script by PHP. For instance, consider the following form: Example 7-1. Simple form variable
When submitted, PHP will create the variable $name, which will will contain whatever what entered into the Name: field on the form. PHP also understands arrays in the context of form variables, but only in one dimension. You may, for example, group related variables together, or use this feature to retrieve values from a multiple select input: Example 7-2. More complex form variables If PHP's track_vars feature is turned on, either by the track_vars configuration setting or the directive, then variables submitted via the POST or GET methods will also be found in the global associative arrays $HTTP_POST_VARS and $HTTP_GET_VARS as appropriate. ------------------------------------------------------------------------ IMAGE SUBMIT variable names When submitting a form, it is possible to use an image instead of the standard submit button with a tag like: When the user clicks somewhere on the image, the accompanying form will be transmitted to the server with two additional variables, sub_x and sub_y. These contain the coordinates of the user click within the image. The experienced may note that the actual variable names sent by the browser contains a period rather than an underscore, but PHP converts the period to an underscore automatically. ------------------------------------------------------------------------ HTTP Cookies PHP transparently supports HTTP cookies as defined by Netscape's Spec. Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users. You can set cookies using the SetCookie() function. Cookies are part of the HTTP header, so the SetCookie function must be called before any output is sent to the browser. This is the same restriction as for the Header() function. Any cookies sent to you from the client will automatically be turned into a PHP variable just like GET and POST method data. If you wish to assign multiple values to a single cookie, just add [] to the cookie name. For example: SetCookie ("MyCookie[]", "Testing", time()+3600); Note that a cookie will replace a previous cookie by the same name in your browser unless the path or domain is different. So, for a shopping cart application you may want to keep a counter and pass this along. i.e. Example 7-3. SetCookie Example $Count++; SetCookie ("Count", $Count, time()+3600); SetCookie ("Cart[$Count]", $item, time()+3600); ------------------------------------------------------------------------ Environment variables PHP automatically makes environment variables available as normal PHP variables. echo $HOME; /* Shows the HOME environment variable, if set. */ Since information coming in via GET, POST and Cookie mechanisms also automatically create PHP variables, it is sometimes best to explicitly read a variable from the environment in order to make sure that you are getting the right version. The getenv() function can be used for this. You can also set an environment variable with the putenv() function. ------------------------------------------------------------------------ Determining variable types Because PHP determines the types of variables and converts them (generally) as needed, it is not always obvious what type a given variable is at any one time. PHP includes several functions which find out what type a variable is. They are gettype(), is_long(), is_double(), is_string(), is_array(), and is_object(). ------------------------------------------------------------------------ Chapter 8. Constants PHP defines several constants and provides a mechanism for defining more at run-time. Constants are much like variables, save for the two facts that constants must be defined using the define() function, and that they cannot later be redefined to another value. The predefined constants (always available) are: __FILE__ The name of the script file presently being parsed. If used within a file which has been included or required, then the name of the included file is given, and not the name of the parent file. __LINE__ The number of the line within the current script file which is being parsed. If used within a file which has been included or required, then the position within the included file is given. PHP_VERSION The string representation of the version of the PHP parser presently in use; e.g. '3.0.8-dev'. PHP_OS The name of the operating system on which the PHP parser is executing; e.g. 'Linux'. TRUE A true value. FALSE A false value. E_ERROR Denotes an error other than a parsing error from which recovery is not possible. E_WARNING Denotes a condition where PHP knows something is wrong, but will continue anyway; these can be caught by the script itself. An example would be an invalid regexp in ereg(). E_PARSE The parser choked on invalid syntax in the script file. Recovery is not possible. E_NOTICE Something happened which may or may not be an error. Execution continues. Examples include using an unquoted string as a hash index, or accessing a variable which has not been set. The E_* constants are typically used with the error_reporting() functionÊfor setting the error reporting level. You can define additional constants using the define() function. Note that these are constants, not C-style macros; only valid scalar data may be represented by a constant. Example 8-1. Defining Constants Example 8-2. Using __FILE__ and __LINE__ ------------------------------------------------------------------------ Chapter 9. Expressions Expressions are the most important building stones of PHP. In PHP, almost anything you write is an expression. The simplest yet most accurate way to define an expression is "anything that has a value". The most basic forms of expressions are constants and variables. When you type "$a = 5", you're assigning '5' into $a. '5', obviously, has the value 5, or in other words '5' is an expression with the value of 5 (in this case, '5' is an integer constant). After this assignment, you'd expect $a's value to be 5 as well, so if you wrote $b = $a, you'd expect it to behave just as if you wrote $b = 5. In other words, $a is an expression with the value of 5 as well. If everything works right, this is exactly what will happen. Slightly more complex examples for expressions are functions. For instance, consider the following function: function foo () { return 5; } Assuming you're familiar with the concept of functions (if you're not, take a look at the chapter about functions), you'd assume that typing $c = foo() is essentially just like writing $c = 5, and you're right. Functions are expressions with the value of their return value. Since foo() returns 5, the value of the expression 'foo()' is 5. Usually functions don't just return a static value but compute something. Of course, values in PHP don't have to be integers, and very often they aren't. PHP supports three scalar value types: integer values, floating point values and string values (scalar values are values that you can't 'break' into smaller pieces, unlike arrays, for instance). PHP also supports two composite (non-scalar) types: arrays and objects. Each of these value types can be assigned into variables or returned from functions. So far, users of PHP/FI 2 shouldn't feel any change. However, PHP takes expressions much further, in the same way many other languages do. PHP is an expression-oriented language, in the sense that almost everything is an expression. Consider the example we've already dealt with, '$a = 5'. It's easy to see that there are two values involved here, the value of the integer constant '5', and the value of $a which is being updated to 5 as well. But the truth is that there's one additional value involved here, and that's the value of the assignment itself. The assignment itself evaluates to the assigned value, in this case 5. In practice, it means that '$a = 5', regardless of what it does, is an expression with the value 5. Thus, writing something like '$b = ($a = 5)' is like writing '$a = 5; $b = 5;' (a semicolon marks the end of a statement). Since assignments are parsed in a right to left order, you can also write '$b = $a = 5'. Another good example of expression orientation is pre- and post-increment and decrement. Users of PHP/FI 2 and many other languages may be familiar with the notation of variable++ and variable--. These are increment and decrement operators. In PHP/FI 2, the statement '$a++' has no value (is not an expression), and thus you can't assign it or use it in any way. PHP enhances the increment/decrement capabilities by making these expressions as well, like in C. In PHP, like in C, there are two types of increment - pre-increment and post-increment. Both pre-increment and post-increment essentially increment the variable, and the effect on the variable is idential. The difference is with the value of the increment expression. Pre-increment, which is written '++$variable', evaluates to the incremented value (PHP increments the variable before reading its value, thus the name 'pre-increment'). Post-increment, which is written '$variable++' evaluates to the original value of $variable, before it was incremented (PHP increments the variable after reading its value, thus the name 'post-increment'). A very common type of expressions are comparison expressions. These expressions evaluate to either 0 or 1, meaning FALSE or TRUE (respectively). PHP supports > (bigger than), >= (bigger than or equal to), == (equal), != (not equal), < (smaller than) and <= (smaller than or equal to). These expressions are most commonly used inside conditional execution, such as if statements. The last example of expressions we'll deal with here is combined operator-assignment expressions. You already know that if you want to increment $a by 1, you can simply write '$a++' or '++$a'. But what if you want to add more than one to it, for instance 3? You could write '$a++' multiple times, but this is obviously not a very efficient or comfortable way. A much more common practice is to write '$a = $a + 3'. '$a + 3' evaluates to the value of $a plus 3, and is assigned back into $a, which results in incrementing $a by 3. In PHP, as in several other languages like C, you can write this in a shorter way, which with time would become clearer and quicker to understand as well. Adding 3 to the current value of $a can be written '$a += 3'. This means exactly "take the value of $a, add 3 to it, and assign it back into $a". In addition to being shorter and clearer, this also results in faster execution. The value of '$a += 3', like the value of a regular assignment, is the assigned value. Notice that it is NOT 3, but the combined value of $a plus 3 (this is the value that's assigned into $a). Any two-place operator can be used in this operator-assignment mode, for example '$a -= 5' (subtract 5 from the value of $a), '$b *= 7' (multiply the value of $b by 7), etc. There is one more expression that may seem odd if you haven't seen it in other languages, the ternary conditional operator: $first ? $second : $third If the value of the first subexpression is true (non-zero), then it the second subexpression is evaluated, and that is the result of the conditional expression. Otherwise, the third subexpression is evaluated, and that is the value. The following example should help you understand pre- and post-increment and expressions in general a bit better: function double($i) { return $i*2; } $b = $a = 5; /* assign the value five into the variable $a and $b */ $c = $a++; /* post-increment, assign original value of $a (5) to $c */ $e = $d = ++$b; /* pre-increment, assign the incremented value of $b (6) to $d and $e */ /* at this point, both $d and $e are equal to 6 */ $f = double($d++); /* assign twice the value of $d before the increment, 2*6 = 12 to $f */ $g = double(++$e); /* assign twice the value of $e after the increment, 2*7 = 14 to $g */ $h = $g += 10; /* first, $g is incremented by 10 and ends with the value of 24. the value of the assignment (24) is then assigned into $h, and $h ends with the value of 24 as well. */ In the beginning of the chapter we said that we'll be describing the various statement types, and as promised, expressions can be statements. However, not every expression is a statement. In this case, a statement has the form of 'expr' ';' that is, an expression followed by a semicolon. In '$b=$a=5;', $a=5 is a valid expression, but it's not a statement by itself. '$b=$a=5;' however is a valid statement. One last thing worth mentioning is the truth value of expressions. In many events, mainly in conditional execution and loops, you're not interested in the specific value of the expression, but only care about whether it means TRUE or FALSE (PHP doesn't have a dedicated boolean type). The truth value of expressions in PHP is calculated in a similar way to perl. Any numeric non-zero numeric value is TRUE, zero is FALSE. Be sure to note that negative values are non-zero and are thus considered TRUE! The empty string and the string "0" are FALSE; all other strings are TRUE. With non-scalar values (arrays and objects) - if the value contains no elements it's considered FALSE, otherwise it's considered TRUE. PHP provides a full and powerful implementation of expressions, and documenting it entirely goes beyond the scope of this manual. The above examples should give you a good idea about what expressions are and how you can construct useful expressions. Throughout the rest of this manual we'll write expr to indicate any valid PHP expression. ------------------------------------------------------------------------ Chapter 10. Operators ------------------------------------------------------------------------ Arithmetic Operators Remember basic arithmetic from school? These work just like those. Table 10-1. Arithmetic Operators examplename result $a + $bAddition Sum of $a and $b. $a - $bSubtraction Remainder of $b subtracted from $a. $a * $bMultiplication Product of $a and $b. $a / $bDivision Dividend of $a and $b. $a % $bModulus Remainder of $a divided by $b. ------------------------------------------------------------------------ String Operators There is only really one string operator -- the concatenation operator ("."). $a = "Hello "; $b = $a . "World!"; // now $b = "Hello World!" ------------------------------------------------------------------------ Assignment Operators The basic assignment operator is "=". Your first inclination might be to think of this as "equal to". Don't. It really means that the the left operand gets set to the value of the expression on the rights (that is, "gets set to"). The value of an assignment expression is the value assigned. That is, the value of "$a = 3" is 3. This allows you to do some tricky things: $a = ($b = 4) + 5; // $a is equal to 9 now, and $b has been set to 4. In addition to the basic assignment operator, there are "combined operators" for all of the binary arithmetic and string operators that allow you to use a value in an expression and then set its value to the result of that expression. For example: $a = 3; $a += 5; // sets $a to 8, as if we had said: $a = $a + 5; $b = "Hello "; $b .= "There!"; // sets $b to "Hello There!", just like $b = $b . "There!"; ------------------------------------------------------------------------ Bitwise Operators Bitwise operators allow you to turn specific bits within an integer on or off. Table 10-2. Bitwise Operators example name result $a & $b And Bits that are set in both $a and $b are set. $a | $b Or Bits that are set in either $a or $b are set. $a ^ $b Xor Bits that are set in $a or $b but not both are set. ~ $a Not Bits that are set in $a are not set, and vice versa. $a << $bShift left Shift the bits of $a $b steps to the left (each step means "multiply by two") $a >> $bShift right Shift the bits of $a $b steps to the right (each step means "divide by two") ------------------------------------------------------------------------ Logical Operators Table 10-3. Logical Operators example name result $a and $bAnd True of both $a and $b are true. $a or $b Or True if either $a or $b is true. $a xor $bOr True if either $a or $b is true, but not both. ! $a Not True if $a is not true. $a && $b And True of both $a and $b are true. $a || $b Or True if either $a or $b is true. The reason for the two different variations of "and" and "or" operators is that they operate at different precedences. (See below.) ------------------------------------------------------------------------ Comparison Operators Comparison operators, as their name imply, allow you to compare two values. Table 10-4. Comparson Operators example name result $a == $bEqual True if $a is equal to $b. $a != $bNot equal True if $a is not equal to $b. $a < $b Less than True if $a is strictly less than $b. $a > $b Greater than True if $a is strictly greater than $b. $a <= $bLess than or equal to True if $a is less than or equal to $b. $a >= $bGreater than or equal to True if $a is greater than or equal to $b. Another conditional operator is the "?:" (or trinary) operator, which operates as in C and many other languages. (expr1) ? (expr2) : (expr3); This expression returns to expr2 if expr1 evalutes to true, and expr3 if expr1 evaluates to false. ------------------------------------------------------------------------ Operator Precedence The precedence of an operator specifies how "tightly" it binds two expressions together. For example, in the expression 1 + 5 * 3, the answer is 16 and not 18 because the multiplication ("*") operator has a higher precedence than the addition ("+") operator. The following table lists the precedence of operators with the lowest-precedence operators listed first. Table 10-5. Operator Precedence Associativity Operators left , left or left xor left and right print left = += -= *= /= .= %= &= != ~= <<= >>= left ? : left || left && left | left ^ left & non-associative== != non-associative< <= > >= left << >> left + - . left * / % right ! ~ ++ -- (int) (double) (string) (array) (object) @ right [ non-associativenew ------------------------------------------------------------------------ Chapter 11. Control Structures Any PHP script is built out of a series of statements. A statement can be an assignment, a function call, a loop, a conditional statement of even a statement that does nothing (an empty statement). Statements usually end with a semicolon. In addition, statements can be grouped into a statement-group by encapsulating a group of statements with curly braces. A statement-group is a statement by itself as well. The various statement types are described in this chapter. ------------------------------------------------------------------------ if The if construct is one of the most important features of many languages, PHP included. It allows for conditional execution of code fragments. PHP features an if structure that is similar to that of C: if (expr) statement As described in the section about expressions, expr is evaluated to its truth value. If expr evaluates to TRUE, PHP will execute statement, and if it evaluates to FALSE - it'll ignore it. The following example would display a is bigger than b if $a is bigger than $b: if ($a > $b) print "a is bigger than b"; Often you'd want to have more than one statement to be executed conditionally. Of course, there's no need to wrap each statement with an if clause. Instead, you can group several statements into a statement group. For example, this code would display a is bigger than b if $a is bigger than $b, and would then assign the value of $a into $b: if ($a > $b) { print "a is bigger than b"; $b = $a; } If statements can be nested indefinitely within other if statements, which provides you with complete flexibility for conditional execution of the various parts of your program. ------------------------------------------------------------------------ else Often you'd want to execute a statement if a certain condition is met, and a different statement if the condition is not met. This is what else is for. else extends an if statement to execute a statement in case the expression in the if statement evaluates to FALSE. For example, the following code would display a is bigger than b if $a is bigger than $b, and a is NOT bigger than b otherwise: if ($a > $b) { print "a is bigger than b"; } else { print "a is NOT bigger than b"; } The else statement is only executed if the if expression evaluated to FALSE, and if there were any elseif expressions - only if they evaluated to FALSE as well (see below). ------------------------------------------------------------------------ elseif elseif, as its name suggests, is a combination of if and else. Like else, it extends an if statement to execute a different statement in case the original if expression evaluates to FALSE. However, unlike else, it will execute that alternative expression only if the elseif conditional expression evaluates to TRUE. For example, the following code would display a is bigger than b, a equal to b or a is smaller than b: if ($a > $b) { print "a is bigger than b"; } elseif ($a == $b) { print "a is equal to b"; } else { print "a is smaller than b"; } There may be several elseifs within the same if statement. The first elseif expression (if any) that evaluates to true would be executed. In PHP, you can also write 'else if' (in two words) and the behavior would be identical to the one of 'elseif' (in a single word). The syntactic meaning is slightly different (if you're familiar with C, this is the same behavior) but the bottom line is that both would result in exactly the same behavior. The elseif statement is only executed if the preceding if expression and any preceding elseif expressions evaluated to FALSE, and the current elseif expression evaluated to TRUE. ------------------------------------------------------------------------ Alternative syntax for if structures: if(): ... endif; PHP offers a different way to group statements within an if statement. This is most commonly used when you nest HTML blocks inside if statements, but can be used anywhere. Instead of using curly braces, if (expr) should be followed by a colon, the list of one or more statements, and end with endif;. Consider the following example: A = 5 In the above example, the HTML block "A = 5" is nested within an if statement written in the alternative syntax. The HTML block would be displayed only if $a is equal to 5. The alternative syntax applies to else and elseif as well. The following is an if structure with elseif and else in the alternative format: if ($a == 5): print "a equals 5"; print "..."; elseif ($a == 6): print "a equals 6"; print "!!!"; else: print "a is neither 5 nor 6"; endif; ------------------------------------------------------------------------ while while loops are the simplest type of loop in PHP. They behave just like their C counterparts. The basic form of a while statement is: while (expr) statement The meaning of a while statement is simple. It tells PHP to execute the nested statement(s) repeatedly, as long as the while expression evaluates to TRUE. The value of the expression is checked each time at the beginning of the loop, so even if this value changes during the execution of the nested statement(s), execution will not stop until the end of the iteration (each time PHP runs the statements in the loop is one iteration). Sometimes, if the while expression evaluates to FALSE from the very beginning, the nested statement(s) won't even be run once. Like with the if statement, you can group multiple statements within the same while loop by surrounding a group of statements with curly braces, or by using the alternate syntax: while (expr): statement ... endwhile; The following examples are identical, and both print numbers from 1 to 10: /* example 1 */ $i = 1; while ($i <= 10) { print $i++; /* the printed value would be $i before the increment (post-increment) */ } /* example 2 */ $i = 1; while ($i <= 10): print $i; $i++; endwhile; ------------------------------------------------------------------------ do..while do..while loops are very similar to while loops, except the truth expression is checked at the end of each iteration instead of in the beginning. The main difference from regular while loops is that the first iteration of a do..while loop is guarenteed to run (the truth expression is only checked at the end of the iteration), whereas it's may not necessarily run with a regular while loop (the truth expression is checked at the beginning of each iteration, if it evaluates to FALSE right from the beginning, the loop execution would end immediately). There is just one syntax for do..while loops: $i = 0; do { print $i; } while ($i>0); The above loop would run one time exactly, since after the first iteration, when truth expression is checked, it evaluates to FALSE ($i is not bigger than 0) and the loop execution ends. Advanced C users may be familiar with a different usage of the do..while loop, to allow stopping execution in the middle of code blocks, by encapsulating them with do..while(0), and using the break statement. The following code fragment demonstrates this: do { if ($i < 5) { print "i is not big enough"; break; } $i *= $factor; if ($i < $minimum_limit) { break; } print "i is ok"; ...process i... } while(0); Don't worry if you don't understand this right away or at all. You can code scripts and even powerful scripts without using this `feature'. ------------------------------------------------------------------------ for for loops are the most complex loops in PHP. They behave like their C counterparts. The syntax of a for loop is: for (expr1; expr2; expr3) statement The first expression (expr1) is evaluated (executed) once unconditionally at the beginning of the loop. In the beginning of each iteration, expr2 is evaluated. If it evaluates to TRUE, the loop continues and the nested statement(s) are executed. If it evaluates to FALSE, the execution of the loop ends. At the end of each iteration, expr3 is evaluated (executed). Each of the expressions can be empty. expr2 being empty means the loop should be run indefinitely (PHP implicitly considers it as TRUE, like C). This may not be as useless as you might think, since often you'd want to end the loop using a conditional break statement instead of using the for truth expression. Consider the following examples. All of them display numbers from 1 to 10: /* example 1 */ for ($i = 1; $i <= 10; $i++) { print $i; } /* example 2 */ for ($i = 1;;$i++) { if ($i > 10) { break; } print $i; } /* example 3 */ $i = 1; for (;;) { if ($i > 10) { break; } print $i; $i++; } /* example 4 */ for ($i = 1; $i <= 10; print $i, $i++) ; Of course, the first example appears to be the nicest one (or perhaps the fourth), but you may find that being able to use empty expressions in for loops comes in handy in many occasions. PHP also supports the alternate "colon syntax" for for loops. for (expr1; expr2; expr3): statement; ...; endfor; Other languages have a foreach statement to traverse an array or hash. PHP uses the while statement and the list() and each() functions for this. See the documentation for these functions for an example. ------------------------------------------------------------------------ break break breaks out of the current looping control-structures. $i = 0; while ($i < 10) { if ($arr[$i] == "stop") { break; } $i++; } ------------------------------------------------------------------------ continue continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the beginning of the next iteration. while (list($key,$value) = each($arr)) { if ($key % 2) { // skip even members continue; } do_something_odd ($value); } ------------------------------------------------------------------------ switch The switch statement is similar to a series of IF statements on the same expression. In many occasions, you may want to compare the same variable (or expression) with many different values, and execute a different piece of code depending on which value it equals to. This is exactly what the switch statement is for. The following two examples are two different ways to write the same thing, one using a series of if statements, and the other using the switch statement: if ($i == 0) { print "i equals 0"; } if ($i == 1) { print "i equals 1"; } if ($i == 2) { print "i equals 2"; } switch ($i) { case 0: print "i equals 0"; break; case 1: print "i equals 1"; break; case 2: print "i equals 2"; break; } It is important to understand how the switch statement is executed in order to avoid mistakes. The switch statement executes line by line (actually, statement by statement). In the beginning, no code is executed. Only when a case statement is found with a value that matches the value of the switch expression does PHP begin to execute the statements. PHP continues to execute the statements until the end of the switch block, or the first time it sees a break statement. If you don't write a break statement at the end of a case's statement list, PHP will go on executing the statements of the following case. For example: switch ($i) { case 0: print "i equals 0"; case 1: print "i equals 1"; case 2: print "i equals 2"; } Here, if $i equals to 0, PHP would execute all of the print statements! If $i equals to 1, PHP would execute the last two print statements, and only if $i equals to 2, you'd get the 'expected' behavior and only 'i equals 2' would be displayed. So, it's important not to forget break statements (even though you may want to avoid supplying them on purpose under certain circumstances). The statement list for a case can also be empty, which simply passes control into the statement list for the next case. switch ($i) { case 0: case 1: case 2: print "i is less than 3 but not negative"; break; case 3: print "i is 3"; } A special case is the default case. This case matches anything that wasn't matched by the other cases. For example: switch ($i) { case 0: print "i equals 0"; break; case 1: print "i equals 1"; break; case 2: print "i equals 2"; break; default: print "i is not equal to 0, 1 or 2"; } The case expression may be any expression that evaluates to a scalar type, that is, integer or floating-point numbers and strings. Arrays or objects are meaningless in that context. ------------------------------------------------------------------------ require The require statement replaces itself with the specified file, much like the C preprocessor's #include works. This means that you can't put a require statement inside of a loop structure and expect it to include the contents of a different file on each iteration. To do that, use an include statement. require 'header.inc'; ------------------------------------------------------------------------ include The include statement includes and evaluates the specified file. This happens each time the include statement is encountered, so you can use an include statement within a looping structure to include a number of different file. $files = array ('first.inc', 'second.inc', 'third.inc'); for ($i = 0; $i < count($files); $i++) { include $files[$i]; } include differs from require in that the include statement is re-evaluated each time it is encountered (and only when it is being executed), whereas the require statement is replaced by the required file when it is first encountered, whether the contents of the file will be evaluated or not (for example, if it is inside an if statement whose condition evaluated to false). Because include is a special language construct, you must enclose it within a statement block if it is inside a conditional block. /* This is WRONG and will not work as desired. */ if ($condition) include($file); else include($other); /* This is CORRECT. */ if ($condition) { include($file); } else { include($other); } When the file is evaluated, the parser begins in "HTML-mode" which will output the contents of the file until the first PHP start tag () is encountered. See also readfile(), require(), virtual(). ------------------------------------------------------------------------ Chapter 12. Functions User-defined functions A function may be defined using syntax such as the following: function foo ($arg_1, $arg_2, ..., $arg_n) { echo "Example function.\n"; return $retval; } Any valid PHP code may appear inside a function, even other functions and class definitions. Functions must be defined before they are referenced. ------------------------------------------------------------------------ Returning values Values are returned by using the optional return statement. Any type may be returned, including lists and objects. function square ($num) { return $num * $num; } echo square (4); // outputs '16'. You can't return multiple values from a function, but similar results can be obtained by returning a list. function small_numbers() { return array (0, 1, 2); } list ($zero, $one, $two) = small_numbers(); ------------------------------------------------------------------------ Function arguments Information may be passed to functions via the argument list, which is a comma-delimited list of variables and/or constants. PHP supports passing arguments by value (the default), passing by reference, and default argument values. Variable-length argument lists are not supported, but a similar effect may be obtained by passing arrays. function takes_array($input) { echo "$input[0] + $input[1] = ", $input[0]+$input[1]; } ------------------------------------------------------------------------ Making arguments be passed by reference By default, function arguments are passed by value (so that if you change the value of the argument within the function, it does not get changed outside of the function). If you wish to allow a function to modify its arguments, you must pass them by reference. If you want an argument to a function to always be passed by reference, you can prepend an ampersand (&) to the argument name in the function definition: function add_some_extra(&$string) { $string .= 'and something extra.'; } $str = 'This is a string, '; add_some_extra($str); echo $str; // outputs 'This is a string, and something extra.' If you wish to pass a variable by reference to a function which does not do this by default, you may prepend an ampersand to the argument name in the function call: function foo ($bar) { $bar .= ' and something extra.'; } $str = 'This is a string, '; foo ($str); echo $str; // outputs 'This is a string, ' foo (&$str); echo $str; // outputs 'This is a string, and something extra.' ------------------------------------------------------------------------ Default argument values A function may define C++-style default values for scalar arguments as follows: function makecoffee ($type = "cappucino") { return "Making a cup of $type.\n"; } echo makecoffee (); echo makecoffee ("espresso"); The output from the above snippet is: Making a cup of cappucino. Making a cup of espresso. The default value must be a constant expression, not (for example) a variable or class member. In PHP 4.0 it's also possible to specify unset for default argument. This means that the argument will not be set at all, if a value is not supplied. Note that when using default arguments, any defaults should be on the right side of any non-default arguments; otherwise, things will not work as expected. Consider the following code snippet: function makeyogurt ($type = "acidophilus", $flavour) { return "Making a bowl of $type $flavour.\n"; } echo makeyogurt ("raspberry"); // won't work as expected The output of the above example is: Warning: Missing argument 2 in call to makeyogurt() in /usr/local/etc/httpd/htdocs/php3test/functest.html on line 41 Making a bowl of raspberry . Now, compare the above with this: function makeyogurt ($flavour, $type = "acidophilus") { return "Making a bowl of $type $flavour.\n"; } echo makeyogurt ("raspberry"); // works as expected The output of this example is: Making a bowl of acidophilus raspberry. ------------------------------------------------------------------------ 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->PHP3 convertor. Warning 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 PHP3 form) to call the old_function. ------------------------------------------------------------------------ Chapter 13. Classes and Objects class A class is a collection of variables and functions working with these variables. A class is defined using the following syntax: items[$artnr] += $num; } // Take $num articles of $artnr out of the cart function remove_item ($artnr, $num) { if ($this->items[$artnr] > $num) { $this->items[$artnr] -= $num; return true; } else { return false; } } } ?> This defines a class named Cart that consists of an associative array of articles in the cart and two functions to add and remove items from this cart. Classes are types, that is, they are blueprints for actual variables. You have to create a variables of the desired type with the new operator. $cart = new Cart; $cart->add_item("10", 1); This creates an object $cart of the class Cart. The function add_item() of that object is being called to add 1 item of article number 10 to the cart. Classes can be extensions of other classes. The extended or derived class has all variables and functions of the base class and what you add in the extended definition. This is done using the extends keyword. class Named_Cart extends Cart { var $owner; function set_owner ($name) { $this->owner = $name; } } This defines a class Named_Cart that has all variables and functions of Cart plus an additional variable $owner and an additional function set_owner(). You create a named cart the usual way and can now set and get the carts owner. You can still use normal cart functions on named carts: $ncart = new Named_Cart; // Create a named cart $ncart->set_owner ("kris"); // Name that cart print $ncart->owner; // print the cart owners name $ncart->add_item ("10", 1); // (inherited functionality from cart) Within functions of a class the variable $this means this object. You have to use $this->something to access any variable or function named something within your current object. Constructors are functions in a class that are automatically called when you create a new instance of a class. A function becomes a constructor when it has the same name as the class. class Auto_Cart extends Cart { function Auto_Cart () { $this->add_item ("10", 1); } } This defines a class Auto_Cart that is a Cart plus a constructor which initializes the cart with one item of article number "10" each time a new Auto_Cart is being made with "new". Constructors can also take arguments and these arguments can be optional, which makes them much more useful. class Constructor_Cart { function Constructor_Cart ($item = "10", $num = 1) { $this->add_item ($item, $num); } } // Shop the same old boring stuff. $default_cart = new Constructor_Cart; // Shop for real... $different_cart = new Constructor_Cart ("20", 17); Caution For derived classes, the constructor of the parent class is not automatically called when the derived class's constructor is called. III. Features Table of Contents 14. Error handling 15. Creating GIF images 16. HTTP authentication with PHP 17. Cookies 18. Handling file uploads 19. Using remote files 20. Connection handling 21. Persistent database connections ------------------------------------------------------------------------ Chapter 14. Error handling There are 4 types of errors and warnings in PHP. They are: * 1 - Normal Function Errors * 2 - Normal Warnings * 4 - Parser Errors * 8 - Notices (warnings you can ignore but which may imply a bug in your code) The above 4 numbers are added up to define an error reporting level. The default error reporting level is 7 which is 1 + 2 + 4, or everything except notices. This level can be changed in the php3.ini file with the error_reporting directive. It can also be set in your Apache httpd.conf file with the php3_error_reporting directive or lastly it may be set at runtime within a script using the error_reporting() function. All PHP expressions can also be called with the "@" prefix, which turns off error reporting for that particular expression. If an error occurred during such an expression and the track_errors feature is enabled, you can find the error message in the global variable $php_errormsg. ------------------------------------------------------------------------ Chapter 15. Creating GIF images PHP is not limited to creating just HTML output. It can also be used to create GIF image files, or even more convenient GIF image streams. You will need to compile PHP with the GD library of image functions for this to work. Example 15-1. GIF creation with PHP This example would be called from a page with a tag like:"; } ?> Instead of simply printing out the $PHP_AUTH_USER and $PHP_AUTH_PW, you would probably want to check the username and password for validity. Perhaps by sending a query to a database, or by looking up the user in a dbm file. Watch out for buggy Internet Explorer browsers out there. They seem very picky about the order of the headers. Sending the WWW-Authenticate header before the HTTP/1.0 401 header seems to do the trick for now. In order to prevent someone from writing a script which reveals the password for a page that was authenticated through a traditional external mechanism, the PHP_AUTH variables will not be set if external authentication is enabled for that particular page. In this case, the $REMOTE_USER variable can be used to identify the externally-authenticated user. Note, however, that the above does not prevent someone who controls a non-authenticated URL from stealing passwords from authenticated URLs on the same server. Both Netscape and Internet Explorer will clear the local browser window's authentication cache for the realm upon receiving a server response of 401. This can effectively "log out" a user, forcing them to re-enter their username and password. Some people use this to "time out" logins, or provide a "log-out" button. Example 16-2. HTTP Authentication example forcing a new name/password "; echo "Old: $OldAuth"; echo "
\n"; } ?> This behavior is not required by the HTTP Basic authentication standard, so you should never depend on this. Testing with Lynx has shown that Lynx does not clear the authentication credentials with a 401 server response, so pressing back and then forward again will open the resource (as long as the credential requirements haven't changed). Also note that this does not work using Microsoft's IIS server and the CGI version of PHP due to a limitation of IIS. ------------------------------------------------------------------------ Chapter 17. Cookies PHP transparently supports HTTP cookies. Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users. You can set cookies using the setcookie() function. Cookies are part of the HTTP header, so setcookie() must be called before any output is sent to the browser. This is the same limitation that header() has. Any cookies sent to you from the client will automatically be turned into a PHP variable just like GET and POST method data. If you wish to assign multiple values to a single cookie, just add [] to the cookie name. For more details see the setcookie() function. ------------------------------------------------------------------------ Chapter 18. Handling file uploads POST method uploads PHP is capable of receiving file uploads from any RFC-1867 compliant browser (which includes Netscape Navigator 3 or later, Microsoft Internet Explorer 3 with a patch from Microsoft, or later without a patch). This feature lets people upload both text and binary files. With PHP's authentication and file manipulation functions, you have full control over who is allowed to upload and what is to be done with the file once it has been uploaded. Note that PHP also supports PUT-method file uploads as used by Netscape Composer and W3C's Amaya clients. See the PUT Method Support for more details. A file upload screen can be built by creating a special form which looks something like this: Example 18-1. File Upload Form The _URL_ should point to a PHP file. The MAX_FILE_SIZE hidden field must precede the file input field and its value is the maximum filesize accepted. The value is in bytes. In this destination file, the following variables will be defined upon a successful upload: * $userfile - The temporary filename in which the uploaded file was stored on the server machine. * $userfile_name - The original name of the file on the sender's system. * $userfile_size - The size of the uploaded file in bytes. * $userfile_type - The mime type of the file if the browser provided this information. An example would be "image/gif". Note that the "$userfile" part of the above variables is whatever the name of the INPUT field of TYPE=file is in the upload form. In the above upload form example, we chose to call it "userfile". Files will by default be stored in the server's default temporary directory. This can be changed by setting the environment variable TMPDIR in the environment in which PHP runs. Setting it using putenv() from within a PHP script will not work. The PHP script which receives the uploaded file should implement whatever logic is necessary for determining what should be done with the uploaded file. You can for example use the $file_size variable to throw away any files that are either too small or too big. You could use the $file_type variable to throw away any files that didn't match a certain type criteria. Whatever the logic, you should either delete the file from the temporary directory or move it elsewhere. The file will be deleted from the temporary directory at the end of the request if it has not been moved away or renamed. ------------------------------------------------------------------------ Common Pitfalls The MAX_FILE_SIZE item cannot specify a file size greater than the file size that has been set in the upload_max_filesize in the PHP3.ini file or the corresponding php3_upload_max_filesize Apache .conf directive. The default is 2 Megabytes. Please note that the CERN httpd seems to strip off everything starting at the first whitespace in the content-type mime header it gets from the client. As long as this is the case, CERN httpd will not support the file upload feature. ------------------------------------------------------------------------ Uploading multiple files It is possible to upload multiple files simultaneously and have the information organized automatically in arrays for you. To do so, you need to use the same array submission syntax in the HTML form as you do with multiple selects and checkboxes: Note: Support for multiple file uploads was added in version 3.0.10. Example 18-2. Uploading multiple forms When the above form is submitted, the arrays $userfile, $userfile_name, and $userfile_size will be formed in the global scope (as well as in $HTTP_POST_VARS). Each of these will be a numerically indexed array of the appropriate values for the submitted files. For instance, assume that the filenames /home/test/review.html and /home/test/xwp.out are submitted. In this case, $userfile_name[0] would contain the value review.html, and $userfile_name[1] would contain the value xwp.out. Similarly, $userfile_size[0] would contain review.html's filesize, and so forth. ------------------------------------------------------------------------ PUT method support PHP provides support for the HTTP PUT method used by clients such as Netscape Composer and W3C Amaya. PUT requests are much simpler than a file upload and they look something like this: PUT /path/filename.html HTTP/1.1 This would normally mean that the remote client would like to save the content that follows as: /path/filename.html in your web tree. It is obviously not a good idea for Apache or PHP to automatically let everybody overwrite any files in your web tree. So, to handle such a request you have to first tell your web server that you want a certain PHP script to handle the request. In Apache you do this with the Script directive. It can be placed almost anywhere in your Apache configuration file. A common place is inside a| Employee name | Salary | $name | \n". "$salary | \n". " \n"); } ?>
|---|
$num fields in line $row:
";
$row++;
for ( $c=0; $c<$num; $c++ ) print $data[$c] . "
";
}
fclose($fp);
fgets
fgets -- get line from file pointer
Description
string fgets(int fp, int length);
Returns a 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 (which
is included in the return value), or on EOF (whichever comes first).
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:
Example 1. Reading a file line by line
$fd = fopen("/tmp/inputfile.txt", "r");
while ($buffer = fgets($fd, 4096)) {
echo $buffer;
}
fclose($fd);
See also fread(), fopen(), popen(), fgetc(), and fsockopen().
fgetss
fgetss -- get line from file pointer and strip HTML tags
Description
string fgetss(int fp, int length);
Identical to fgets(), except that fgetss attempts to strip any HTML and PHP
tags from the text it reads.
See also fgets(), fopen(), fsockopen(), popen(), and strip_tags().
file
file -- read entire file into an array
Description
array file(string filename);
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.
See also readfile(), fopen(), and popen().
file_exists
file_exists -- Check whether a file exists.
Description
int file_exists(string filename);
Returns true if the file specified by filename exists; false otherwise.
The results of this function are cached. See clearstatcache() for more
details.
fileatime
fileatime -- get 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 results of this function are cached. See clearstatcache() for more
details.
filectime
filectime -- get 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 results of this function are cached. See clearstatcache() for more
details.
filegroup
filegroup -- get file group
Description
int filegroup(string filename);
Returns the group ID of the owner of the file, or false in case of an error.
The results of this function are cached. See clearstatcache() for more
details.
fileinode
fileinode -- get file inode
Description
int fileinode(string filename);
Returns the inode number of the file, or false in case of an error.
The results of this function are cached. See clearstatcache() for more
details.
filemtime
filemtime -- get file modification time
Description
int filemtime(string filename);
Returns the time the file was last modified, or false in case of an error.
The results of this function are cached. See clearstatcache() for more
details.
fileowner
fileowner -- get file owner
Description
int fileowner(string filename);
Returns the user ID of the owner of the file, or false in case of an
The results of this function are cached. See clearstatcache() for more
details. error.
fileperms
fileperms -- get file permissions
Description
int fileperms(string filename);
Returns the permissions on the file, or false in case of an error.
The results of this function are cached. See clearstatcache() for more
details.
filesize
filesize -- get file size
Description
int filesize(string filename);
Returns the size of the file, or false in case of an error.
The results of this function are cached. See clearstatcache() for more
details.
filetype
filetype -- get 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.
The results of this function are cached. See clearstatcache() for more
details.
flock
flock -- portable advisory file locking
Description
bool flock(int fp, int operation);
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 fp which must be an open file pointer. operation is one
of the following values:
* To acquire a shared lock (reader), set operation to 1.
* To acquire an exclusive lock (writer), set operation to 2.
* To release a lock (shared or exclusive), set operation to 3.
* If you don't want flock() to block while locking, add 4 to operation.
flock() allows you to perform a simple reader/writer model which can be used
on virtually every platform (including most Unices and even Windows).
flock() returns true on success and false on error (e.g. when a lock could
not be acquired).
fopen
fopen -- open file or URL
Description
int fopen(string filename, string mode);
If filename begins with "http://" (not case sensitive), an HTTP 1.0
connection is opened to the specified server and a file pointer is returned
to the beginning of the text of the response.
Does not handle HTTP redirects, so you must include trailing slashes on
directories.
If filename begins with "ftp://" (not case sensitive), an ftp connection to
the specified server is opened and a pointer to the requested file is
returned. If the server does not support passive mode ftp, this will fail.
You can open files for either reading and writing via ftp (but not both
simultaneously).
If filename begins with anything else, the file will be opened from the
filesystem, and a file pointer to the file opened is returned.
If the open fails, the function returns false.
mode may be any of the following:
* '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.
As well, mode may contain the letter 'b'. This is useful only on systems
which differentiate between binary and text files (i.e., it's useless on
Unix). If not needed, this will be ignored.
Example 1. fopen() example
$fp = fopen("/home/rasmus/file.txt", "r");
$fp = fopen("http://www.php.net/", "r");
$fp = fopen("ftp://user:password@example.com/", "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.
$fp = fopen("c:\\data\\info.txt", "r");
See also fclose(), fsockopen(), and popen().
fpassthru
fpassthru -- output all remaining data on a file pointer
Description
int fpassthru(int fp);
Reads to EOF on the given file pointer and writes the results to standard
output.
If an error occurs, fpassthru() returns false.
The file pointer must be valid, and must point to a file successfully opened
by fopen(), popen(), or fsockopen(). The file is closed when fpassthru() is
done reading it (leaving fp useless).
If you just want to dump the contents of a file to stdout you may want to
use the readfile(), which saves you the fopen() call.
See also readfile(), fopen(), popen(), and fsockopen()
fputs
fputs -- write to a file pointer
Description
int fputs(int fp, string str, int [length]);
fputs() is an alias to fwrite(), and is identical in every way. Note that
the length parameter is optional and if not specified the entire string will
be written.
fread
fread -- Binary-safe file read
Description
string fread(int fp, int length);
fread() reads up to length bytes from the file pointer referenced by fp.
Reading stops when length bytes have been read or EOF is reached, whichever
comes first.
// get contents of a file into a string
$filename = "/usr/local/something.txt";
$fd = fopen( $filename, "r" );
$contents = fread( $fd, filesize( $filename ) );
fclose( $fd );
See also fwrite(), fopen(), fsockopen(), popen(), fgets(), fgetss(), file(),
and fpassthru().
fseek
fseek -- seek on a file pointer
Description
int fseek(int fp, int offset);
Sets the file position indicator for the file referenced by fp to offset
bytes into the file stream. Equivalent to calling (in C) fseek( fp, offset,
SEEK_SET ).
Upon success, returns 0; otherwise, returns -1. Note that seeking past EOF
is not considered an error.
May not be used on file pointers returned by fopen() if they use the
"http://" or "ftp://" formats.
See also ftell() and rewind().
ftell
ftell -- tell file pointer read/write position
Description
int ftell(int fp);
Returns the position of the file pointer referenced by fp; 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().
See also fopen(), popen(), fseek() and rewind().
fwrite
fwrite -- Binary-safe file write
Description
int fwrite(int fp, string string, int [length]);
fwrite() writes the contents of string to the file stream pointed to by fp.
If the length argument is given, writing will stop after length bytes have
been written or the end of string is reached, whichever comes first.
Note that if the length argument is given, then the magic_quotes_runtime
configuration option will be ignored and no slashes will be stripped from
string.
See also fread(), fopen(), fsockopen(), popen(), and fputs().
set_file_buffer
set_file_buffer -- Sets file buffering on the given file pointer
Description
int fwrite(int fp, int buffer);
set_file_buffer() sets the buffering for write operations on the given
filepointer fp to buffer bytes. If buffer is 0 then write operations are
unbuffered.
The function returns 0 on success, or EOF if the request cannot be honored.
Note that the default for any fopen with calling set_file_buffer is 8K.
See also fopen().
is_dir
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.
The results of this function are cached. See clearstatcache() for more
details.
See also is_file() and is_link().
is_executable
is_executable -- tells whether the filename is executable
Description
bool is_executable(string filename);
Returns true if the filename exists and is executable.
The results of this function are cached. See clearstatcache() for more
details.
See also is_file() and is_link().
is_file
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.
The results of this function are cached. See clearstatcache() for more
details.
See also is_dir() and is_link().
is_link
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.
The results of this function are cached. See clearstatcache() for more
details.
See also is_dir() and is_file().
is_readable
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.
The results of this function are cached. See clearstatcache() for more
details.
See also is_writeable().
is_writeable
is_writeable -- tells whether the filename is writeable
Description
bool is_writeable(string filename);
Returns true if the filename exists and is writeable. 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.
The results of this function are cached. See clearstatcache() for more
details.
See also is_readable().
link
link -- Create a hard link
Description
int link(string target, string link);
Link() creates a hard link.
See also the symlink() to create soft links, and readlink() along with
linkinfo().
linkinfo
linkinfo -- Get 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.
See also symlink(), link(), and readlink().
mkdir
mkdir -- make directory
Description
int mkdir(string pathname, int mode);
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.
mkdir("/path/to/my/dir", 0700);
Returns true on success and false on failure.
See also rmdir().
pclose
pclose -- close process file pointer
Description
int pclose(int fp);
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
popen -- open process file pointer
Description
int 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.
$fp = popen( "/bin/ls", "r" );
See also pclose().
readfile
readfile -- output a file
Description
int readfile(string filename);
Reads a file and writes it to standard output.
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.
If filename begins with "http://" (not case sensitive), an HTTP 1.0
connection is opened to the specified server and the text of the response is
written to standard output.
Does not handle HTTP redirects, so you must include trailing slashes on
directories.
If filename begins with "ftp://" (not case sensitive), an ftp connection to
the specified server is opened and the requested file is written to standard
output. If the server does not support passive mode ftp, this will fail.
If filename begins with neither of these strings, the file will be opened
from the filesystem and its contents written to standard output.
See also fpassthru(), file(), fopen(), include(), require(), and virtual().
readlink
readlink -- Return 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.
See also symlink(), readlink() and linkinfo().
rename
rename -- rename a file
Description
int rename(string oldname, string newname);
Attempts to rename oldname to newname.
Returns true on success and false on failure.
rewind
rewind -- rewind the position of a file pointer
Description
int rewind(int fp);
Sets the file position indicator for fp 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 fopen().
See also fseek() and ftell().
rmdir
rmdir -- remove directory
Description
int rmdir(string dirname);
Attempts to remove the directory named by pathname. The directory must be
empty, and the relevant permissions must permit this.
If an error occurs, returns 0.
See also mkdir().
stat
stat -- give information about a file
Description
array stat(string filename);
Gathers the statistics of the file named by filename.
Returns an array with the statistics of the file with the following
elements:
1. device
2. inode
3. inode protection mode
4. number of links
5. user id of owner
6. group id owner
7. device type if inode device *
8. size in bytes
9. time of last access
10. time of last modification
11. time of last change
12. blocksize for filesystem I/O *
13. number of blocks allocated
* - only valid on systems supporting the st_blksize type--other systems
(i.e. Windows) return -1
The results of this function are cached. See clearstatcache() for more
details.
lstat
lstat -- give 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.
Returns an array with the statistics of the file with the following
elements:
1. device
2. inode
3. number of links
4. user id of owner
5. group id owner
6. device type if inode device *
7. size in bytes
8. time of last access
9. time of last modification
10. time of last change
11. blocksize for filesystem I/O *
12. number of blocks allocated
* - only valid on systems supporting the st_blksize type--other systems
(i.e. Windows) return -1
The results of this function are cached. See clearstatcache() for more
details.
symlink
symlink -- Create a symbolic link
Description
int symlink(string target, string link);
symlink() creates a symbolic link from the existing target with the
specified name link.
See also link() to create hard links, and readlink() along with linkinfo().
tempnam
tempnam -- create unique file name
Description
string tempnam(string dir, string prefix);
Creates a unique temporary filename in the specified directory. If the
directory does not exist, tempnam() may generate a filename in the system's
temporary directory.
The behaviour of the tempnam() function is 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.
Returns the new temporary filename, or the null string on failure.
Example 1. tempnam() example
$tmpfname = tempnam( "/tmp", "FOO" );
touch
touch -- set modification time of file
Description
int touch(string filename, int time);
Attempts to set the 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.
If the file does not exist, it is created.
Returns true on success and false otherwise.
umask
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
unlink -- Delete a file
Description
int unlink(string filename);
Deletes filename. Similar to the Unix C unlink() function.
Returns 0 or FALSE on an error.
See also rmdir() for removing directories.
XVIII. HTTP functions
These functions let you manipulate the output sent back to the remote
browser right down to the HTTP protocol level.
Table of Contents
header Ñ Send a raw HTTP header
setcookie Ñ Send a cookie
header
header -- Send a raw HTTP header
Description
int header(string string);
The Header() function is used at the top of an HTML file to send raw HTTP
header strings. See the HTTP 1.1 Specification for more information on raw
http headers. Note: Remember that the Header() function must be called
before any actual output is sent either by normal HTML tags or from PHP. It
is a very common error to read code with include() or with auto_prepend and
have spaces or empty lines in this code that force output before header() is
called.
header("Location: http://www.php.net"); /* Redirect browser to PHP web site */
exit; /* Make sure that code below does not get executed when we redirect. */
PHP scripts often generate dynamic HTML 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
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Pragma: no-cache"); // HTTP/1.0
setcookie
setcookie -- Send a cookie
Description
int 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 header
information. Cookies must be sent before any other headers are sent (this is
a restriction of cookies, not PHP). This requires you to place calls to this
function before any or
>
The optional imageinfo parameter allows you to extract some extended
information from the image file. Currently this will return the diffrent JPG
APP markers in an associative Array. Some Programs use these APP markers to
embedd text information in images. A very common one in to embed IPTC
http://www.xe.net/iptc/ information in the APP13 marker. You can use the
iptcparse() function to parse the binary APP13 marker into something
readable.
Example 2. GetImageSize returning IPTC
Note: This function does not require the GD image library.
ImageArc
ImageArc -- draw a partial ellipse
Description
int imagearc(int im, int cx, int cy, int w, int h, int s, int e, int col);
ImageArc draws a partial ellipse centered at cx, cy (top left is 0,0) in the
image represented by im. 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.
ImageChar
ImageChar -- draw a character horizontally
Description
int imagechar(int im, int font, int x, int y, string c, int col);
ImageChar draws the first character of c in the image identified by id with
its upper-left at x,y (top left is 0,0) with the color col. If font is 1, 2,
3, 4 or 5, a built-in font is used (with higher numbers corresponding to
larger fonts).
See also imageloadfont().
ImageCharUp
ImageCharUp -- draw a character vertically
Description
int imagecharup(int im, int font, int x, int y, string c, int col);
ImageCharUp draws the character c vertically in the image identified by im
at coordinates x, y (top left is 0, 0) with the color col. If font is 1, 2,
3, 4 or 5, a built-in font is used.
See also imageloadfont().
ImageColorAllocate
ImageColorAllocate -- allocate a color for an image
Description
int imagecolorallocate(int im, int red, int green, int blue);
ImageColorAllocate returns a color identifier representing the color
composed of the given RGB components. The im argument is the return from the
imagecreate() function. ImageColorAllocate must be called to create each
color that is to be used in the image represented by im.
$white = ImageColorAllocate($im, 255,255,255);
$black = ImageColorAllocate($im, 0,0,0);
ImageColorTransparent
ImageColorTransparent -- define a color as transparent
Description
int imagecolortransparent(int im, int [col]);
ImageColorTransparent sets the transparent color in the im image to col. im
is the image identifier returned by imagecreate() and col is a color
identifier returned by imagecolorallocate().
The identifier of the new (or current, if none is specified) transparent
color is returned.
ImageCopyResized
ImageCopyResized -- copy and resize part of an image
Description
int imagecopyresized(int dst_im, int src_im, int dstX, int dstY, int srcX,
int srcY, int dstW, int dstH, int srcW, int srcH);
ImageCopyResized copies a rectangular portion of one image to another image.
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.
ImageCreate
ImageCreate -- create a new image
Description
int imagecreate(int x_size, int y_size);
ImageCreate returns an image identifier representing a blank image of size
x_size by y_size.
ImageCreateFromGif
ImageCreateFromGif -- create a new image from file or URL
Description
int imagecreatefromgif(string filename);
imagecreatefromgif() returns an image identifier representing the image
obtained from the given filename.
imagecreatefromgif() 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 GIF:
Example 1. Example to handle an error during creation (courtesy
vic@zymsys.com )
function LoadGif($imgname)
{
$im = @imagecreatefromgif($imgname); /* Attempt to open */
if ($im == "") { /* See if it failed */
$im = ImageCreate(150,30); /* Create a blank image */
$bgc = ImageColorAllocate($im,255,255,255);
$tc = ImageColorAllocate($im,0,0,0);
ImageFilledRectangle($im,0,0,150,30,$bgc);
ImageString($im,1,5,5,"Error loading $imgname",$tc); /* Output an errmsg */
}
return $im;
}
Note: Since all GIF support was removed from the GD library in
version 1.6, this function is not available if you are using that
version of the GD library.
ImageDashedLine
ImageDashedLine -- draw a dashed line
Description
int imagedashedline(int im, int x1, int y1, int x2, int y2, int col);
ImageLine draws a dashed line from x1,y1 to x2,y2 (top left is 0,0) in image
im of color col.
See also imageline().
ImageDestroy
ImageDestroy -- destroy an image
Description
int imagedestroy(int im);
ImageDestroy frees any memory associated with image im. im is the image
identifier returned by the imagecreate() function.
ImageFill
ImageFill -- flood fill
Description
int imagefill(int im, int x, int y, int col);
ImageFill performs a flood fill starting at coordinate x, y (top left is
0,0) with color col in the image im.
ImageFilledPolygon
ImageFilledPolygon -- draw a filled polygon
Description
int imagefilledpolygon(int im, array points, int num_points, int col);
ImageFilledPolygon creates a filled polygon in image im. points is a PHP
array containing the polygon's vertices, ie. points[0] = x0, points[1] = y0,
points[2] = x1, points[3] = y1, etc. num_points is the total number of
vertices.
ImageFilledRectangle
ImageFilledRectangle -- draw a filled rectangle
Description
int imagefilledrectangle(int im, int x1, int y1, int x2, int y2, int col);
ImageFilledRectangle creates a filled rectangle of color col in image im
starting at upper left coordinates x1, y1 and ending at bottom right
coordinates x2, y2. 0, 0 is the top left corner of the image.
ImageFillToBorder
ImageFillToBorder -- flood fill to specific color
Description
int imagefilltoborder(int im, int x, int y, int border, int col);
ImageFillToBorder performs a flood fill whose border color is defined by
border. The starting point for the fill is x,y (top left is 0,0) and the
region is filled with color col.
ImageFontHeight
ImageFontHeight -- get font height
Description
int imagefontheight(int font);
Returns the pixel height of a character in the specified font.
See also imagefontwidth() and imageloadfont().
ImageFontWidth
ImageFontWidth -- get font width
Description
int imagefontwidth(int font);
Returns the pixel width of a character in font.
See also imagefontheight() and imageloadfont().
ImageGif
ImageGif -- output image to browser or file
Description
int imagegif(int im, string filename);
imagegif() creates the GIF file in filename from the image im. The im
argument is the return from the imagecreate() function.
The image format will be GIF87a unless the image has been made transparent
with imagecolortransparent(), in which case the image format will be GIF89a.
The filename argument is optional, and if left off, the raw image stream
will be output directly. By sending an image/gif content-type using
header(), you can create a PHP script that outputs GIF images directly.
Note: Since all GIF support was removed from the GD library in
version 1.6, this function is not available if you are using that
version of the GD library.
ImageInterlace
ImageInterlace -- enable or disable interlace
Description
int imageinterlace(int im, int [interlace]);
ImageInterlace() turns the interlace bit on or off. If interlace is 1 the im
image will be interlaced, and if interlace is 0 the interlace bit is turned
off.
This functions returns whether the interlace bit is set for the image.
ImageLine
ImageLine -- draw a line
Description
int imageline(int im, int x1, int y1, int x2, int y2, int col);
ImageLine draws a line from x1,y1 to x2,y2 (top left is 0,0) in image im of
color col.
See also imagecreate() and imagecolorallocate().
ImageLoadFont
ImageLoadFont -- load a new font
Description
int imageloadfont(string file);
ImageLoadFont loads a user-defined bitmap font and returns an identifier for
the font (that is always greater than 5, so it will not conflict with the
built-in fonts).
The font file format is currently binary and architecture dependent. This
means you should generate the font files on the same type of CPU as the
machine you are running PHP on.
Table 1. Font file format
byte positionC data description
type
byte 0-3 int number of characters in the font
byte 4-7 int value of first character in the font (often 32 for
space)
byte 8-11 int pixel width of each character
byte 12-15 int pixel height of each character
byte 16- char array with character data, one byte per pixel in
each character, for a total of
(nchars*width*height) bytes.
See also ImageFontWidth() and ImageFontHeight().
ImagePolygon
ImagePolygon -- draw a polygon
Description
int imagepolygon(int im, array points, int num_points, int col);
ImagePolygon creates a polygon in image id. points is a PHP array containing
the polygon's vertices, ie. points[0] = x0, points[1] = y0, points[2] = x1,
points[3] = y1, etc. num_points is the total number of vertices.
See also imagecreate().
ImageRectangle
ImageRectangle -- draw a rectangle
Description
int imagerectangle(int im, int x1, int y1, int x2, int y2, int col);
ImageRectangle creates a rectangle of color col in image im starting at
upper left coordinate x1,y1 and ending at bottom right coordinate x2,y2. 0,0
is the top left corner of the image.
ImageSetPixel
ImageSetPixel -- set a single pixel
Description
int imagesetpixel(int im, int x, int y, int col);
ImageSetPixel draws a pixel at x,y (top left is 0,0) in image im of color
col.
See also imagecreate() and imagecolorallocate().
ImageString
ImageString -- draw a string horizontally
Description
int imagestring(int im, int font, int x, int y, string s, int col);
ImageString draws the string s in the image identified by im at coordinates
x,y (top left is 0,0) in color col. If font is 1, 2, 3, 4 or 5, a built-in
font is used.
See also imageloadfont().
ImageStringUp
ImageStringUp -- draw a string vertically
Description
int imagestringup(int im, int font, int x, int y, string s, int col);
ImageStringUp draws the string s vertically in the image identified by im at
coordinates x,y (top left is 0,0) in color col. If font is 1, 2, 3, 4 or 5,
a built-in font is used.
See also imageloadfont().
ImageSX
ImageSX -- get image width
Description
int imagesx(int im);
ImageSX returns the width of the image identified by im.
See also imagecreate() and imagesy().
ImageSY
ImageSY -- get image height
Description
int imagesy(int im);
ImageSY returns the height of the image identified by im.
See also imagecreate() and imagesx().
ImageTTFBBox
ImageTTFBBox -- give the bounding box of a text using TypeType fonts
Description
array ImageTTFBBox(int size, int angle, string fontfile, string text);
This function calculates and returns the bounding box in pixels a TrueType
text.
text
The string to be measured.
size
The font size.
fontfile
The name of the TrueType font file. (Can also be an URL.)
angle
Angle in degrees in which text will be measured.
ImageTTFBBox() returns an array with 8 elements representing four points
making the bounding box of the text:
0lower left corner, X position
1lower left corner, Y position
2lower right corner, X position
3lower right corner, Y position
4upper right corner, X position
5upper right corner, Y position
6upper left corner, X position
7upper left corner, Y position
The points are relative to the text regardless of the angle, so "upper left"
means in the top left-hand corner seeing the text horizontallty.
This function requires both the GD library and the Freetype library.
See also ImageTTFText().
ImageTTFText
ImageTTFText -- write text to the image using a TrueType fonts
Description
array ImageTTFText(int im, int size, int angle, int x, int y, int col,
string fontfile, string text);
ImageTTFText draws the string text in the image identified by im, starting
at coordinates x,y (top left is 0,0), at an angle of angle in color col,
using the TrueType font file identified by fontfile.
The coordinates given by x,y will define the basepoint of the first
character (roughly the lower-left corner of the character). This is
different from the ImageString(), where x,y define the upper-right corner of
the first character.
angle is in degrees, with 0 degrees being left-to-right reading text (3
o'clock direction), and higher values representing a counter-clockwise
rotation. (i.e., a value of 90 would result in bottom-to-top reading text).
fontfile is the path to the TrueType font you wish to use.
text is the text string which may include UTF-8 character sequences (of the
form: { ) to access characters in a font beyond the first 255.
col is the color index. Using the negative of a color index has the effect
of turning off antialiasing.
ImageTTFText() returns an array with 8 elements representing four points
making the bounding box of the text. The order of the points is upper left,
upper right, lower right, lower left. The points are relative to the text
regardless of the angle, so "upper left" means in the top left-hand corner
when you see the text horizontallty.
This example script will produce a black GIF 400x30 pixels, with the words
"Testing..." in white in the font Arial.
Example 1. ImageTTFText
This function requires both the GD library and the FreeType library.
See also ImageTTFBBox().
ImageColorAt
ImageColorAt -- get the index of the color of a pixel
Description
int imagecolorat(int im, int x, int y);
Returns the index of the color of the pixel at the specified location in the
image.
See also imagecolorset() and imagecolorsforindex().
ImageColorClosest
ImageColorClosest -- get the index of the closest color to the specified
color
Description
int imagecolorclosest(int im, int red, int green, int blue);
Returns the index of the color in the palette of the image which is
"closest" to the specified RGB value.
The "distance" between the desired color and each color in the palette is
calculated as if the RGB values represented points in three-dimensional
space.
See also imagecolorexact().
ImageColorExact
ImageColorExact -- get the index of the specified color
Description
int imagecolorexact(int im, int red, int green, int blue);
Returns the index of the specified color in the palette of the image.
If the color does not exist in the image's palette, -1 is returned.
See also imagecolorclosest().
ImageColorResolve
ImageColorResolve -- get the index of the specified color or its closest
possible alternative
Description
int imagecolorresolve(int im, int red, int green, int blue);
This function is guaranteed to return a color index for a requested color,
either the exact color or the closest possible alternative.
See also imagecolorclosest().
ImageColorSet
ImageColorSet -- set the color for the specified palette index
Description
bool imagecolorset(int im, int index, int red, int green, int blue);
This sets the specified index in the palette to the specified color. This is
useful for creating flood-fill-like effects in paletted images without the
overhead of performing the actual flood-fill.
See also imagecolorat().
ImageColorsForIndex
ImageColorsForIndex -- get the colors for an index
Description
array imagecolorsforindex(int im, int index);
This returns an associative array with red, green, and blue keys that
contain the appropriate values for the specified color index.
See also imagecolorat() and imagecolorexact().
ImageColorsTotal
ImageColorsTotal -- find out the number of colors in an image's palette
Description
int imagecolorstotal(int im);
This returns the number of colors in the specified image's palette.
See also imagecolorat() and imagecolorsforindex().
ImagePSLoadFont
ImagePSLoadFont -- load a PostScript Type 1 from file
Description
int imagepsloadfont(string filename);
In the case everything went right, a valid font index will be returned and
can be used for further purposes. Otherwise the function returns false and
prints a message describing what went wrong.
See also imagepsfreefont().
ImagePSFreeFont
ImagePSFreeFont -- free memory used by a PostScript Type 1 font
Description
void imagepsfreefont(int fontindex);
See also imagepsloadfont().
ImagePSEncodeFont
ImagePSEncodeFont -- change the character encoding vector of a font
Description
int imagepsencodefont(string encodingfile);
Loads a character encoding vector from from a file and changes the fonts
encoding vector to it. As a PostScript fonts default vector lacks most of
the character positions above 127, you'll definitely want to change this if
you use an other language than english. The exact format of this file is
described in T1libs documentation. T1lib comes with two ready-to-use files,
IsoLatin1.enc and IsoLatin2.enc.
If you find yourself using this function all the time, a much better way to
define the encoding is to set ps.default_encoding in the configuration file
to point to the right encoding file and all fonts you load will
automatically have the right encoding.
ImagePSText
ImagePSText -- to draw a text string over an image using PostScript Type1
fonts
Descriptiom
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 is expressed in pixels.
foreground is the color in which the text will be painted. background is the
color to which the text will try to fade in with antialiasing. No pixels
with the color background are actually painted, so the background image does
not need to be of solid color.
The coordinates given by x, y will define the origin (or reference point) of
the first character (roughly the lower-left corner of the character). This
is different from the ImageString(), where x, y define the upper-right
corner of the first character. Refer to PostScipt documentation about fonts
and their measuring system if you have trouble understanding how this works.
space allows you to change the default value of a space in a font. This
amount is added to the normal value and can also be negative.
tightness allows you to control the amount of white space between
characters. This amount is added to the normal character width and can also
be negative.
angle is in degrees.
antialias_steps allows you to control the number of colours used for
antialiasing text. Allowed values are 4 and 16. The higher value is
recommended for text sizes lower than 20, where the effect in text quality
is quite visible. With bigger sizes, use 4. It's less computationally
intensive.
Parameters space and tightness are expressed in character space units, where
1 unit is 1/1000th of an em-square.
Parameters space, tightness, angle and antialias are optional.
This function returns an array containing the following elements:
0lower left x-coordinate
1lower left y-coordinate
2upper right x-coordinate
3upper right y-coordinate
See also imagepsbbox().
ImagePSBBox
ImagePSBBox -- give the bounding box of a text rectangle using PostScript
Type1 fonts
Description
array imagepsbbox(string text, int font, int size, int space, int width,
float angle);
size is expressed in pixels.
space allows you to change the default value of a space in a font. This
amount is added to the normal value and can also be negative.
tightness allows you to control the amount of white space between
characters. This amount is added to the normal character width and can also
be negative.
angle is in degrees.
Parameters space and tightness are expressed in character space units, where
1 unit is 1/1000th of an em-square.
Parameters space, tightness and angle are optional.
The bounding box is calculated using information available from character
metrics, and unfortunately tends to differ slightly from the results
achieved by actually rasterizing the text. If the angle is 0 degrees, you
can expect the text to need 1 pixel more to every direction.
This function returns an array containing the following elements:
0lower left x-coordinate
1lower left y-coordinate
2upper right x-coordinate
3upper right y-coordinate
See also imagepstext().
XXII. IMAP functions
To get these functions to work, you have to compile PHP with --with-imap.
That requires the c-client library to be installed. Grab the latest version
from ftp://ftp.cac.washington.edu/imap/ and compile it. Then copy
c-client/c-client.a to /usr/local/lib or some other directory on your link
path and copy c-client/rfc822.h, mail.h and linkage.h to /usr/local/include
or some other directory in your include path.
Table of Contents
imap_append Ñ Append a string message to a specified mailbox
imap_base64 Ñ Decode BASE64 encoded text
imap_body Ñ Read the message body
imap_check Ñ Check current mailbox
imap_close Ñ Close an IMAP stream
imap_createmailbox Ñ Create a new mailbox
imap_delete Ñ Mark a messge for deletion from current mailbox
imap_deletemailbox Ñ Delete a mailbox
imap_expunge Ñ Delete all messages marked for deletion
imap_fetchbody Ñ Fetch a particular section of the body of the message
imap_fetchstructure Ñ Read the structure of a particular message
imap_header Ñ Read the header of the message
imap_headers Ñ Returns headers for all messages in a mailbox
imap_listmailbox Ñ Read the list of mailboxes
imap_getmailboxes Ñ Read the list of mailboxes, returning detailed
information on each one
imap_listsubscribed Ñ List all the subscribed mailboxes
imap_getsubscribed Ñ List all the subscribed mailboxes
imap_mail_copy Ñ Copy specified messages to a mailbox
imap_mail_move Ñ Move specified messages to a mailbox
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_renamemailbox Ñ Rename an old mailbox to new mailbox
imap_reopen Ñ Reopen IMAP stream to new mailbox
imap_subscribe Ñ Subscribe to a mailbox
imap_undelete Ñ Unmark the message which is marked deleted
imap_unsubscribe Ñ Unsubscribe from a mailbox
imap_qprint Ñ Convert a quoted-printable string to an 8 bit string
imap_8bit Ñ Convert an 8bit string to a quoted-printable string.
imap_binary Ñ Convert an 8bit string to a base64 string.
imap_scanmailbox Ñ Read the list of mailboxes, takes a string to search for
in the text of the mailbox
imap_mailboxmsginfo Ñ Get information about the current mailbox
imap_rfc822_write_address Ñ Returns a properly formatted email address given
the mailbox, host, and personal info.
imap_rfc822_parse_adrlist Ñ Parses an address string
imap_setflag_full Ñ Sets flags on messages
imap_clearflag_full Ñ Clears flags on messages
imap_sort Ñ
imap_fetchheader Ñ Returns header for a message
imap_uid Ñ This function returns the UID for the given message sequence
number.
imap_msgno Ñ This function returns the message sequence number for the given
UID.
imap_search Ñ This function returns an array of messages matching the given
search criteria.
imap_last_error Ñ This function returns the last IMAP error (if any) that
occurred during this page request.
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_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_status Ñ This function returns status information on a mailbox other
than the current one.
imap_append
imap_append -- Append a string message to a specified mailbox
Description
int imap_append(int imap_stream, string mbox, string message, stringflags);
Returns true on sucess, false on error.
imap_append() appends a string message to the specified mailbox mbox. If the
optional flags is specified, writes the flags to that mailbox also.
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.
imap_base64
imap_base64 -- Decode BASE64 encoded text
Description
string imap_base64(string text);
imap_base64() function decodes BASE-64 encoded text. The decoded message is
returned as a string.
imap_body
imap_body -- Read the message body
Description
string imap_body(int imap_stream, int msg_number, int flags);
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_check
imap_check -- Check current mailbox
Description
array imap_check(int 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 : date of the message
Driver : driver
Mailbox : name of the mailbox
Nmsgs : number of messages
Recent : number of recent messages
imap_close
imap_close -- Close an IMAP stream
Description
int imap_close(int imap_stream, int flags);
Close the imap stream. Takes an optional flag CL_EXPUNGE, which will
silently expunge the mailbox before closing.
imap_createmailbox
imap_createmailbox -- Create a new mailbox
Description
int imap_createmailbox(int imap_stream, string mbox);
imap_createmailbox() creates a new mailbox specified by mbox.
Returns true on success and false on error.
imap_delete
imap_delete -- Mark a messge for deletion from current mailbox
Description
int imap_delete(int imap_stream, int msg_number);
Returns true.
imap_delete() function marks message pointed by msg_number for deletion.
Actual deletion of the messages is done by imap_expunge().
imap_deletemailbox
imap_deletemailbox -- Delete a mailbox
Description
int imap_deletemailbox(int imap_stream, string mbox);
imap_deletemailbox() deletes the specified mailbox.
Returns true on success and false on error.
imap_expunge
imap_expunge -- Delete all messages marked for deletion
Description
int imap_expunge(int imap_stream);
imap_expunge() deletes all the messages marked for deletion by
imap_delete().
Returns true.
imap_fetchbody
imap_fetchbody -- Fetch a particular section of the body of the message
Description
string imap_fetchbody(int imap_stream, int msg_number, string part_number,
flags flags);
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 ()e a bitmask with one or more of the
following
* FT_UID - The msgono is a UID
* FT_PEEK - Do not set the \Seen flag if not already set
* FT_UID - The return string is in "internal" format, without any attempt
to canonicalize CRLF
imap_fetchstructure
imap_fetchstructure -- Read the structure of a particular message
Description
array imap_fetchstructure(int imap_stream, int msg_number);
This function causes a fetch of all the structured information for the given
msg_number. The returned value is an object with following elements.
type, encoding, ifsubtype, subtype, ifdescription, description, ifid,
id, lines, bytes, ifparameters
It also returns an array of objects called parameters[]. This object has
following properties.
attribute, value
In case of multipart, it also returns an array of objects of all the
properties, called parts[].
imap_header
imap_header -- Read the header of the message
Description
object imap_header(int imap_stream, int msg_number, int fromlength, int
subjectlength, int 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
imap_headers -- Returns headers for all messages in a mailbox
Description
array imap_headers(int imap_stream);
Returns an array of string formatted with header info. One element per mail
message.
imap_listmailbox
imap_listmailbox -- Read the list of mailboxes
Description
array imap_listmailbox(int imap_stream, string ref, string pat);
Returns an array containing the names of the mailboxes.
imap_getmailboxes
imap_getmailboxes -- Read the list of mailboxes, returning detailed
information on each one
Description
array imap_getmailboxes(int imap_stream, string ref, string pat);
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.
ref should normally be just the IMAP server, in the form:
{imap_server:imap_port}, and pattern specifies where in the mailbox
hierarchy to start searching. If you want all mailboxes, pass pattern as an
empty string.
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.
imap_listsubscribed
imap_listsubscribed -- List all the subscribed mailboxes
Description
array imap_listsubscribed(int imap_stream, string ref, string pattern);
Returns an array of all the mailboxes that you have subscribed. The ref and
pattern arguments specify the base location to search from and the pattern
the mailbox name must match.
imap_getsubscribed
imap_getsubscribed -- List all the subscribed mailboxes
Description
array imap_getsubscribed(int 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_mail_copy
imap_mail_copy -- Copy specified messages to a mailbox
Description
int imap_mail_copy(int imap_stream, string msglist, string mbox, int flags);
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.
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
imap_mail_move -- Move specified messages to a mailbox
Description
int imap_mail_move(int imap_stream, string msglist, string mbox);
Moves mail messages specified by msglist to specified mailbox. msglist is a
range not just message numbers.
Returns true on success and false on error.
imap_num_msg
imap_num_msg -- Gives the number of messages in the current mailbox
Description
int imap_num_msg(int stream_id);
Return the number of messages in the current mailbox.
imap_num_recent
imap_num_recent -- Gives the number of recent messages in current mailbox
Description
int imap_num_recent(int imap_stream);
Returns the number of recent messages in the current mailbox.
imap_open
imap_open -- Open an IMAP stream to a mailbox
Description
int imap_open(string mailbox, string username, string password, int flags);
Returns an IMAP stream on success and false on error. This function can also
be used to open streams to POP3 and NNTP servers. To connect to an IMAP
server running on port 143 on the local machine, do the following:
$mbox = imap_open("{localhost:143}INBOX","user_id","password");
To connect to a POP3 server on port 110 on the local server, use:
$mbox = imap_open("{localhost/pop3:110}INBOX","user_id","password");
To connect to an NNTP server on port 119 on the local server, use:
$nntp = imap_open("{localhost/nntp:119}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.
The options are a bit mask with one or more of the following:
* OP_READONLY - Open mailbox read-only
* OP_ANONYMOUS - Dont use or update a .newsrc for news
* OP_HALFOPEN - For IMAP and NNTP names, open a connection but dont open
a mailbox
* CL_EXPUNGE - Expunge mailbox automatically upon mailbox close
imap_ping
imap_ping -- Check if the IMAP stream is still active
Description
int imap_ping(int 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.
imap_renamemailbox
imap_renamemailbox -- Rename an old mailbox to new mailbox
Description
int imap_renamemailbox(int imap_stream, string old_mbox, string new_mbox);
This function renames on old mailbox to new mailbox.
Returns true on success and false on error.
imap_reopen
imap_reopen -- Reopen IMAP stream to new mailbox
Description
int imap_reopen(string imap_stream, string mailbox, string [flags]);
Returns true on success and false on error.
This function reopens the specified stream to new mailbox.
The options are a bit mask with one or more of the following:
* OP_READONLY - Open mailbox read-only
* OP_ANONYMOUS - Dont use or update a .newsrc for news
* OP_HALFOPEN - For IMAP and NNTP names, open a connection but dont open
a mailbox
* CL_EXPUNGE - Expunge mailbox automatically upon mailbox close
imap_subscribe
imap_subscribe -- Subscribe to a mailbox
Description
int imap_subscribe(int imap_stream, string mbox);
Subscribe to a new mailbox.
Returns true on success and false on error.
imap_undelete
imap_undelete -- Unmark the message which is marked deleted
Description
int imap_undelete(int imap_stream, int msg_number);
This function removes the deletion flag for a specified message, which is
set by imap_delete().
Returns true on success and false on error.
imap_unsubscribe
imap_unsubscribe -- Unsubscribe from a mailbox
Description
int imap_unsubscribe(int imap_stream, string mbox);
Unsubscribe from a specified mailbox.
Returns true on success and false on error.
imap_qprint
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
Returns an 8 bit (binary) string
imap_8bit
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.
Returns a quoted-printable string
imap_binary
imap_binary -- Convert an 8bit string to a base64 string.
Description
string imap_binary(string string);
Convert an 8bit string to a base64 string.
Returns a base64 string
imap_scanmailbox
imap_scanmailbox -- Read the list of mailboxes, takes a string to search for
in the text of the mailbox
Description
array imap_scanmailbox(int imap_stream, string string);
Returns an array containing the names of the mailboxes that have string in
the text of the mailbox.
imap_mailboxmsginfo
imap_mailboxmsginfo -- Get information about the current mailbox
Description
array imap_mailboxmsginfo(int imap_stream);
Returns information about the current mailbox. Returns FALSE on failure.
The imap_mailboxmsginfo() function checks the current mailbox status on the
server and returns the information in an object with following properties.
Date : date of the message
Driver : driver
Mailbox : name of the mailbox
Nmsgs : number of messages
Recent : number of recent messages
Unread : number of unread messages
Size : mailbox size
imap_rfc822_write_address
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 given the mailbox, host, and
personal info.
imap_rfc822_parse_adrlist
imap_rfc822_parse_adrlist -- Parses an address string
Description
string imap_rfc822_parse_adrlist(string address, string default_host);
This function parses the address tring and for each address, returns an
array of objects. The 4 objects are:
mailbox - the mailbox name (username)
host - the host name
personal - the personal name
adl - at domain source route
imap_setflag_full
imap_setflag_full -- Sets flags on messages
Description
string imap_setflag_full(int 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 options are a bit mask with one or more of the following:
ST_UID The sequence argument contains UIDs instead of
sequence numbers
imap_clearflag_full
imap_clearflag_full -- Clears flags on messages
Description
string imap_clearflag_full(int 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 options are a bit mask with one or more of the following:
ST_UID The sequence argument contains UIDs instead of
sequence numbers
imap_sort
imap_sort --
Description
string imap_sort(int stream, int criteria, int reverse, int options);
Returns an array of message numbers sorted by the given parameters
Rev 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_fetchheader
imap_fetchheader -- Returns header for a message
Description
stringimap_fetchheader(int imap_stream, int msgno, int flags);
This function causes a fetch of the complete, unfiltered RFC 822 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_uid
imap_uid -- This function returns the UID for the given message sequence
number.
Description
int imap_uid(int imap_stream, int msgno);
This function returns the UID for the given message sequence number. It is
the inverse of imap_msgno().
imap_msgno
imap_msgno -- This function returns the message sequence number for the
given UID.
Description
int imap_msgno(int imap_stream, int uid);
This function returns the message sequence number for the given UID. It is
the inverse of imap_uid().
imap_search
imap_search -- This function returns an array of messages matching the given
search criteria.
Description
array imap_search(int imap_stream, string criteria, int flags);
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 (eg FROM "joe
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
uncomplete or inaccurate. Searcher beware.
Valid values for flags are SE_UID, which causes the returned array to
contain UIDs instead of messages sequence numbers.
imap_last_error
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_errors
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_alerts
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_status
imap_status -- This function returns status information on a mailbox other
than the current one.
Description
object imap_status(int 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.
XXIII. PHP options & information
Table of Contents
error_log Ñ send an error message somewhere
error_reporting Ñ set which PHP errors are reported
getenv Ñ Get the value of an environment variable
get_cfg_var Ñ Get the value of a PHP configuration option.
get_current_user Ñ Get the name of the owner of the current PHP script.
get_magic_quotes_gpc Ñ Get the current active configuration setting of magic
quotes gpc.
get_magic_quotes_runtime Ñ Get the current active configuration setting of
magic_quotes_runtime.
getlastmod Ñ Get time of last page modification.
getmyinode Ñ Get the inode of the current script.
getmypid Ñ Get PHP's process ID.
getmyuid Ñ Get PHP script owner's UID.
getrusage Ñ Get the current resource usages.
phpinfo Ñ Output lots of PHP information.
phpversion Ñ Get the current PHP version.
extension_loaded Ñ find out whether an extension is loaded
putenv Ñ Set the value of an environment variable.
set_magic_quotes_runtime Ñ Set the current active configuration setting of
magic_quotes_runtime.
set_time_limit Ñ limit the maximum execution time
error_log
error_log -- send an error message somewhere
Description
int error_log(string message, int message_type, string [destination], string
[extra_headers]);
Sends an error message to the web server's error log, a TCP port or to a
file. The first parameter, message, is the error message that should be
logged. The second parameter, message_type says where the message should go:
Table 1. error_log() log types
0message is sent to PHP's system logger, using the Operating System's
system logging mechanism or a file, depending on what the error_log
configuration directive is set to.
1message is sent by email to the address in the destination parameter.
This is the only message type where the fourth parameter, extra_headers
is used. This message type uses the same internal function as Mail()
does.
2message is sent through the PHP debugging connection. This option is only
available if remote debugging has been enabled. In this case, the
destination parameter specifies the host name or IP address and
optionally, port number, of the socket receiving the debug information.
3message is appended to the file destination.
Example 1. error_log() examples
// Send notification through the server log if we can not
// connect to the database.
if (!Ora_Logon($username, $password)) {
error_log("Oracle database not available!", 0);
}
// Notify administrator by email if we run out of FOO
if (!($foo = allocate_new_foo()) {
error_log("Big trouble, we're all out of FOOs!", 1,
"operator@mydomain.com");
}
// other ways of calling error_log():
error_log("You messed up!", 2, "127.0.0.1:7000");
error_log("You messed up!", 2, "loghost");
error_log("You messed up!", 3, "/var/tmp/my-errors.log");
error_reporting
error_reporting -- set which PHP errors are reported
Description
int error_reporting(int [level]);
Sets PHP's error reporting level and returns the old level. The error
reporting level is a bitmask of the following values (follow the links for
the internal values to get their meanings):
Table 1. error_reporting() bit values
valueinternal name
1 E_ERROR
2 E_WARNING
4 E_PARSE
8 E_NOTICE
16 E_CORE_ERROR
32 E_CORE_WARNING
getenv
getenv -- Get the value of an environment variable
Description
string getenv(string varname);
Returns the value of the environment variable varname, or false on an error.
$ip = getenv("REMOTE_ADDR"); // get the ip number of the user
You can see a list of all the environmental variables by using phpinfo().
You can find out what many of them mean by taking a look at the CGI
specification, specifically the page on environmental variables.
get_cfg_var
get_cfg_var -- Get the value of a PHP configuration option.
Description
string get_cfg_var(string varname);
Returns the current value of the PHP configuration variable specified by
varname, or false if an error occurs.
It will not return configuration information set when the PHP was compiled,
or read from an Apache configuration file (using the
php3_configuration_option directives).
To check whether the system is using a configuration file, try retrieving
the value of the cfg_file_path configuration setting. If this is available,
a configuration file is being used.
get_current_user
get_current_user -- Get the name of the owner of the current PHP script.
Description
string get_current_user(void);
Returns the name of the owner of the current PHP script.
See also getmyuid(), getmypid(), getmyinode(), and getlastmod().
get_magic_quotes_gpc
get_magic_quotes_gpc -- Get the current active configuration setting of
magic quotes gpc.
Description
long get_magic_quotes_gpc(void);
Returns the current active configuration setting of magic_quotes_gpc. (0 for
off, 1 for on)
See also get_magic_quotes_runtime(), set_magic_quotes_runtime().
get_magic_quotes_runtime
get_magic_quotes_runtime -- Get the current active configuration setting of
magic_quotes_runtime.
Description
long get_magic_quotes_runtime(void);
Returns the current active configuration setting of magic_quotes_runtime. (0
for off, 1 for on)
See also get_magic_quotes_gpc(), set_magic_quotes_runtime().
getlastmod
getlastmod -- Get time of last page modification.
Description
int getlastmod(void);
Returns the time of the last modification of the current page. The value
returned is a Unix timestamp, suitable for feeding to date(). Returns false
on error.
Example 1. getlastmod() example
// outputs e.g. 'Last modified: March 04 1998 20:43:59.'
echo "Last modified: ".date( "F d Y H:i:s.", getlastmod() );
See alse date(), getmyuid(), get_current_user(), getmyinode(), and
getmypid().
getmyinode
getmyinode -- Get the inode of the current script.
Description
int getmyinode(void);
Returns the current script's inode, or false on error.
See also getmyuid(), get_current_user(), getmypid(), and getlastmod().
getmypid
getmypid -- Get PHP's process ID.
Description
int getmypid(void);
Returns the current PHP process ID, or false on error.
Note that when running as a server module, separate invocations of the
script are not guaranteed to have distinct pids.
See also getmyuid(), get_current_user(), getmyinode(), and getlastmod().
getmyuid
getmyuid -- Get PHP script owner's UID.
Description
int getmyuid(void);
Returns the user ID of the current script, or false on error.
See also getmypid(), get_current_user(), getmyinode(), and getlastmod().
getrusage
getrusage -- Get the current resource usages.
Description
array getrusage(int [who]);
This is an interface to getrusage(2). It returns an associative array
containing the data returned from the system call. If who is 1, getrusage
will be called with RUSAGE_CHILDREN. All entries are accessible by using
their documented field names.
Example 1. Getrusage Example
$dat = getrusage();
echo $dat["ru_nswap"]; # number of swaps
echo $dat["ru_majflt"]; # number of page faults
echo $dat["ru_utime.tv_sec"]; # user time used (seconds)
echo $dat["ru_utime.tv_usec"]; # user time used (microseconds)
See your system's man page for more details.
phpinfo
phpinfo -- Output lots of PHP information.
Description
int phpinfo(void);
Outputs a large amount of information about the current state of PHP. This
includes information about PHP compilation options and extensions, the PHP
version, server information and environment (if compiled as a module), the
PHP environment, OS version information, paths, master and local values of
configuration options, HTTP headers, and the GNU Public License.
See also phpversion().
phpversion
phpversion -- Get the current PHP version.
Description
string phpversion(void);
Returns a string containing the version of the currently running PHP parser.
Example 1. phpversion() example
// prints e.g. 'Current PHP version: 3.0rel-dev'
echo "Current PHP version: ".phpversion();
See also phpinfo().
extension_loaded
extension_loaded -- find out whether an extension is loaded
Description
bool extension_loaded(string name);
Returns true if the extension identified by name is loaded. You can see the
names of various extensions by using phpinfo().
See also phpinfo().
Note: This function was added in 3.0.10.
putenv
putenv -- Set the value of an environment variable.
Description
void putenv(string setting);
Adds setting to the environment.
Example 1. Setting an Environment Variable
putenv("UNIQID=$uniqid");
set_magic_quotes_runtime
set_magic_quotes_runtime -- Set the current active configuration setting of
magic_quotes_runtime.
Description
long set_magic_quotes_runtime(int new_setting);
Set the current active configuration setting of magic_quotes_runtime. (0 for
off, 1 for on)
See also get_magic_quotes_gpc(), get_magic_quotes_runtime().
set_time_limit
set_time_limit -- limit the maximum execution time
Description
void set_time_limit(int seconds);
Set the number of seconds a script is allowed to run. If this is reached,
the script returns a fatal error. The default limit is 30 seconds or, if it
exists, the max_execution_time value defined in the configuration file. If
seconds is set to zero, no time limit is imposed.
When called, set_time_limit() restarts the timeout counter from zero. In
other words, if the timeout is the default 30 seconds, and 25 seconds into
script execution a call such as set_time_limit(20) is made, the script will
run for a total of 45 seconds before timing out.
XXIV. Informix functions
The Informix driver for Online (ODS) 7.x, SE 7.x and Universal Server (IUS)
9.x is implemented in "functions/ifx.ec" and "functions/php3_ifx.h". ODS 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.
Configuration notes:
Before you run the "configure" script, make sure that the
"INFORMIXDIR" variable has been set.
The configure script will autodetect the libraries and include
directories, if you run "configure --with_informix=yes". You can
overide this detection by specifying "IFX_LIBDIR", "IFX_LIBS" and
"IFX_INCDIR" in the environment. The configure script will also
try to detect your Informix server version. It will set the
"HAVE_IFX_IUS" conditional compilation variable if your Informix
version >= 9.00.
Some notes on the use of BLOBs (TEXT and BYTE columns):
BLOBs are normally addressed by integer 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, without the use of blob id's for select queries.
ifx_byteasvarchar(1) : return BYTE columns as if they were VARCHAR
columns, without the use of 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.
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.
Table of Contents
ifx_connect Ñ Open Informix server connection
ifx_pconnect Ñ Open persistent Informix connection
ifx_close Ñ Close Informix connection
ifx_query Ñ Send Informix query
ifx_prepare Ñ Prepare an SQL-statement for execution
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_affected_rows Ñ Get number of rows affected by a query
ifx_getsqlca Ñ Get the contents of sqlca.sqlerrd[0..5] after a query
ifx_fetch_row Ñ Get row as enumerated array
ifx_htmltbl_result Ñ Formats all rows of a query into a HTML table
ifx_fieldtypes Ñ List of Informix SQL fields
ifx_fieldproperties Ñ List of SQL fieldproperties
ifx_num_fields Ñ Returns the number of columns in the query
ifx_num_rows Ñ Count the rows already fetched a query
ifx_free_result Ñ Releases resources for the query
ifx_create_char Ñ Creates an char object
ifx_free_char Ñ Deletes the char object
ifx_update_char Ñ Updates the content of the char object
ifx_get_char Ñ Return the content of the char object
ifx_create_blob Ñ Creates an blob object
ifx_copy_blob Ñ Duplicates the given blob object
ifx_free_blob Ñ Deletes the blob object
ifx_get_blob Ñ Return the content of a blob object
ifx_update_blob Ñ Updates the content of the blob object
ifx_blobinfile_mode Ñ Set the default blob mode for all select queries
ifx_textasvarchar Ñ Set the default text mode
ifx_byteasvarchar Ñ Set the default byte mode
ifx_nullformat Ñ Sets the default return value on a fetch row
ifxus_create_slob Ñ Creates an slob object and opens it
ifx_free_slob Ñ Deletes the slob object
ifxus_close_slob Ñ Deletes the slob object
ifxus_open_slob Ñ Opens an slob object
ifxus_tell_slob Ñ Returns the current file or seek position
ifxus_seek_slob Ñ Sets the current file or seek position
ifxus_read_slob Ñ Reads nbytes of the slob object
ifxus_write_slob Ñ Writes a string into the slob object
ifx_connect
ifx_connect -- Open Informix server connection
Description
int ifx_connect(string [database] , string [userid] , string [password] );
Returns an 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().
See also ifx_pconnect(), and ifx_close().
Example 1. Connect to a Informix database
$conn_id = ifx_pconnect (mydb@ol_srv1, "imyself", "mypassword");
ifx_pconnect
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_close
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().
See also: ifx_connect(), and ifx_pconnect().
Example 1. Closing a Informix connection
$conn_id = ifx_connect (mydb@ol_srv, "itsme", "mypassword");
... some queries and stuff ...
ifx_close($conn_id);
ifx_query
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.
An integer "result_id" 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. 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 ifx_connect() was called, and use
it.
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 mask and can be either
IFX_SCROLL, IFX_HOLD, or both or'ed together. Non-select queries are
"execute immediate".
For either query type the number of (estimated or real) affected rows is
saved for retrieval by ifx_affected_rows().
If 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).
See also: ifx_connect().
Example 1. Show all rows of the "orders" table as a html table
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