only for RuBoard - do not distribute or recompile |
PHP has very few built-in functions. When you use the configuration script and the compiler to build PHP, you cause functions to become visible to PHP. For all intents and purposes, they are "built in."
Some functions become available when you build PHP on a system that has a particular library. Other functions must be compiled in by specifying the functionality required on the configure command line. The sheer number of libraries available to PHP precludes listing all of them in this book. You will find a comprehensive list at http://www.php.net.
One of the strengths of PHP is its strong suite of array manipulation functions. Arrays are covered in more depth in the chapter on PHP. The following section covers a useful subset of the array functions. (A complete PHP manual is online at http://www.php.net/manual.)
Description array is a construct, which creates and fills an array in one step.
Usage:
<?php $myArray = array (1, 2, 3, 4, 5); ?>
Description: Returns an associative array that contains the number of times each element occurred, with the key to that value being the element in the input array. In other words, if "hello" is in the CheckedArray three times, an array is returned that, when indexed by "hello", returns 3.
See Also: array, array_diff
Usage:
<?php $myArray = array (1, 1, 3, 3, 3, 4, 5); $Frequency = array_count_values($myArray); // the following prints "Frequency of 1 is 2" echo "Frequency of 1 is ".$Frequency["1"]."<BR>"; //$Frequency["1"]=2,$Frequency["3"]=3,$Frequency["4"]=1,$Frequency["5"]=1 ?>
Description: Returns an array that consists of all the members in CheckedArray that don't exist in any of the TestArrays.
See Also: array, array_count_values
Usage:
<?php $myArray = array (1, 2, 3, 4, 5); $myArray2 = array (4, 5, 6); $MyArray3 = array (3, 4, 5); $DifferenceArray = array_diff($myArray,$myArray2,$myArray3); // $DifferenceArray has in it the values 1,2 ?>
Description: Returns an array containing values that are present in all of the arrays. This is the logical reverse of the array_diff() function.
See Also: array_diff
Usage:
<?php $myArray = array (1, 2, 3, 4, 5); $myArray2 = array (4, 5, 6); $MyArray3 = array (3, 4, 5); $Intersect = array_intersect($myArray,$myArray2,$myArray3); // $Intersect now contains the values 4,5 ?>
Description: Returns an array containing the keys in the CheckedArray. If LookForThisValue is specified, only the key for that value is returned.
See Also: array_count_values
Usage:
<?php $myArray = array (1, 2, 3, 4, 5); $Frequency = array_count_values($myArray); //$Frequency["1"]=2,$Frequency["3"]=3,$Frequency["4"]=1,$Frequency["5"]=1 $FreqKey = array_keys($Frequency); //$FreqKey now contains "1","3","4","5" ?>
Description: Appends MergeArray1, MergeArray2, and so forth to StartArray. If one of the MergeArrayx arrays has a string key (for example, " color ") that is duplicated in StartArray, the last new value for that key will overwrite the value in StartArray. Simple numeric keys (normal indexes) are not overwritten, but the values are appended and placed in the new array.
See Also: array_diff
Usage:
<?php $myArray = array ("brown"=>1, "red"=>2); $myArray2 = array ("brown"=>12, "orange"=>5); $MergedArray = array_merge($myArray,$myArray2); // The new array is $MergedArray[] // $MergedArray["brown"] == 12, $MergedArray["red"] == 2 // $MergedArray["orange"] == 5 ?>
Description: Pads a copy of the WorkArray with the ValueToPadWith so the array is the size of PadToThisSize. If PadToThisSize is the same size as or smaller than the array is already, no padding occurs. It returns the padded array.
See Also: array_pop
Usage:
<?php $myArray = array (1, 2, 3); $paddedArray = array_pad($myArray,6,99); // $paddedArray now has 1,2,3,99,99,99 ?>
Description: Removes the last element in WorkArray, and returns the value removed from the array.
See Also: array_push
Usage:
<?php $myArray = array (1, 2, 3, 4, 5); $n = array_pop($myArray); echo "Value removed is $n<BR>";// $n is 5 // $myArray now has 1,2,3,4 ?>
Description: Adds Value1, Value2, and so forth onto the end of WorkArray, and returns the size of the new array. Adding one element is the same as doing $array[] = $newValue;
See Also: array_pop
Usage:
<?php $myArray = array (1, 2, 3, 4, 5); $n = array_push($myArray,6,7); echo "There are now $n elements in $myArray<BR>"; // prints "There are now 7 elements in $myArray ?>
Description: Returns an array that has the order of the elements in WorkArray reversed .
Usage:
<?php $myArray = array (1, 2, 3); $myArray2 = array_reverse($WorkArray); echo "Reversed Array element "; for ($index = 0 ; $index < count($myArray2); $index++) echo "$index = ".$myArray2[$index].", "; echo "<br>"; // prints Reversed Array element 0 = 3, 1 = 2, 3 = 1 ?>
Description: Removes the first element in WorkArray, and returns the value removed from the array. All remaining elements are moved down one.
See Also: array_pop
Usage:
<?php $myArray = array (1, 2, 3, 4, 5); $n = array_shift($myArray); echo "Value removed is $n<BR>";// $n is a 1 // $myArray now has 2,3,4,5 ?>
Description: Removes elements from WorkArray, starting at OffsetIndex for Length elements. If ReplacementArray is provided, the elements removed in WorkArray are replaced by the elements in ReplacementArray. If there are more elements in ReplacementArray than cut, the extra elements will be inserted.
If OffsetIndex is negative, the offset is calculated from the end of the array. If OffsetIndex is positive, the offset is calculated from the beginning of the array. Items are removed starting at the OffsetIndex value.
If Length is omitted, the rest of the array from OffsetIndex is used. If Length is positive, it specifies the number of elements to cut. If Length is negative, then it specifies the number of elements to leave on the end of the array from the end of the cut. For an example, see the usage section.
If OffsetIndex and Length have values that would cause no elements to be removed from the array, and ReplacementArray is specified, then elements from ReplacementArray are added into WorkArray starting at OffsetIndex. Array_splice returns the removed elements in an array.
See Also: array_push, array_pop, array_shift
Usage:
<?php $myArray = array (1, 2, 3, 4, 5); $myArray2 = array (6 , 7 , 8); $myArray3 = array (9, 10, 11); $RemovedItems = array_splice($myArray,3,1,$myArray2); echo "myArray=<BR>"; for ($index = 0 ; $index < count($myArray); $index++) echo "item $index = ".$myArray[$index]."<br>"; echo "<BR>RemovedItems=<BR>"; for ($index = 0 ; $index < count($RemovedItems); $index++) echo "item $index = ".$RemovedItems[$index]."<br>"; echo "<BR>myArray2=<BR>"; $RemovedItems = array_splice($myArray2,2,0,$myArray3); for ($index = 0 ; $index < count($myArray2); $index++) echo "item $index = ".$myArray2[$index]."<br>"; /* The following is printed: myArray= item 0 = 1 item 1 = 2 item 2 = 3 item 3 = 6 item 4 = 7 item 5 = 8 item 6 = 5 RemovedItems= item 0 = 4 myArray2= item 0 = 6 item 1 = 7 item 2 = 9 item 3 = 10 item 4 = 11 item 5 = 8 */ $myArray = array (1, 2, 3, 4, 5); $myArray2 = array (6 , 7 , 8); $RemovedItems = array_splice($myArray,2,-1,$myArray2); echo "myArray=<BR>"; for ($index = 0 ; $index < count($myArray); $index++) echo "item $index = ".$myArray[$index]."<br>"; echo "<BR>RemovedItems=<BR>"; for ($index = 0 ; $index < count($RemovedItems); $index++) echo "item $index = ".$RemovedItems[$index]."<br>"; /* The following is printed: myArray= item 0 = 1 item 1 = 2 item 2 = 6 item 3 = 7 item 4 = 8 item 5 = 5 RemovedItems= item 0 = 3 item 1 = 4 */ ?>
Description: Puts Value1, Value2, and so on onto the front of the WorkArray, and returns the final number of elements in the array.
See Also: array_shift
Usage:
<?php $myArray = array (1, 2, 3, 4, 5); $n = array_unshift($myArray, 10, 11, 12);// $n is 8 // $myArray is now 10,11,12,1,2,3,4,5 ?>
Description: Returns the values in an array. This is best used with an associative array. It effectively turns the associative indexes into numerical indexes.
Usage:
<?php $myArray = array ("brown"=>1, "red"=>2); $newArray = array_values($myArray); // $newArray is now (1, 2), and // $newArray[0] = 1, $newArray[1]=2 item 2 = 9 item 3 = 10 item 4 = 11 item 5 = 8 */ $myArray = array (1, 2, 3, 4, 5); $myArray2 = array (6 , 7 , 8); $RemovedItems = array_splice($myArray,2,-1,$myArray2); echo "myArray=<BR>";
for ($index = 0 ; $index < count($myArray); $index++) echo "item $index = ".$myArray[$index]."<br>"; echo "<BR>RemovedItems=<BR>"; for ($index = 0 ; $index < count($RemovedItems); $index++) echo "item $index = ".$RemovedItems[$index]."<br>"; /* The following is printed: myArray= item 0 = 1 item 1 = 2 item 2 = 6 item 3 = 7 item 4 = 8 item 5 = 5 RemovedItems= item 0 = 3 item 1 = 4 */ ?>
Description: Puts Value1 , Value2 , and so on onto the front of the WorkArray , and returns the final number of elements in the array.
See Also: array_shift
Usage:
<?php $myArray = array (1, 2, 3, 4, 5); $n = array_unshift($myArray, 10, 11, 12);// $n is 8 // $myArray is now 10,11,12,1,2,3,4,5 ?>
Description: Returns the values in an array. This is best used with an associative array. It effectively turns the associative indexes into numerical indexes.
Usage:
<?php $myArray = array ("brown"=>1, "red"=>2); $newArray = array_values($myArray); // $newArray is now (1, 2), and // $newArray[0] = 1, $newArray[1]=2 ?>
Description: Calls FunctionName for each and every element in WorkArray , handing the function the array value, the array key, and UserSuppliedData. If the user -defined function defines the value to be passed by reference, the value in the array can be changed directly. If you do not want to provide the UserSuppliedData , or if your function takes more than three parameters, call the walk function with an @ prepended to squelch warnings from PHP: @array_walk($array,"func");
Usage:
<?php // this function defines the value to be passed by reference // to allow it to change the array value directly // and doubles each array value without checking to see // if it is actually a number! Function DoubleArrayValues(&$ArrayValue, $ArrayKey, $UserSuppliedData) {/*function work here */ echo "array value *2 == ".($ArrayValue*2)."<BR>"; // now double the value in the array $ArrayValue = $ArrayValue * 2; } $myArray = array (1, 2, 3, 4, 5); @array_walk($myArray,"DoubleArrayValues"); for ($index = 0 ; $index < count($myArray); $index++) echo "array value is now ".$myArray[$index]."<br>"; reset($myArray); // rest the array curso ?>
Description: Sorts an array in reverse order, per SortFlags. This function only affects associative arrays. The associative index still works, but the natural order in the array is affected. The reset() function must be called after using arsort() to reset the array cursor. The SortFlags can be one of the following:
SORT_REGULAR ”Compare each element in the array normally, as their type would dictate .
SORT_NUMERIC ”Compare each element in the array as numbers only.
SORT_STRING ”Compare each element in the array as strings only.
See Also: asort , sort , reset , array_values , each
Usage:
<?php $myArray = array("first"=>"brown","second"=> "red", "third"=>"blue", "fourth"=>"green", "fifth"=>"pink"); $myArray2 = array_values($myArray); echo "<BR>natural order =<BR>"; for ($index = 0 ; $index < count($myArray2); $index++) echo "item $index = ".$myArray2[$index]."<br>"; arsort($myArray); reset($myArray); echo "<BR>reverse sorted=<BR>"; $myArray2 = array_values($myArray); for ($index = 0 ; $index < count($myArray2); $index++) echo "item $index = ".$myArray2[$index]."<br>"; echo "note that 'first' is still ".$myArray["first"]."<BR>"; /* the following is printed: natural order = item 0 = brown item 1 = red item 2 = blue item 3 = green item 4 = pink reverse sorted= item 0 = red item 1 = pink item 2 = green item 3 = brown item 4 = blue note that 'first' is still brown *?>
Description: Sorts an array in order, per SortFlags. This function only affects associative arrays. The associative index still works, but the natural order in the array is affected. The reset() function must be called after using asort() to reset the array cursor. See arsort() for SortFlags definition.
See Also: arsort , reset , array_values , each
Usage:
<?php $myArray = array("first"=>"brown","second"=> "red", "third"=>"blue", "fourth"=>"green", "fifth"=>"pink"); $myArray2 = array_values($myArray); echo "<BR>natural order =<BR>"; for ($index = 0 ; $index < count($myArray2); $index++) echo "item $index = ".$myArray2[$index]."<br>"; asort($myArray); reset($myArray); echo "<BR> sorted=<BR>"; $myArray2 = array_values($myArray); for ($index = 0 ; $index < count($myArray2); $index++) echo "item $index = ".$myArray2[$index]."<br>"; echo "note that 'first' is still ".$myArray["first"]."<BR>"; /* prints this: natural order = item 0 = brown item 1 = red item 2 = blue item 3 = green item 4 = pink sorted= item 0 = blue item 1 = brown item 2 = green item 3 = pink item 4 = red note that 'first' is still brown *?>
Description: Returns the number of elements in WorkArray. If the variable is not an array, but has been set, it returns 1. If the variable is not set, or if the variable has been initialized with an empty array, it returns 0.
See Also: array , array_values , each
Usage:
<?php $myArray = array (1, 2, 3, 4, 5); for ($index = 0 ; $index < count($myArray); $index++) echo "array index $index is now ".$myArray[$index]."<br>"; /* prints this: array index 0 is now 1 array index 1 is now 2 array index 2 is now 3 array index 3 is now 4 array index 4 is now 5 *?>
Description: Returns the value that the array cursor points to.
See Also: key , each , next
NOTE
In PHP, an invisible array cursor exists for each array. This array cursor is used by several functions to allow PHP to "walk" through arrays one element at a time. You should call the reset() function before you start using any array function that manipulates this cursor, to guarantee you will start at the beginning of the array.
Usage:
<?php $myArray = array (1, 2, 3, 4, 5); reset($myArray); $value = current($myArray);// $value is now == ?>
Description: Returns a four-element array (from the WorkArray array cursor position) consisting of the key and value from an array indexed by 0 and 1, as well as by "key" and "value" , respectively. If the WorkArray cursor points past the end of WorkArray , each returns FALSE. The each function advances the array cursor, unless it is already past the end of the array.
See Also: reset
Usage:
<?php $myArray = array("first"=>"brown","second"=> "red", "third"=>"blue", "fourth"=>"green", "fifth"=>"pink"); reset($myArray);// reset the array cursor (not needed in this case) while ($snoop = each($myArray)) { echo "key ".$snoop["key"]." has a value of ".$snoop["value"]."<BR>"; echo "key [index 0] ".$snoop[0]." has a value [index 1] of ".$snoop[1]."<BR>"; } /* prints this : key first has a value of brown key [index 0] first has a value [index 1] of brown key second has a value of red key [index 0] second has a value [index 1] of red key third has a value of blue key [index 0] third has a value [index 1] of blue key fourth has a value of green key [index 0] fourth has a value [index 1] of green key fifth has a value of pink key [index 0] fifth has a value [index 1] of pink *?>
Description: Sets the array cursor to the last element in the array.
See Also: prev , next , current , each , end , reset
Usage:
<?php $myArray = array (1, 2, 3, 4, 5); end($myArray); $value = current($myArray);// $value is now == ?>
Description: Returns TRUE if value SearchFor is found in SearchedArray. It returns FALSE if the variable is not found.
See Also: array
Usage:
<?php $myArray = array("first"=>"brown","second"=> "red", "third"=>"blue", "fourth"=>"green", "fifth"=>"pink"); if (in_array("pink",$myArray)) echo "found pink in myArray<BR>";// prints this messag?>
Description: Returns the key for the current array cursor position.
See Also: prev , next , current , each , end , reset
Usage:
<?php $myArray = array("first"=>"brown","second"=> "red", "third"=>"blue", "fourth"=>"green", "fifth"=>"pink"); reset($myArray);// reset the array cursor (not needed in this case) $key = key($myArray); // $key now == "first?>
Description: Sorts an array's keys in reverse order, per SortFlags. This function only affects associative arrays. The associative index still works, but the natural order of the values in the array is affected. The reset() function must be called after using krsort() to reset the array cursor. See arsort() for SortFlags definition.
See Also: arsort , assort, reset , array_values , each
Usage:
<?php $myArray = array("first"=>"brown","second"=> "red", "third"=>"blue", "fourth"=>"green", "fifth"=>"pink"); $myArray2 = array_values($myArray); echo "<BR>natural order =<BR>"; for ($index = 0 ; $index < count($myArray2); $index++) echo "item $index = ".$myArray2[$index]."<br>"; krsort($myArray); reset($myArray); echo "<BR> sorted=<BR>"; $myArray2 = array_values($myArray); reset($myArray); while(list($key,$value) = each($myArray)) print "The sorted key is $key, and its value is $value<BR>"; echo "<br>"; for ($index = 0 ; $index < count($myArray2); $index++) echo "Natural order item $index = ".$myArray2[$index]."<br>"; echo "note that 'first' is still ".$myArray["first"]."<BR>"; /* prints this: natural order = item 0 = brown item 1 = red item 2 = blue item 3 = green item 4 = pink sorted= The sorted key is third, and its value is blue The sorted key is second, and its value is red The sorted key is fourth, and its value is green The sorted key is first, and its value is brown The sorted key is fifth, and its value is pink Natural order item 0 = blue Natural order item 1 = red Natural order item 2 = green Natural order item 3 = brown Natural order item 4 = pink note that 'first' is still brown *?>
Description: Sorts an array's keys in order, per SortFlags. This function only affects associative arrays. The associative index still works, but the natural order of the values in the array is affected. The reset() function must be called after using ksort() to reset the array cursor. See arsort() for SortFlags definition.
See Also: arsort , assort , reset , array_values , each
Usage:
<?php $myArray = array("first"=>"brown","second"=> "red", "third"=>"blue", "fourth"=>"green", "fifth"=>"pink"); $myArray2 = array_values($myArray); echo "<BR>natural order =<BR>"; for ($index = 0 ; $index < count($myArray2); $index++) echo "item $index = ".$myArray2[$index]."<br>"; ksort($myArray); reset($myArray); echo "<BR> sorted=<BR>"; $myArray2 = array_values($myArray); reset($myArray); while(list($key,$value) = each($myArray)) print "The sorted key is $key, and its value is $value<BR>"; echo "<br>"; for ($index = 0 ; $index < count($myArray2); $index++) echo "Natural order item $index = ".$myArray2[$index]."<br>"; echo "note that 'first' is still ".$myArray["first"]."<BR>"; /* prints this: natural order = item 0 = brown item 1 = red item 2 = blue item 3 = green item 4 = pink sorted= The sorted key is fifth, and its value is pink The sorted key is first, and its value is brown The sorted key is fourth, and its value is green The sorted key is second, and its value is red The sorted key is third, and its value is blue Natural order item 0 = pink Natural order item 1 = brown Natural order item 2 = green Natural order item 3 = red Natural order item 4 = blue note that 'first' is still brown *?>
Description: list is a PHP construct that assigns variables values as if they were array elements. You can use this with any function that returns a list of items, such as mysql_fetch_row() or each() .
See Also: prev , current , each , end , reset
Usage:
<?php $myArray = array("first"=>"brown","second"=> "red", "third"=>"blue", "fourth"=>"green", "fifth"=>"pink"); while(list($key,$value) = each($myArray)) print "The key is $key, and its value is $value<BR>"; echo "<br>"; /* prints this The key is first, and its value is brown The key is second, and its value is red The key is third, and its value is blue The key is fourth, and its value is green The key is fifth, and its value is pink *?>
Description: Advances the array cursor, and then returns the value that the array cursor points to, or FALSE if at the end of the array. It also returns FALSE if the array element at that location is empty.
See Also: prev , current , each , end , reset
Usage:
<?php $myArray = array (1, 2, 3, 4, 5); reset($myArray); $value = next($myArray);// $value is now == ?>
Description: array is a construct, which creates and fills an array in one step.
See Also: next, current , each , end , reset
Usage:
<?php $myArray = array (1, 2, 3, 4, 5); end($myArray); $value = prev($myArray);// $value is now == ?>
Description: Sorts an array in reverse order, per SortFlags. The associative index is destroyed . The reset() function must be called after using sort() to reset the array cursor. See arsort() for SortFlags definition.
See Also: arsort , assort , reset , array_values , each
Usage:
<?php $myArray = array (4, 2, 1, 3, 5); for ($index = 0 ; $index < count($myArray); $index++) echo "array index $index is now ".$myArray[$index]."<br>"; rsort($myArray); echo "<BR>reverse sorted =<BR>"; for ($index = 0 ; $index < count($myArray); $index++) echo "array index $index is now ".$myArray[$index]."<br>"; /* prints this: array index 0 is now 4 array index 1 is now 2 array index 2 is now 1 array index 3 is now 3 array index 4 is now 5 reverse sorted = array index 0 is now 5 array index 1 is now 4 array index 2 is now 3 array index 3 is now 2 array index 4 is now 1 *?>
Description: Sorts an array in order, per SortFlags. The associative index is destroyed. The reset() function must be called after using sort() to reset the array cursor. See arsort() for SortFlags definition.
See Also: arsort , assort , reset , array_values , each
Usage:
<?php $myArray = array (4, 2, 1, 3, 5); for ($index = 0 ; $index < count($myArray); $index++) echo "array index $index is now ".$myArray[$index]."<br>"; rsort($myArray); echo "<BR>reverse sorted =<BR>"; for ($index = 0 ; $index < count($myArray); $index++) echo "array index $index is now ".$myArray[$index]."<br>"; /* prints this: array index 0 is now 4 array index 1 is now 2 array index 2 is now 1 array index 3 is now 3 array index 4 is now 5 reverse sorted = array index 0 is now 1 array index 1 is now 2 array index 2 is now 3 array index 3 is now 4 array index 4 is now 5 *?>
Description: Sorts an array by calling a user-supplied function which return 0 when elements are equal, -1 when the first element is less than the second element, and 1 when the first element is greater than the second element. The user function can be a standalone function or a method within an object. To call it as a function within an object, pass the object and the name of the method as an array to usort .
See Also: asort
Usage:
<?php $myArray = array (1, 3, 2, 5, 4); Function cmp($a,$b) { if ($a>$b) return 1; if ($a<$b) return 1; return 0; // must be equal } usort($arr,"cmp");// $myArray now = 1,2,3,4,5 /* an alternative method */ $myArray = array (1, 3, 2, 5, 4); Class sort { Var $misc; Function compare($a,$b) { if ($a>$b) return 1; if ($a<$b) return 1; return 0; // must be equal } } $MySort = new sort; usort($arr,array($MySort,"compare") ?>
Description: Sorts an array by calling a user-supplied function which return 0 when elements are equal, -1 when the first element is less than the second element, and 1 when the first element is greater than the second element. The user function can be a standalone function, or a method within an object. To call it as a function within an object, pass the object and the name of the method as an array to usort. This should not be used on an associative array. You must call reset() after using usort() to reset the array cursor.
See Also: asort , arsort , reset , array_values , each
Usage:
<?php $myArray = array (1, 3, 2, 5, 4); Function cmp($a,$b) {
if ($a>$b) return 1; if ($a<$b) return 1; return 0; // must be equal } usort($arr,"cmp");// $myArray now = 1,2,3,4,5 /* an alternative method */ $myArray = array (1, 3, 2, 5, 4); Class sort { Var $misc; Function compare($a,$b) { if ($a>$b) return 1; if ($a<$b) return 1; return 0; // must be equal } } $MySort = new sort; usort($arr,array($MySort,"compare")?>
Description: Sorts an associative array by calling a user-supplied function which return 0 when elements are equal, -1 when the first element is less than the second element, and 1 when the first element is greater than the second element. The user function can be a standalone function or a method within an object. To call it as a function within an object, pass the object and the name of the method as an array to usort. You must call reset() after using uasort() to reset the array cursor.
See Also: asort , usort , arsort , reset , array_values , each
Usage:
<?php Function cmp($a,$b) { if ($a>$b) return 1; if ($a<$b) return -1; return 0; // must be equal } Class sort { Var $misc; Function compare($a,$b) { if ($a>$b)
return 1; if ($a<$b) return -1; return 0; // must be equal } } $myArray = array("first"=>"brown","second"=> "red", "third"=>"blue", "fourth"=>"green", "fifth"=>"pink"); while(list($key,$value) = each($myArray)) print "The key is $key, and its value is $value<BR>"; echo "<br>"; uasort($myArray,"cmp");// $myArray now = 1,2,3,4,5 reset($myArray); echo "Sorted array =<BR>"; while(list($key,$value) = each($myArray)) print "The key is $key, and its value is $value<BR>"; echo "<br>"; /* an alternative method */ $myArray = array("first"=>"brown","second"=> "red", "third"=>"blue", "fourth"=>"green", "fifth"=>"pink"); $MySort = new sort; uasort($myArray,array($MySort,"compare")); echo "<BR>alternative sort method<BR>"; while(list($key,$value) = each($myArray)) print "The key is $key, and its value is $value<BR>"; echo "<br>"; /* prints this: The key is first, and its value is brown The key is second, and its value is red The key is third, and its value is blue The key is fourth, and its value is green The key is fifth, and its value is pink Sorted array = The key is third, and its value is blue The key is first, and its value is brown The key is fourth, and its value is green The key is fifth, and its value is pink The key is second, and its value is red alternative sort method The key is third, and its value is blue The key is first, and its value is brown The key is fourth, and its value is green The key is fifth, and its value is pink The key is second, and its value is red *?>
Description: Sorts an associative array's keys by calling a user-supplied function which return 0 when elements are equal, -1 when the first element is less than the second element, and 1 when the first element is greater than the second element. The user function can be a standalone function or a method within an object. To call it as a function within an object, pass the object and the name of the method as an array to usort. You must call reset() after using uksort() to reset the array cursor.
See Also: asort , usort , uasort , arsort , reset , array_values , each
Usage:
<?php Function cmp($a,$b) { if ($a>$b)
return 1; if ($a<$b) return -1;
return 0; // must be equal } Class sort { Var $misc; Function compare($a,$b) { if ($a>$b) return 1; if ($a<$b) return -1; return 0; // must be equal } } $myArray = array("first"=>"brown","second"=> "red", "third"=>"blue", "fourth"=>"green", "fifth"=>"pink"); while(list($key,$value) = each($myArray)) print "The key is $key, and its value is $value<BR>"; echo "<br>"; uksort($myArray,"cmp");// $myArray now = 1,2,3,4,5 reset($myArray); echo "Sorted array =<BR>"; while(list($key,$value) = each($myArray)) print "The key is $key, and its value is $value<BR>"; echo "<br>"; /* an alternative method */ $myArray = array("first"=>"brown","second"=> "red", "third"=>"blue", "fourth"=>"green", "fifth"=>"pink");
$MySort = new sort; uksort($myArray,array($MySort,"compare")); echo "<BR>alternative sort method<BR>"; while(list($key,$value) = each($myArray)) print "The key is $key, and its value is $value<BR>"; echo "<br>"; $myArray = array("first"=>"brown","second"=> "red", "third"=>"blue", "fourth"=>"green", "fifth"=>"pink"); /* prints this: The key is first, and its value is brown The key is second, and its value is red The key is third, and its value is blue The key is fourth, and its value is green The key is fifth, and its value is pink Sorted array = The key is fifth, and its value is pink The key is first, and its value is brown The key is fourth, and its value is green The key is second, and its value is red The key is third, and its value is blue alternative sort method The key is fifth, and its value is pink The key is first, and its value is brown The key is fourth, and its value is green The key is second, and its value is red The key is third, and its value is blue *?>
Input and Output, also known as I/O, falls into two categories: sending or receiving text to and from a Web browser, and reading and writing data to a data storage device.
Getting text from Web browsers has already been covered in the Variables section in this appendix. The special case of file upload will be covered later in the File I/O section.
When sending text to a Web browser, you can use echo() , print() , printf() , flush() , and die(). Text that is placed outside of PHP tags is sent unmodified to the Web browser.
You can read data from a file and print it to the Web browser. You can also print data that is derived from databases or calculations. A few debugging functions are available to PHP that send text to a Web browser. These functions include phpinfo() , phpversion() , and show_source() .
This section covers general I/O functions available to the programmer. Some of these functions perform other tasks at the same time.
Description: Outputs a string and quit executing the current script. You can use the Perl-like syntax:
function_call() or die ('string');
This syntax can be used with any function that can return false when it has failed.
See Also: exit
Usage:
<?php $a = 2; $b = 3; if ($a == 3) die ("A is a bad value, exiting<p>\n"); if ($b == 3) die; // exit without printing a message $file = fopen("filename","r") or die ("file did not open<p>")?>
Description: Loads a PHP extension at runtime. The extension_dir configuration directive must be set in php.ini.
NOTE
PHP 3 uses php3.ini as its configuration file. PHP<\2> 4 changed the configuration file to php4.ini. On the Windows platform, if you try to use any php3_*.dll extensions under PHP 4, it will fail.
Usage: This is mainly useful under the Windows operating system. You must uncomment the extension=php_*.dll lines in php.ini under Windows to enable loading of the extension automatically. If you are doing it under Unix and Apache, change the .dll to .so in the php.ini file.
dl('php_myextension.dll' or die ('Extension myextension failed to load');
To do the same thing under Linux or Unix, you would use the following type of command:
dl('calendar.so');
Description: Outputs a string to the Web browser. If you use only one string in the output list, you can enclose it in parentheses.
See Also: print , printf , flush
Usage:
echo 'Hello George',' how are you doing?'; echo ("Hello World");
Description: Halts parsing of the script at that point. The function does not return.
See Also: die
Usage:
<?php if ($a == 3) exit; // stop! Don't return?>
Description: Clears the output buffer by pushing all text to the Web browser, including text in whatever program or CGI scrip PHP is currently using.
Usage:
<?php print("hello"); // this may not yet show on the web browser flush; // it is now printed for sur?>
Description: Outputs a string. The print statement is not an actual function, but a PHP construct. You can see some unwanted side effects of using it. If you find you have problems, use printf() or echo instead.
Usage:
<?php print "Hello World<BR>"; print ("Hello Again!<BR>")?>
Description: Outputs a string based on format. The number of arguments is variable. The format statement is a string. If it contains an escape character, the % character, the information following that character tells the printf code what to do. All other characters in the format string are copied verbatim to the output.
When the printf code encounters a % , it looks past the % for directives. These directives tell printf how to print the values represented by the arguments following the format string, in order. If no directives are in the format string, the arguments are ignored. If too few directives are in the format string, the additional arguments are ignored. If too many directives are in the format string, the resulting output is undetermined. The following list describes the characters following the escape character. These descriptions are in the same basic order of possible occurrence in the format string:
”Specifies zero padding. Zeros will be filled in on the left until the spacing requirements are met.
'<c> ”Specifies padding using the character specified by <c>. The specified character will be filled in on the left until the spacing requirements are met.
”The negative field with flag tells PHP to left-justify the answer. The answer is right-padded with blanks.
”An optional decimal digit string of arbitrary length that specifies a minimum field width. If the converted value has fewer spaces than the field width, it will be padded with spaces on the left. If the negative flag is used, the padding will be on the right.
”An optional precision, consisting of a period ('.') followed by an optional decimal digit string of arbitrary length. This is the minimum number of digits to display after the decimal point. No digits present indicates to display 6 digits after the decimal point. This value has no effect on the display of numbers, which are not doubles.
b ”Use the argument as an integer and print it as a binary number.
c ”Use the argument as a integer and print it as an ASCII character of that value.
d ”Use the argument as an integer and print as an integer number.
f ”Use the argument as a floating point number and print accordingly .
o ”Use the argument as an integer and print as an octal (base 8) number.
s ”Use the argument as a string and print it accordingly.
x ”Use the argument as an integer number and print as a lower case hexadecimal number.
X ”Use the argument as an integer number and print as an upper case hexadecimal number.
% ”Print this character literally. No conversion is done.
A non-existing or small field width will be expanded to hold the result of the conversion. No characters will be truncated.
See Also: print , echo , flush
Usage:
<?php // the following prints "Hello, My Name Is George, a=3" printf("%s, %s, a=%d","Hello","My Name Is George",3); // the following prints "The value of pi is 3.14159" printf("The value of pi is %.5f", 4 * atan(1.0))?>
Description: Returns TRUE if the client is disconnected. This can be used in conjunction with ignore_user_abort() or register_shutdown_function() , and with connection_timeout() or connection_status(). You can't send anything to a Web browser when the connection has been aborted.
See Also: connection_timeout , connection_status , register_shutdown_function , ignore_user_abort
Usage:
<?php function shutdown() { if (connection_aborted()) { /* handle an abort by the user here*/ } else { /* handle a normal shutdown here */ } } register_shutdown_function("shutdown")?>
Description: Returns a bitfield containing Web browser connection status. A 0 is Normal Status, 1 is Aborted Status, 2 is Timeout Status, 3 is both. You can't send anything to a Web browser when the connection has been aborted or timed out.
See Also: connection_timeout , connection_aborted , register_shutdown_function , ignore_user_abort
Usage:
<?php function shutdown() { if (connection_status() != 0) { /* handle a timeout or an abort by the user here*/ } else { /* handle a normal shutdown here */ } } register_shutdown_function("shutdown")?>
Description: Returns a TRUE if the connection with the Web browser has timed out.
See Also: connection_status , connection_aborted , register_shutdown_function , ignore_user_abort
Usage:
<?php function shutdown() { if (connection_status() != 0) { /* handle a timeout here*/ } else { /* handle a normal shutdown here */ } } register_shutdown_function("shutdown")?>
Description: Returns an associative array containing all the headers in the current HTTP request. You must be using PHP as an Apache module to use this function.
Usage:
<?php $SessionHeaders = getallheaders(); while (list($OneHeader, $HeaderValue) = each($SessionHeaders)) { echo "$OneHeader: $HeaderValue<br>\n"; ?>
Description: This function requires browscap.ini , which is installed on Windows systems, and under PHP 3, get_browser() does not appear to work under Red Hat 6.1. Later versions of PHP might fix the problem. The browscap.ini file provided with Windows is a proprietary file and should not be copied to any other system. You can get a browscap.ini file from http://www.cyscape.com/asp/browscap/, after answering a questionnaire.
Usage:
<?php $browser = get_browser(); echo "browser name ".$browser->browser?>
Description: Sends the string as a raw header to the browser. More information on raw headers is available at http://www.w3.org/Protocols/rfc2068/rfc2068. This function must be called before any other output is done to work properly.
See Also: getallheaders
Usage:
<?php header("Location: http://www.new.net"); /*Redirect browser to another site*?>
Description: Changes abort setting only if abort_setting is given. Always
returns previous setting. In the abort_setting , 0 is Normal Status, 1 is Abort setting, 2 is Timeout setting, 3 is both.
See Also: connection_status , connection_aborted , register_shutdown_function , connection_timeout
Usage:
<?php /* read the status without changing */ $CurrentAbortSetting = ignore_user_abort(); /* set the status */ ignore_user_abort(3); /* ignore both timeout and abort *?>
Description: Parses a binary IPTC block into single tags. For more information, see http://www.xe.net/iptc/. The array returned has the tag marker as the index, and the value in the array is the value of the tag. A false is returned if it is not a valid IPTC block. Note that although most image functions require the GD library, this one does not.
Usage:
<?php $ImageSize = GetImageSize("myimage.jpg",&$ImageInfo); if (isset($ImageInfo["APP13"])) { $iptcData = iptcparse($ImageInfo["APP13"]); var_dump($iptcData); ?>
Description: Sends a cookie to a browser. You must send a cookie before any other headers are sent. If you send a cookie with PHP, place the code before the <HTML> or <HEAD> tags in the Web page.
You must have a CookieName. All other arguments are optional. If you only have a CookieName , the cookie of that name at the Web browser is deleted. To skip an argument, use an empty string ( "" ) for the string arguments, and 0 for the CookieExpiration and CookieSecurity arguments.
CookieName is an arbitrary name.
CookieValue is an arbitrary value, and can be any text string.
CookieExpiration is in seconds. CookieExpiration is most easily built using the time() function, and adding an arbitrary number of seconds to it.
CookiePath is a subdirectory to store a cookie in. Internet Explorer 4, service pack 1, does not appear to handle the path properly.
CookieDomain is a string that specifies the domain name for the cookie, such as .mydomain.com .
CookieSecure is a flag that tells PHP to send the cookie over an https (secure) connection.
Note that Internet Explorer 3.x and Netscape Navigator 4.05 don't appear to handle cookies properly if path and time aren't set.
Usage:
<?php setcookie("MyTestCookie","First Cookie!"); setcookie("MySecondCookie","Expires soon!",time()+7200); // this cookie expires in 2 hours $value = "yes!"; //the following cookie is sent secure, //will expire in 3 hours, and is sent over // a secure link. It will be placed in directory "mycookies" setcookie("MyThirdCookie",$value,time()+7200+3600, "/mycookies/",".mydomain.com",1); // You can't access these cookies now, until the page is refreshed // Once they reload the page, the cookies are available the following ways: echo $MyTestCookie; echo $HTTP_COOKIE_VARS["MyTestCookie"]; echo $MySecondCookie?>
Description: Strips the path information away and returns the filename.
See Also: dirname , chdir
Usage:
<?php $filepath = "/home/httpd/html/test/index.php3"; $file = basename($filepath); // $file now equals "index.php3?>
Description: Changes the current working directory to be the directory in DirectoryPath. You must have permission to enter this directory. It returns FALSE if it failed, TRUE if it succeeded.
See Also: basename , dirname
Usage:
<?php chdir ("/home/html/httpd/test/mydata") or die ("Could not change into directory")?>
Description: Changes the group the filename is in. You must own the file, or be the superuser, and must be in the group you want to change the file to. Returns TRUE (1) if successful, FALSE (0) if failed. Under Windows this does nothing. This command, along with chown and chmod , is useful for system administration and power users.
See Also: chown , chmod
Usage:
<?php if (chgrp("/home/httpd/html/test/new.dat","nobody")) echo "Change group succeeded."; else echo "Change group failed."?>
Description: Changes the read, write, and execute characteristics for this file. The format is best given in octal, using a leading 0. When given in octal, three numbers are used to specify the owner of the file, the group the file is in, and all others, in order.
NOTE
In binary, the bits for each number are in the order of read (100), write (010), and execute (001). In octal, these values would be 4 (read), 2 (write), 1 (execute). To set a file to be readable, writeable , and executable (rwx) by everyone, the Mode would be 0777. To only let the owner have rwx privileges, the value would be 0700. To let everyone read the file, and only the owner write and execute the file, the value would be 0744. To let everyone, including the owner, read and execute but not write the file, the Mode would be 0555.
Only the owner, the superuser, or someone with write privileges to the file can change its mode. Even if the file can't be written by the owner, the owner can change its mode and make it writeable.
Returns TRUE on success, FALSE on fail.
See Also: chown , chgrp
Usage:
<?php if (chmod("myfile",0777)) echo "success!"; else echo "could not change file mode"?>
Description: Changes the owner of the filename. You must own the file or be the superuser. Returns TRUE if successful, FALSE if failed. Under Windows this does nothing and returns TRUE .
See Also: chmod , chgrp
Usage:
<?php if (chown("myfile","brucelee")) echo "success!"; else echo "could not change file owner"?>
Description: Clears the file status cache. The results of the following calls are cached from the first call, so subsequent calls are faster: stat , lstat , file_exists , is_writeable , is_readable , is_executable , is_file , is_dir , is_link , filectime , fileatime , filemtime , fileinode , filegroup , fileowner , filesize , filetype , and fileperms .
This call clears that cache. It will make the next call much slower, but will force an update of the cache. This update will reflect the current state of the file at the time of the update. The newly cached information will be used in subsequent calls.
See Also: lstat , file_exists , is_writeable , is_readable, is_executable , is_file , is_dir , is_link , filectime , fileatime , filemtime , fileinode , filegroup , fileowner , filesize , filetype , and fileperms .
Usage:
<?php $status = stat("myfilename"); /* information used */ clearstatcache()?>
Description: Closes the directory opened by opendir .
See Also: opendir , readdir , rewinddir , dir
Usage:
<?php $dirH = opendir("/home/httpd/html/test"); closedir($dirH)?>
Description: Makes a copy of SourceFile and names it DestinationFile. Returns TRUE for success, FALSE for failure. You must have read privilege to the source file and write privilege to the destination directory.
See Also: rename , chmod
Usage:
<?php copy("/home/httpd/html/test/index.php3","/home/httpd/html/test/index.bak") or die ("Unable to copy index.php3")?>
Description: This function is listed in the PHP documentation, and explained as being a dummy manual entry. You must create it yourself if you want to use it.
See Also: unlink, unset
Usage:
<?php function delete($filename){ return (unlink($filename)); } delete("/home/httpd/html/test/index.bak") or die("unable to delete this filename")?>
Description: An internal pseudo-object. DirectoryName is opened. The dir object's path and handle attributes are set to represent the open directory's information.
The skeleton of the user visible class definition of the dir object is as follows :
class DirClass { var $handle; var $path; function read(){} function rewind(){} function close(){ }
See Also: opendir , readdir , rewinddir
Usage:
<?php $DirObj = dir("/etc/httpd/conf"); printf ("Directory handle is %d<p>",$DirObj->handle); printf ("Directory path is %s<p>",$DirObj->path); while ($DirectoryEntry = $DirObj->read()) { printf("Item: %s<p>",$DirectoryEntry); }
rewinddir($DirObj->handle); $DirObj->Close()?>
Description: Returns the directory portion of the FullPath .
See Also: basename
Usage:
<?php $DirName = dirname("/home/test/index"); echo $DirName; // prints "/home/test?>
Description: Returns the number of bytes free on the disk containing DirectoryName .
See Also: dirname
Usage:
<?php $FreeSpace = diskfreespace("/home"); echo "Number of bytes available on /home is ".$FreeSpace?>
Description: Closes file represented by FilePointer. Returns TRUE on success, FALSE on failure.
See Also: fopen , feof , fgetc , fgetcsv , fgetss , flock , fpassthru , fputs , fread , fsockopen , fseek , ftell , fwrite , pclose , popen , rewind , set_file_buffer
Usage:
<?php $FilePointer = fopen ("/home/httpd/html/test/data.dat","r"); fclose($FilePointer) or die ("could not close data.dat")?>
Description: Returns TRUE if at the end of the file represented by FilePointer , FALSE otherwise .
See Also: fclose , fopen , fgetc , fgetcsv , fgetss , flock , fopen , fpassthru , fputs , fread , fsockopen , fseek , ftell , fwrite , pclose , popen , rewind , set_file_buffer
Usage:
<?php $fp = fopen("test.dat","r"); while (!feof($fp)) $data =fread($fp,100); fclose($fp)?>
Description: Returns a single character string from file pointed to by FilePointer. Returns FALSE upon failure.
See Also: fopen , popen , fread , fgets , fsockopen
Usage:
<?php $file = fopen("test.dat","r") or die ("failed to open test.dat"); if ($str = fgetc($file)) echo "got character ".$str?>
Description: Reads a CSV file and return an array of the fields read from the file. FilePointer is the result of an fopen. Length must be longer than the longest field in the CSV file. The Delimiter defaults to be a comma ( , ) unless you specify it.
See Also: fopen , fgets
Usage:
<?php $numrows = 1; $csvFile = fopen("myfile.csv","r") or die ("open of myfile.csv failed<BR>"); for (;;) { if ($csvData =fgetcsv($csvFile,1000)) { $number = count($csvData); echo "<p> $number fields in row $numrows"; $numrows++; for ($k = 0 ; $k < $number ; $k++) echo $csvData[$k]."<p>"; } fclose($csvFile); ?>
Description: Returns a string from file pointed to by FilePointer, of maximum length dictated by argument Length. The string stops being read from the file at the newline character, at Length-1 bytes, or at end of file. Returns FALSE at a failure, usually caused by being at end of file when requesting a string.
See Also: fopen , fread
Usage:
<?php $fp = fopen("test.dat","r"); while ($line = fgets($fp,81)) echo "retrieved line ".$line."<p>"; fclose(fp)?>
Description: Reads a string from a file, and strip HTML and PHP tags from the string. It is identical to fgets in all other respects.
See Also: fopen , fgets
Usage:
<?php $fp = fopen("test.php3","r"); while ($line = fgets($fp,81)) echo "retrieved line ".$line."<p>"; fclose(fp)?>
Description: Reads an entire file into an array. It works identically to readfile in all other respects.
See Also: readfile , count
Usage:
<?php $FileArray = file("test.dat"); for ($k = 0 ; $k < count($FileArray); $k++) echo "line #".$k." ".$FileArray[$k]."<p>"?>
Description: Returns TRUE if file exists, FALSE otherwise.
See Also: clearstatcache , fopen
Usage:
<?php if (file_exists("test.dat")) echo "test.dat exists"; else echo "test.dat does not exist"?>
Description: Returns the time that the file was last accessed. It returns FALSE if an error occurs, which is usually an indication the file does not exist.
See Also: clearstatcache , fopen
Usage:
<?php $ftime = fileatime("test.dat") or die ("could not get info on test.dat")?>
Description: Returns the time the file was last changed. It returns FALSE if an error occurs, which is usually an indication the file does not exist.
See Also: fileatime , clearstatcache , fopen
Usage:
<?php $ftime = filectime("test.dat") or die ("could not get info on test.dat")?>
Description: Returns the group ID number of the group the file is in. It returns FALSE if an error occurs, which is usually an indication the file does not exist.
See Also: clearstatcache , fopen
Usage:
<?php $fgroup = filegroup("test.dat"); if ($fgroup == False) echo "no information on test.dat"?>
Description: Returns the file system inode of the file. It returns FALSE if an error occurs, which is usually an indication the file does not exist.
See Also: clearstatcache , fopen
Usage:
<?php $finode = fileinode("test.dat"); if ($finode == False) echo "no information on test.dat"?>
Description: Returns the time the file was last modified. It returns FALSE if an error occurs, which is usually an indication the file does not exist.
See Also: clearstatcache , fopen
Usage:
<?php $ftime = filemtime("test.dat")?>
Description: Returns the ID number of the owner of the file. It returns FALSE if an error occurs, which is usually an indication the file does not exist.
See Also: clearstatcache , fopen
Usage:
<?php $fowner = fileowner("test.dat"): if (!$fowner) echo "file owner not obtained"?>
Description: Returns a number representing the file permissions. It returns FALSE if an error occurs, which is usually an indication the file does not exist. See the permissions explanation under chmod .
See Also: chmod , clearstatcache , fopen
Usage:
<?php $fperms = fileperms("test.dat"); if (!$fperms) echo "could not get file permissions"?>
Description: Returns the size of a file in bytes. It returns FALSE if an error occurs, which is usually an indication the file does not exist.
See Also: clearstatcache , fopen
Usage:
<?php $fsize = filesize("test.dat") or die ("could not get file size for test.dat")?>
Description: Returns a string indicating type of file. It returns FALSE if an error occurs, which is usually an indication the file does not exist. The possible returns are block , char , dir , fifo , file , link , and unknown .
See Also: clearstatcache , fopen
Usage:
<?php $ftype = filetype("test.dat)?>
Description: Locks a file using a portable advisory method. This method of file locking works across most operating systems, including Windows. Returns FALSE on failure, TRUE on success. You must first open the file using fopen(). The type of lock requested is one of the following:
1 ”A shared lock for reading.
2 ”An exclusive lock for writing.
3 ”Release a lock (either 1 or 2).
4 ”Added to the previous numbers to prevent a block on this file while requesting a lock. If a block occurs, your program will hang until the lock is granted.
See Also: fopen
Usage:
<?php $fp = fopen("test.dat","a+"); if (flock($fp,2+4)) echo "locked"; else echo "could not get a lock"?>
Description: If a normal filename is given, a file will be opened for reading or writing or both as specified by mode. In all cases, a FALSE is returned for a failure.
If the filename argument begins with http:// (not case sensitive), an HTTP 1.0 connection is made with the Web server containing the page, and the internal file pointer is positioned at the beginning of the response. You must include a trailing slash ( / ) after a directory name. The file is opened for reading only.
If the filename argument begins with "ftp://" ftp:// (not case sensitive), a passive FTP connection is made with the server, and the internal file pointer is positioned at the beginning of the response. The FTP session can be opened for reading or writing, but not both at the same time. If a passive connection is not supported by the FTP server, this will fail.
The Mode a file is opened for can include one or more of the following character sets:
r ”Open for reading only. The internal file position pointer is placed at the beginning of the file.
r+ ”Open for reading and writing. The internal file position pointer is placed at the beginning of the file.
w ”Open for writing only. The internal file position pointer is placed at the beginning of the file. The file is shortened to zero bytes in length. If the file does not exist, it will be created. If permissions for the directory do not allow for creating the file, or if the creation fails for other reasons, an error is returned.
w+ ”Open for reading and writing. The internal file position pointer is placed at the beginning of the file. If the file does not exist, it will be created. If permissions for the directory do not allow for creating the file, or the creation fails for other reasons, an error is returned.
a ”Open for writing only. The internal file position pointer is placed at the end of the file. If the file does not exist, it will be created. If permissions for the directory do not allow for creating the file, or the creation fails for other reasons, an error is returned.
a+ ”Open for reading and writing. The internal file position pointer is placed at the end of the file. If the file does not exist, it will be created. If permissions for the directory do not allow for creating the file, or the creation fails for other reasons, an error is returned.
b ”This letter can follow the r , the w , or the a. On non-Unix systems, it can be used to tell the OS that the file is a binary file rather than a text file. If it is not needed, it is ignored.
See Also: feof , fgetc , fgetcsv , fgetss , flock , fclose , fpassthru , fputs , fread , fsockopen , fseek , ftell , fwrite , pclose , popen , rewind , set_file_buffer
Usage:
<?php $fp = fopen("/home/httpd/html/test/test.php3","a+") or die ("could not open test.php3"); $fp = fopen("http://www.php.net","r") or die ("web page not available"); $fp = fopen("ftp://ftp.redhat.com/pub/linux/dosutils/fips.com","r") or die ("ftp file not available")?>
Description: Sends all data left in a file to the standard output. If an error occurs, returns FALSE. The file must have been opened by fopen or popen or fsockopen. When fpassthru is finished, the file is closed, and FilePointer can no longer be used.
See Also: fopen , popen , fsockopen , fclose , readfile
Usage:
<?php $fp = fopen("test.dat","r"); if (!fpassthru($fp)) echo ("error dumping file")?>
Description: fputs is identical to fwrite. If Length is not specified, the entire string is written.
See Also: fwrite , fopen
Usage:
<?php $fp = fopen("test.dat","w+"); if (!fwrite($fp, "This is a test\n")) echo ("Could not write to test.dat"); fclose($fp)?>
Description: Reads up to Length bytes from FilePointer , or when EOF is reached.
See Also: fopen , fgets , fgetss , fpassthru
Usage:
<?php $fp = fopen("test.dat","r"); $Data = fread($fp, 1000); fclose($fp)?>
Description: Sets the internal file position pointer referenced by FilePointer to the byte count indicated by Offset. Returns 0 on success, -1 on failure. You can seek past EOF without an error. This function cannot be used on http:// or "ftp://" ftp:// files.
See Also: fopen , ftell , rewind
Usage:
<?php $fp = fopen("test.dat","r"); /* seek 10 bytes into the file */ fseek($fp, 10); $Data = fread($fp,20); // read 20 bytes starting at location 10 fclose($fp)?>
Description: Returns the current offset into the file opened with fopen , unless the file is an http:// or "ftp://" ftp:// file. Returns FALSE if an error occurs.
See Also: fseek , fopen
Usage:
<?php $fp = fopen("test.dat","r"); fseek($fp,10); $Offset = ftell($fp);// $Offset is now 10 fclose($fp?>
Description: Writes a maximum Length bytes from argument String to the file pointed to by FilePointer. Length is optional, and if used, will cause the configuration option magic_quotes_runtime to be ignored. When that configuration option is ignored, slashes will not be stripped from string. If Length is not given, the entire string will be written to the file.
See Also: fopen , fsockopen , popen , fputs , set_file_buffer
Usage:
<?php $fp = fopen("test.dat","w"); $Str = "This is a test"; fwrite($fp,$Str,5) ; fclose($fp)?>
Description: Returns TRUE if Name exists and is a directory, FALSE otherwise.
See Also: clearstatcache , is_file , is_link , is_executable , is_writeable , is_readable
Usage:
<?php if(is_dir("/home")) echo("/home is a directory"); else echo("/home is not a directory")?>
Description: Returns TRUE if FileName exists and is executable, FALSE otherwise. The test made is for the user the Web browser runs as. This is usually the user 'nobody'. That user has limited privileges.
See Also: clearstatcache , is_dir , is_file , is_link , is_readable , is_writeable
Usage:
<?php if(is_executable("/bin/ls")) echo("/bin/ls is executable"); else echo("/bin/ls is not executable")?>
Description: Returns TRUE if FileName exists and is a file (as opposed to a pipe, device, or directory), FALSE otherwise.
See Also: clearstatcache , is_link , is_executable , is_dir , is_readable , is_writeable
Usage:
<?php if(is_file("/bin/ls")) echo("/bin/ls is a file"); else echo("/bin/ls is not a file")?>
Description: Returns TRUE if FileName exists and is a symbolic link, FALSE otherwise.
See Also: clearstatcache , is_file , is_dir , is_executable , is_readable , is_writeable
Usage:
<?php if(is_link("/bin/ls")) echo("/bin/ls is a symbolic link"); else echo("/bin/ls is not a symbolic link")?>
Description: Returns TRUE if FileName exists and is a readable file, FALSE otherwise. The test made is for the user the Web browser runs as. This is usually the user 'nobody'. That user has limited privileges.
See Also: clearstatcache , is_file , is_dir , is_executable , is_writeable
Usage:
<?php if(is_readable("/bin/ls")) echo("/bin/ls is a readable file"); else echo("/bin/ls is not a readable file")?>
Description: Returns TRUE if FileName exists and is a writeable file, FALSE otherwise. The test made is for the user the Web browser runs as. This is usually the user 'nobody'. That user has limited privileges.
See Also: clearstatcache , is_file , is_dir , is_executable , is_readable
Usage:
<?php
if(is_writeable("/bin/ls")) echo("/bin/ls is a writeable file"); else echo("/bin/ls is not a writeable file")?>
Description: This function is identical to stat , except that if FileName is a symbolic link, the status of the symbolic link is returned instead of the status of the file pointed to by the symbolic link. An array is returned. The array elements are as follows, with item 1 being index 1 into the array (for example, $a[1] == item 1):
Device.
Inode.
Number of links.
User ID of owner.
Group ID the file or dir or device is in.
Device type if inode device. This is only valid on systems that support the st_blksize type. Under Windows, it returns -1.
Size in bytes.
Time of last access.
Time of last modification.
Time of last change.
Block size for file system I/O. This is only valid on systems that support the st_blksize type. Under Windows, it returns \1 .
Number of blocks allocated.
See Also: clearstatcache , stat
Usage:
<?php $Stats = lstat("/home/httpd/html/test/test.php3); for ($k = 0 ; $k < count($Stats) ; $k++) echo "Statistic number $k =".$Stats[$k]."<p>"?>
Description: Creates a hard link of LinkName to Target FileName. For soft links, see symlink .
See Also: symlink , readlink , linkinfo
Usage:
<?php link("/home/httpd/html/test/test.php3","/home/httpd/html/test/test.test")?>
Description: Returns the st_dev field from the Unix C library stat structure, as obtained by the lstat system call. Returns FALSE in case of error. This is used to verify that a link really exists.
See Also: link
Usage:
<?php if (linkinfo("/home/httpd/html/test/test.lnk")) echo "link exists."?>
Description: Creates the directory DirPathAndName with permissions defined by Mode. For more information on permissions, see the note under chmod .
See Also: chmod, fopen
Usage:
<?php if (mkdir("/home/httpd/html/test/test.dir",0700)) echo "directory created"?>
Description: Opens a directory specified by DirPathAndName and return a handle to it. The handle is used in readdir , rewinddir , and closedir .
See Also: readdir , rewinddir , closedir
Usage:
<?php $dirHandle = opendir("/home/httpd/html/test"); closedir($dirHandle)?>
Description: Close the pipe opened with popen .
See Also: popen
Usage:
<?php $pp = popen("/bin/ls -l","r"); pclose($pp)?>
Description: Executes a program specified by Command , and return a file pointer to be used by fgets , fgetss , fputs. The Mode can be "r" or "w" but not both. You must close the file pointer using pclose .
See Also: pclose , fgets
Usage:
<?php $pp = popen("/bin/ls -l","r"); while ($line = fgets($pp,256)) { echo "line received was ".$line."<p>"; } pclose($pp)?>
Description: Returns the filename of the next file in directory opened by opendir. Returns FALSE at end of list. The filenames are not returned in any particular order.
See Also: opendir , closedir , rewinddir
Usage:
<?php $dp = opendir("."); while ($fileName = readdir($dp)) echo $fileName."<p>"; closedir($dp)?>
Description: Reads a file and puts it to standard output. Returns the number of bytes written to standard output. If an error occurs, returns FALSE , and prints an error message unless it is called with an @ sign in front ( @readfile() ). The readfile function follows the same rules for http:// and
ftp://" ftp:// files as described under the fopen function. For an alternate method of reading an entire file, see the file function.
See Also: fopen , file
Usage:
<?php @readfile("/home/httpd/html/test/test.php3")?>
Description: If the file is a symbolic link, it returns the name of the file it links to, or FALSE in case of an error.
See Also: linkinfo , symlink
Usage:
<?php echo "/dev/cdrom links to ".readlink("/dev/cdrom")?>
Description: Renames a file or directory from OldName to NewName . Returns TRUE on success, FALSE on failure.
See Also: fopen
Usage:
<?php rename("test.php3", "test.old")?>
Description: Resets the file position pointer, as reported by ftell , to the beginning of the file.
See Also: fopen , fseek
Usage:
<?php $fp = fopen("test.txt","r"); $line = fgets($fp,80); rewind($fp); // set pointer back to beginning $line2 = fgets($fp,80); // $line2 and $line are the same fclose($fp)?>
Description: Resets the directory pointer to the beginning.
See Also: opendir , dir
Usage:
<?php $dh = opendir("/home"); while ($name = readdir($dh)) { //processing of directory names here } rewinddir($dh); // point back to beginning while($name2 = readdir($dh)) { // do processing of same name list } closedir($dh)?>
Description: Attempts to remove directory specified by PathAndDirName . You must have permission to do this, and the directory must be empty. Returns FALSE upon error.
See Also: opendir , chmod , fopen , mkdir
Usage:
<?php rmdir("/home/httpd/html/test/test.dir") or die ("test.dir was not removed")?>
Description: Sets the size of the buffer used for input and output to BufferSize bytes. If BufferSize is 0 , then writes are not buffered. This setting would provide the most safety, and the slowest speed. It returns 0 on success, EOF upon failure.
See Also: fopen
Usage:
<?php $fp = fopen("test.dat","r") or die("could not open test.dat<BR>"); if(set_file_buffer($fp,16384) != 0) echo("file buffer set failed!"); fclose($fp); ?>
Description: This function is identical to lstat , except that the file pointed to by the symbolic link is queried. Refer to the lstat function description.
See Also: lstat , fopen
Usage:
<?php $statArray = stat("test.dat"); echo "owner id =".$statArray[4]."<P>"?>
Description: Creates a soft link LinkName that points to TargetName.
See Also: readlink , linkinfo , link
Usage:
<?php symlink("test.dat", "test.lnk"); // test.lnk is now a link pointing to test.da?>
Description: Creates a unique filename in the specified directory DirName , using Prefix as the beginning of the filename. On Windows, the TMP environment variable overrides the DirName parameter. Under Linux, the TMPDIR environment variable overrides the DirName parameter. Other Unix systems behave differently. Use man to look up the tempnam(3) system function to determine how this function will work on your system. Returns the temporary filename upon success, a null string on failure.
See Also: fopen
Usage:
<?php $tn = tempnam("/tmp","boo"); if ($tn == "") echo "tempnam failed."?>
Description: Changes the FileName modification time to the Time argument. If Time is not present, current system time is used. The file is created if it
does not exist. Returns TRUE on success, FALSE on failure.
See Also: stat
Usage:
<?php touch("/tmp/test.foo");// create test.foo, // or set it to current modification time $sA = stat("/tmp/test.foo"); echo "modification time is ".$sA[9]."<P>"?>
Description: Sets the umask to Mask & 0777. When being used as a server module, the umask is returned to previous state after each run is finished. A umask specifies bits to be turned off when a function is executed to create a file. To turn off the write bits on a file for 'group' and 'others', you would set the umask to 022. For more information on modes, see chmod . The old umask is returned. To get the current umask , call umask with no argument.
See Also: chmod , fopen , touch
Usage:
<?php oldmask =umask(022)?>
Description: Deletes Filename. See rmdir to remove a directory. Returns FALSE on error. You must have permission to delete the file.
See Also: rmdir , fopen , chmod
Usage:
<?php unlink("test.dat")?>
Description: Searches DNS records, looking for Type of entry corresponding to Host . Returns TRUE if Host found, FALSE otherwise. Host can be the name in the form of name.domain.com , or an IP address in the form of 172.16.1.1 . The Type can be A (Address), MX (Mail Exchange), NS (Name Server), SOA (Authority), PTR (IP Address Pointer to Name), CNAME
(Alias), or ANY (Any record whatsoever).
See Also: getmxrr , gethostbyaddr , gethostbyname
Usage:
<?php if (checkdnsrr("foo.mydomain.com","ANY")) echo ("Host DNS entry exists!"); else echo ("could not locate host DNS entry")?>
Description: Closes the connection to the system logger. The use of this call is optional because the connection will be closed when PHP exits.
See Also: openlog , syslog
Usage:
<?php closelog()?>
Description: Enables the internal PHP debugger and connects it to IPAddress , in the form of 172.16.1.1 .
See Also: debugger_off
Usage:
<?php debugger_on("172.16.1.1")?>
Description: Turns off the internal PHP debugger.
See Also: debugger_on
Usage:
<?php debugger_off()?>
Description: Either set up a TCP stream connection to a HostName on PortNumber or a Unix connection to a socket specified by Hostname. For the Unix connection, the PortNumber must be 0 . If the TimeOut argument exits, it is the number of seconds before timing out and giving up on a connection. The TimeOut argument is passed to the connect system call.
If an error occurs, the function returns FALSE , otherwise it returns a file pointer. If the function returns FALSE , and if ErrorNumber and ErrorString are included in the call, they are filled in with the cause of the error.
The socket will be opened in the blocking mode unless you use the set_socket_blocking function call.
See Also: fclose , set_socket_blocking , pfsockopen
Usage:
<?php // try connecting to the web server at php HQ $fp = fsockopen("www.php.net", 80, &$ErrorNumber, &$ErrorString, 30); if (!$fp)// if an error occurred, print it { printf("Error number %d, %s<p>\n",$ErrorNumber, $ErrorString); exit; } fputs($fp,"GET / HTTP/1.0\n\n");// ask the web server for data while (!feof($fp))// print each line from the web page printf("%s",fgets($fp,255)); fclose($fp); ?>
Description: Returns the hostname specified by IPAddress . If an error occurs, it returns the IPAddress string.
See Also: gethostbyname
Usage:
<?php $Name = gethostbyaddr("172.16.1.1"); if ($Name == "172.16.1.1") echo "Host name not found!"; ?>
Description: Returns the IPAddress string of the Internet host specified by HostName .
See Also: gethostbyaddr , gethostbynamel
Usage:
<?php echo "Ip Address of mydomain.com is ".gethostbyname("mydomain.com")."<P>"; ?>
Description: Returns a list of addresses that resolve to HostName .
See Also: gethostbyname , checkdnsrr , getmxrr
Usage:
<?php $HostArray = gethostbynamel("foo.com"); while(list($key,$value) = each($HostArray)) echo "$key : $value <P>"; ?>
Description: Searches DNS for MX (Mail Exchange) records corresponding to HostName . Returns TRUE if any records are found, FALSE otherwise. MXHosts contains the list of MX records found. If MXHostWeight exists, it will have the weight of the MXHosts . The MXHost with the smallest MXHostWeight is the preferred mail server for the domain the host belongs to.
See Also: checkdnsrr , gethostbyname , gethostbyaddr
Usage:
<?php if (!getmxrr("foo.com",$MXHosts,$MXHostWeight)) echo "no mail exchange records found!"; ?>
Description: Opens a connection to the system logger for the program. The string Ident is added to each entry in the log file, and is customarily set to the program or script name. The Option is an OR of any of the following values:
1 ” LOG_PID ”Log the pid with each message
2 ” LOG_CONS ”Log to the console if errors in sending to the syslog facility
4 ” LOG_ODELAY ”Delay opening connection until first syslog() . This is the default behavior.
8 ” LOG_NDELAY ”Don't delay opening connection
32 ” LOG_PERROR ”Log to stderr as well
The Facility should be set to one of the following values:
0x8 ” LOG_USER (which is 1<<3) ”User level logging messages
0x50 ” LOG_AUTHPRIV (which is 10<<3) ”Authorization error.
More information can be found in the syslog(3) man pages, and in the /usr/ include/src/syslog.h header file.
This call is optional, as syslog will call it if necessary, setting Ident to FALSE .
See Also: closelog , syslog , /usr/include/sys/syslog.h
Usage:
<?php if (!openlog("MyPHP Program:",4,8)) echo("openlog failed"); ?>
Description: Opens a persistent Internet or Unix socket. This function works exactly like fsockopen , except that the connection remains alive after the script finishes running.
See Also: fsockopen
Usage:
<?php $fp = pfsockopen("www.php.net", 80, &$ErrorNumber, &$ErrorString, 30); ?>
Description: If Mode is FALSE , the socket is switched to non-blocking mode. If TRUE , it is switched to blocking mode. In blocking mode, calls like fgets() will wait until data is received. In non-blocking mode, those calls will return immediately, without transferring data, if the socket is hung waiting for an event.
See Also: fsockopen
Usage:
<?php $fp = fsockopen("www.php.net", 80, &$ErrorNumber, &$ErrorString, 30); set_socket_blocking($fp,FALSE);// set non-blocking. ?>
Description: syslog opens a connection to the system logging facility and sends it LogMessage . LogMessage is a string that follows the printf formatting rules and argument list, with one exception. If the LogMessage string contains %m , then it will be replaced by the error message string that is produced by strerror() .
The Priority argument must be one of the following values:
0 ” LOG_EMERG ”System is unusable
1 ” LOG_ALERT ”Action must be taken immediately
2 ” LOG_CRIT ”Critical error
3 ” LOG_ERR ”Error indicator
4 ” LOG_WARNING ”A warning indicator
5 ” LOG_NOTICE ”Send a notification to the logs
6 ” LOG_INFO ”An FYI message
7 ” LOG_DEBUG ”Debug-level information
See Also: openlog , /usr/include/sys/syslog.h
Usage:
<?php $LOG_ERR = 3; syslog($LOG_ERR,"Error %m in PHP script %s on line %s\n",__FILE__,__LINE__); ?>
NIS is a network-based authentication method. It allows one machine to hold all the authentication records for all users in your domain. You must configure PHP with the --with-yp setting before compiling to use these functions. More information on using and setting up NIS can be found on Red Hat systems under the /usr/doc directory after installing the NIS package, and on the Web at http://europe.redhat.com/documentation/HOWTO/NIS-HOWTO.php3.
Description: Returns the default domain the computer is in, or FALSE .
See Also: yp_errno , yp_err_string , yp_master , yp_match , yp_order , yp_first , yp_next
Usage:
<?php $NISDomain = yp_get_default_domain(); if (!$NISDomain) { echo "Domain request failed! Error number ".yp_errno(); echo " ".yp_err_string()."<P>"; } else echo "NIS Domain is ".$NISDomain."<P>"; ?>
Description: Returns the order number for Domain in Map , or FALSE .
See Also: yp_get_default_domain() , yp_errno , yp_err_string , yp_master , yp_match , yp_first
Usage:
<?php $order =yp_order($MyDomain, $MyMap) or die("Error number ".yp_errno()." ,".yp_err_string()); /* $order is availble for use*/ ?>
Description: Returns the machine name of the Master NIS server for Map , or FALSE .
See Also: yp_errno , yp_err_string , yp_order , yp_get_default_domain , yp_first , yp_next , yp_match
Usage:
<?php $Master = yp_master($MyDomain, $MyMap); if (!$Master) echo "NIS error number ".yp_errno()." ,".yp_err_string(); ?>
Description: Returns the value for Key in Map in Domain , or FALSE for failure. The Key must be an exact match.
See Also: yp_get_default_domain() , yp_errno , yp_err_string , yp_master
Usage:
<?php $NISMatch = yp_match($MyDomain, "password.byname","billsm"); if (!$NISMatch) echo "NIS error number ".yp_errno()." ,".yp_err_string(); ?>
Description: Returns the first entry in the Map for Domain , or FALSE for failure in a key-value string array.
See Also: yp_get_default_domain() , yp_errno , yp_err_string , yp_master , yp_match ,
yp_next , yp_order
Usage:
<?php $NISEntry = yp_first($MyDomain, $MyMap); if (!$NISEntry) echo "NIS error number ".yp_errno()." ,".yp_err_string(); else echo "Entry has key ".key($NISEntry)." and value ".value(key($NISEntry)); ?>
Description: Returns the next key-value pair in Map in Domain that occurs after Key , or FALSE .
See Also: yp_get_default_domain() , yp_errno , yp_err_string , yp_master , yp_match , yp_order , yp_first
Usage:
<?php $NISEntry = yp_first($MyDomain, $MyMap); if (!$NISEntry) echo "NIS error number ".yp_errno()." ,".yp_err_string(); else { echo "Entry has key ".key($NISEntry); echo " and value ".value(key($NISEntry)); $key = key($NISEntry); while (1) { if (!($NISEntry = yp_next($MyDomain, $MyMap, $key))) break; // exit $key = key($NISEntry); echo "Entry has key ".$key." and value ".value($key); }// end of while }// end of else ?>
Description: Returns error code for previous NIS operation. The possible error codes are as follows:
1 ”Arguments passed in function are bad
2 ”RPC failure. Domain is unbound
3 ”Can't bind to server on this domain
4 ”No such map in server domain
5 ”No such key in map
6 ”Internal yp_server or client error
7 ”Resource allocation fail
8 ”No more records in map database
9 ”Can't communicate with portmapper
10 ”Can't communicate with yp_bind
11 ”Can't communicate with yp_serv
12 ”Local domain name not set
13 ” yp database is bad
14 ” yp version mismatch
15 ”Access violation
16 ”Database busy
See Also: yp_get_default_domain() , yp_errno , yp_err_string , yp_master , yp_match , yp_order , yp_first , yp_next
Usage:
<?php $NISEntry = yp_first($MyDomain, $MyMap); if (!$NISEntry) echo "NIS error number ".yp_errno()." ,".yp_err_string(); ?>
Description: Returns the error string that describes the last NIS operation error. See the error code list in yp_errno .
See Also: yp_get_default_domain() , yp_errno , yp_master , yp_match , yp_order , yp_first , yp_next
Usage:
<?php $NISEntry = yp_first($MyDomain, $MyMap); if (!$NISEntry) echo "NIS error number ".yp_errno()." ,".yp_err_string(); ?>
The functions in this section are specific to the Apache Web server. PHP must be installed as an Apache module for these functions to work.
Description: Performs a partial request for a URI, and returns the information in a class. The attributes of the class are as follows:
class { var status; var the_request; var status_line; var method; var content_type; var handler; var uri; var filename; var path_info; var args; var boundry; var no_cache; var no_local_copy; var allowed; var send_bodyct; var bytes_sent; var byterange; var clength; var unparsed_uri; var mtime; var request_time; }
See Also: apache_note
Usage:
<?php $URIInfo = apache_lookup_uri($File); echo "Status is ".$URIInfo->status; ?>
Description: Gets and sets values in the Apache notes table. If called with a NoteValue , it sets the NoteName in the table to NoteValue . If called without a NoteValue , it retrieves the NoteName from the table.
See Also: apache_lookup_uri , getallheaders
Usage:
<?php apache_note("MyNote","This is my note"); // set the note echo "My Note is ".apache_note("MyNote"); ?>
Description: Returns an associative array of all HTTP headers in the current request.
See Also: apache_note , apache_lookup_uri
Usage:
<?php $SessionHeaders = getallheaders(); while (list($OneHeader, $HeaderValue) = each($SessionHeaders)) { echo "$OneHeader: $HeaderValue<br>\n"; } ?>
Description: Includes a filename, identical to the statement <!--#include virtual --> in Apache. You can use this to include CGI scripts, .shtml files, or any other files.
The virtual() command will cause the Apache server to perform a sub-request and the resulting output of the cgi script, .shtml, .html, .php, or etc page will be included in the PHP code.
A require() or include() command includes the raw file in the PHP code, without processing it first.
This function only works when PHP is installed as a module.
See Also: require , include
Usage:
<?php virtual("MyFileName.cgi"); ?>
These functions are available only if you have compiled the calendar extensions in dl/calendar directory under the php main directory, and
installed it into your system. For more information, see the dl() function in this appendix.
These functions are useful for converting from one calendar system to another. You must first convert your source calendar date to a Julian Day, and then from the Julian Day to your destination calendar date. You are allowed to manipulate days as far back as 4000 BC. A good online reference for calendars is http://genealogy.org/scottlee/cal-overview.html.
Description: Converts a Julian Day to a Gregorian calendar day. The result is in the form of mm/dd/yy .
See Also: gregoriantojd , jdtojulian , juliantojd , jdtojewish , jewishtojd , jdtofrench , frenchtojd , jdmonthname , jddayofweek
Usage:
<?php $JulianDay = gregoriantojd(2,3,4); echo "For JulianDay=$JulianDay, Gregorian is "; echo jdtogregorian($JulianDay)."<BR>"; ?>
Description: Converts a Month, Day, Year to a JulianDayCount . The year can range from 4714 B.C. “9999 A.D. on the Gregorian Calendar.
See Also: jdtogregorian , jdtojulian , jdtofrench , juliantojd , jdtojewish , jewishtojd , frenchtojd , jdmonthname , jddayofweek
Usage:
<?php $JulianDay = gregoriantojd(2,3,4); echo "French Republican for ".$JulianDay." is ".jdtofrench($JulianDay); ?>
Description: Converts JulianDayCount to the Julian Date.
See Also: jdtogregorian , gregoriantojd , jdtofrench , juliantojd , jdtojewish , jewishtojd , frenchtojd , jdmonthname , jddayofweek
Usage:
<?php $JulianDay = gregoriantojd(2,3,4); echo "Julian Date for ".$JulianDay." is ".jdtojulian($JulianDay); ?>
Description: Changes a Julian calendar Month, Day, Year to a JulianDayCount .
See Also: jdtogregorian , gregoriantojd , jdtofrench , jdtojulian , jdtojewish , jewishtojd , frenchtojd , jdmonthname , jddayofweek
Usage:
<?php $JulianDay = juliantojd(2,3,1900); echo "The Julian Day Count for JulianDate of 2/3/1900 is $JulianDay<br>"; ?>
Description: Converts a JulianDayCount to a Jewish calendar date.
See Also: jdtogregorian , gregoriantojd , jdtofrench , jdtojulian , juliantodj , jewishtojd , frenchtojd , jdmonthname , jddayofweek
Usage:
<?php $JulianDay = gregoriantojd(2,3,4); echo "Jewish Date for ".$JulianDay." is ".jdtojewish($JulianDay); ?>
Description: Converts a Jewish calendar day to a JulianDayCount .
See Also: jdtogregorian , gregoriantojd , jdtofrench , frenchtojd , jdtojulian , juliantojd , jdtojewish , jdmonthname , jddayofweek
Usage:
<?php $JulianDay = jewishtojd(2,3,4); echo "Jewish Date for ".$JulianDay." is ".jdtojewish($JulianDay); ?>
Description: Converts a French Republican calendar date to a JulianDayCount .
See Also: jdtogregorian , gregoriantojd , jdtojulian , juliantojd , jdtojewish , frenchtojd ,
jdmonthname , jddayofweek
Usage:
<?php $JulianDay = frenchtojd(2,3,4); echo "French Date for ".$JulianDay." is ".jdtofrench($JulianDay); ?>
Description: Converts a French Republican calendar day to a JulianDayCount .
See Also: jdtogregorian , gregoriantojd , jdtojulian , juliantojd , jdtojewish , jdtofrench , jdmonthname , jddayofweek
Usage:
<?php $JulianDay = frenchtojd(2,3,4); echo "French Date for ".$JulianDay." is ".jdtofrench($JulianDay); ?>
Description: Takes a JulianDayCount and returns the month it is in. The Mode controls the return format and is one of the following:
0 ”Gregorian, abbreviated
1 ”Gregorian, full
2 ”Julian, abbreviated
3 ”Julian, full
4 ”Jewish
5 ”French Republican
See Also: jdtogregorian , gregoriantojd , jdtojulian , juliantojd , jdtojewish , jdtofrench , frenchtojd , jddayofweek
Usage:
<?php $JulianDay = frenchtojd(2,3,4); echo "French Month for ".$JulianDay." is ".jdmonthname($JulianDay,5); ?>
Description: Returns the day of the week for JulianDayCount . The return is either a number or a string, depending upon Mode , which is one of the following:
0 ”Return a number from 0 “6, with zero being Sunday.
1 ”Return the day of the week as an English name using the Gregorian calendar.
2 ”Return abbreviated English name using the Gregorian calendar.
See Also: jdtogregorian , gregoriantojd , jdtojulian , juliantojd , jdtojewish , jdtofrench , frenchtojd , jdmonthname
Usage:
<?php $JulianDay = gregoriantojd(2,3,4); echo "Day of week for ".$JulianDay." is ".jddayofweek($JulianDay,1); ?>
Description: Returns the Unix timestamp for midnight on Easter for a given year. The year must be from 1970 “2037. See easter_days for years outside this range.
See Also: easter_days
Usage:
<?php echo "Easter is on ". date(easter_date(2000)); ?>
Description: Returns the number of days after March 21 that Easter falls on for that year. Use the current year if no year is given.
See Also: easter_date
Usage:
<?php echo "Easter is ".easter_days(2000)." days after March 14 for year 2000"; ?>
Description: Returns TRUE if a date is valid, FALSE otherwise. The year must be between 0 “32767, the month must be between 1 “12, and the day must be within the correct number of days for the month. Leap years are understood correctly.
See Also: strftime , date , getdate , gmdate , mktime , gmmktime , time , microtime
Usage:
<?php if (checkdate(1,50,32)) echo "this date is valid"; else echo "this date is invalid"; ?>
Description: Returns a string controlled by Format for the date in TimeStamp , or the current system date if TimeStamp not given. The Format consists of characters, and can be one or more of the following:
a ”am or pm (lowercase)
A ”AM or PM (uppercase)
d ”Day of month with leading zeros
D ”Day of week using three-letter abbreviations: Mon, Tue, Wed, Thu, Fri, Sat, Sun
F ”Name of the month
h ” Hour from 01 “12, with leading zeros
H ”Hour from 00 “23, with leading zeros
g ”Hour from 1 “12, without leading zeros
G ”Hour from 0 “23, without leading zeros
I ”Minutes from 00 “59, with leading zeros
j ”Day of month from 1 “31 without leading zeros
l ”(lowercase L) English text day of week, Monday through Friday
L ”Boolean leap year indicator. 0 is not a leap year, 1 is a leap year.
m ”Month from 01 “12, with leading zeros
n ”Month from 1 “12, without leading zeros
M ”Month, English text three letter abbreviation, Jan through Dec.
s ”Seconds 00 “59
S ”English text suffix, two letters , such as th and nd. The number 2 would print 2nd.
t ”Number of days in the given month.
U ”Seconds since the epoch , which is January 1, 1970 for Unix systems.
w ”Day of week, from 0 (Sunday) to 6 (Saturday)
Y ”The 4 digit year, for example, 1999.
y ”The 2 digit year, for example, 99.
z ”Day of the year, from 0 “365
Z ”Time zone offset in seconds. If used with gmdate() , will always return 0.
Any characters in the format string that are not recognized are printed as is. You can use mktime() to provide the TimeStamp argument and deal with dates in the past or future.
See Also: gmdate , checkdate , mktime
Usage:
<?php /* print something like It is now Monday, Jan 5th, 3:45pm */ echo "It is now".date("D, M jS, g:ia")."<P>"; ?>
Description: Returns a string formatted by the Format argument for the time given in TimeStamp . If TimeStamp is not given, use the current local time. Locale-specific words for month, day, and other items follow the settings done using setlocale() .
The format string consists of one or more of the following:
%a ”Abbreviated weekday name per current locale
%A ”Full weekday name per current locale
%b ”Abbreviated month name per current locale
%B ”Full month name per current locale
%c ”Preferred date and time per current locale
%d ”Day of month from 01 “31
%H ”Hour from 00 “23
%I ”Hour from 1 “12
%j ”Day of year from 001 “366
@$:
A
MySQL and PHP from scratch
%m ”Month from 1 “12
%M ”Minutes as a decimal number
%p ”am/pm indicator per current locale
%S ”Seconds from 00 “59
%U ”Week number in current year, starting with the first Sunday in the year as day 1, week 1.
%W ”Week number in current year, starting with the first Monday in the year as day 1, week 1.
%w ”Day of the week, from 0 (Sunday) to 6 (Saturday).
%x ”Locale-specified date without time
%X ”Locale-specified time without date
%y ”The 2 digit year, 00 “99
%Y ”The 4 digit year, that is, 2000 “2099
%Z ”Time zone name or abbreviations
%% ”The % character
See Also: setlocale , date
Usage:
<?php /* print something like "It is now Monday, January 1, 2000" */ echo "It is now ".strftime("%A, %B %d, %Y")."<P>"; ?>
Description: Returns an associative array with the following elements and values:
Array Index | Value |
---|---|
"seconds" | seconds |
"minutes" | minutes |
"hours" | hours |
"mday" | day of month |
"wday" | number of day of week |
"mon" | number of month |
"year" | number of year |
"yday" | numeric day of year |
"weekday" | day of week, 'Monday' thru 'Sunday' |
"month" | month name, 'January' thru 'December' |
See Also: date , gmdate , strftime
Usage:
<?php $TimeNow = getdate(time()); echo "The time is now ".$TimeNow["hours"].":".$TimeNow["minutes"]."<P>"; ?>
Description: Returns the date per the Format string, using TimeStamp as GMT time. In all other respects, it is identical to the date() function, using the same formatting.
See Also: date
Usage:
<?php /* print something like It is now Monday, Jan 5th, 3:45pm, Greenwich Mean Time */ echo "It is now".date("D, M jS, g:ia")." Greenwich Mean Time<P>"; ?>
Description: A string formatted by the Format argument for the time given in TimeStamp as GMT time. This function behaves exactly like strftime() in all other respects, including the Format string.
See Also: strftime
Usage:
<?php /* print something like "It is now Monday, January 1, 2000, GMT" */ echo "It is now ".strftime("%A, %B %d, %Y").", GMT<P>"; ?>
Description: Returns a Unix time in seconds per the time in the argument list. If any or all of the arguments are left out going from right to left, the current time is used to fill in for each missing argument. The only argument that isn't self explanatory is the is_dst , which is set to 1 for daylight savings time, or 0 otherwise.
See Also: date , time
Usage:
<?php // change January 1, 1999, 12:30 pm to seconds and back to a day echo "Date is ".date("D, M jS, g:ia",mktime(12,30,0,1,1,1999,0)); ?>
Description: Returns the current Unix time in seconds.
See Also: mktime,date
Usage:
<?php // change current time to seconds and back to a day echo "Date is ".date("D, M jS, g:ia",time()); ?>
Description: Returns a string xxx yyy, where yyy is the Unix time in seconds, and the xxx is the number of microseconds that have passed since the second clicked over.
See Also: time,date
Usage:
<?php echo "Microseconds, Seconds are ".microtime(); ?>
LDAP stands for Lightweight Directory Access Protocol. It is a partial implementation of the X.500 standard. LDAP was first described in RFC 1777 and RFC 1778, which can be found at "ftp://ftp.isi.edu/in-notes/rfc1777.txt," ftp://ftp.isi.edu/in-notes/rfc1777.txt, and rfc1778.txt at the same location.
Using LDAP, you can implement a centralized database, which contains contact information, public encryption keys, email addresses, and other information. Public LDAP servers are on the Internet. A URL for a list of these servers is http://www. dante .net/np/pdi.html.
A good place to start looking for more information on LDAP is http://www.umich.edu/dirsvcs/ldap/index.html. You must retrieve and compile the University of Michigan LDAP client libraries version 3.3, or use the Netscape Directory SDK before LDAP will work. You must also compile LDAP support into PHP. An open source LDAP is at http://www.openldap.org. It may work with PHP.
To enable LDAP extensions, you must use the configure option ”with -ldap=DIRNAME before compiling php. If the =DIRNAME is left off, the directory will be /usr/local/ldap.
An LDAP database has a tree-like structure similar to the directory structure on your hard drive. The root directory is called the world. The directories in the root are called countries . Inside country directories, you will find directories for companies, organizations, or places. Within those directories you will find people or things.
To get to a piece of information within an LDAP database, you must provide enough details to distinguish the information from other information. This is called the distinguished name, and is abbreviated DN.
Assume George Smith works for manufacturing in a company named Global Star, based in the United States. A DN for George Smith would look something like this:
cn=George Smith,ou=Manufacturing,o=Global Star,c=US
You would read the DN from right to left. The country is the US. The organization is Global Star. The organizational unit is Manufacturing. The common name is George Smith.
No hard and fast rules exist about organizing information in LDAP servers. If you write code to access LDAP servers, you must understand the structure of the information on those servers. Different servers will
have different rules. If you apply the wrong rules to a server, you will not get information back.
Many servers allow anonymous access for read of information. Most servers require a password for any other type of access. Before accessing a server, you need to know the name or IP address of the server. You need to know the base dn of the server information you are after, which is the country and the organization. In our previous example, the base dn would be o=Global Star,c=US.
Description: Adds entries in an LDAP directory. Returns TRUE for success, FALSE for failure. The Entry array is indexed by attribute. If an attribute has multiple values, it is indexed starting with zero. For example:
Entry["AttributeNumber1]="Attribute Value"; Entry["AttributeNumber2][0]="Attribute 2, first value"; Entry["AttributeNumber2][1]="Attribute 2, second value";
See Also: ldap_bind
Usage:
<?php $LdapServer = ldap_connect("MyMachine"); // mymachine hosts an LDAP server if ($LdapServer) { // obtain write access ldap_bind($LdapServer,"cn=root, o=Current CompanyName, c=US","password"); // now create the entry array $Entry["cn"]="User Name"; $Entry["sn"]="Name"; // the surname $Entry["mail"]="user.name@foo.com";// the email address $Entry["objectclass"]="person"; // now put the data onto the server ldap_add($LdapServer,"cn=root, o=Current CompanyName, c=US",$Entry); ldap_close($LdapServer); } else echo "did not connect to LDAP server on MyMachine"; ?>
Description: Binds to the specified BindRDN using BindPassword. Returns TRUE on success, FALSE on failure. If the BindRDN and BindPassword arguments are not used, anonymous access is attempted.
See Also: ldap_connect,ldap_close
Usage:
<?php $LdapServer = ldap_connect("MyMachine"); // mymachine hosts an LDAP server if ($LdapServer) { // obtain write access if (!ldap_bind($LdapServer,"cn=root, o=Current CompanyName, c=US","password")) die ("Write access to LDAP server not obtained!"); // the connection is now ready for write } ?>
Description: This function is identical to ldap_unbind. It attempts to close the link specified by LinkIdentifier, and returns TRUE on success, FALSE on failure.
See Also: ldap_unbind,ldap_bind
Usage:
<?php $LdapServer = ldap_connect("MyMachine"); // mymachine hosts an LDAP server // other code here ldap_close($LdapServer); ?>
Description: Attempts to connect to LDAP server on HostName on PortNumber. Returns a positive link number on success, FALSE on failure. If HostName and PortNumber are not specified, the already open link number is returned. PortNumber is optional and defaults to 389 if not specified.
See Also: ldap_add,ldap_close,ldap_bind
Usage:
<?php $LdapServer = ldap_connect("MyMachine"); // mymachine hosts an LDAP server if ($LdapServer) { // other work here } ?>
Description: Returns the number of entries in the previous search results given by ResultIdentifier, or FALSE on error.
See Also: ldap_search,ldap_bind
Usage:
<?php $LdapServer = ldap_connect("MyMachine"); // mymachine hosts an LDAP server if ($LdapServer) { $dn = " o=Current CompanyName, c=US"; $partialName = "Pe"; $LookFor = "|(sn=$partialName*)(givenname=$partialName*))"; $LookInCategories = array("ou","sn","givenname","mail"); $SearchResult = ldap_search($LdapServer,$dn,$LookFor,$LookInCategories); echo "Search returned ".ldap_count_entries($LdapServer,$SearchResult)." <P>"; } ?>
Description: Deletes an entry from an LDAP directory. Returns TRUE on success, FALSE on failure.
See Also: ldap_add,ldap_bind
Usage:
<?php $LdapServer = ldap_connect("MyMachine"); // mymachine hosts an LDAP server if ($LdapServer) { // obtain write accesss if (!ldap_bind($LdapServer,"cn=root, o=Current CompanyName, c=US", "password")) die ("Write access to LDAP server not obtained!"); $dn = "sn=Goodby Goodbar, o=Current CompanyName, c=US"; if (!ldap_delete($LdapServer,$dn)) echo "delete failed"; } ?>
Description: Converts the DN to a user-friendly name format by stripping off the identifier type names.
See Also: ldap_bind
Usage:
<?php $dn = "sn=Goodby Goodbar, o=Current CompanyName, c=US"; echo "User friendly format is ".ldap_dn2ufn($dn); ?>
Description: Splits the DN returned by ldap_get_dn() into its component parts . Each component part is called a Relative Distinguished Name, or RDN. If WithAttributes is 0, only the RDN is returned. If it is 1, the RDN's
are returned with their values.
See Also: ldap_bind
Usage:
<?php $dn = "sn=Goodby Goodbar, o=Current CompanyName, c=US"; $result = ldap_explode_dn($dn, FALSE); for ($i = 1 ; $i <= $result["count"]; $i++) echo "item $i = ".$result[$i]."<P>"; ?>
Description: Returns the first attribute in ResultEntryIdentifier, or FALSE on error. Use ldap_next_attribute() to continue reading attributes.
See Also: ldap_next_attribute,ldap_bind,ldap_first_entry
Usage:
<?php $LdapServer = ldap_connect("MyMachine"); // mymachine hosts an LDAP server if ($LdapServer) { $dn = " o=Current CompanyName, c=US"; $partialName = "Pe"; $LookFor = "|(sn=$partialName*)(givenname=$partialName*))"; $LookInCategories = array("ou","sn","givenname","mail"); $SearchResult = ldap_search($LdapServer,$dn,$LookFor,$LookInCategories); $LDAPEntry = ldap_first_entry($LdapServer, $SearchResult); $Attribute = ldap_first_attribute($LdapServer,$LDAPEntry,&$BERIDPointer); echo "Search returned first attribute =$Attribute <P>"; // consume all of the attributes while ($Attribute) $Attribute = ldap_next_attribute($LdapServer,$LDAPEntry,&$BERIDPointer); ldap_free_result($SearchResult); // free memory used. } ?>
Description: Returns the result entry identifier for the first entry, or FALSE for failure.
See Also: ldap_first_attribute
Usage:
<?php $SearchResult = ldap_search($LdapServer,$dn,$LookFor,$LookInCategories); $LDAPEntry = ldap_first_entry($LdapServer, $SearchResult); A MySQL and PHP from scratch ?>
Description: Frees memory allocated to store the result of a search. Returns TRUE on success, FALSE on error. This call is not strictly required because all memory will be freed when PHP script exits.
See Also: ldap_first_attribute,ldap_search
Usage:
<?php $LookInCategories = array("ou","sn","givenname","mail"); $SearchResult = ldap_search($LdapServer,$dn,$LookFor,$LookInCategories); ldap_free_result($SearchResult); // free memory used. ?>
Description: Returns all entry information in an array, or FALSE on error. The ["count"] index is the number of attributes for the entry. The ["attributename"]["count"] multidimensional index is the number of values for attributename.
See Also: ldap_first_attribute,ldap_search
Usage:
<?php $E= ldap_first_entry($LdapServer,$SearchResult); $att = ldap_get_attributes($LdapServer, $E); for ($index = 0; $index < $att["count"]; $index++) { echo $att[$index]."<P>";// list the attributes for ($i2 = 0 ; $i2 < $att[$att[$index]]["count"]; $i2++) echo $att[$att[$index]][$i2]."<P>"; // list the values } ?>
Description: Returns the DN of the result entry obtained from a search, or FALSE on error.
See Also: ldap_first_attribute,ldap_search
Usage:
<?php $SearchResult = ldap_search($LdapServer,$dn,$LookFor,$LookInCategories); echo "DN is ".ldap_get_dn($LdapServer,$SearchResult); ?>
Description: Returns a multidimensional array of all entries, or FALSE on error. The ["count"] index is the number of entries returned. The index [0]["dn"] is the DN of the first entry of the result. The index [0]["count"] is the number of attributes for the first entry. The index [0][0] is the first attribute for the first entry.
See Also: ldap_first_attribute,ldap_search
Usage:
<?php $ent = ldap_get_entries($LdapServer, $SearchResult); for ($index = 0; $index < $ent["count"]; $index++) { echo $ent[$index]["dn"]."<P>";// list the entry for ($i2 = 0 ; $i2 < $ent[$index]["count"]; $i2++) echo $ent[$index][$i2]."<P>"; // list the values } ?>
Description: Returns an array of values for the Attribute, or FALSE for failure. The index ["count"] is the number of values returned.
See Also: ldap_first_attribute
Usage:
<?php $SearchResult = ldap_search($LdapServer,$dn,$LookFor,$LookInCategories); $LDAPEntry = ldap_first_entry($LdapServer, $SearchResult); $val = ldap_get_values($LdapServer, $LDAPEntry, "mail"); for ($index = 0 ; $index < $val["count"]; $index++) echo "entry number $index is $val[$index]<P>"; ?>
Description: Returns a search result identifier, or FALSE if an error occurs. ldap_list uses Filter to search on the BaseDN directory with the scope set to LDAP_SCOPE_ONELEVEL. This is roughly equivalent to doing an ls command on a directory. If you are looking for specific attributes, the Attributes array must be supplied.
See Also: ldap_first_attribute,ldap_search
Usage:
<?php // search for organizations in Russia, using previously opened connection $BaseDN = "c=RU"; $Filter = "o=*"; $Attributes = array("o"); A MySQL and PHP from scratch $SearchResult = ldap_list($LdapServer,$BaseDN,$Filter, $Attributes); $ent = ldap_get_entries($LdapServer, $SearchResult); for ($index = 0; $index < $ent["count"]; $index++) { echo $ent[$index]["dn"]."<P>";// list the entry for ($i2 = 0 ; $i2 < $ent[$index]["count"]; $i2++) echo $ent[$index][$i2]."<P>"; // list the values } ?>
Description: Modifies an entry. Works exactly like ldap_add, except existing entry information is replaced. Returns TRUE for success, FALSE for failure.
See Also: ldap_add
Usage:
<?php $LdapServer = ldap_connect("MyMachine"); // mymachine hosts an LDAP server if ($LdapServer) { // obtain write access ldap_bind($LdapServer,"cn=root, o=Current CompanyName, c=US", "password"); // now create the entry array $Entry["cn"]="User Name"; $Entry["sn"]="Name"; // the surname $Entry["mail"]="user.name@foo.com";// the email address $Entry["objectclass"]="person"; // now put the data onto the server ldap_modify($LdapServer,"cn=root, o=Current CompanyName, c=US",$Entry); ldap_close($LdapServer); } ?>
Description: Returns the next attribute in an entry, or FALSE on error. The ResultEntryIdentifier is obtained from the call to ldap_first_attribute.
See Also: ldap_first_attribute
Usage:
<?php $Attribute = ldap_first_attribute($LdapServer,$LDAPEntry,&$BERIDPointer); echo "Search returned first attribute =$Attribute <P>"; while ($Attribute) $Attribute = ldap_next_attribute($LdapServer,$LDAPEntry,&$BERIDPointer); Appendix A PHP Language Reference ?>
Description: Returns the entry identifier for the next entry in the ResultEntryIdentifier, which was returned from the ldap_first_entry call. It returns FALSE at the end of the list.
See Also: ldap_first_entry
Usage:
<?php $LDAPEntry = ldap_first_entry($LdapServer, $SearchResult); while ($LDAPEntry) { $LDAPEntry = ldap_next_entry($LdapServer, $LDAPEntry); // do work here } ?>
Description: Returns a search result identifier, or FALSE on error. It works like ldap_search or ldap_list, but only searches in the BaseDN.
See Also: ldap_connect,ldap_first_entry,ldap_search
Usage:
<?php $dn = " o=Current CompanyName, c=US"; $partialName = "Pe"; $LookFor = "|(sn=$partialName*)(givenname=$partialName*))"; $LookInCategories = array("ou","sn","givenname","mail"); $SearchResult = ldap_read($LdapServer,$dn,$LookFor,$LookInCategories); ?>
Description: Returns a search identifier, or FALSE on error. It works like ldap_search or ldap_list, except it searches from the BaseDN down into every tree below BaseDN.
See Also: ldap_list,ldap_connect,ldap_search,ldap_first_attribute
Usage:
<?php $dn = " o=Current CompanyName, c=US"; $partialName = "Pe"; $LookFor = "|(sn=$partialName*)(givenname=$partialName*))"; $LookInCategories = array("ou","sn","givenname","mail"); $SearchResult = ldap_read($LdapServer,$dn,$LookFor,$LookInCategories); ?>
Description: Closes the connection to the server opened with ldap_connect. Returns TRUE on success, FALSE on failure.
See Also: ldap_connect
Usage:
<?php $LdapServer = ldap_connect("MyMachine"); // mymachine hosts an LDAP server ldap_unbind($LdapServer); ?>
To use MySQL with PHP, you must configure PHP with the --with-mysql=DIRNAME option before compiling and installing PHP. You must also have MySQL installed and operational.
You have full control over a MySQL database, depending on the privileges of the username you use to log on to the database with. The password is typically in the clear in the PHP script, so it is best to carefully limit the privileges of the script's username.
The mysql functions will typically print an error message if a problem occurs, unless an '@' is prepended to the function call (for example, @mysql_connect() ). This error message is also available in $phperrmsg.
Description: Returns the number of rows affected by the last INSERT,UPDATE, or DELETE SQL query on the server specified by LinkIdentifier. The one exception is a DELETE without a WHERE clause; in that case the number of rows returned is zero.
See Also: mysql_num_rows
Usage:
<?php $MySQLLink = mysql_connect("localhost","username", "password"); mysql_select_db("imp",$MySQLLink); $Query = "DELETE FROM names WHERE firstname like %Joe%"; $result = mysql_query($Query, $MySQLLink); echo "There were ".mysql_affected_rows($MySQLLink)." changed<p>"; ?>
Description: Closes the link to the MySQL database specified by LinkIdentifier, unless the link is a persistent link opened with mysql_pconnect. Returns TRUE on success, FALSE on failure. This call is not absolutely necessary, as non-persistent links will be closed when the PHP script exits.
See Also: mysql_connect,mysql_pconnect
Usage:
<?php $MySQLLink = mysql_connect("localhost","username", "password"); mysql_close($MySQLLink); ?>
Description: Establishes a connection to a MySQL server. If there are no arguments, the defaults are 'localhost' for Hostname, username of PHP script process for UserName, and an empty password for Password. Returns TRUE on success, FALSE on failure. The Hostname can also include a port number to connect to (for example, localhost:4192 ), or a path to a socket (for example, localhost:/localsock/mysql ).
If this call is made a second time, the already open link identifier will be returned.
See Also: mysql_close,mysql_pconnect
Usage:
<?php $MySQLLink = mysql_connect("localhost","username", "password"); mysql_close($MySQLLink); ?>
Description: Creates a new database on the MySQL server pointed to by LinkIdentifier. You must have logged in as a user with enough privileges for this to work. Returns TRUE on success, or FALSE on failure. You can also use mysql_createdb() for backward compatibility.
See Also: mysql_connect,mysql_drop_db
Usage:
<?php $MySQLLink = mysql_connect("localhost","username", "password"); mysql_create_db("NewDatabase",$MySQLLink); mysql_close($MySQLLink); ?>
Description: Moves the internal row pointer that is associated with a ResultIdentifier to the specified RowNumber. Returns TRUE on success, FALSE on failure. You would typically use mysql_fetch_row() as the next call.
See Also: mysql_fetch_row()
Usage:
<?php $MySQLLink = mysql_connect("localhost","username", "password"); mysql_select_db("mydb",$MySQLLink); $Query = "SELECT * FROM names"; $result = mysql_query($Query, $MySQLLink); mysql_data_seek($result,2); // seek row number 2 mysql_close($MySQLLink); ?>
Description: Selects a database and runs a query on it. Returns a result identifier, or FALSE on error. If you don't specify the LinkIdentifier, it will try to find a previously opened link to use. If it does not find a previously opened link, it will essentially call mysql_connect() with no arguments. For backward compatibility, mysql() can be used instead of mysql_db_query().
See Also: mysql_connect
Usage:
<?php $result = myqsl_db_query("MyDB", "SELECT * from names"); if (!$result) echo ("query failed); ?>
Description: CAUTION: This call attempts to remove an entire database from the server! Be sure you want to do this! You must be logged on to the server as a user with enough privileges to use this call. For backward compatibility, mysql_dropdb can be used instead of mysql_drop_db.
Returns TRUE on success, FALSE on failure.
See Also: mysql_connect,mysql_create_db
Usage:
<?php $MySQLLink = mysql_connect("localhost","username", "password"); mysql_drop_db("MyDB");// no more database! ?>
Description: This function retrieves error numbers from the MySQL database backend.
See Also: mysql_error
Usage:
<?php mysql_connect("NoSuchServerName"); echo "Error ".mysql_errorno()." -- ".mysql_error()."<P>"; ?>
Description: Returns the error string from the last MySQL call.
See Also: mysql_errorno
Usage:
<?php mysql_connect("NoSuchServerName"); echo "Error ".mysql_errorno()." -- ".mysql_error()."<P>"; ?>
Description: Returns an array of the fetched row, or FALSE if there are no more rows. This function stores data in associative indices using the field names as keys, as well as numeric indices. If two or more columns of the result have the same field name, the last field name will be the one indexed by association. You must use the numeric index of the column to retrieve the other columns .
The ResultType argument is optional, and is one of the following defines: MYSQL_ASSOC,MYSQL_NUM, or MYSQL_BOTH.
See Also: mysql_fetch_row,mysql_connect
Usage:
<?php $result = myqsl_db_query("MyDB", "SELECT * from names"); $RowArray = mysql_fetch_array($result); print ("Name = $RowArray["name"]<P>"); ?>
Description: Fetches the field at FieldOffset, or the next field available if FieldOffset not supplied, and returns it in an object. The object has the following properties:
name ” Column name
table ” The table the column belongs to
max_length ” Column maximum length
not_null ” Set to 1 if column cannot be null
primary_key ” Set to 1 if column is a primary key
unique_key ” Set to 1 if column is a unique key
multiple_key ” Set to 1 if column is a non-unique key
blob ” Set to 1 if column is a BLOB
type ” Type of the column
unsigned ” Set to 1 if the column is unsigned
zerofill ” Set to 1 if column is zero filled
If the indicator fields (for example, numeric ) are not set to 1; they are set to 0.
See Also: mysql_field_seek,mysql_fetch_lengths,mysql_field_len,mysql_field_table,mysql_field_name,mysql_field_type,mysql_field_flags
Usage:
<?php // using previously opened and selected database $result = mysql_query($query, $MySQLLink); if ($FieldObj = mysql_fetch_field($result)) echo "Field name is ".$FieldObj->name." from table ".$FieldObj->table; ?>
Description: Returns an array containing the lengths of each field in the last row fetched by mysql_fetch_row, or FALSE if error. The first field length is at index [0].
See Also: mysql_fetch_row,mysql_fetch_array,mysql_fetch_fields,mysql_fetch_object,mysql_num_fields
Usage:
<?php // using previously opened link $result = mysql_query($query,$MySQLLink); $NumFields = mysql_num_fields($result); $FieldLengths = mysql_fetch_lengths($result); for ($index = 0 ; $index < $NumFields ; $index++) echo "Field #$index length = ".$FieldLengths[$index]."<P>"; ?>
Description: Returns an object that has attributes that correspond to the fetched row, or FALSE if no more rows exist. ResultType is optional, and can be one of the following values: MYSQL_ASSOC,MYSQL_NUM, or MYSQL_BOTH. The column names become attribute names.
See Also: mysql_fetch_row,mysql_free_result
Usage:
<?php // using already open connection $result = mysql_query($query,$MySQLLink); if ($RowObj = mysql_fetch_object($result)) echo "The Name column contains ".$RowObj->name." <P>"; ?>
Description: Returns an array that contains the fetched row, or FALSE if no more rows exist. The first entry in the array is an index [0].
See Also: mysql_fetch_object,mysql_fetch_array,mysql_data_seek,mysql_fetch_lengths,mysql_free_result
Usage:
<?php // using previously opened connections $result = mysql_query($query,$MySQLLink); $RowArray = mysql_fetch_array($result); $NumFields = mysql_num_fields($result); for ($index = 0 ; $index < $NumFields; $index++) echo "Field #$index = ".$RowArray[$index]."<P>"; ?>
Description: Returns the name of the field specified by FieldIndex in the Result, starting at index [0]. For backward compatibility, mysql_fieldname can be used instead.
See Also: mysql_fetch_object,mysql_fetch_array,mysql_data_seek,mysql_fetch_lengths,mysql_free_result
Usage:
<?php // using previously opened connection $result = mysql_query($query,$MySQLLink); echo "First field name is ".mysql_field_name($result,0); ?>
Description: Moves the internal field pointer to FieldIndex in Result set. If mysql_fetch_field is called without a FieldIndex parameter, the field pointed to by this function is returned.
See Also: mysql_fetch_field
Usage:
<?php // using previously opened connection $result = mysql_query($query, $MySQLLink); mysql_field_seek($result,3) or die ("could not seek to field 3"); $FieldObj = mysql_fetch_field($result); // fetches field 3 ?>
Description: Returns the name of the table for FieldIndex in Result set. For backward compatibility, mysql_fieldtable can be used.
See Also: mysql_fetch_field
Usage:
<?php // using previously opened connection $result = mysql_query($query,$MySQLLink); echo "Table name of first field is ".mysql_field_table($result, 0); ?>
Description: Returns the type of the field specified by FieldIndex in the Result, starting at index [0]. For backward compatibility, mysql_fieldtype can be used instead.
See Also: mysql_field_name
Usage:
<?php // using previously opened connection $result = mysql_query($query,$MySQLLink); echo "Type of first field is ".mysql_field_type($result,0); ?>
Description: Returns the field flags for the FieldIndex in Result set, separated by spaces. The following flag words can be returned: auto_increment,binary,blob,enum,multiple_key,not_null,primary_key,timestamp,unique_key,unsigned,zerofill. For backward compatibility, mysql_fieldflags can be used instead. The explode() function can be used to break up the long string.
See Also: mysql_field_name,mysql_fetch_object
Usage:
<?php // using previously opened connection $result = mysql_query($query,$MySQLLink); echo "Flags of first field is ".mysql_field_Flags($result,0); ?>
Description: Returns the length of the field specified by FieldIndex for Result set. For backward compatibility mysql_fieldlen can be used.
See Also: mysql_fetch_field
Usage:
<?php // using previously opened connection $result = mysql_query($query,$MySQLLink); echo "Length of first field is ".mysql_field_len($result,0); ?>
Description: Frees the memory that was used by Result set. This function only needs to be used if you are using too much memory during the execution of a script. All memory used during execution of a script is freed when the script exits. For backward compatibility mysql_freeresult can be used.
See Also: mysql_fetch_row,mysql_connect,mysql_close
Usage:
<?php // using previously opened link $result = mysql_query($query,$MySQLLink); mysql_free_result($result); // release memory occupied by this call ?>
Description: Returns the ID generated by the last INSERT SQL query for an AUTO_INCREMENT field. The LinkIdentifier is the identifier from the mysql_connect call, and is entirely optional.
See Also: mysql_fetch_field
Usage:
<?php // using previously opened link $query = "INSERT into demographics (income, age) values (1111.11,22); $result = mysql_query($query,$MySQLLink); A MySQL and PHP from scratch echo "Auto Increment key value is ".mysql_insert_id($MySQLLink)."<P>"; ?>
Description: Returns a result identifier that contains information about the TableName in DatabaseName, or -1 if an error occurs. To retrieve the information you would use the functions mysql_field_flags,mysql_field_len,mysql_field_name, or mysql_field_type. If an error occurs, the error string will be placed in $phperrmsg. For backward compatibility mysql_listfields can be used.
See Also: mysql_field_flags,mysql_field_len,mysql_field_name,mysql_field_type,mysql_connect
Usage:
<?php // using previously opened connection $result = mysql_list_fields("MyDB", "MyTable",$MySQLLink); echo "Flags of first field is ".mysql_field_Flags($result,0); echo "Type of first field is ".mysql_field_type($result,0); ?>
Description: Returns a result identifier containing the databases the MySQL daemon identified by LinkIdentifier is hosting. You will use the mysql_tablename function to retrieve information from the result set. For backward compatibility mysql_listdbs can be used.
See Also: mysql_tablename
Usage:
<?php // using previously opened connection $result = mysql_list_dbs($MySQLLink); echo "First database name is ".mysql_tablename($result,0)." <P>"; ?>
Description: Returns a result pointer containing the tables in DatabaseName for connection specified by optional LinkIdentifier. You use the mysql_tablename function to get the table names from the result set. For backward compatibility mysql_listtables can be used.
See Also: mysql_tablename,mysql_db_query
Usage:
<?php // using previously opened connection $result = mysql_list_tables("MyDB",$MySQLLink); echo "First table name is ".mysql_tablename($result,0)." <P>"; ?>
Description: Returns the number of fields in Result set. For backward compatibility mysql_numfields can be used.
See Also: mysql_fetch_row,mysql_db_query
Usage:
<?php // using previously opened connection $result = mysql_query($query,$MySQLLink); $NumFields = mysql_num_fields($result); echo "There are $NumFields number of fields<P>"; ?>
Description: Returns the number of rows in Result set. For backward compatibility mysql_numrows can be used.
See Also: mysql_db_query,mysql_query,mysql_fetch_row,mysql_connect
Usage:
<?php // using a previously opened link $result = mysql_query($query,$MySQLLink); echo "The number of rows returned is ".mysql_num_rows($result)."<P>"; ?>
Description: This function works exactly like mysql_connect, except the persistent link identifier returned will not be closed when the PHP script exits. This provides quicker startup if the link was previously opened by the same or different script. The hostname, username, and password must all match; otherwise a new connection is attempted.
See Also: mysql_connect,mysql_pclose
Usage:
<?php $PersistentLink = mysql_pconnect("Hostname", "username", "password"); ?>
Description: Sends the QueryString to the database specified by the optional LinkIdentifier and returns the result set. If LinkIdentifier is missing, the last opened link is used. If no link exists, a link is attempted using mysql_connect with no arguments. The return is FALSE if an error occurred.
See Also: mysql_connect,mysql_db_query
Usage:
<?php $MySQLLink = mysql_connect("localhost","username", "password"); $result = mysql_query("select * from MyTable",$MySQLLink); ?>
Description: Returns one cell from a Result set. ' Field ' can be the field index (as an integer), the field name (as a string), or the field table dot name (for example, "TableName.FieldName"). If the column name is aliased, use the alias to retrieve the field. For example if you used "SELECT * from names as FirstName," then you would use "FirstName" for the Field argument.
This function should not be used because it is such a slow way to retrieve data. Also, you should not use this function with other functions that fetch fields from the Result set. It is better to use the functions mysql_fetch_row,mysql_fetch_array, or mysql_fetch_object.
See Also: mysql_fetch_row,mysql_fetch_array,mysql_fetch_object
Usage:
<?php // using previously opened link $result = mysql_query($query,$MySQLLink); echo "first field in first row is ".mysql_result($result,0,0); ?>
Description: Selects the current active database on server specified by optional LinkIdentifier. Each mysql_query call after this uses the currently active database. If LinkIdentifier is not provided, the last opened link is used. If no link exists, a connection is attempted using mysql_connect called with no arguments. The function returns TRUE on success, or FALSE on failure. For backward compatibility mysql_selectdb can be used.
See Also: mysql_connect,mysql_pconnect,mysql_query
Usage:
<?php $MySQLLink = mysql_connect("localhost","username", "password"); mysql_select_db("mydb",$MySQLLink); $Query = "SELECT * FROM names"; $result = mysql_query($Query, $MySQLLink);// query is made on "mydb" ?>
Description: Returns the name of a table from the last Result set when used with mysql_list_tables. The function mysql_num_rows can be used to determine the number of tables returned in Result.
See Also: mysql_list_tables,mysql_list_dbs
Usage:
<?php // using previously opened connection $result = mysql_list_tables("MyDB",$MySQLLink); echo "First table name is ".mysql_tablename($result,0)." <P>"; ?>
To use SNMP on Red Hat, you must install the SNMP package. SNMP server functionality is available on Windows NT, but not Windows 95/98. You will find more about SNMP at the commercial site, http://www.snmp.com.
The snmp package provided with the PHP download is in the dl/snmp directory. You must get the ucd-3.2 snmp library and compile and install it. Take the header files asn1.h,snmp_api.h,snmp_client.h,snmp_impl.h,snmp.h,parse.h from the snmp library and copy them to /usr/local/include. Change into the dl/snmp library in the PHP distribution and build the library. See the README file in the dl/snmp directory for more information.
To use SNMP, use the dl command, dl("/path/to/snmp.so") in your script. Alternatively, you can specify the snmp library in the PHP3.ini file.
Description: Returns the SNMP object value or FALSE on error. The object is specified by ObjectID. The SNMP agent is specified by HostName. The SNMP read community is specified by Community. The optional Timeout specifies how long to wait for an answer. The optional Retries specifies how many times to try before giving up.
See Also: snmp_walk
Usage:
<?php $SystemContact=snmpget("HostName.com","public","system.SysContact.0"); ?>
Description: Sets the SNMP object named ObjectID of Type to Value on HostName in Community. The optional Timeout specifies how long to wait for an answer. The optional Retries specifies how many times to try before giving up. Returns TRUE for success or FALSE for failure.
See Also: snmpget
Usage:
<?php $result = snmpset("HostName.com","private","system.SystContact.0", "OID","Bill Smith"); ?>
Description: Returns an array of SNMP values starting from ObjectID on HostName in Community, or FALSE if an error occurs. The optional Timeout specifies how long to wait for an answer. The optional Retries specifies how many times to try before giving up.
If Community is null, the SNMP values start from the root of the SNMP tree, and the entire tree is returned.
See Also: snmpget
Usage:
<?php $ResultArray = snmpwalk("Hostname.com","public",""); // get entire tree for ($index = 0 ; $index < count(ResultArray); $index++) echo "Item number $index = ".$REsultArray[$index]."<P>"; ?>
Description: Returns an associative array with object IDs and values starting from ObjectID on HostName for Community, or FALSE if an error occurs. The optional Timeout specifies how long to wait for an answer. The optional Retries specifies how many times to try before giving up.
If Community is null, the SNMP values start from the root of the SNMP tree, and the entire tree is returned.
See Also: snmpget,snmpwalk
Usage:
<?php $ResultArray = snmpwalkoid("hostname.com","public",""); // look at each part of the array and print its name and value for (reset($ResultArray); $Identifier = key($ResultArray); next($ResultArray)) echo "For $Identifier, value is = $ResultArray[$Identifier]<P>"; ?>
Description: If you are using the UCD Library, this returns the current quick_print value. The value of quick_print is 0 by default (off).
See Also: snmpget
Usage:
<?php $QPValue = snmp_get_quick_print(); ?>
Description: Sets the value of quick_print in the UCD library to QuickPrintValue. If it is a 1, the library will return "quick printed" values. In other words, only the value will be printed. If the value is 0, which is the default, all the information about the object will be printed, including the type. Also, when the value is 0, additional hex values are printed for all strings less than four characters in length.
See Also: snmpget
Usage:
<?php snmp_set_quick_print(0); echo snmpget("hostname.com","public","system.SysContact.0")."<P>"; ?>
PHP allows you to create constants to be used in your code. Constants cannot be changed once created. A set of pre-defined constants is also available to the user.
Description: Associate CONSTANT_NAME with ' Constant Value '. PHP will replace every occurrence of CONSTANT_NAME with ' Constant Value ' before parsing the script. C -like macro definitions are not currently supported.
See Also: defined constants
Usage:
<?php define("MY_SCRIPT_NAME", "PHP define test script"); define("NUMBER_OF_ITEMS", 3); echo MY_SCRIPT_NAME." has ".NUMBER_OF_ITEMS." in it<P>"; ?>
Description: The following constants are defined whenever a PHP script starts executing:
E_ERROR ” An error other than parsing, from which recovery is not possible. Used with the error_reporting() function.
E_WARNING ” An error which PHP recognizes. PHP will continue executing. Used with the error_reporting() function.
E_PARSE ” An error where PHP can't parse the script because of a syntax error. Recovery is not possible. Used with the error_reporting() function.
E_NOTICE ” Something happened . It might not be an error. PHP continues executing. Used with the error_reporting() function.
FALSE ” A false value. Can be used in any PHP statement. Always a 0 under PHP.
__FILE__ ” The PHP file currently being parsed. If the constant is in an included file, it is the name of the include file.
__LINE__ ” The number of the current line being parsed.
PHP_VERSION ” The version of PHP currently being used.
PHP_OS ” The name of the operating system PHP is running under.
TRUE ” A true value. Can be used in any PHP statement. Always a 1 under PHP.
See Also: define
Usage:
<?php if ($MyErrorIndicater == TRUE) echo "Detected an error at "._LINE_." in "._FILE_."<P>"; Appendix A PHP Language Reference ?>
You can get the size of images in PHP without the GD library installed. For all of the other functionality, the GD library is required. The latest GD library is available at http://www.boutell.com/gd/. This library is included with the standard Red Hat distribution and is usually installed by default.
Description: Returns the size of a GIF, JPG, or PNG image file, the dimensions of the image, the file type, and a height or width text string that can be used within an HTML IMG tag.
The array returned contains the following indexed elements:
Index 0 ”Width of the image in pixels
Index 1 ”Height of image in pixels
Index 2 ”The image type. 1 = GIF, 2 = JPG, 3 = PNG
Index 3 ”Text string containing the height and width parameters: "height=xxx width=xxx". This string can be used directly in an IMG tag.
The ImageInformation is optional, and allows you to obtain extended information from the file. It currently gives you the JPG APP markers in an associative array. You can recover IPTC information that has been embedded in the APP13 marker. See http://www.xe.net/ipc/. You can use the iptcparse function to read the binary APP13 marker information.
The GD library is not required to use this function.
Usage: iptcparse
<?php $ImgSize = getimagesize("file.jpg",&InfoArray); // if the image contains an APP13 marker, display it if (isset($InfoArray["APP13"])) { $iptc = ipctparse($InfoArray["APP13]); var_dump($iptc); } ?>
Description: Draws a partial ellipse of Color centered at CoordX,CoordY, with the top left being (0,0) in the image specified by Image. The ellipses
width and height are specified by Width and Height. The start and end points are specified in degrees by StartDegrees and EndDegrees.
The Color argument must be created by ImageColorAllocate.
See Also: imagecreate,imagecolorallocate
Usage:
<?php $Image = imagecreate(100,200); // create a 100 by 200 pixel imageCharUp $black = imagecolorallocate($Image,0,0,0); $white = imagecolorallocate($image,255,255,255); imagearc($Image,50,100, 25, 50, 270, 30, $white); ?>
Description: Horizontally draws the first character of Char in the Image with upper-left corner at X,Y with Color. If the font number is 1, 2, 3, 4, or 5, a built-in font is used. If higher numbers are used, the fonts are larger.
See Also: imageloadfont,imagecreate
Usage:
<?php $Image = imagecreate(100,200); // create a 100 by 200 pixel imageCharUp $black = imagecolorallocate($Image,0,0,0); $white = imagecolorallocate($image,255,255,255); imagechar($Image,1,20, 20, "H", $white); ?>
Description: Vertically draws the first character of Char in the Image with upper-left corner at X,Y with Color. If the font number is 1, 2, 3, 4, or 5, a built-in font is used. If higher numbers are used, the fonts are larger.
See Also: imagecreate,imagechar,imageloadfont
Usage:
<?php $Image = imagecreate(100,200); // create a 100 by 200 pixel imageCharUp $black = imagecolorallocate($Image,0,0,0); $white = imagecolorallocate($image,255,255,255); imagecharup($Image,1,40, 40, "H", $white); ?>
Description: Returns a color identifier for the color composed of the Red,Green, and Blue components . Image is the return from imagecreate. You must call this function for each color that is to be used in the image.
See Also: imagecreate,imagechar,imageloadfont
Usage:
<?php $Image = imagecreate(100,200); // create a 100 by 200 pixel imageCharUp $black = imagecolorallocate($Image,0,0,0); $white = imagecolorallocate($image,255,255,255); $red = imagecolorallocate($image,255,0,0); $green = imagecolorallocate($image,0,255,0); $blue = imagecolorallocate($image,0,0,255); ?>
Description: Sets the transparent color in Image to Color. If Color is not specified, the current transparent color is returned.
See Also: creatimage,imagecolorallocate
Usage:
<?php $Image = imagecreate(100,200); // create a 100 by 200 pixel imageCharUp $black = imagecolorallocate($Image,0,0,0); $white = imagecolorallocate($image,255,255,255); $red = imagecolorallocate($image,255,0,0); $green = imagecolorallocate($image,0,255,0); $blue = imagecolorallocate($image,0,0,255); imagecolortransparent($Image,$green); // green is now transparent ?>
Description: Copies a rectangular portion of SourceImg to DestImg. If SourceX,SourceY are different from DestX,DestY, the image is stretched or shrunk to fit. The coordinates refer to the upper-left corner of the images. You can copy within an image by using the same parameter for SourceImg and DestImg. If the copied regions overlap, the results cannot be predictable.
See Also: imagecreate,imagecolorallocate
Usage:
<?php $Image = imagecreate(100,200); // create a 100 by 200 pixel imageCharUp $Image2 = imagecreate(200,400); // create a 200 by 400 pixel imageCharUp $black = imagecolorallocate($Image,0,0,0); $white = imagecolorallocate($image,255,255,255); A MySQL and PHP from scratch $red = imagecolorallocate($image,255,0,0); $green = imagecolorallocate($image,0,255,0); $blue = imagecolorallocate($image,0,0,255); $black = imagecolorallocate($Image2,0,0,0); $white = imagecolorallocate($image2,255,255,255); $red = imagecolorallocate($image2,255,0,0); $green = imagecolorallocate($image2,0,255,0); $blue = imagecolorallocate($image2,0,0,255); imagecharup($Image2,1,40, 40, "H", $white); imagecopyresized($Image,$Image2,0,0,0,0,100,200,200,400); ?>
Description: Returns an image identifier representing a blank image Width pixels by Height pixels. The Width is also referred to as X, the Height is also referred to as Y. The concepts for drawing images are borrowed from Euclidean geometry.
See Also: imagecolorallocate,imagedestroy
Usage:
<?php $Image = imagecreate(100,200); // create a 100 by 200 pixel imageCharUp $Image2 = imagecreate(200,400); // create a 200 by 400 pixel imageCharUp ?>
Description: This function is removed starting with version 1.6 of the GD library because of patent restrictions. The patent holder for compressed GIF technology is charging fees for the use of compressed GIF technology on Web sites. Before you use compressed GIFS on your Web site, you must obtain an agreement that can involve payment of fees. For this reason, most free Web sites are moving to the PNG format.
Description: Draws a dashed line of Color in Image starting at coordinates X1,Y1 to coordinates X2,Y2
See Also: imagecreate,imageline
Usage:
<?php $Image = imagecreate(100,200); // create a 100 by 200 pixel imageCharUp $black = imagecolorallocate($Image,0,0,0); $white = imagecolorallocate($image,255,255,255); imagedashedline($Image,1,1,30,40,$white); ?>
Description: Frees the memory associated with Image. Image is the image identifier returned from imagecreate.
See Also: imagecreate
Usage:
<?php $Image = imagecreate(100,200); // create a 100 by 200 pixel imageCharUp imagedestroy($Image); ?>
Description: Floods an Image with Color starting at coordinates X,Y.
See Also: imagecreate
Usage:
<?php $Image = imagecreate(100,200); // create a 100 by 200 pixel imageCharUp $black = imagecolorallocate($Image,0,0,0); $white = imagecolorallocate($image,255,255,255); imageflood($Image,$white); ?>
Description: Creates a polygon filled by Color at the array specified by Points for the NumberOfVertices in Image. The Points array is in pairs. Points[0]=X1, Points[1]=Y1, Points[2]=X2, Points[3]=Y2, and so forth.
See Also: imagecreate,imagecolorallocate
Usage:
<?php $Image = imagecreate(100,200); // create a 100 by 200 pixel imageCharUp $black = imagecolorallocate($Image,0,0,0); $white = imagecolorallocate($image,255,255,255); $Points = array(10,10,20,20,10,20); imagefilledpolygon($Image,Points,3,$white); ?>
Description: Creates a rectangle filled with Color in Image starting at upper-left corner Y1,Y1 to lower-right corner X2,Y2. The upper-left corner of the image is 0,0.
See Also: imagecreate,imagecolorallocate
Usage:
<?php $Image = imagecreate(100,200); // create a 100 by 200 pixel imageCharUp $black = imagecolorallocate($Image,0,0,0); $white = imagecolorallocate($image,255,255,255); imagefilledrectangle($image,5,5,50,50,$white); ?>
Description: Floods Image with Color using a border color of Border, starting at upper-left corner X,Y.
See Also: imagecreate
Usage:
<?php $Image = imagecreate(100,200); // create a 100 by 200 pixel imageCharUp $black = imagecolorallocate($Image,0,0,0); $white = imagecolorallocate($image,255,255,255); imagefloodfill($Image,5,5,$white,$black); ?>
Description: Returns the height in pixels of the specified font.
See Also: imagecreate,imageloadfont,imagefontwidth,imagechar,imagecharup
Usage:
<?php $Height = imagefontheight(1);// get height of built in font $FontNumber = imageloadfont("MyFont.file"); $Height2 = imagefontheight($FontNumber); // get height of loaded font ?>
Description: Returns the width in pixels of a character in Font.
See Also: imagefontheight,imageloadfont,imagecreate
Usage:
<?php $Width = imagefontwidth(1);// get height of built in font $FontNumber = imageloadfont("MyFont.file"); $Width2 = imagefontwidth($FontNumber); // get height of loaded font ?>
Description: This function was removed from the GD library starting with version 1.6 because of patent restrictions. See the note on imagecreatefromgif.
Description: Sets interlace for Image to Interlace value. If Interlace is 1, the Image will be interlaced. If Interlace is 0, the Image will not be interlaced. If the optional Interlace parameter is not provided, the current Interlace setting is returned.
Usage:
<?php $CurrentInterlace = imageinterlace($Image); imageinterlace($Image,1);// set interlace ?>
Description: Draws a line using Color from X1,Y1 to X2,Y2 in Image. The coordinate 0,0 is the top left corner of the images.
See Also: imagecreate,imagecolorallocate,imagedashedline
Usage:
<?php $Image = imagecreate(100,200); // create a 100 by 200 pixel imageCharUp $black = imagecolorallocate($Image,0,0,0); $white = imagecolorallocate($image,255,255,255); imageline($Image,0,0, 25,25,$white); ?>
Description: Loads a user-defined bitmap font and returns a font identifier number for it. This number is always greater than 5. Built-in fonts have numbers from 1 “5.
Bitmapped fonts are architecture dependent, and do not scale well. You must generate the font file on the same type of machine you will be running PHP on. For example, a bitmap font file created on an Alpha CPU might not work on a X86 (Intel) CPU.
See Also: imagefontheight,imagefontwidth,imagecreate
Usage:
<?php $FontNumber = imageloadfont("MyFont.file"); A MySQL and PHP from scratch $Width2 = imagefontwidth($FontNumber); // get height of loaded font ?>
Description: Creates a polygon using Color at the array specified by Points for the NumberOfVertices in Image. The Points array is in pairs. Points[0]=X1, Points[1]=Y1, Points[2]=X2, Points[3]=Y2, and so forth.
See Also: imagecreate,imagefilledpolygon
Usage:
<?php $Image = imagecreate(100,200); // create a 100 by 200 pixel imageCharUp $black = imagecolorallocate($Image,0,0,0); $white = imagecolorallocate($image,255,255,255); $Points = array(10,10,20,20,10,20); imagepolygon($Image,Points,3,$white); ?>
Description: Creates a rectangle using Color in Image starting at upper-left corner Y1,Y1 to lower-right corner X2,Y2. The upper-left corner of the image is 0,0.
See Also: imagecreate
Usage:
<?php $image = imagecreate(100,200); // create a 100 by 200 pixel imageCharUp $black = imagecolorallocate($Image,0,0,0); $white = imagecolorallocate($image,255,255,255); imagerectangle($image,5,5,50,50,$white); ?>
Description: Draws a pixel in Image at X,Y using Color. The top left of the image is 0,0.
See Also: imagecreate,imagecolorallocate
Usage:
<?php $image = imagecreate(100,200); // create a 100 by 200 pixel imageCharUp $black = imagecolorallocate($Image,0,0,0); $white = imagecolorallocate($image,255,255,255); imagesetpixel($image,5,5,$white); ?>
Description: Draws the String in Image using Color at coordinates X,Y. The top left of the image is 0,0. Fonts 1 “5 specify a built-in font.
See Also: imagecreate,imageloadfont
Usage:
<?php $Image = imagecreate(100,200); // create a 100 by 200 pixel imageCharUp $black = imagecolorallocate($Image,0,0,0); $white = imagecolorallocate($image,255,255,255); imagestring($Image,50,50,"Hi",$white); ?>
Description: Draws the String vertically in Image using Color at coordinates X,Y. The top left of the image is 0,0. Fonts 1 “5 specify a built-in font.
See Also: imagestring, imagecreate, imageloadfont
Usage:
<?php $Image = imagecreate(100,200); // create a 100 by 200 pixel imageCharUp $black = imagecolorallocate($Image,0,0,0); $white = imagecolorallocate($image,255,255,255); imagestringup($Image,100,50,"Hi",$white); ?>
Description: Returns the width of the image specified by Image.
See Also: imagecreate
Usage:
<?php $Image = imagecreate(100,200); // create a 100 by 200 pixel imageCharUp echo "image is ".imagesx($Image)." pixels wide"; ?>
Description: Returns the height of the image specified by Image.
See Also: imagecreate
Usage:
<?php $Image = imagecreate(100,200); // create a 100 by 200 pixel imageCharUp echo "image is ".imagesy($Image)." pixels tall"; ?>
Description: Calculates and returns in an array the box that bounds a TrueType Font in Font FileName using font Size along the Angle. The Font FileName can also be a URL.
The array contains the X,Y coordinates of the lower-left corner in indexes 0,1, X,Y coordinates of the lower-right corner in 2,3, X,Y coordinates of upper-right corner in 4,5, and the X,Y coordinates of upper-left corner in 6,7.
You must have the GD library and the Freetype library installed.
See Also: imagettftext
Usage:
<?php $BR = imagettfbbox(10,0,"TimesRoman","Test!"); echo "Upper left corner is at X= $BR[0], Y=$BR[1]"; ?>
Description: Draws the string Text in Image starting a coordinate X,Y on Angle in Color using TrueType font in Font FileName. The X,Y coordinates are more or less the lower-left of the first character, also known as the base point. The image string function's X,Y coordinates specify the upper-right corner of the first character.
The Angle is in degrees. Zero (0) degrees is left to right, horizontally printed text. The degrees increment counter-clockwise, with 90 degrees being straight up, bottom to top.
The Text string can also contain UTF-8 character sequences, similar to Ţ, to allow you to print more than 255 individual characters.
The array contains the X,Y coordinates of the upper-left corner in indexes 0,1, X,Y coordinates of the upper-right corner in 2,3, X,Y coordinates of lower-right corner in 4,5, X,Y coordinates of lower-left corner in 6,7.
See Also: imagettfbbox
Usage:
<?php $Image - imagecreate(400,400); $white = imagecolorallocate($Image,255,255,255); imagettftext($image,10,0,20,10,$white,"TimesRoman.TTF","Test!"); ?>
Description: Returns the index of the color of the pixel at X,Y in Image.
See Also: imagecolorallocate,imagecolorset,imagecolorsforindex
Usage:
<?php $Image - imagecreate(400,400); $white = imagecolorallocate($Image,255,255,255); $ColorIndex = imagecolorat($Image, 10,10); ?>
Description: Returns the index of the color specified by Red,Green,Blue that is in Image. The closest color to the requested RGB value is returned.
See Also: imagecolorallocate,imagecolorset,imagecolorsexact
Usage:
<?php $Image - imagecreate(400,400); $white = imagecolorallocate($Image,255,255,255); $red = imagecolorallocate($Image,255,0,0); $ColorIndex = imagecolorclosest($image,255,0,0); //returns the index of red ?>
Description: Returns the index of the color specified by Red,Green,Blue in the palette of Image. If the color does not exists, a -1 is returned.
See Also: imagecolorclosest
Usage:
<?php $Image - imagecreate(400,400); $white = imagecolorallocate($Image,255,255,255); $ColorIndex = imageColorExact($Image, 255,255,255); //return white's index ?>
Description: Returns a color index for the color specified by Red,Green,Blue. The closest color index will be returned.
See Also: imagecreate,imagecolorset
Usage:
<?php $Image - imagecreate(400,400); $white = imagecolorallocate($Image,255,255,255); A MySQL and PHP from scratch $ColorIndex = imagecolorresolve($Image, 255,255,255); // returns index for white ?>
Description: Returns an associative array containing red, green, and blue keys containing the values for the ColorIndex in Image.
See Also: imagecreate,imagecolorset
Usage:
<?php $Image - imagecreate(400,400); $white = imagecolorallocate($Image,255,255,255); $ColorIndex = imagecolorresolve($Image, 255,255,255); // return index for white $RGBArray = imagecolorsforindex($Image,$ColorIndex); // return RGB for white echo "Red value for white is ".$RGBArray["red"]; ?>
Description: Returns the total number of colors in Image 's palette.
See Also: imagecolorat,imagecolorsforindex,imagecreate
Usage:
<?php $Image - imagecreate(400,400); $white = imagecolorallocate($Image,255,255,255); $red = imagecolorallocate($Image,255,0,0); $black = imagecolorallocate($Image,0,0,0); $blue = imagecolorallocate($Image,0,0,255); $NumOfColors = imagecolorstotal($Image); ?>
Description: Sets the specified index in Image to specified color. You can use this to change the background color instantly, creating a flood fill effect.
See Also: imagecolorat,imagecolorsforindex,imagecreate
Usage:
<?php $Image = imagecreate(400,400); $black = imagecolorallocate($Image,0,0,0); imagecolorset($Image,$black,255,0,0); // change black to red ?>
Description: Returns the bounding box for the string Text using Font index (from imagepsloadfont ), at an Angle in degrees, and returns the bounding box in an array.
The Size argument is in pixels. The optional Space and Tightness arguments are expressed in units, which are fractions of em-square units. A value of 1 is 1/1000th of an em-square.
The Space parameter is signed, and added to the default value of a space in the font. The Tightness parameter is also signed, and is added to the amount of whitespace between characters.
The returned array contains the X,Y coordinates of the lower-left corner in indexes 0,1, and the X,Y coordinates of the upper-right corner in index 2,3. You need to add 1 pixel to each direction in the returned box if the Angle parameter is zero degrees.
See Also: imagecreate,imagepsfreefont,imagepsloadfont
Usage:
<?php $FontIndex = imagepsloadfont("MyPSType1Font"); $Image = imagecreate(400,400); imagepsbbox("Display This!", $FontIndex, 10, 3, 2, 0); ?>
Description: Changes the fonts encoding vector to the character encoding vector found in FontEncoding FileName. This is most typically used to allow support for languages other than English. The exact format of the encoding format is fount in T1libs documentation. The ps.default_encoding configuration entry also controls this behavior.
See Also: imagecreate,imagepsloadfont
Usage:
<?php imagepsencodefont("MyPS1EncodeFile");// modify PS1 encoding ?>
Description: Frees the memory allocated by imagepsloadfont.
See Also: imagecreate,imagepsloadfont
Usage:
<?php $FontIndex = imagepsloadfont("MyPSType1Font"); imagepsfreefont($FontIndex);// free the font ?>
Description: Returns a font index for the PostScript Type 1 font loaded, or FALSE upon error. An error message is printed describing the error.
See Also: imagecreate,imagepsfreefont
Usage:
<?php $FontIndex = imagepsloadfont("MyPSType1Font"); ?>
Description: Draws the string Text on top of Image using Font index (from imagepsloadfont ), using Foreground and Background colors at an Angle in degrees, and returns the bounding box in an array.
The Size argument is in pixels. The optional Space and Tightness arguments are expressed in units, which are fractions of em-square units. A value of 1 is 1/1000th of an em-square.
The text will try to fade into the Background color using AntiAliasingSteps, although no pixels with the Background color are actually painted . The allowed values are between 4 “16. You should use higher values for fonts smaller than 20 points. For larger fonts, use the value of 4. The larger the value of AntiAliasingSteps, the more computation time is required.
The X, Y arguments are roughly the lower-left corner of the first character. The Space parameter is signed, and added to the default value of a space in the font. The Tightness parameter is also signed, and is added to the amount of whitespace between characters.
The array contains the X,Y coordinates of the lower-left corner in indexes 0,1, and the X,Y coordinates of the upper-right corner in index 2,3.
See Also: imagecreate,imagepsfreefont,imagepsloadfont
Usage:
<?php $FontIndex = imagepsloadfont("MyPSType1Font"); $Image = imagecreate(400,400); $white = imagecolorallocate($Image,255,255,255); Appendix A PHP Language Reference $red = imagecolorallocate($Image,255,0,0); $black = imagecolorallocate($Image,0,0,0); $blue = imagecolorallocate($Image,0,0,255); imagepstext($Image,"Display This!", $FontIndex, 10, $white, $black, 200, 10, 3, 2, 0, 12); ?>
The Image functions ImageColorClosestHWB(),ImageCopyMerge(),ImagePaletteCopy() and ImageCreateFromWBMP() were recently added to PHP 4.0.1, so are now in the current version. Because they are so new, they have not been documented. A basic synopsis of the functions is included in this section.
Description: Gets the index of the color, which has the hue, white, and blackness nearest to the given color.
See Also: ImageColorClosest
Description: Merges one part of an image with another. Also based on the percentage indicated. If set to 100, it will function identically to imagecopy. If 0, it will take no action.
See Also: ImageCopy
Description: Copies a palette from one image to another, attempting to match the colors in the target image to the colors in the source palette.
Description: Creates a new image from a WBMP file or URL.
See Also: ImageCreateFromGIF,ImageCreateFromJPEG,ImageCreateFromPNG
IMAP functionality requires PHP configuration and ancillary package installment. All of the necessary functions required to enable PHP to use IMAP are covered in the PHP installation chapter in this book.
IMAP stands for Internet Message Access Protocol. The IMAP implemented by PHP is IMAP 4. You can get more information at http://www.imap.org.
Description: Returns an array containing the IMAP alert messages generated by this script, or since the last imap_alerts call. The errors are cleared by this call.
See Also: imap_errors,imap_last_error
Usage:
<?php $MyBox = imap_open("{MyMail.server.com}INBOX",$MyUserName,$Password); imap_delete($MyBox1,1);// mark message 1 for deletion imap_close($MyBox1,CL_EXPUNGE);// remove deleted messages $IA = imap_alerts(); echo "first imap alert is $IA[0]"; ?>
Description: Appends the string Message to MailBox along with the optional string Flags. The end of line terminator in a string is "\n", except for the Cyrus IMAP server, which requires "\r\n". ImapStream is the value returned from imap_open.
See Also: imap_open
Usage:
<?php $MyBox = imap_open("{MyMail.server.com}INBOX",$MyUserName,$Password); imap_append($MyBox,"INBOX","A Brand New Message in in your mbox!"); imap_close($MyBox); ?>
Description: Decode a BASE-64 encoded text and return the message as a string.
See Also: base64_decode
Usage:
<?php $ClearTextString = imap_base64($Base64EncodedString"); ?>
Description: Returns the body of the message with number MessageNumber in the current open mailbox specified by ImapStream. The optional Flags argument is a bitmask with one or more of the following values OR 'd together:
FT_UID ” The MessageNumber is a User ID.
FT_PEEK ” Do not change the state of the Seen flag. This allows you to "peek" at a message.
FT_INTERNAL ” The return string is in internal format. Do not change ending to CRLF.
See Also: imap_open
Usage:
<?php $MyBox = imap_open("{MyMail.server.com}INBOX",$MyUserName,$Password); $BodyText = imap_body($MyBox,1); // read the first message imap_close($MyBox); ?>
Description: Returns information about the current mailbox in an array, or FALSE on failure. The object returned has the following properties:
object { var $Date; var $Driver; var $Mailbox; var $Nmsgs; var $Recent; };
See Also: imap_open
Usage:
<?php $MyBox = imap_open("{MyMail.server.com}INBOX",$MyUserName,$Password); $MyMail = imap_check($MyBox); echo "My box contains ".$MyMail->Nmsgs." messages<P>"; imap_close($MyBox); ?>
Description: Closes the mailbox specified by ImapStream. If the optional contains CL_EXPUNGE, the mailbox will be silently cleared of deleted messages before closing.
See Also: imap_open
Usage:
<?php $MyBox = imap_open("{MyMail.server.com}INBOX",$MyUserName,$Password); $MyMail = imap_check($MyBox); echo "My box contains ".$MyMail->Nmsgs." messages<P>"; imap_close($MyBox,CL_EXPUNGE); ?>
Description: Creates a new mailbox specified by MboxName on the IMAP server specified by ImapStream. A mailbox can be thought of as a folder to store a message in. Returns TRUE on success, FALSE on failure.
See Also: imap_open
Usage:
<?php $MyBox = imap_open("{MyMail.server.com}INBOX",$MyUserName,$Password); if (!imap_createmailbox($MyBox,"Personal"))//create mailbox named personal echo "Mailbox create failed!<P>"; imap_close($MyBox,CL_EXPUNGE); ?>
Description: Marks MessageNumber for deletion from IMAP account specified by ImapStream. Returns TRUE.
See Also: imap_expunge,imap_close,imap_open
Usage:
<?php $MyBox = imap_open("{MyMail.server.com}INBOX",$MyUserName,$Password); imap_delete($MyBox,1);// mark message 1 for deletion imap_close($MyBox,CL_EXPUNGE);// remove deleted messages ?>
Description: Deletes the mailbox MailBoxName in IMAP account specified by ImapStream. Returns TRUE on success, FALSE on failure.
See Also: imap_open
Usage:
<?php $MyBox = imap_open("{MyMail.server.com}INBOX",$MyUserName,$Password); if (!imap_deletemailbox($MyBox,"Personal"))// delete mailbox 'Personal' echo "could not delete mailbox!<P>"; imap_close($MyBox,CL_EXPUNGE); ?>
Description: Returns an array of all the IMAP error messages generated since the beginning of the session, or since the last call to imap_errors. When imap_errors is called, the errors are cleared.
See Also: imap_last_error,imap_open
Usage:
<?php $MyBox = imap_open("{MyMail.server.com}INBOX",$MyUserName,$Password); imap_delete($MyBox1,1);// mark message 1 for deletion imap_close($MyBox1,CL_EXPUNGE);// remove deleted message $IMAPErrors = imap_errors(); echo "the first error is $IMAPErrors[0]"; ?>
Description: Remove all mail previously marked for deletion from IMAP account specified by ImapStream. Returns TRUE.
See Also: imap_open,imap_delete,imap_close
Usage:
<?php $MyBox = imap_open("{MyMail.server.com}INBOX",$MyUserName,$Password); imap_delete($MyBox,1);// mark message 1 for deletion imap_expunge($MyBox);// remove the message imap_close($MyBox); ?>
Description: Returns an array of objects containing mailbox information. The objects have the following attributes:
object { var $name; // name of the mailbox var $delimiter; // hiearchy delimiter for this mailbox var $attributes; }
The name is the name of the mailbox. The delimiter is the hierarchy delimiter for the hierarchy the mailbox is in. The attribute is a bitmask consisting of one or more of the following:
LATT_NOINFERIORS ” This mailbox has no mailboxes below it.
LATT_NOSELECT ” This is a container, not a mailbox. It cannot be opened.
LATT_MARKED ” This mailbox is marked by UW-IMAPD.
LATT_UNMARKED ” This mailbox was unmarked by UW-IMAPD.
Reference is the IMAP server using the format "{ImapServer:ImapPort}". The Pattern argument specifies where to start searching, with an empty string or the * character specifying all mailboxes. If you pass the % character in Pattern, you are specifying only mailboxes in the current level, and none of the mailboxes below that level. A pattern argument of "~/mail/%" will return all the mailboxes in the ~mail directory.
Usage:
<?php $MyBox = imap_open("{MyMail.server.com}INBOX",$MyUserName,$Password); $Mailbox = imap_getmailboxes($MyBox,"{MyMail.server.com:143}","*"); echo "First Mailbox is ".$Mailbox[0]->name."<P>"; imap_close($MyBox); ?>
Description: This function works identically to imap_getmailboxes, except that it returns just the mailboxes the user is subscribed to.
See Also: imap_getmailboxes,imap_open
Usage:
<?php $MyBox = imap_open("{MyMail.server.com}INBOX",$MyUserName,$Password); $Mailbox = imap_getsubscribed($MyBox,"{MyMail.server.com:143}","*"); echo "First Subscribed Mailbox is ".$Mailbox[0]->name."<P>"; imap_close($MyBox); ?>
Description: Fetches a particular section of the body of the message specified by MessageNumber in account specified by ImapStream, and returns the section as a string. The PartNumber is a string of integers delimited by a period. These integers index into the body part list per the IMAP4 specification. The body parts are not decoded by this function. The Flags are a bit mask with one or more of the following OR 'd together:
FT_UID ” The MessageNumber is a UserID.
FT_PEEK ” Do not change the state of the Seen flag. This allows you to "peek" at a message.
FT_UID ” The returned string is in internal format, without the ending changed to CRLF.
See Also: imap_open,imap_body,imap_close
Usage:
<?php $MyBox = imap_open("{MyMail.server.com}INBOX",$MyUserName,$Password); $PartOfMessage = imap_fetchbody($MyBox,1,1); Appendix A PHP Language Reference imap_close($MyBox); ?>
Description: Return all of the structured information for Message number in account specified by ImapStream in an object. The object has the following attributes:
object { var $type; // integer var $encoding; // integer var $ifsubtype; // boolean var $subtype; //string subtype var $ifdescription; // boolean var $description; // string var $ifid; // integer var $id; // String var $lines; // Integer var $bytes;// Integer var $ifparameters; // boolean var $parameters; // array of objects var $parts; // array of objects }
If the message is a multipart message, an array of objects of all the properties is returned in the attribute parts[]. The array of objects called parameters[] consists of objects having the following attributes:
object { var $attribute; // attribute of the parameter var $value; // value of the parameter }
See Also: imap_open,imap_body,imap_close
Usage:
<?php $MyBox = imap_open("{MyMail.server.com}INBOX",$MyUserName,$Password); $MsgStructure = imap_fetchstructure($MyBox,1); echo "Message type is ".$MsgStructure->type."<P>"; imap_close($MyBox); ?>
Description: Returns an object containing header elements from MesssageNumber in account specified by ImapStream. The optional FromLength and SubjectLength are used to limit the number of characters read from each of these attributes. Some of the header elements returned are
remail
date
Date
subject
Subject
in_reply_to
message_id
newsgroups
followup_to
references
message flags
toaddress
to[] ” An array of objects from the To line containing personal, adl (address list), mailbox, and host.
fromaddress
from[] ” An array of objects on the From line containing personal, adl (address list), mailbox, and host.
ccaddress ” Up to 1024 characters
cc[] ” An array of objects on the Cc line, containing personal, adl (address list), mailbox, and host.
bccaddress ” Up to 1024 characters
bcc[] ” An array of objects on the Bcc line, containing personal, adl (address list), mailbox, and host.
reply_toaddress ” Up to 1024 characters
reply_tp[] ” An array of objects on the Reply_to_line, containing personal, adl (address list), mailbox, and host.
senderaddress ” Up to 1024 characters
sender[] ” An array of objects on the sender line, containing personal, adl (address list), mailbox, and host.
return_path ” Up to 1024 characters
r eturn_path[] ” An array of objects on the return_path line, containing personal, adl (address list), mailbox, and host.
udate ” Unix time format mail message date
fetchfrom ” From line of maximum fromlength characters.
fetchsubject ” From line of maximum subjectlength characters.
The message flags attribute previously listed is an object containing the following attributes:
Recent ” R ”Recent message, has been seen; N ”Recent message, has not been seen, ' ' ”Message is not recent.
Unseen ” U ”Unseen message that is also not recent; ”Message is recent.
Answered ” A ”Message has been answered; ' ' ”Message has not been answered.
Deleted ” D ”Deleted; ' ' ”not deleted.
Draft ” X ”Message is a draft; ' ' ”Message is not a draft.
Flagged ” F ”Message is flagged; ' ' ”Message is not flagged.
The Recent and Unseen flags have interesting combinations. To know that a message is Unseen, you use this combinational test: Unseen == 'U' || Recent == 'N'.
See Also: imap_open
Usage:
<?php $MyBox = imap_open("{MyMail.server.com}INBOX",$MyUserName,$Password); $MsgHeader = imap_header($MyBox,1); echo "Message To Address is ".$MsgHeader->toaddress."<P>"; imap_close($MyBox); ?>
Description: Returns an array of strings containing header information, with one array element per mail message.
See Also: imap_open
Usage:
<?php $MyBox = imap_open("{MyMail.server.com}INBOX",$MyUserName,$Password); $Msgs = imap_headers($MyBox); echo "Message header info for first msg is ".$Msgs[0]."<P>"; imap_close($MyBox); ?>
Description: Returns the text of the last IMAP error that occurred in the current script page. The error information is not reset; repeated calls return the same information unless new errors occur.
See Also: imap_open,imap_errors
Usage:
<?php $MyBox = imap_open("{MyMail.server.com}INBOX",$MyUserName,$Password); $Msgs = imap_headers($MyBox1); echo "Last error Message ".imap_last_error()."<P>"; imap_close($MyBox); ?>
Description: Returns an array containing mailbox names. The Reference and Pattern have the same format as described in imap_getmailboxes.
See Also: imap_open,imap_getmailboxes
Usage:
<?php $MyBox = imap_open("{MyMail.server.com}INBOX",$MyUserName,$Password); $Mbox = imap_listmailbox($MyBox,"{MyMail.server.com:143}","*"); echo "The first mailbox is ".$Mbox[0]."<P>"; imap_close($MyBox); ?>
Description: Returns an array of all of the mailboxes that you have subscribed. The Reference and Pattern have the same format as described in imap_getmailboxes.
Usage: imap_open,imap_getmailboxes
<?php $MyBox = imap_open("{MyMail.server.com}INBOX",$MyUserName,$Password); $Mbox = imap_listsubscribed($MyBox,"{MyMail.server.com:143}","*"); echo "The first mailbox is ".$Mbox[0]."<P>"; imap_close($MyBox); ?>
Description: Copies messages specified by the list or range specified by MsgList to Mailbox for server specified by ImapStream. Returns TRUE on success, FALSE on error. The Flags parameter is a bitmask containing one or more of the following:
CP_UID ” The sequence numbers are UIDS (User ID's).
CP_MOVE ” Delete the messages from the current mailbox after copying.
Usage:
<?php $MyBox = imap_open("{MyMail.server.com}INBOX",$MyUserName,$Password); $Mbox = imap_mail_copy($MyBox,"2","SAVED",CP_MOVE); // move to the saved mailbox imap_close($MyBox); ?>
Description: Copies messages specified by the list or range specified by MsgList to Mailbox for server specified by ImapStream. Returns TRUE on success, FALSE on error.
Usage:
<?php $MyBox = imap_open("{MyMail.server.com}INBOX",$MyUserName,$Password); $Mbox = imap_mail_move($MyBox,"2","SAVED");// move to the saved mailbox imap_close($MyBox); ?>
Description: Returns the number of messages in the current mailbox.
See Also: imap_open,imap_num_recent
Usage:
<?php $MyBox = imap_open("{MyMail.server.com}INBOX",$MyUserName,$Password); $Mbox = imap_num_msg($MyBox); echo "Number of messages in mailbox is $Mbox<P>"; imap_close($MyBox); ?>
Description: Returns the number of recent messages in the current mailbox.
See Also: imap_open,imap_num_msg
Usage:
<?php $MyBox = imap_open("{MyMail.server.com}INBOX",$MyUserName,$Password); $Mbox = imap_num_recent($MyBox); echo "Number of recent messages in mailbox is $Mbox<P>"; imap_close($MyBox); ?>
Description: Returns an IMAP stream on success or FALSE on error. You can also open a connection to a POP3 or an NNTP server. The Mailbox is in the form of "{server.domain.com:143}INBOX", where 143 is the port for the IMAP server, and INBOX is the mailbox name. The UserName is the login name for the user, and Password is the password on the account.
To use this function to log on to a POP3 server on the local machine, you would use "{localhost/pop3:110}INBOX" for the MailBox parameter. To log into an NNTP server on the local machine, you would use "{localhost/nntp:119}newsgroup.name" for the MailBox parameter. The ' localhost ' string can be replaced with a name or IP address to connect to other machines.
The optional Flags parameter is a bitmask with one or more of the following OR 'd together:
OP_READONLY ” Open mailbox for reading only.
OP_ANONYMOUS ” Don't use the .newsrc file, and don't update it, when reading news.
OP_HALFOPEN ” Used with IMAP and NNTP: Open the connection, but don't open a mailbox.
CL_EXPUNGE ” Expunge deleted messages automatically when the mailbox is closed.
See Also: imap_close
Usage:
<?php $MyBox = imap_open("{MyMail.server.com}INBOX", $MyUserName,$Password,CL_EXPUNGE); imap_close($MyBox); ?>
Description: Returns TRUE if the stream is still valid. This can be used as a keep alive for servers which have an automatic timeout because of inactivity. It can cause the server to notify you of new mail.
See Also: imap_open,imap_close
Usage:
<?php $MyBox = imap_open("{MyMail.server.com}INBOX",$MyUserName,$Password); $Mbox = imap_ping($MyBox); if ($Mbox) Appendix A PHP Language Reference echo "mailbox connection is still active<P>"; else echo "mailbox connection is NOT active<P>"; imap_close($MyBox); ?>
Description: Renames OldMailboxName to NewMailboxName on server specified by ImapStream. Returns TRUE on success and FALSE on error.
See Also: imap_open
Usage:
<?php $MyBox = imap_open("{MyMail.server.com}INBOX",$MyUserName,$Password); $Mbox = imap_renamemailbox($MyBox,"PERSONAL", "OLDPERSONAL"); imap_close($MyBox); ?>
Description: Reopens the specified stream to the new mailbox. Returns TRUE on success, or FALSE on failure.
The optional Flags parameter are a bitmask with one or more of the following OR'd together:
OP_READONLY ” Open mailbox as read only.
OP_ANONYMOUS ” Don't use the .newsrc file, and don't update it, when reading news.
OP_HALFOPEN ” Used with IMAP and NNTP: Open the connection, but don't open a mailbox.
CL_EXPUNGE ” Expunge deleted messages automatically when the mailbox is closed.
See Also: imap_open
Usage:
<?php $MyBox = imap_open("{MyMail.server.com}INBOX",$MyUserName,$Password); $Mbox = imap_reopen($MyBox,"{MyMail.server.com}INBOX"); imap_close($MyBox); ?>
Description: Subscribes you to a new Mailbox on server specified by ImapStream. Returns TRUE on success and FALSE on error.
See Also: imap_open
Usage:
<?php $MyBox = imap_open("{MyMail.server.com}INBOX",$MyUserName,$Password); $Mbox = imap_subscribe($MyBox,"PERSONAL"); imap_close($MyBox); ?>
Description: Removes the deletion flag for the message specified by MsgNumber on server specified by ImapStream. Returns TRUE on success, or FALSE on error.
See Also: imap_delete,imap_open
Usage:
<?php $MyBox = imap_open("{MyMail.server.com}INBOX",$MyUserName,$Password); $Mbox = imap_undelete($MyBox,1); imap_close($MyBox); ?>
Description: Unsubscribes you from the Mailbox on the server specified by ImapStream.
See Also: imap_delete,imap_open
Usage:
<?php $MyBox = imap_open("{MyMail.server.com}INBOX",$MyUserName,$Password); $Mbox = imap_unsubscribe($MyBox,"PERSONAL"); imap_close($MyBox); ?>
Description: Converts a quoted-printable string to an 8 bit (binary). Returns the string.
Usage:
<?php $ConvertedString = imap_qprint($QuotedPrintableString); ?>
Description: Converts an 8 bit string to a quoted printable string. Returns the quoted-printable string.
See Also: imap_open
Usage:
<?php $QuotedPrintableString = imap_8bit($EightBitBinaryString); ?>
Description: Converts an 8-bit binary string to a Base64 string. Returns the Base64 string.
See Also: imap_8bit, imap_open
Usage:
<?php $Base64String = imap_binary($EightBitBinaryString); ?>
Description: Returns an array containing the names of mailboxes that have SearchString in the text of the mailbox.
Usage:
<?php $MyBox = imap_open("{MyMail.server.com}INBOX",$MyUserName,$Password); $Mbox = imap_scanmailbox($MyBox,"in");??? imap_close($MyBox); ?>
Description: Returns information about the mailbox specified by ImapStream in an array of objects, or FALSE on failure. The object contains the following attributes:
object { var $Date; // date of the message var $Driver; // driver var $Mailbox; // name of the mailbox var $Nmsgs; // number of messages var $Recent; // number of recent messages var $Unread; // number of unread messages var $Size; // mailbox size }
See Also: imap_open
Usage:
<?php $MyBox = imap_open("{MyMail.server.com}INBOX",$MyUserName,$Password); $MboxInfo = imap_mailboxmsginfo($MyBox); echo "Date of first message is ".$MboxInfo[0]->Date; imap_close($MyBox); ?>
Description: Returns the message number for the given UID. It is the complement of imap_uid.
See Also: imap_open, imap_uid
Usage:
<?php $MyBox = imap_open("{MyMail.server.com}INBOX",$MyUserName,$Password); $MboxUID = imap_uid($MyBox,1); $MboxNumber = imag_msgno($MyBox,$MboxUID); echo "Msg Number of UID $MboxUID is $MboxNumber<P>"; imap_close($MyBox); ?>
Description: Returns an email address given the Mailbox, HostName, and PersonalInfo. The Mailbox parameter is the account name which is the login ID under Linux. The HostName parameter is the machine and domain name, the PersonalInfo is the user's real name.
See Also: imap_open, imap_rfc822_parse_adrlist
Usage:
<?php $Address = imap_rfc822_write_address("jsmith","host.domain.com","John Smith"); ?>
Description: Parses the addresses that are in the AddressString, and returns an array of objects containing the addresses. The attributes of each of the objects are as follows:
object { var $mailbox;// username var $host; // host name var $personal; // person's name var $adl; // domain source route }
See Also: imap_open, imap_rfc822_write_address
Usage:
<?php $AdrInfo = imap_rfc822_parse_adrlist($AddressList, "mydomain.com") echo "First mailbox is ".$AdrInfo[0]->mailbox; ?>
Description: Adds the Flag parameter to the messages specified by Sequence for mailbox specified by ImapStream. The Options parameter can be set to ST_UID to indicate the Sequence parameter contains user ID's (UID's) as opposed to sequence numbers.
See Also: imap_open
Usage:
<?php $MyBox = imap_open("{MyMail.server.com}INBOX",$MyUserName,$Password); $MboxInfo = imap_setflag_full($MyBox,"1","R"); imap_close($MyBox); ?>
Description: Deletes the Flag parameter from the messages specified by Sequence for mailbox specified by ImapStream. The Options parameter can be set to ST_UID to indicate the Sequence parameter contains user IDs (UIDs) as opposed to sequence numbers.
See Also: imap_setflag_full
Usage:
<?php $MyBox = imap_open("{MyMail.server.com}INBOX",$MyUserName,$Password); $MboxInfo = imap_setflag_full($MyBox,"1","R"); imap_close($MyBox); ?>
Description: Returns an array of message numbers sorted by Reverse and Criteria. If Reverse is 1, the sorting is in reverse. If Reverse is 0, sorting is normal. The Criteria parameter can be only one of the following:
SORTDATE ” Message date
SORTARRIVAL ” Arrival date
SORTFROM ” Sort using first FROM address in messages
SORTSUBJECT ” Sort by message subject
SORTTO ” Sort by first TO address in messages
SORTCC ” Sort by first CC address in messages
SORTSIZE ” Sort by size of messages in octets
The Options parameter is one or more of the following OR'd together:
SE_UID ” Return UID's (user ID's) instead of sequence numbers
SE_NOPREFETCH ” Don't pre-fetch searched messages
Usage:
<?php $MyBox = imap_open("{MyMail.server.com}INBOX",$MyUserName,$Password); $MboxInfo = imap_sort($MyBox, SORTFROM, 0, SE_NOPREFETCH); echo "First message sorted by From address is message number $MboxInfo<P>"; imap_close($MyBox); ?>
Description: Returns the unfiltered RFC822 format header of the specified MessageNumber as a text string. The Flags parameter can be one of the following:
FT_UID ” The MessageNumber is a UID.
FT_INTERNAL ” The string returned is in internal format.
FT_PREFETCH ” The RFC822 text should be pre-fetched at the same time the header is returned. This can save some time when reading all of a message.
See Also: imap_open
Usage:
<?php $MyBox = imap_open("{MyMail.server.com}INBOX",$MyUserName,$Password); $MboxInfo = imap_fetchheader($MyBox, 1,FT_INTERNAL); echo "Message number 1 header is $MboxInfo<P>"; imap_close($MyBox); ?>
Description: Searches the mailbox specified by ImapStream using Criteria, returning an array of message numbers. Criteria is a string containing keywords separated by spaces. A multiword argument contained in the string must be quoted (for example, "Chery Marie"). The keywords are one or more of the following:
ALL ” Return all messages matching rest of the criteria list.
ANSWERED ” Match messages with the \\ANSWERED flag set.
BCC "search string" ” Match messages with "search string" in the Bcc: field.
BEFORE "date" ” Match messages with Date: before "date."
BODY "search string" ” Match messages with "search string" in the message body.
CC "search string" ” Match messages with "search string" in the Cc: field.
DELETED ” Match messages that are deleted.
FLAGGED ” Match messages with the \\FLAGGED flag set. This is also known as the "Important" or "Urgent" flag.
FROM "search string" ” Match messages with the "search string" in the From: field.
KEYWORD "search string" ” Match messages with "search string" as a keyword.
NEW ” Match messages that are new.
OLD ” Match messages that are old.
ON "date" ” Match messages with Date: field matching "date."
RECENT ” Match messages with the \\RECENT flag set.
SEEN ” Match messages that have been seen (the \\SEEN flag is set).
SINCE "date" ” Match messages with Date: field later than "date."
SUBJECT "search string" ” Match messages with search string in the Subject: field.
TEXT "search string" ” Match messages with "search string" in the text.
TO "search string" ” Match messages with "search string" in the To: field.
UNANSWERED ” Match messages that have not been answered.
UNDELETED ” Match messages that are not deleted.
UNFLAGGED ” Match messages that are not flagged.
UNKEYWORD "keyword" ” Match messages that do not have the keyword "keyword."
UNSEEN ” Match messages not yet seen.
According to the online documentation, this list was derived from reading the UW c-client code, and may contain errors. The search strings are case sensitive: "Sue" and "sue" are two different names.
The Flags argument can be the value SE_UID, which forces the returned array to contain user ID's (UID's) rather than message sequence numbers.
See Also: imap_open
Usage:
<?php $MyBox = imap_open("{MyMail.server.com}INBOX",$MyUserName,$Password); $Mbox = imap_search($MyBox,"UNSEEN FROM joe",0); echo "First unread message from joe is message number $Mbox<P>"; imap_close($MyBox); ?>
Description: Returns information on an arbitrary mailbox specified by MailBox. The object has the following attributes:
object { var $messages;// number of messages var $recent;// number of recent messages var $unseen;// new messages var uidnext;// next uid var uidvalidity;// changes when uid not valid var $flags;// which of the attributes are valid }
The flags argument controls the information returned in the object, and can be one or more of the following OR'd together:
SA_MESSAGES ” Return the number of messages in the mailbox in the attribute messages.
SA_RECENT ” Return the number of recent messages in the mailbox in the attribute recent.
SA_UNSEEN ” Return the number of unseen messages in the mailbox in the attribute unseen.
SA_UIDNEXT ” Return the next uid to be used in the mailbox in the attribute uidnext.
SA_UIDVALIDITY ” Set the attribute uidnext to a constant that changes when UIDs for the mailbox may no longer be valid.
SA_ALL ” Set all of the above flags.
The flags attribute contains the previous flags. You can test using the above bitmasks to determine which attributes have been filled in.
See Also: imap_open
Usage:
<?php $MyBox = imap_open("{MyMail.server.com}INBOX",$MyUserName,$Password); $Status = imap_status($MyBox,"PERSONAL",SA_UNSEEN); echo "You have ".$Status->unseen." unseen messages in mailbox PERSONAL<P>"; imap_close($MyBox,CL_EXPUNGE);// remove deleted messages ?>
Description: Returns the UID (user ID) for the given MessageNumber. This function is the complement to imap_msgno.
See Also: imap_msgno, imap_open
Usage:
<?php $MyBox = imap_open("{MyMail.server.com}INBOX",$MyUserName,$Password); $MboxUID = imap_uid($MyBox,"1"); echo "User ID of message number 1 is $MboxUID<P>"; imap_close($MyBox); ?>
Description: Returns the absolute value of Number. The return type is float if the Number argument is float; otherwise the return type is int.
See Also: min, max
Usage:
<?php $A = -32; echo "absolute value of $A is ".abs($A)."<P>"; ?>
Description: Returns the arc cosine of Number in radians.
See Also: asin, atan, tan, sin, cos
Usage:
<?php $a = 30.0; echo "Arc Cosing of $a is ".acos($a)."<P>"; ?>
Description: Returns the arc sine of Number in radians.
Description: Returns the arc tangent of Number in radians.
See Also: acos, asin, tan
Usage:
<?php $a = 30.0; echo "Arc tangent of $a is ".atan($a)."<P>"; ?>
Description: Returns the arc tangent in radians of coordinates X and Y. This is similar to calculating arc tangent of X,Y, except the signs of X and Y are used to determine the quadrant of the answer.
See Also: atan, tan
Usage:
<?php $At2 = atan2(3.0,4.0); ?>
Description: Returns a string containing Number changed to base specified by ToBase. The parameters FromBase and ToBase must be numbers from 2 “36. Bases higher than base 10 will have numbers represented by letters a “z, with 10 being the letter a, 11 b, 12 c, and so forth.
See Also: bindec
Usage:
<?php $dec = base_convert("FF",16,10); // convert from base 16 to base 10 ?>
Description: Returns the binary number in BinaryString converted to decimal. The largest binary number that can be converted is 31 1's in a row.
See Also: octdec, base_convert
Usage:
<?php $decimal = bindec("1111");// $decimal is now 15 ?>
Description: Returns the next highest integer value from floating point Number.
See Also: floor, round
Usage:
<?php $Num = ceil(3.2); // $Num is now 4 ?>
Description: Returns the cosine of Number in radians.
See Also: sin, tan, atan, acos, asin
Usage:
<?php $Cosine = cos(1.0); ?>
Description: Returns a string which is decimal Number converted to binary. The largest number that can be converted is 2147483647.
See Also: bindec, octdec, base_convert
Usage:
<?php $Binary = decbin(15); // $Binary is now "1111" ?>
Description: Returns Number converted to hexadecimal in a string. The largest number that can be converted to hexadecimal is 2147483647.
See Also: base_convert, hexdec, decbin, bindec
Usage:
<?php $Hex = dechex(16); // $Hex is now "10" ?>
Description: Returns Number converted to octal in a string. The largest number that can be converted to octal is 2147483647.
See Also: base_convert, octdec
Usage:
<?php $Octal = decoct(8); // $Octal is now "10" ?>
Description: Returns e raised to the power of Number.
See Also: pow
Usage:
<?php $Esquared = exp(2); ?>
Description: Returns the next lowest integer value from floating point Number.
See Also: ceil, round
Usage:
<?php $FloorInt = floor(3.4); // $FloorInt is now 3 ?>
Description: Returns the largest value that can be returned by a call to rand().
See Also: rand
Usage:
<?php $MaxRand = getrandmax(); ?>
Description: Returns HexadecimalNumber converted to decimal from base 16. The largest number that can be converted is 2147483647.
Usage: base_convert, dechex
<?php $DecimalNumber = hexdec("FF"); // $DecimalNumber is now 255 ?>
Description: Returns the log to the base e of Number.
See Also: log10, exp, pow
Usage:
<?php $LogBaseE = log(2); ?>
Description: Returns the log base 10 of Number.
See Also: log10, log, pow, exp
Usage:
<?php $LogBase10 = log10(20); ?>
Description: Returns the highest value from the arguments. If Number1 is an array, the highest value in the array is returned. You must have Number2 if Number1 is a string, integer, or float. You can have as many arguments as you want.
See Also: min
Usage:
<?php $MaxValue = max(1,2,3,12);// $MaxValue is 12 ?>
Description: Returns the lowest value from the argument list. If the first argument is an array, the lowest value from the array is returned. If Number1 is a string, integer, or float, Number2 must be provided. You can have an unlimited number of arguments.
See Also: max
Usage:
<?php $MinNumber = min (4, 3, 7, 22, 1); ?>
Description: Returns a random number using a Mersenne Twister random generator. This should be suitable for cryptographic purposes, and is faster than the default libc random number generator. If this function is called without Minimum and Maximum parameters, the number returned will be between 0 “RAND_MAX. You need to seed the random number generator with mt_srand().
See Also: mt_srand
Usage:
<?php mt_srand((double)microtime()*1000000); // seed a pseudo random value $Random = mt_rand(); ?>
Description: Seed the mt random number generator with a starting value.
See Also: mt_rand
Usage:
<?php mt_srand((double)microtime()*1000000); // seed a pseudo random value ?>
Description: Returns the maximum value that a call to mt_rand() will produce.
See Also: mt_rand, mt_srand
Usage:
<?php $MaxValue = mt_getrandmax(); ?>
Description: Returns Number formatted per the arguments. You can have 1, 2, or 4 arguments to this function. With one argument supplied, Number will be formatted without a decimal point, but with a comma between each group of thousands. If two arguments are supplied, Number will be formatted with Decimals number of decimals, with a period (".") in front and a comma (",")between every group of thousands. If all arguments are supplied, Number will be formated with Decimals number of decimals, the DecimalPoint string will be used instead of a period ("."), and the ThousandsSeparator string will be used instead of a comma between groups of thousands.
See Also: max
Usage:
<?php $Num = number_format(10000); // $Num is now "10,000" ?>
Description: Returns the decimal number represented by OctalString. The largest number that can be converted is 017777777777 octal, or 2147483647 decimal.
See Also: decoct, base_convert
Usage:
<?php $Dec = octdec("1773"); ?>
Description: Returns an approximation of pi, which is an irrational number that starts 3.14159265358979323846 .
See Also: sin, cos, tan
Usage:
<?php echo "pi is approximately ".pi()."<P>"; ?>
Description: Returns the result of raising Base to the power of Exponent.
Usage:
<?php $Answer = pow(2,3);//$Answer is 8 ?>
Description: Returns a pseudo random number between 0 “RAND_MAX when no parameters are provided. When Minimum and Maximum are provided, the random number is a value from Minimum to Maximum.
See Also: srand , mt_rand
Usage:
<?php srand(microtime()*1000); $Random = rand(); ?>
Description: Returns the rounded value of Number.
See Also: ceil, floor
Usage:
<?php $Answer = round(2.3); // $Answer is 2 $Answer = round(2.5); // $Answer is 3 ?>
Description: Returns the sine of Number in radians.
See Also: cos, tan
Usage:
<?php $Answer = sin(1); ?>
Description: Returns the square root of Number.
See Also: pow
Usage:
<?php $Answer = sqrt(4); // returns 2 ?>
Description: Seeds the random number generator with RandomSeedValue.
See Also: rand
Usage:
<?php srand(time()); ?>
Description: Returns the tangent of Angle in radians.
See Also: sin, cos
Usage:
<?php $Answer = tan(1); ?>
Description: Executes the PHP code in CodeString. One possible use for this function is to store code in files or databases for later execution.
The statements within the string must end with a semicolon. You might also have to escape characters in the string (such as the $ character) to avoid substituting a string value for a string name. To include quotes in a string you might have to escape the '"' character with a backslash. Any variable created or assigned a value in a CodeString retains its value throughout the rest of the script.
See Also: include, require
Usage:
<?php $CodeString = "echo 'this is a test<P>';"; eval(CodeString); // will echo "this is a test<P>" ?>
Description: Returns the argument specified by ArgumentNumber. The number 0 is the first argument. When used with func_num_args, you can create variable length user defined functions.
See Also: func_num_args
Usage:
<?php function foo(){ $NumberOfArguments = func_num_args(); echo "Argument number 1 passed to foo() is ".func_get_arg(0)."<P>"; } foo(10, 11, 12, 13); // prints Argument number 1 passed to foo is 10 ?>
Description: Returns an array containing each of the arguments passed to the current user-defined function.
See Also: func_num_args
Usage:
<?php function foo(){ $NumberOfArguments = func_num_args(); $ArgArray = function_get_args(); echo "Argument number 1 passed to foo() is ".$ArgArray[0]."<P>"; } foo(10, 11, 12, 13); // prints Argument number 1 passed to foo is 10 ?>
Description: Returns the number of arguments passed to the current user-defined function.
See Also: func_get_arg
Usage:
<?php function foo(){ $NumberOfArguments = func_num_args(); echo "Number of arguments passed to foo() is $NumberOfArguments<P>"; } foo(10, 11, 12, 13); // prints Number of arguments passed to foo() is 4 ?>
Description: Returns TRUE if the function has been defined, FALSE otherwise.
See Also: function_num_args
Usage:
<?php function foo() { $a = 3; } if (function_exists("foo")) echo "foo() does exist<P>"; if (!function_exists("foo2")) echo "foo2() does not exist<P>"; ?>
Description: Wastes the specified NumberOfBytes in an unrecoverable fashion while the current script is running. This memory will only be recovered when the script ends. It is useful for testing your PHP application under adverse conditions.
See Also: free
Usage:
<?php echo "leaking a lot of memory !<P>"; leak(10000000); ?>
Description: Sends email addressed ToAddress with the subject SubjectLine containing the MessageBody, along with the optional AdditionalHeaders. The ToAddress can be a list of addresses separated by commas. If you include ExtraHeaders, the headers should be separated by the newline character. Returns TRUE on success, FALSE on failure.
See Also:
Usage:
<?php $Result = mail("bill.smith@company.com","This is a test message", "Hello there!"); if (!$Result) echo "Message was not sent<P>"; ?>
Description: Returns a binary string containing Argument1 N packed into it per the Format string. This function is similar to the Perl pack function, and the formatting codes work the same. The format code is a character that defines what you are formatting, followed by an optional number that specifies how many characters are in the Argument. For example, a format code of a10 specifies a NUL (ASCII 0) padded string of 10 characters in length. The format codes are as follows:
'@' ” Fill the packed string with NUL bytes to the position specified by the repeat count.
'a' ” NUL padded string ”The repeat count following the 'a' is the number of characters in the string. If fewer than repeat count number of characters, the string is filled out with NULs.
'A' ” Space-padded string ”The repeat count following the 'a' is the number of characters in the string. If fewer than repeat count number of characters, the string is filled out with spaces (ASCII ' ').
'c' ” Signed character ” Convert the number argument to a signed character.
'C' ” Unsigned character ”Convert the number argument to an unsigned character.
'd' ” Double (float) ”The number argument will be stored as a double width floating point number.
'f' ” Float ”The number argument will be stored as a floating pointer number.
'h' ” Hexadecimal string conversion ”The number argument will be stored as a hex string, low nibble first.
'H' ” Hexadecimal string conversion ”The number argument will be stored as a hex string, high nibble first.
'i' ” Signed integer ”The number argument will be stored as a signed integer (native byte order).
'I' ” Unsigned integer ”The number argument will be stored as an unsigned integer (native byte order).
'l' ” Signed long ”The number argument will be stored as a signed long (32 bits, native byte order).
'L' ” Unsigned long ”The number argument will be stored as an unsigned long (32 bits, native byte order).
'n' ” Unsigned short ”The number argument will be stored as an unsigned short (16 bits, big endian byte order).
'N' ” Unsigned long ”The number is saved as an unsigned long (32 bits, big endian byte order).
's' ” Signed short ”The number is saved as a signed short (16 bits, native byte order).
'S' ” Unsigned short ”The number is saved as an unsigned short (16 bits, native byte order).
'v' ” Unsigned short ”The number is saved as an unsigned short (16 bits, little endian byte order).
'V' ” Unsigned long ”The number is saved as an unsigned long (32 bits, little endian byte order).
'x' ” NUL byte (ASCII 0) ”Store an ASCII 0.
'X' ” Back up the packed string storage pointer 1 byte. The next directive will overwrite the previous directive.
See Also: unpack
Usage:
<?php $Binary = pack("a5a5","hello","this I");// $Binary has "hello this " ?>
The following functions aid in the execution of external programs. You must be careful when executing external commands due to the inherent security risks involved. In the past, programs have inadvertantly allowed a cracker to copy system files from arbitrary locations.
Description: Returns a string containing backslashes in front of any characters in the Command string that can cause problems when executed by a shell program.
See Also: quotemeta, pack
Usage:
<?php $Command = "wrong; format; for ; command"; $BetterCommand = escapeshellcmd($Command); echo "The command '$Command' was changed to '$BetterCommand'<P>"; ?>
Description: Executes the command and returns the last line from the resulting output of the command. If the optional ResultArray argument is supplied, all of the resulting output lines from the command will be stored in it, one element per line, starting at the end of the array. To clear the array, use unset on it first. If the optional ReturnVariable argument is supplied, the return value of the command will be stored in it.
See Also: passthru , unset
Usage:
<?php $Command = "ls"; exec ($Command, $ReturnArray, $ReturnValue); echo "The first line of return is $ReturnArray[0]<P>"; ?>
Description: Returns the result of executing Command, exactly like the C version of the function. If the optional ReturnValue argument is supplied, the return value of the executed command is stored there.
See Also: passthru, exec
Usage:
<?php system("ls",$ReturnValue); // run the ls command ?>
Description: Executes Command and returns the result to the browser without filtering. This is useful for calling programs that generate images. For example, you could set the content-type to "image/gif" and call a program that generates a gif image stream. This would put the image directly to the browser.
See Also: exec, fpassthru
Usage:
<?php passthru("ls",$ReturnValue); // run the ls command and display ?>
Description: Registers the function specified by FunctionName to be executed when the PHP script processing is complete. No output to the browser can be done by this function. This function will be called when the user presses STOP on the browser, or when the script terminates for any reason.
See Also: exec
Usage:
<?php function MyShutdownFunction() { $Exit = TRUE; // do other work here } register_shutdown_function("MyShutdownFunction"); // to be called when quitting ?>
Description: Returns a string containing a byte-stream representation of SomeValue that can be stored on any storage device. You use this function to store PHP data without losing type, structure, or value information. To recover the SomeValue, use the unserialize() function.
You can serialize integers, floats, strings, arrays, and objects. Object attributes are saved, but object methods are lost.
See Also: unserialize
Usage:
<?php $MyData = "This is a test"; $SaveData = serialize($MyData); // The $SaveData string may be written to a file or database here ?>
Semaphores are used by tasks to communicate with each other. You can think of them in the same term as Railway Flags, being set or reset. Shared memory is a memory region that several programs can read and write simultaneously . Sharing information using shared memory is very fast.
If you are executing a daemon on the same system the Web server is running on, the daemon can communicate with a PHP script using semaphores and shared memory, greatly expanding what the PHP script can do. Alternatively, PHP can execute a program and communicate with that program using semaphores and shared memory.
As always, you must look at such activities with the security risks in mind.
Description: Returns a semaphore ID that is used to access a System V semaphore with the given key. If the semaphore exists, it is created with the permissions specified by PermissionBits. If no PermissionBits argument exists, the permissions are set to 0666. The number of processes that can acquire this semaphore simultaneously is set by the MaximimumAcquire argument. If the argument does not exist, the default is set to 1 if the process finds it is the only process attached to the semaphore.
If you call sem_get() a second time using the same key, a new sempahore identifier will be returned. The same semaphore will be accessed.
See Also: sem_acquire, sem_release
Usage:
<?php $Key = microtime()*100000; $Semaphore = sem_get($Key,2,0666); ?>
Description: Acquires a semaphore, and returns TRUE on success, or FALSE on failure. This function will hang the PHP script until the semaphore can be acquired. If the PHP script attempts to acquire an already acquired , it can hang forever, if the MaxAcquire value provided in sem_get is exceeded. If you do not explicitly release the semaphore before exiting the PHP script, it will be automatically released, and a warning message will be generated.
To use a semaphore in conjunction with another application, get the semaphore, then acquire it. Do some work while it is acquired, and place the result of the work in shared memory or in a file on the disk. Then release the semaphore. When the semaphore is released, the other application can acquire it and then pick up the information you have placed in shared memory or on disk.
See Also: sem_get, sem_release
Usage:
<?php $Key = microtime()*100000;// random key $Semaphore = sem_get($Key,2,0666); if (sem_acquire($Semaphore)) echo "semaphore acquired<P>"; else echo "semaphore not acquired<P>"; ?>
Description: Release a semaphore previously acquired, and return TRUE on success or FALSE on failure. If the semaphore was not previously acquired, a warning message will be generated.
See Also: sem_acquire, sem_get
Usage:
<?php $Key = microtime()*100000;// random key $Semaphore = sem_get($Key,2,0666); if (sem_acquire($Semaphore)) echo "semaphore acquired<P>"; else echo "semaphore not acquired<P>"; // do some work here sem_release($Semaphore); ?>
Description: Returns an ID that can be used to access System V shared memory using the given Key. The first call will create the memory of size MemorySize with optional permission bits specified by Permissions. If Permissions is not specified, the default permissions are 0666.
A second call to shm_attach using the same Key will return a different ID, but will refer to the same memory. In this case, the MemorySize and Permissions arguments will be ignored.
See Also: shm_detach
Usage:
<?php $Key = 91055; $MemoryID =shm_attach($Key, 1000, 0666); // get 1000 bytes of memory if (!$MemoryID) echo "could not get shared memory!<P>"; ?>
Description: Detach from the shared memory as specified by the SharedMemoryID obtained from shm_attach. This does not delete the shared memory.
See Also: shm_attach, shm_remove
Usage:
<?php $Key = 91055; $MemoryID =shm_attach($Key, 1000, 0666); // get 1000 bytes of memory if (!$MemoryID) { echo "could not get shared memory!<P>"; exit; | shm_detach($MemoryID); // remove self from memory ?>
Description: Removes shared memory from the Unix system. All data in the memory is deleted.
See Also: shm_attach, shm_detach
Usage:
<?php $Key = 91055; $MemoryID =shm_attach($Key, 1000, 0666); // get 1000 bytes of memory if (!$MemoryID) { echo "could not get shared memory!<P>"; exit; } shm_detach($MemoryID); // detach self from memory shm_remove($MemoryID); // delete the memory ?>
Description: Inserts or changes Variable in shared memory using VariableKey. All variable types are supported.
See Also: shm_get, shm_acquire
Usage:
<?php $Key = 91055; $MemoryID =shm_attach($Key, 1000, 0666); // get 1000 bytes of memory if (!$MemoryID) { echo "could not get shared memory!<P>"; exit; } $VariableKey = 121212; $MyData = "This is a test"; shm_put_var($MemoryID, $VariableKey, $MyData); ?>
Description: Returns the variable from shared memory specified by SharedMemoryID using VariableKey. This does not delete the variable from memory.
See Also: shm_get, shm_acquire, shm_remove_var
Usage:
<?php $Key = 91055; $MemoryID =shm_attach($Key, 1000, 0666); // get 1000 bytes of memory if (!$MemoryID) { echo "could not get shared memory!<P>"; exit; } $VariableKey = 121212; $MyData = shm_get_var($MemoryID, $VariableKey); // see shm_put_var ?>
Description: Removes the variable from shared memory. The space occupied by the variable is available for reuse.
See Also: shm_get, shm_acquire, shm_get_var
Usage:
<?php $Key = 91055; $MemoryID =shm_attach($Key, 1000, 0666); // get 1000 bytes of memory if (!$MemoryID) { echo "could not get shared memory!<P>"; exit; } $VariableKey = 121212; $MyData = shm_remove_var($MemoryID, $VariableKey); // see shm_put_var ?>
Description: This function delays program execution for the number of seconds specified by Seconds.
See Also: usleep
Usage:
<?php sleep(10); // wait 10 seconds ?>
Description: Returns a unique identifier with Prefix string on front, based on the current time in microseconds. The prefix string is limited to 114 characters.
See Also: rand
Usage:
<?php $UniqueKey = uniqid("Me"); $UniqueKey2 = uniqid(mt_rand()); ?>
Description: Unpacks data from BinaryDataString as specified by FormatString and returns the result in an array.
See Also: pack
Usage:
<?php $BinaryDataString = pack("c1",10); $ResultArray = unpack("c1", $BinaryDataString); echo "ResultArray[0]= ".$ResultArray[0]."<P>"; ?>
Description: Changes a serialized variable and changes it back into a PHP variable. The variable type is the same as when it was serialized. If an object is serialized, its methods are not saved in the serial string.
See Also: serialize
Usage:
<?php $MyData = 12; $Serial = serialize($MyData); $MyRecoveredData = unserialize($Serial); // $MyRecoveredData == $MyData ?>
Description: This function halts program execution for the given number of microseconds. The results of this call are unpredictable, as it can take hundreds of micro-seconds to call the underlying code and return from it. Also, operating system scheduling activities can cause you to sleep much longer. The sleep function tends to be much more accurate.
See Also: sleep
Usage:
<?php usleep(1000); // sleep 1000 microseconds ?>
The following functions allow you to set runtime parameters that affect how PHP processes scripts and get runtime parameter information from your system. These functions are useful for debugging or for tuning system performance.
Description: Sends the error message specified by Message to the location specified by MessageType and Destination. The ExtraHeaders parameter specifies extra information to send with the error message when the error message is being sent by email.
The Destination parameter specifies where the message should go as follows:
0 ” Sends Message to the PHP system logger or a file, depending on the error_log configuration directive in the php3.ini file.
1 ” Sends the message by email to the address specified by Destination, using ExtraHeaders information. It uses the same internal functions as the mail() function does.
2 ” Sends the message though the PHP debugging connection to the address:port specified by Destination, if remote debugging has been enabled.
3 ” Appends the message to the end of the file specified by Destination.
See Also: debugger_on
Usage:
<?php error_log("My very own Error Message",0); // log an error to the system logger ?>
Description: Returns the current error reporting level, and sets PHP's error reporting level to the Level argument, if given. The error reporting level is a bitmask of the following values OR'd together:
1 ”E_ERROR
2 ”E_WARNING
4 ”E_PARSE
8 ”E_NOTICE
16 ”E_CORE_ERROR
32 ”E_CORE_WARNING
The warning level can also be set in the PHP3.ini file.
See Also: error_log
Usage:
<?php error_reporting(E_ERROR | E_WARNING); ?>
Description: Returns the value of an environment variable specified by VariableName, or FALSE on failure.
See Also: phpinfo
Usage:
<?php $Path = getenv("PATH"); // returns the current path ?>
Description: Returns the value of the configuration variable specified by VariableName, or FALSE on failure, as set in the configuration file specified by cfg_file_path configuration variable.
See Also: phpinfo
Usage:
<?php $ConfigFile = get_cfg_var("cfg_file_path"); // if set, configuration file is used ?>
Description: Returns the name of the owner running the current PHP script.
See Also: getmyuid, getmypid, getmyinode, getlastmod
Usage:
<?php $UserName = get_current_user(); ?>
Description: Returns a Unix timestamp which is the time of the last modification of the current page the PHP script is running on, or FALSE on error.
See Also: date
Usage:
<?php $LastMod = getlastmod(); echo "This page modified on ".date("F d Y",$LastMod)."<P>"; ?>
Description: Calls the system function getrusage, and returns an associative array containing the data returned from that function. A value of 1 for the optional Who argument will call getrusage with RUSAGE_CHILDREN. See the man pages for getrusage for the field name definitions, which are the associative array indexes.
See Also: getmyuid
Usage:
<?php $RUsage = getrusage();// call for me echo "Current time used is ".$RUsave["ru_utime.tv_sec"]." seconds<P>"; ?>
Description: Returns the current active configuration setting for magic_quotes_gpc. The function returns a 1 if quotes are on, 0 if off.
See Also: get_magic_quotes_runtime, set_magic_quotes_runtime
Usage:
<?php $MagicSetting = get_magic_quotes_gpc(); ?>
Description: Returns the current active magig_quotes_runtime setting. The function returns a 1 if quotes are on, 0 if off.
See Also: get_magic_quotes_gpc, set_magic_quotes_runtime
Usage:
<?php $MagicRuntime = get_magic_quotes_runtime(); ?>
Description: Sets the current active magig_quotes_runtime setting to NewSetting. The NewSetting should be a 1 if quotes are to be on, 0 if off.
See Also: get_magic_quotes_gpc, get_magic_quotes_runtime
Usage:
<?php set_magic_quotes_runtime(1);// turn quotes on ?>
Description: Returns the inode of the current page the PHP script is running on, or FALSE on error. This value can be used as a unique but determinable key for feeding to shm_get.
See Also: getmypid, getlastmod, getmyuid, get_current_user
Usage:
<?php $MyInode = getmyinode(); ?>
Description: Returns the process ID of the current PHP script, or FALSE on error. If PHP is running as a server module, it is not guaranteed that separate invocations of the script will have different process IDs.
See Also: getmyinode, getlastmod, getmyuid, get_current_user
Usage:
<?php ?>
Description: Returns the user ID of the PHP script, or FALSE on error. Under Apache on Red Hat systems, this is usually the user nobody.
See Also: getmypid, getlastmod, getmyinode, get_current_user
Usage:
<?php $MyUID = getmyuid(); ?>
Description: This function sends almost all information about the current state of PHP to a Web browser. It is useful for determining whether you have certain features enabled. It also gives you OS information, server information, environment information, and master and local configuration information.
See Also: phpversion
Usage:
<?php phpinfo(); ?>
Description: Returns a string containing the currently running PHP's version.
See Also: phpinfo
Usage:
<?php $Ver = phpversion(); echo "Current PHP version is ".$Ver."<P>"; ?>
Description: Returns TRUE if the extension specified by ExtensionName is loaded, FALSE otherwise.
See Also: phpinfo
Usage:
<?php $ImapIn = extension_loaded("imap"); if ($ImapIn) echo "Imap extension is loaded<P>"; else echo "Imap extension is not loaded<P>"; ?>
Description: Adds the EnvironmentSetting string to the environment.
See Also: getenv
Usage:
<?php $MyID = getmyuid(); putenv("MYID=$MyID"); ?>
Description: Sets the number of seconds a script is allowed to run before being terminated with a fatal error. A value of 0 disables the time limit. The default is 30 seconds, or the value defined in the configuration file setting for max_execution_time.
When this function is called, it resets the timeout counter to zero. If you were to continuously call this function, the script would never time out.
See Also: phpinfo
Usage:
<?php set_time_limit(15); // the script will now timeout in 15 seconds set_time_limit(0);// the script will never timeout now ?>
Description: Returns a string with backslashes in front of characters that need to be quoted for database queries or exec calls. The characters escaped are backslash (\), single quote ( ' ), double quote (), and NUL (ASCII 0).
See Also: stripslashes, htmlspecialchars, quotemeta
Usage:
<?php $MyString = " This \ string 'requires' backslashes"; $MyNewString = addslashes($MyString); ?>
Description: Returns an ASCII string containing the bytewise, high nibble first hexadecimal representation of the binary string specified by StringToBeConverted.
See Also: octdec, decoct
Usage:
<?php $MyKey = mhash(MHASH_SHA1,"This is a test"); echo "The hash value is ".bin2hex($MyKey)."<P>\n"; ?>
Description: Returns the StringToBeTrimmed without any trailing whitespace.
See Also: trim
Usage:
<?php $TrimedString = chop("This is a test "); ?>
Description: Returns a one -character string containing the character specified by ASCIICharacter.
See Also: ord, sprintf
Usage:
<?php $MyChar = chr(0x41); // the letter A is in $MyChar ?>
Description: Splits the String argument into smaller chunks , inserting every optional ChunkLength characters, which defaults to 76, the optional EndOfLineString, which defaults to "\r\n". The String argument is untouched.
See Also: ereg_replace
Usage:
<?php $ConvertedString = chunk_split(base64_encode($MyData)); ?>
Description: Converts the String argument from one Cyrillic character set specified by FromCharSet to the set specfied by ToCharSet. The allowable values for the from and to set are as follows:
k ” koi8-r
w ” windows \1251
I ” iso8859-5
a ” x-cp866
d ” x-cp866
m ” x-mac-cyrillic
Usage:
<?php $NewString = convert_cyr_string($OldCyrillicString,"k","a"); ?>
Description: Encrypts a string using standard Unix DES encryption. The optional Salt string is a two-character string that will be randomly generated by PHP if you do not provide it. If your system supports multiple encryption types, the following constants will be set. If they are set to 0, the type is not supported. If they are set to 1, the type is supported.
CRYPT_STD_DES ” Standard DES encryption with a 2 character SALT
CRYPT_EXT_DES ” Standard DES encryption with a 9 character SALT
CRYPT_MD5 ” MD5 encryption with a 12 character SALT starting with $1$
CRYPT_BLOWFISH ” Extended DES encryption with a 16 character SALT starting with $2$
There is no decryption function, because crypt uses a one-way algorithm. If you feed it the same data with the same SALT, you will get the same encryption out. The encryption values can then be compared for a match.
See Also: mt_srand
Usage:
<?php $EncryptedString = crypt("This is a test"); echo "The encrypted string for 'This is a test' is $EncryptedString<P>"; ?>
Description: Echoes all arguments to the browser. You do not have to use parentheses with echo because echo is not really a function.
See Also: print, printf, flush
Usage:
<?php echo "This is a test", " of the echo "," command <P>"; ?>
Description: This function does a case-sensitive search of String for matches to the regular expression in Pattern and returns TRUE if a match for Pattern was found, or FALSE if no matches were found or an error occurred. If the optional array argument Regs is given, the substring matches will be stored in it. $Regs[0] will contain a copy of String. $Regs[1] will contain the first substring match, and so on.
See Also: eregi , ereg_replace, eregi_replace
Usage:
<?php // locate the year from the date function $d = date("M, Y"); ereg("([0-9]{4})",$d,$Regs); echo "Year is $Regs[1]<P>"; ?>
Description: Scans String for matches to Pattern, then replaces the matches with Replacement, and returns the modified string. If no matches are found, String is returned unchanged.
If Pattern contains substrings in parentheses, then Replacement can contain references that govern replacement. The references are of the form \\number, where number is 0 “9. A \\0 will be replaced by the entire contents of String. A \\1 will be replaced by the text matching the first parenthesized substring. A \\2 will be replaced by the text matching the second parenthesized substring, and so on.
See Also: ereg, eregi, eregi_replace
Usage
<?php // print The brown dog is not pink $String = "The red dog is not pink"; echo ereg_replace(" red", " brown", $String); // print The red dog is not blue echo ereg_replace("()pink", "\1blue",$String); // print The brown dog is not pink echo ereg_replace("(()red)", "\2brown",$String); ?>
Description: This function works identically to ereg, except that it is not case sensitive.
See Also: ereg
Usage:
<?php // find BlUe $String = "I feel BlUe"; if (eregi("blue",$String)) echo "Found blue!<P>"; ?>
Description: This function works the same as ereg_replace, except that it is not case sensitive.
See Also: ereg_replace
Usage:
<?php // print The brown dog is not pink $String = "The RED dog is not pink"; echo eregi_replace(" red", " brown", $String); ?>
Description: Returns an array of strings created by splitting String apart at the Separator characters.
See Also: split, implode
Usage:
<?php $String = "item1,item2,item3"; $Items = explode(",",$String); echo "Items[0]=".$Items[0]."<P>"; ?>
Description: Flushes the output buffers, causing all text held by PHP or anything behind PHP (such as a CGI script, Web server, and so forth) to be pushed to the user's browser. Using this function ensures the user sees all generated output to date.
See Also: printf, print, echo
Usage:
<?php echo "this is a test"; flush(); ?>
Description: Opens FileName and parses it line by line for meta tags of the form <meta name=" myname " content="Bill Smith"> and returns an array. The value of the 'name=' property becomes the key in the array. The value of the 'content=' property becomes the value in the array. Special characters are changed to '_', and all characters are converted to lowercase. If the optional UseIncludePath is set to 1, PHP will try to open the file using the standard include path.
See Also: include, replace
Usage:
<?php $MetaArray = get_meta_tags("MyFileName",1); echo "my name is ".$MetaArray["myname"]."<P>"; ?>
Description: Returns a string that converts certain characters to HTML entities. You can use this function to avoid a user hijacking of your Web site by preventing user-supplied text from containing HTML markup commands. The following characters are translated:
'&' becomes ' & '
'''' becomes ' " '
'<' becomes ' < '
'>' becomes ' > '
See Also: htmlentities
Usage:
<?php $String = "<HREF http://www.somewhere.com>"; $NewString = htmlspecialchars($String); echo $String." becomes ".$NewString."<P>"; ?>
Description: This function works the same as htmlspecialchars, except that all characters are replaced by entities which have HTML entity equivalents using the ISO-8559-1 characters, if the replacements exists.
See Also: htmlspecialchars, nl2br
Usage:
<?php $String = "<HREF http://www.somewhere.com>"; $NewString = htmlentities($String); echo $String." becomes ".$NewString."<P>"; ?>
Description: Returns a string containing StringFragments joined together with ConcatString between each fragment.
See Also: explode, split, join
Usage:
<?php $List[0]="ball"; $List[1]="doll"; $NewString = implode(", ",$List); echo $NewString."<P>";// echo "ball, doll" ?>
Description: join is identical to implode in every respect
See Also: implode
Usage:
<?php $List[0]="ball"; $List[1]="doll"; $NewString = join(", ",$List); echo $NewString."<P>";// echo "ball, doll" ?>
Description: Trims spaces from the start of a string and returns the string.
See Also: chop, trim
Usage:
<?php $Str = " this is a test "; echo ltrim($Str)."<P>";// prints "this is a test" ?>
Description: Calculates the MD5 hash of String.
See Also: crypt
Usage:
<?php $Hash = md5("This is a test"); ?>
Description: Converts newline characters to the HTML <BR> line break, and returns a string with the HTML break before all newline characters.
See Also: htmlspecialchars
Usage:
<?php $Str = "This is\na test \n of this\n"; echo nl2br($Str); ?>
Description: Returns the ASCII value of the first character in Character string. This is the complement to chr.
See Also: chr
Usage:
<?php $Str = "0"; if (ord($Str) == 0x30) echo "The first character is 0!"; ?>
Description: Parses String and sets variables as if the string were a URL being passed to a PHP page starting up.
See Also: getenv
Usage:
<?php $String = "Page=1&Word[]=the&Word[]=best&line=the+best"; parse_str($String); echo "Page = $Page<P>"; echo $Word[0]; // echos the echo $Word[1]; // echos best echo $line; // echos "the best" ?>
PHP implements a set of regular expression parser functions that are compatible with how Perl operates. An entire book could be written on Perl regular expressions. I will cover enough information to get you started. For help, http://engpub1.bu.edu/bioinfo/BE561/PERL5.html is a good beginning resource. Another good thing to do is visit your favorite search site (http://www.mamma.com, http://www.yahoo.com, http://www.google.com, http://www.excite.com, http://www.dogpile.com) and look for "Perl regular expression."
You must enclose the expression in delimiters. A forward slash (/) is a good delimiter, and is commonly used in Perl. You cannot use an alphabetic character or a backslash (\) as a delimiter, but all other characters are fair game. If you use a delimiter within an expression, you must escape it with a backslash. You can follow the end delimiter with pattern modifiers that affect how the regular expression is processed .
Within the delimiters, the following character sequences affect the pattern match. This is not an exhaustive list, but will suffice for most uses:
\A ” Matches only at the beginning of the string.
\b ” Matches a word boundary, unless looking for a character. If looking for a character, \b represents a backspace .
\B ” Matches a non-word boundary.
\d ” Matches a numeric character.
\D ” Matches a non-numeric character.
\w ” Matches any alphanumeric character, including an underline (_).
\W ” Matches any non-alphanumeric character.
\s ” Matches a whitespace.
\S ” Matches a non-white space.
\Z ” Matches only at the end of a string.
\n, \r, \f, \t, \NNN ” Matches newline, return, form feed, tab, arbitrary number (as you would expect).
\<n'th> ” Within a pattern, matches the n'th occurrence of substring. Use $<n'th> outside of a pattern.
$+ ” Returns whatever the last bracket match matched.
$& ” Returns the entire matched string.
$` ” Returns everything before the matched string.
$' ” Returns everything after the matched string.
^ ” Matches the beginning of the string.
$ ” Matches the end of the string.
.* ” Matches everything following.
. ” Matches any character except newline.
| ” The "OR" function, separating alternatives in the pattern match.
() ” Groups items together.
[] ” Looks for characters (character-class matching).
* ” A quantifier that matches 0 or more times, equivalent to writing {0,}.
+ ” A quantifier that matches 1 or more times, equivalent to writing {1,}.
? ” A quantifier that matches 0 or 1 times, equivalent to writing {0,1}. It is also a modifier that forces the minimum number of matches possible. You follow the quantifier with the ? (for example, *?).
{n} ” A quantifier that matches exactly n times. Limited to 65536.
{n,} ” A quantifier that matches at least n times. Limited to 65536.
{n,m} ” A quantifier that matches at least n but not more than m times. Limited to 65536 for both n and m.
I ” Pattern modifier ”Ignores case.
g ” Pattern modifier ”Replaces all possible matches rather than the first match.
U ” Pattern modifier ”Has the same effect as following quantifiers by a ?, but operates on the entire pattern.
x ” Pattern modifier ”Ignores whitespaces except when escaped or inside a character class.
Description: Searches SearchedString for regular expression in Pattern, and places the information in optional MatchesFound array. $MatchesFound[0] will contain the text that matched the full Pattern. Index [1] will contain the text that matches the first parenthetical subpattern. Index [2] will contain the next parenthetical subpattern, and so on. Returns TRUE if a match was found, FALSE otherwise.
See Also: preg_match_all, preg_replace, preg_split
Usage:
<?php $Found = preg_match("/page\s+#(\d+)/i","found on page #12.",$text); if ($Found) echo "Item is found on page ".$text[1]."<P>"; ?>
Description: Searches SearchedString for matches to Pattern and puts the result in MatchesFound in the order specified by optional Order. Returns the number of full pattern matches found, or FALSE otherwise. Order can be one of the following:
PREG_PATTERN_ORDER ” In this order, $MatchesFound[0] is an array of full-pattern matches, $MatchesFound[1] is an array of strings matched by the first parenthetical subpattern. Index [2] is an array of strings matched by the second parenthetical subpattern, and so on. This is the default.
PREG_SET_ORDER ” In this order, $MatchesFound[0] is an array of the first set of matches. Index [1] is an array of the second set of matches, and so on.
See Also: preg_match, preg_replace, preg_split
Usage:
<?php preg_match_all("/<[^>]+>(.*)<\/[^>]+>/U","<b>Name: </b>", $text, PREG_SET_ORDER); echo $text[0][1]."<P>\n"; // will echo "name:" ?>
Description: Searches Searched for matches to Pattern and replaces the matches with Replacement. Every argument can be an array, or all can be strings.
If Pattern contains substrings in parentheses, then Replacement can contain references that govern replacement. The references are of the form \\number, where number is 0 “99. A \\0 will be replaced by the entire contents of matched pattern. A \\1 will be replaced by the text matching the first parenthesized substring. A \\2 will be replaced by the text matching the second parenthesized substring, and so on.
If no matches are found in Searched, the function returns it unchanged. If Pattern and Replacement are arrays, then a value is sequentially taken from each array and used to do search and replace on Searched. If Replacement has fewer values than Pattern, then an empty string is used for the missing entries. If Pattern is an array and Replacement is a string, Replacement is used for every value of Pattern.
See Also: preg_match_all
Usage:
<?php $Pattern = array("/(19|20\d{2})\/(\d{1,2})\/(\d{1,2})/", "/^\s*{(\w+)}\s*=/"); $Replacement = array("\3/\4/\1", "\1 ="); $S =print preg_replace($Pattern, $Replacement, "{Date} = 2000/6/19"); echo $S."<P>\n";// echos Date = 6/19/2000 ?>
Description: Returns an array of substrings of SearchedString split around Pattern matches. If optional Limit is given, then only a maximum Limit substrings are returned.
See Also: explode, split, preg_match, preg_replace
Usage:
<?php $S = "this is a test"; $Words = preg_split("/[\s]+/",$S); ?>
Description: preg_quote puts a backslash in front of every character that is part of a regular expression syntax in String. This allows you to search a regular expression string for a match. The regular expression characters escaped are '. \\ + * ? [ ^ ] $ () { } = ! < > | :'
See Also: AddSlashes
Usage:
<?php $S = "/<[\s,]+>"; $S2 = preg_quote($S); ?>
Description: Returns an array consisting of the elements in SearchedArray that match the Pattern. This function only exists in PHP 4.0 or above.
See Also: preg_match_all
Usage:
<?php $SearchedArray = array(1.0,2,3.0); $Pattern = "|^(\d+)?\.\d+$|"; $SA=print preg_replace($Pattern, $SearchedArray); // $SA contains all floating point numbers in $SearchedArray ?>
Description: Returns an 8-bit binary string that is the result of decoding the quoted printable string. This function is similar to imap_qprint.
See Also: imap_qprint
Usage:
<?php $DecodedString = quoted_printable_decode($EncodedString); ?>
Description: Returns a string with a backslash character in front of every one of the following characters: . \ + * ? [ ^ ] ($)
See Also: addslashes, htmlspecialchars, nl2br, stripslashes
Usage:
<?php $Str = "Hello, Are you jim?"; $QMString = quotemeta($Str);// put a \ before ? ?>
Description: Returns a string with URL percent (%) sequences decoded into characters. The string "hello%20mr%20Bill" is decoded into "hello mr Bill".
See Also: htmlspecialchars, rawurlencode
Usage:
<?php $DecodedString = rawurldecode($EncodedString); ?>
Description: Returns String modified according to RFC1738, where most non-alphanumeric characters are replaced by percent ( % ) escape sequences. This prevents characters from being interpreted as special URL delimiters, or being mangled by email systems.
See Also: rawurldecode
Usage:
<?php $EncodedString = rawurlencode("This is a test (</ &) today"); ?>
Description: Sets the local as specified by Locale, with the categories specified by Category, and returns the current locale or FALSE if locale functionality is not implemented. An invalid category name will return FALSE and generate a warning message. The Category argument must be one of the following:
"LC_COLLATE" ” String comparison (not yet implemented in PHP)
"LC_CTYPE" ” Character classification and conversion in functions like strtoupper()
"LC_MONETARY" ” Not yet implemented in PHP, for the function localconv()
"LC_NUMERIC" ” For decimal separator
"LC_TIME" ” For date and time formatting with strftime()
"LC_ALL" ” For all of the previous combined
If Locale is an empty string, the locale names will be set from the environment variables of the same name, or from 'LANG'. If Locale is "0", the locale setting is not changed, but the current setting is returned.
See Also: strtolower, strtoupper, ucfirst, strftime, gmstrftime,
Usage:
<?php setlocale("LC_TIME","de_DE"); echo "Time in German is ".strftime("%A."))."<P>"; ?>
Description: Calculates the similarity between the string argument First and the string argument Second and returns the similarity in percent in the Percent argument. The function returns the number of matching characters in both strings.
See Also: soundex
Usage:
<?php $NumChars = similar_text("red","read",$P); echo "the similarity in percent between red and read is $P<P>"; ?>
Description: Returns the four-character soundex key of String. Words that are pronounced similarly produce the same soundex key.
See Also: similar_text
Usage:
<?php $S1 = soundex("Knuth"); $S2 = soundex("Kant"); echo "Knuth soundex = $S1, Kant soundex = $S2<P>"; ?>
A new function added in PHP 4.0.1 is similar to similar_text, but much more powerful. It is called levenshtein and calculates the levenshtein distance between two strings. Such applications include fuzzy searches, spell checking, and recommending different search words.
Description: This function returns the Levenshtein-Distance between the two argument strings or -1 if one of the argument strings is longer than the limit of 255 characters.
The Levenshtein distance is defined as the minimal number of characters you have to replace, insert, or delete to transform str1 into str2. The complexity of the algorithm is O(m*n), where n and m are the length of str1 and str2 (rather good when compared to similar_text(), which is O(max(n,m)**3), but still expensive).
See Also: soundex(), similar_text() and metaphone().
Usage:
<?php $Distance = levenshtein("red","read"); echo "The levenshtein distance is $Distance"; ?>
Description: Returns an array of maximum size Limit of strings split apart at Pattern, or FALSE on failure.
See Also: explode, implode
Usage:
<?php $Str= "create an array of first 5 words"; $MyArray = split(" ",$Str,5); ?>
Description: Returns a string formatted by the rules in FormatString. This function works exactly like printf() in all respects (except printf outputs to a browser, and sprintf puts the result in a string). See printf() for the formatting rules.
See Also: printf
Usage:
<?php $TryNumber = 1; $Str = sprintf("This is try number %d<P>\n",$TryNumber); echo $Str; ?>
Description: Returns a regular expression which will match the argument String, regardless of case.
See Also: ereg
Usage:
<?php echo sql_regcase("This "); ?>
Description: This function is an alias for strstr and works identically.
See Also: strstr
Usage:
<?php $Found = strchr("Look for one in this", "one"); ?>
Description: Returns a negative number if String1 is less than String2, a positive number if String1 is greater than String2, and 0 if they are equal. This function does a case-sensitive comparison.
See Also: ereg, substr, strstr
Usage:
<?php if (strcmp("abb","abc")<0) echo "String 1 comes before String 2 in the alphabet."; ?>
Description: counts the number of characters that occur before String2 is found in String1.
See Also: strspn
Usage:
<?php $Num = strcspn("abcdef","def"); echo "There were $Num characters in string 1 before 'def'<P>"; ?>
Description: Strips all HTML and PHP tags from the given string, using the same functionality as is found in fgetss. This function can be used to prevent user hijacking of a Web page that provides bulletin board or message board functionality.
See Also: fgetss
Usage:
<?php $MyStr = '<?php kill("/etc/passwd")?>'; $MyNewStr = strip_tags($MyStr); echo "The clean string is $MyNewStr"; ?>
Description: Returns a string with backslashes removed. For example, \" becomes ", and \\ becomes \.
See Also: addslashes
Usage:
<?php $S = "\'This is a test\'"; A MySQL and PHP from scratch $S1 = stripslashes($S); echo $S1; ?>
Description: Returns the length of argument String
See Also: substr
Usage:
<?php $Len = strlen("This is a test"); ?>
Description: Returns the last occurrence of SearchChar in SearchedString, or FALSE. If SearchChar is a string of more than one character, only the first character is used. If SearchChar is an integer, it is taken as an ordinal and the character it represents is searched for.
See Also: strpos, strrchr , substr, strstr
Usage:
<?php $S ="This is a string"; $Pos = strrpos($S,"s"); echo "The last s in $S is at position $Pos<P>"; ?>
Description: Returns the position of SearchFor in SearchedString, or FALSE if not found. All of SearchFor is used in the check, unlike strrpos. If SearchChar is an integer, it is taken as an ordinal and the character it represents is searched for. The optional Offset argument specifies the character position in the string to start searching.
See Also: strrpos, strrchr, substr, strstr
Usage:
<?php $S ="This is a string"; $Pos = strpos($S,"s a"); echo "'s a' is found at position $Pos<P>"; ?>
Description: Returns the rest of SearchedString starting at the last occurrence of SearchFor, or FALSE if not found. If SearchFor is a string of more than one character, only the first character is used. If SearchChar is an integer, it is taken as an ordinal and the character it represents is searched for.
See Also: substr, strstr, strpos
Usage:
<?php $S ="This is a string"; $Pos = strrchr($S,"s"); echo "$Pos<P>";// echos "string" ?>
Description: Returns a reversed String.
See Also: strrpos, substr
Usage:
<?php $Rev = "madam im adam"; echo "Palindrome of $Rev is ".strrev($Rev)."<P>"; ?>
Description: Returns the length of the first part of String1 that consists entirely of characters in String2.
See Also: strcspn
Usage:
<?php $S ="This is a string"; $Pos = strspn($S,"s a"); echo "length is $Pos<P>"; ?>
Description: Returns the rest of SearchedString from the first occurrence of SearchFor, or FALSE if no match found. If SearchFor is an integer, it is converted as an ordinal and that character is searched for.
See Also: strrchr, substr, ereg
Usage:
<?php $Found = strchr("Look for one in this", "one"); ?>
Description: Returns the next token from String split apart at any one of the delimiters in TokenDelimiters. The first call to strtok requires the String to break apart. The subsequent calls only require the TokenDelimiter. The functions split and explode can also be used, except strtok allows multiple delimiters.
See Also: split, explode
Usage:
<?php $S = "This string containg 5 tokens"; $Token = strtok($S," "); // grab tokens at the space $c=0; while ($Token) { $c++; echo "Token number $c is $Token<P>"; $Token=strtok(" "); } ?>
Description: Returns the argument String converted to lowercase. Only alphabetic characters as defined by the current locale are converted.
See Also: ucfirst, strtoupper
Usage:
<?php $S = "ThIS IS a TesT"; $lc = strtolower($S); echo "'$S' in lower case is '$lc'<P>"; ?>
Description: Returns argument String converted to uppercase. Only alphabetic characters as defined by the current locale are converted.
See Also: strtolower, ucfirst
Usage:
<?php $S = "This is a TesT"; $lc = strtoupper($S); echo "'$S' in uppet case is '$lc'<P>"; ?>
Description: This function replaces all occurrences of SearchFor string with the ReplaceWithString in the SearchedString. This function is much faster than ereg_replace, and can be used on binary strings.
See Also: ereg_replace
Usage:
<?php $S = "The brown dog is not blue"; $S2 = str_replace("brown", "red", $S); echo $S2; ?>
Description: This function translates all occurrences of the From string into the To string in the SearchedString argument. It is similar to str_replace, except that if From and To are of different lengths, the longer string is truncated to the same length as the shorter before the translation.
See Also: str_replace, ereg_replace
Usage:
<?php $S = "The brown dog is not blue"; $S2 = strtr($S,"bro","red"); echo $S2;// you get "The redwn ddg is ndt rlud" ?>
Description: Returns the part of SearchedString specified by StartOffset for the optional Length. If Length is not given, the rest of the string after counting StartOffset characters into the string is returned.
If StartOffset is negative, the starting point is the end of the string counting backwards . For example, a -1 specifies the last character in the string. A -2 specifies the second character from the end of the string, and so on. If StartOffset is incorrect for the size of the string, one character will be returned.
If Length is negative, the returned string will end Length characters from the end of the string. If Length, being too large of a negative value, would cause a negative length string to be returned, one character at StartOffset will be returned.
See Also: strstr
Usage:
<?php $RS = substr("123456", -1); // $RS= "6" $RS = substr("123456", -2); // $RS= "56" $RS = substr("123456", -1); // $RS= "6" $RS = substr("123456",-4, 1); // $RS= "3" $RS = substr("123456", 2); // $RS= "3456" $RS = substr("123456", 2,2); // $RS= "34" ?>
Description: This function returns String with spaces removed from the beginning and end of a string.
See Also: chop, ltrim
Usage:
<?php $S = " this is a test "; $S1 = trim($S);//$S1 == "this is a test" ?>
Description: This function capitalizes the first letter of String, if that letter is alphabetic per the current locale setting.
See Also: strtoupper, strtolower, ucword
Usage:
<?php $S = "this is a test."; $S2 = ucfirst($S); // $S2=="This is a test." ?>
Description: This function capitalizes the first letter of each word in String, if that letter is alphabetic per the current locale setting.
See Also: strtoupper, strtolower, ucfirst
Usage:
<?php $S = "this is a test."; $S2 = ucfirst($S); // $S2=="This is a test." ?>
Description: Returns an associative array containing the various parts of URLString. The components returned are "scheme," "host," "port," "user," "pass," "path," "query," and "fragment."
See Also: urldecode
Usage:
<?php $U = "http://www.mydomain.com:80/start/index.html"; $UArray = parse_url($U); echo "Host is ".$Uarray["host"]; ?>
Description: Decodes the %xx encoding in a string (where xx is a number), and returns the decoded string.
See Also: urlencode
Usage:
<?php $U = "%32"; echo "The value of encoded string '%U' is "; echo htmlspecialchars(urldecode($U))."<P>"; ?>
Description: Returns String modified mostly according to RFC1738, where most non-alphanumeric characters are replaced by percent (%) escape sequences. The difference in the encoding is that spaces are encoded as a plus sign (+). This prevents characters from being interpreted as special URL delimiters, or being mangled by email systems. This function can be used to encode a URL string query to pass variables to another Web page.
See Also: rawurlencode, urldecode
Usage:
<?php // encode a url, allowing the user to click on it echo '<A HREF=webpageurl?Var1=',urlencode($SomeData),'>'; ?>
Description: Encodes binary string DataString using base64 encoding. Base64 encoding allows binary data to be transported through email systems that strip the most significant bits from characters.
See Also: base64_decode, chunk_split
Usage:
<?php $EncodedString = base64_encode($BinaryString); ?>
Description: Decodes EncodedDataString and returns a binary data string.
See Also: base64 _ encode
Usage:
<?php $DecodedDataString = base64_decode($EncodedString); ?>
The following functions operate on variables. You can query or change the type of a variable. You can also test for the existence of variables, or destroy them so they don't exist within PHP.
Description: Returns the PHP variable type for Variable. The possible returns are as follows:
integer
double
string
array
object
unknown type
See Also: setttype
Usage:
<?php $V = 32; $T = gettype($V); // $T == "integer" ?>
Description: Returns the floating point value of Variable. Variable can be any scalar type, and cannot be an array or an object.
See Also: intval, strval, settype, getttype
Usage:
<?php $V = 31; $DV = doubleval($V); // $DV == 31.00 ?>
Description: Returns the integer value of Variable using the optional Base as the numeric base for the conversion. If Base is not provide, base 10 is assumed. Variable can be any scalar type, and cannot be an array or an object.
See Also: doubleval, strval, settype, gettype
Usage:
<?php $V = 32.34; $IV = intval($V,10); // $IV == 32 ?>
Description: Returns FALSE if Variable is set, and is not empty and non-zero value, TRUE otherwise.
See Also: isset, unset
Usage:
<?php $S = empty($T); // if $T is not set or is zero, it is empty if ($S) echo "$T is empty"; ?>
Description: Returns TRUE if Variable is an array, FALSE otherwise.
See Also: is_double, is_float, is_int, is_integer, is_real, is_string, is_long, is_object
Usage:
<?php if (is_array($ArrayVariable)) echo "$ArrayVariable is an array<P>"; ?>
Description: Returns TRUE if Variable is a double, FALSE otherwise. is_float
and is_real are aliases for this function.
See Also: is_array, is_float, is_int, is_integer, is_real, is_string, is_long, is_object
Usage:
<?php $ID = is_double($DoubleVar); if ($ID) echo "$DoubleVar is a double"; ?>
Description: This function is an alias for is_double. It works exactly the same.
See Also: is_double, is_real, is_int, is_integer, is_string, is_object, is_array, is_long
Usage:
<?php $ID = is_float($DoubleVar); if ($ID) echo "$DoubleVar is a float"; ?>
Description: This function is an alias for is_long. It works exactly the same as is_long.
See Also: is_double, is_real, is_int, is_integer, is_string, is_object, is_array, is_long
Usage:
<?php $I = is_int($LongVar); if ($I) echo "$LongVar is an int"; ?>
Description: This function is an alias for is_long. It works exactly the same as is_long.
See Also: is_double, is_real, is_int, is_integer, is_string, is_object, is_array, is_long
Usage:
<?php $I = is_integer($LongVar); if ($I) echo "$LongVar is an integer"; ?>
Description: Returns TRUE if Variable is a long integer, FALSE otherwise. is_int and is integer are aliases for is_long and can be used in its place.
See Also: is_double, is_float, is_string, is_array, is_object
Usage:
<?php if (is_long($LongVar)) echo "$LongVar is a Long integer"; ?>
Description: Returns TRUE if Variable is an object, FALSE otherwise.
See Also: is_double, is_float, is_string, is_array, is_long
Usage:
<?php if (is_long($ObjVar)) echo "$ObjVar is an object"; ?>
int is_real(mixed Variable)
Description: Returns TRUE if Variable is a float, FALSE otherwise. This function is an alias for is_double.
See Also: is_double, is_float, is_string, is_array, is_long, is_object
Usage:
<?php $ID = is_real($DoubleVar); if ($ID) echo "$DoubleVar is a real number (float)"; ?>
Description: Returns TRUE if Variable is a string, FALSE otherwise.
See Also: is_double, is_float, is_array, is_long, is_object
Usage:
<?php if (is_string($StringVar)) echo "$StringVar is a string"; ?>
Description: Returns TRUE if Variable exists, FALSE otherwise. Variables don't exist until they have been assigned a value or had a value put into them by a function. If a variable has been unset(), then isset() will return FALSE.
See Also: empty, unset
Usage:
<?php $a = 1; if (isset($a)) echo "$a exists"; unset($a); if (!isset($a)) echo "$a does not exist now"; if (!isset($b)) echo "$b does not exist"; ?>
Description: Sets Variable to Type. Returns TRUE if successful, FALSE if failure. The Type string can be one of the following:
array
double
integer
object
string
See Also: gettype
Usage:
<?php $a = 3; settype($a,"string"); echo "$a is now a string"; ?>
Description: Returns the string value of Variable, which can be any scalar type. Variable cannot be an array or an object.
See Also: doubleval, intval, setttype
Usage:
<?php $a = 33; $S = strval($a); echo "$a is now $S<P>"; ?>
Description: Removes Variable from PHP and returns TRUE. The variable no longer exists.
See Also: settype, isset
Usage:
<?php $a = 3; unset($a); // a no longer exists ?>
Description: This function returns structured information about an expression that includes its type and value. Arrays are explored recursively with values indented to show structure.
See Also: print_r()
Usage:
<pre> <?php $a = array (1, 2, array ("a", "b", "c")); var_dump ($a); ?> </pre>
Using the SWF module from reality.sgi.com/grafica/flash/, PHP has extensive Shockwave Flash Support. Upon compiling PHP (after libswf has been installed), all you need to do is configure --with-swf[=DIR], where >DIR is a location containing the directories include and lib. The include directory must contain the swf.h and libswf.a files.
NOTE
Many functions are available through PHP to the libswf module. Documenting them all would probably be pointless. Here is a quick listing of the important functions:
swf_openfile ” Opens a new Shockwave Flash file.
swf_closefile ” Closes the current Shockwave Flash file.
swf_labelframe ” Labels the current frame.
swf_showframe ” Displays the current frame.
swf_setframe ” Switches to a specified frame.
swf_getframe ” Gets the frame number of the current frame.
swf_addcolor ” Sets the global add color to the rgba value specified.
swf_placeobject ” Place an object onto the screen.
swf_modifyobject ” Modify an object.
swf_removeobject ” Remove an object.
swf_nextid ” Return the next free object ID.
swf_defineline ” Defines a line.
swf_definerect ” Defines a rectangle.
swf_definepoly ” Defines a polygon.
swf_startshape ” Starts a complex shape.
swf_shapefillsolid ” Sets the current fill style to the specified color.
swf_shapemoveto ” Moves the current position.
swf_shapelineto ” Draws a line.
swf_shapecurveto ” Draws a quadratic B&err#350;zier curve between two points.
swf_shapecurveto3 ” Draws a cubic B&err#350;zier curve.
swf_shapearc ” Draws a circular arc.
swf_endshape ” Completes the definition of the current shape.
swf_definefont ” Defines a font.
swf_setfont ” Change the current font.
swf_fontsize ” Changes the font size.
swf_definetext ” Defines a text string.
swf_textwidth ” Gets the width of a string.
swf_pushmatrix ” Pushes the current transformation matrix back onto the stack.
swf_popmatrix ” Restores a previous transformation matrix.
swf_scale ” Scale the current transformation.
swf_translate ” Translates the current transformations.
swf_rotate ” Rotates the current transformation.
only for RuBoard - do not distribute or recompile |