Wednesday 13 November 2013



Java supports three types of comments. The first two are the // and the /* */. The third type is called a documentation comment. It begins with the character sequence /** and it ends with */.
Documentation comments allow you to embed information about your program into the program itself. You can then use the javadoc utility program to extract the information and put it into an HTML file.
Documentation comments make it convenient to document your programs.

The javadoc Tags:

The javadoc utility recognizes the following tags:
TagDescriptionExample
@authorIdentifies the author of a class.@author description
@deprecatedSpecifies that a class or member is deprecated.@deprecated description
{@docRoot}Specifies the path to the root directory of the current documentationDirectory Path
@exceptionIdentifies an exception thrown by a method.@exception exception-name explanation
{@inheritDoc}Inherits a comment from the immediate superclass.Inherits a comment from the immediate surperclass.
{@link}Inserts an in-line link to another topic.{@link name text}
{@linkplain}Inserts an in-line link to another topic, but the link is displayed in a plain-text font.Inserts an in-line link to another topic.
@paramDocuments a method's parameter.@param parameter-name explanation
@returnDocuments a method's return value.@return explanation
@seeSpecifies a link to another topic.@see anchor
@serialDocuments a default serializable field.@serial description
@serialDataDocuments the data written by the writeObject( ) or writeExternal( ) methods@serialData description
@serialFieldDocuments an ObjectStreamField component.@serialField name type description
@sinceStates the release when a specific change was introduced.@since release
@throwsSame as @exception.The @throws tag has the same meaning as the @exception tag.
{@value}Displays the value of a constant, which must be a static field.Displays the value of a constant, which must be a static field.
@versionSpecifies the version of a class.@version info

Documentation Comment:

After the beginning /**, the first line or lines become the main description of your class, variable, or method.
After that, you can include one or more of the various @ tags. Each @ tag must start at the beginning of a new line or follow an asterisk (*) that is at the start of a line.
Multiple tags of the same type should be grouped together. For example, if you have three @see tags, put them one after the other.
Here is an example of a documentation comment for a class:
/**
* This class draws a bar chart.
* @author Zara Ali
* @version 1.2
*/

What javadoc Outputs?

The javadoc program takes as input your Java program's source file and outputs several HTML files that contain the program's documentation.
Information about each class will be in its own HTML file. Java utility javadoc will also output an index and a hierarchy tree. Other HTML files can be generated.
Since different implementations of javadoc may work differently, you will need to check the instructions that accompany your Java development system for details specific to your version.

Example:

Following is a sample program that uses documentation comments. Notice the way each comment immediately precedes the item that it describes.
After being processed by javadoc, the documentation about the SquareNum class will be found in SquareNum.html.
import java.io.*;

/**
* This class demonstrates documentation comments.
* @author Ayan Amhed 
* @version 1.2
*/
public class SquareNum {
   /**
   * This method returns the square of num.
   * This is a multiline description. You can use
   * as many lines as you like.
   * @param num The value to be squared.
   * @return num squared.
   */
   public double square(double num) {
      return num * num;
   }
   /**
   * This method inputs a number from the user.
   * @return The value input as a double.
   * @exception IOException On input error.
   * @see IOException
   */
   public double getNumber() throws IOException {
      InputStreamReader isr = new InputStreamReader(System.in);
      BufferedReader inData = new BufferedReader(isr);
      String str;
      str = inData.readLine();
      return (new Double(str)).doubleValue();
   }
   /**
   * This method demonstrates square().
   * @param args Unused.
   * @return Nothing.
   * @exception IOException On input error.
   * @see IOException
   */
   public static void main(String args[]) throws IOException
   {
      SquareNum ob = new SquareNum();
      double val;
      System.out.println("Enter value to be squared: ");
      val = ob.getNumber();
      val = ob.square(val);
      System.out.println("Squared value is " + val);
   }
}
Now, process above SquareNum.java file using javadoc utility as follows:
$ javadoc SquareNum.java
Loading source file SquareNum.java...
Constructing Javadoc information...
Standard Doclet version 1.5.0_13
Building tree for all the packages and classes...
Generating SquareNum.html...
SquareNum.java:39: warning - @return tag cannot be used\
                      in method with void return type.
Generating package-frame.html...
Generating package-summary.html...
Generating package-tree.html...
Generating constant-values.html...
Building index for all the packages and classes...
Generating overview-tree.html...
Generating index-all.html...
Generating deprecated-list.html...
Building index for all classes...
Generating allclasses-frame.html...
Generating allclasses-noframe.html...
Generating index.html...
Generating help-doc.html...
Generating stylesheet.css...
1 warning
$

AJAX Poll

The following example will demonstrate a poll where the result is shown without reloading.


Example Explained - The HTML Page

When a user choose an option above, a function called "getVote()" is executed. The function is triggered by the "onclick" event:
<html>
<head>
<script>
function getVote(int)
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("poll").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","poll_vote.php?vote="+int,true);
xmlhttp.send();
}
</script>
</head>
<body>

<div id="poll">
<h3>Do you like PHP and AJAX so far?</h3>
<form>
Yes:
<input type="radio" name="vote" value="0" onclick="getVote(this.value)">
<br>No:
<input type="radio" name="vote" value="1" onclick="getVote(this.value)">
</form>
</div>

</body>
</html>
The getVote() function does the following:
  • Create an XMLHttpRequest object
  • Create the function to be executed when the server response is ready
  • Send the request off to a file on the server
  • Notice that a parameter (vote) is added to the URL (with the value of the yes or no option)

The PHP File

The page on the server called by the JavaScript above is a PHP file called "poll_vote.php":
<?php
$vote = $_REQUEST['vote'];

//get content of textfile
$filename = "poll_result.txt";
$content = file($filename);

//put content in array
$array = explode("||", $content[0]);
$yes = $array[0];
$no = $array[1];

if ($vote == 0)
  {
  $yes = $yes + 1;
  }
if ($vote == 1)
  {
  $no = $no + 1;
  }

//insert votes to txt file
$insertvote = $yes."||".$no;
$fp = fopen($filename,"w");
fputs($fp,$insertvote);
fclose($fp);
?>

<h2>Result:</h2>
<table>
<tr>
<td>Yes:</td>
<td>
<img src="poll.gif"
width='<?php echo(100*round($yes/($no+$yes),2)); ?>'
height='20'>
<?php echo(100*round($yes/($no+$yes),2)); ?>%
</td>
</tr>
<tr>
<td>No:</td>
<td>
<img src="poll.gif"
width='<?php echo(100*round($no/($no+$yes),2)); ?>'
height='20'>
<?php echo(100*round($no/($no+$yes),2)); ?>%
</td>
</tr>
</table>
The value is sent from the JavaScript, and the following happens:
  1. Get the content of the "poll_result.txt" file
  2. Put the content of the file in variables and add one to the selected variable
  3. Write the result to the "poll_result.txt" file
  4. Output a graphical representation of the poll result

The Text File

The text file (poll_result.txt) is where we store the data from the poll.
It is stored like this:
0||0
The first number represents the "Yes" votes, the second number represents the "No" votes.
Note: Remember to allow your web server to edit the text file. Do NOT give everyone access, just the web server (PHP).
The PHP array functions are part of the PHP core. No installation is required to use these functions.
Function Description
array() Creates an array
array_change_key_case() Changes all keys in an array to lowercase or uppercase
array_chunk() Splits an array into chunks of arrays
array_column() Returns the values from a single column in the input array
array_combine() Creates an array by using the elements from one "keys" array and one "values" array
array_count_values() Counts all the values of an array
array_diff() Compare arrays, and returns the differences (compare values only)
array_diff_assoc() Compare arrays, and returns the differences (compare keys and values)
array_diff_key() Compare arrays, and returns the differences (compare keys only)
array_diff_uassoc() Compare arrays, and returns the differences (compare keys and values, using a user-defined key comparison function)
array_diff_ukey() Compare arrays, and returns the differences (compare keys only, using a user-defined key comparison function)
array_fill() Fills an array with values
array_fill_keys() Fills an array with values, specifying keys
array_filter() Filters the values of an array using a callback function
array_flip() Flips/Exchanges all keys with their associated values in an array
array_intersect() Compare arrays, and returns the matches (compare values only)
array_intersect_assoc() Compare arrays and returns the matches (compare keys and values)
array_intersect_key() Compare arrays, and returns the matches (compare keys only)
array_intersect_uassoc() Compare arrays, and returns the matches (compare keys and values, using a user-defined key comparison function)
array_intersect_ukey() Compare arrays, and returns the matches (compare keys only, using a user-defined key comparison function)
array_key_exists() Checks if the specified key exists in the array
array_keys() Returns all the keys of an array
array_map() Sends each value of an array to a user-made function, which returns new values
array_merge() Merges one or more arrays into one array
array_merge_recursive() Merges one or more arrays into one array recursively
array_multisort() Sorts multiple or multi-dimensional arrays
array_pad() Inserts a specified number of items, with a specified value, to an array
array_pop() Deletes the last element of an array
array_product() Calculates the product of the values in an array
array_push() Inserts one or more elements to the end of an array
array_rand() Returns one or more random keys from an array
array_reduce() Returns an array as a string, using a user-defined function
array_replace() Replaces the values of the first array with the values from following arrays
array_replace_recursive() Replaces the values of the first array with the values from following arrays recursively
array_reverse() Returns an array in the reverse order
array_search() Searches an array for a given value and returns the key
array_shift() Removes the first element from an array, and returns the value of the removed element
array_slice() Returns selected parts of an array
array_splice() Removes and replaces specified elements of an array
array_sum() Returns the sum of the values in an array
array_udiff() Compare arrays, and returns the differences (compare values only, using a user-defined key comparison function)
array_udiff_assoc() Compare arrays, and returns the differences (compare keys and values, using a built-in function to compare the keys and a user-defined function to compare the values)
array_udiff_uassoc() Compare arrays, and returns the differences (compare keys and values, using two user-defined key comparison functions)
array_uintersect() Compare arrays, and returns the matches (compare values only, using a user-defined key comparison function)
array_uintersect_assoc() Compare arrays, and returns the matches (compare keys and values, using a built-in function to compare the keys and a user-defined function to compare the values)
array_uintersect_uassoc() Compare arrays, and returns the matches (compare keys and values, using two user-defined key comparison functions)
array_unique() Removes duplicate values from an array
array_unshift() Adds one or more elements to the beginning of an array
array_values() Returns all the values of an array
array_walk() Applies a user function to every member of an array
array_walk_recursive() Applies a user function recursively to every member of an array
arsort() Sorts an associative array in descending order, according to the value
asort() Sorts an associative array in ascending order, according to the value
compact() Create array containing variables and their values
count() Returns the number of elements in an array
current() Returns the current element in an array
each() Returns the current key and value pair from an array
end() Sets the internal pointer of an array to its last element
extract() Imports variables into the current symbol table from an array
in_array() Checks if a specified value exists in an array
key() Fetches a key from an array
krsort() Sorts an associative array in descending order, according to the key
ksort() Sorts an associative array in ascending order, according to the key
list() Assigns variables as if they were an array
natcasesort() Sorts an array using a case insensitive "natural order" algorithm
natsort() Sorts an array using a "natural order" algorithm
next() Advance the internal array pointer of an array
pos() Alias of current()
prev() Rewinds the internal array pointer
range() Creates an array containing a range of elements
reset() Sets the internal pointer of an array to its first element
rsort() Sorts an indexed array in descending order
shuffle() Shuffles an array
sizeof() Alias of count()
sort() Sorts an indexed array in ascending order
uasort() Sorts an array by values using a user-defined comparison function
uksort() Sorts an array by keys using a user-defined comparison function
usort() Sorts an array using a user-defined comparison function
The calendar extension contains functions that simplifies converting between different calendar formats.
It is based on the Julian Day Count, which is a count of days starting from January 1st, 4713 B.C.
Note: To convert between calendar formats, you must first convert to Julian Day Count, then to the calendar of your choice.
Note: The Julian Day Count is not the same as the Julian Calendar!

Installation

For these functions to work, you have to compile PHP with --enable-calendar.
The Windows version of PHP has built-in support for this extension.

PHP 5 Calendar Functions

Function Description
cal_days_in_month() Returns the number of days in a month for a specified year and calendar
cal_from_jd() Converts a Julian Day Count into a date of a specified calendar
cal_info() Returns information about a specified calendar
cal_to_jd() Converts a date in a specified calendar to Julian Day Count
easter_date() Returns the Unix timestamp for midnight on Easter of a specified year
easter_days() Returns the number of days after March 21, that the Easter Day is in a specified year
frenchtojd() Converts a French Republican date to a Julian Day Count
gregoriantojd() Converts a Gregorian date to a Julian Day Count
jddayofweek() Returns the day of the week
jdmonthname() Returns a month name
jdtofrench() Converts a Julian Day Count to a French Republican date
jdtogregorian() Converts a Julian Day Count to a Gregorian date
jdtojewish() Converts a Julian Day Count to a Jewish date
jdtojulian() Converts a Julian Day Count to a Julian date
jdtounix() Converts Julian Day Count to Unix timestamp
jewishtojd() Converts a Jewish date to a Julian Day Count
juliantojd() Converts a Julian date to a Julian Day Count
unixtojd() Converts Unix timestamp to Julian Day Count

PHP 5 Predefined Calendar Constants

Constant Type PHP Version
CAL_GREGORIAN Integer PHP 4
CAL_JULIAN Integer PHP 4
CAL_JEWISH Integer PHP 4
CAL_FRENCH Integer PHP 4
CAL_NUM_CALS Integer PHP 4
CAL_DOW_DAYNO Integer PHP 4
CAL_DOW_SHORT Integer PHP 4
CAL_DOW_LONG Integer PHP 4
CAL_MONTH_GREGORIAN_SHORT Integer PHP 4
CAL_MONTH_GREGORIAN_LONG Integer PHP 4
CAL_MONTH_JULIAN_SHORT Integer PHP 4
CAL_MONTH_JULIAN_LONG Integer PHP 4
CAL_MONTH_JEWISH Integer PHP 4
CAL_MONTH_FRENCH Integer PHP 4
CAL_EASTER_DEFAULT Integer PHP 4.3
CAL_EASTER_ROMAN Integer PHP 4.3
CAL_EASTER_ALWAYS_GREGORIAN Integer PHP 4.3
CAL_EASTER_ALWAYS_JULIAN Integer PHP 4.3
CAL_JEWISH_ADD_ALAFIM_GERESH Integer PHP 5.0
CAL_JEWISH_ADD_ALAFIM Integer PHP 5.0
CAL_JEWISH_ADD_GERESHAYIM Integer PHP 5.0
The date/time functions allow you to get the date and time from the server where your PHP script runs. You can then use the date/time functions to format the date and time in several ways.
Note: These functions depend on the locale settings of your server. Remember to take daylight saving time and leap years into consideration when working with these functions.

Installation

The PHP date/time functions are part of the PHP core. No installation is required to use these functions.

Runtime Configuration

The behavior of these functions is affected by settings in php.ini:
Name Description Default PHP Version
date.timezone The default timezone (used by all date/time functions) "" PHP 5.1
date.default_latitude The default latitude (used by date_sunrise() and date_sunset())  "31.7667" PHP 5.0
date.default_longitude The default longitude (used by date_sunrise() and date_sunset()) "35.2333" PHP 5.0
date.sunrise_zenith The default sunrise zenith (used by date_sunrise() and date_sunset()) "90.83" PHP 5.0
date.sunset_zenith The default sunset zenith (used by date_sunrise() and date_sunset()) "90.83" PHP 5.0


PHP 5 Date/Time Functions

Function Description
checkdate() Validates a Gregorian date
date_add() Adds days, months, years, hours, minutes, and seconds to a date
date_create_from_format() Returns a new DateTime object formatted according to a specified format
date_create() Returns a new DateTime object
date_date_set() Sets a new date
date_default_timezone_get() Returns the default timezone used by all date/time functions
date_default_timezone_set() Sets the default timezone used by all date/time functions
date_diff() Returns the difference between two dates
date_format() Returns a date formatted according to a specified format
date_get_last_errors() Returns the warnings/errors found in a date string
date_interval_create_from_date_string() Sets up a DateInterval from the relative parts of the string
date_interval_format() Formats the interval
date_isodate_set() Sets the ISO date
date_modify() Modifies the timestamp
date_offset_get() Returns the timezone offset
date_parse_from_format() Returns an associative array with detailed info about a specified date, according to a specified format
date_parse() Returns an associative array with detailed info about a specified date
date_sub() Subtracts days, months, years, hours, minutes, and seconds from a date
date_sun_info() Returns an array containing info about sunset/sunrise and twilight begin/end, for a specified day and location
date_sunrise() Returns the sunrise time for a specified day and location
date_sunset() Returns the sunset time for a specified day and location
date_time_set() Sets the time
date_timestamp_get() Returns the Unix timestamp
date_timestamp_set() Sets the date and time based on a Unix timestamp
date_timezone_get() Returns the time zone of the given DateTime object
date_timezone_set() Sets the time zone for the DateTime object
date() Formats a local date and time
getdate() Returns date/time information of a timestamp or the current local date/time
gettimeofday() Returns the current time
gmdate() Formats a GMT/UTC date and time
gmmktime() Returns the Unix timestamp for a GMT date
gmstrftime() Formats a GMT/UTC date and time according to locale settings
idate() Formats a local time/date as integer
localtime() Returns the local time
microtime() Returns the current Unix timestamp with microseconds
mktime() Returns the Unix timestamp for a date
strftime() Formats a local time and/or date according to locale settings
strptime() Parses a time/date generated with strftime()
strtotime() Parses an English textual datetime into a Unix timestamp
time() Returns the current time as a Unix timestamp
timezone_abbreviations_list() Returns an associative array containing dst, offset, and the timezone name
timezone_identifiers_list() Returns an indexed array with all timezone identifiers
timezone_location_get() Returns location information for a specified timezone
timezone_name_from_ abbr() Returns the timezone name from abbreviation
timezone_name_get() Returns the name of the timezone
timezone_offset_get() Returns the timezone offset from GMT
timezone_open() Creates new DateTimeZone object
timezone_transitions_get() Returns all transitions for the timezone
timezone_version_get() Returns the version of the timezone db


PHP 5 Predefined Date/Time Constants

Constant Description
DATE_ATOM Atom (example: 2005-08-15T16:13:03+0000)
DATE_COOKIE HTTP Cookies (example: Sun, 14 Aug 2005 16:13:03 UTC)
DATE_ISO8601 ISO-8601 (example: 2005-08-14T16:13:03+0000)
DATE_RFC822 RFC 822 (example: Sun, 14 Aug 2005 16:13:03 UTC)
DATE_RFC850 RFC 850 (example: Sunday, 14-Aug-05 16:13:03 UTC)
DATE_RFC1036 RFC 1036 (example: Sunday, 14-Aug-05 16:13:03 UTC)
DATE_RFC1123 RFC 1123 (example: Sun, 14 Aug 2005 16:13:03 UTC)
DATE_RFC2822 RFC 2822 (Sun, 14 Aug 2005 16:13:03 +0000)
DATE_RSS RSS (Sun, 14 Aug 2005 16:13:03 UTC)
DATE_W3C World Wide Web Consortium (example: 2005-08-14T16:13:03+0000)
The directory functions allow you to retrieve information about directories and their contents.

Installation

The PHP directory functions are part of the PHP core. No installation is required to use these functions.

PHP 5 Directory Functions

Function Description
chdir() Changes the current directory
chroot() Changes the root directory
closedir() Closes a directory handle
dir() Returns an instance of the Directory class
getcwd() Returns the current working directory
opendir() Opens a directory handle
readdir() Returns an entry from a directory handle
rewinddir() Resets a directory handle
scandir() Returns an array of files and directories of a specified directory
The error and logging functions allows error handling and logging.
The error functions allow users to define error handling rules, and modify the way the errors can be logged.
The logging functions allow users to log applications and send log messages to email, system logs or other machines.

Installation

The error and logging functions are part of the PHP core. There is no installation needed to use these functions.

PHP Error and Logging Functions

PHP: indicates the earliest version of PHP that supports the function.
Function Description PHP
debug_backtrace() Generates a backtrace 4
debug_print_backtrace() Prints a backtrace 5
error_get_last() Gets the last error occurred 5
error_log() Sends an error to the server error-log, to a file or to a remote destination 4
error_reporting() Specifies which errors are reported 4
restore_error_handler() Restores the previous error handler 4
restore_exception_handler() Restores the previous exception handler 5
set_error_handler() Sets a user-defined function to handle errors 4
set_exception_handler() Sets a user-defined function to handle exceptions 5
trigger_error() Creates a user-defined error message 4
user_error() Alias of trigger_error() 4


PHP Error and Logging Constants

PHP: indicates the earliest version of PHP that supports the constant.
Value Constant Description PHP
1 E_ERROR Fatal run-time errors. Errors that cannot be recovered from. Execution of the script is halted  
2 E_WARNING Non-fatal run-time errors. Execution of the script is not halted  
4 E_PARSE Compile-time parse errors. Parse errors should only be generated by the parser  
8 E_NOTICE Run-time notices. The script found something that might be an error, but could also happen when running a script normally  
16 E_CORE_ERROR Fatal errors at PHP startup. This is like an E_ERROR in the PHP core 4
32 E_CORE_WARNING Non-fatal errors at PHP startup. This is like an E_WARNING in the PHP core 4
64 E_COMPILE_ERROR Fatal compile-time errors. This is like an E_ERROR generated by the Zend Scripting Engine 4
128 E_COMPILE_WARNING Non-fatal compile-time errors. This is like an E_WARNING generated by the Zend Scripting Engine 4
256 E_USER_ERROR Fatal user-generated error. This is like an E_ERROR set by the programmer using the PHP function trigger_error() 4
512 E_USER_WARNING Non-fatal user-generated warning. This is like an E_WARNING set by the programmer using the PHP function trigger_error() 4
1024 E_USER_NOTICE User-generated notice. This is like an E_NOTICE set by the programmer using the PHP function trigger_error() 4
2048 E_STRICT Run-time notices. PHP suggest changes to your code to help interoperability and compatibility of the code 5
4096 E_RECOVERABLE_ERROR Catchable fatal error. This is like an E_ERROR but can be caught by a user defined handle (see also set_error_handler()) 5
6143  E_ALL All errors and warnings, except of level E_STRICT 5

The filesystem functions allow you to access and manipulate the filesystem.

Installation

The filesystem functions are part of the PHP core. There is no installation needed to use these functions.

Runtime Configuration

The behavior of the filesystem functions is affected by settings in php.ini.
Filesystem configuration options:
Name Default Description Changeable
allow_url_fopen "1" Allows fopen()-type functions to work with URLs (available since PHP 4.0.4) PHP_INI_SYSTEM
user_agent NULL Defines the user agent for PHP to send (available since PHP 4.3) PHP_INI_ALL
default_socket_timeout "60" Sets the default timeout, in seconds, for socket based streams (available since PHP 4.3) PHP_INI_ALL
from "" Defines the anonymous FTP password (your email address) PHP_INI_ALL
auto_detect_line_endings "0" When set to "1", PHP will examine the data read by fgets() and file() to see if it is using Unix, MS-Dos or Mac line-ending characters (available since PHP 4.3) PHP_INI_ALL


Unix / Windows Compatibility

When specifying a path on Unix platforms, the forward slash (/) is used as directory separator. However, on Windows platforms, both forward slash (/) and backslash (\) can be used.

PHP 5 Filesystem Functions

Function Description
basename() Returns the filename component of a path
chgrp() Changes the file group
chmod() Changes the file mode
chown() Changes the file owner
clearstatcache() Clears the file status cache
copy() Copies a file
delete() See unlink() or unset()
dirname() Returns the directory name component of a path
disk_free_space() Returns the free space of a directory
disk_total_space() Returns the total size of a directory
diskfreespace() Alias of disk_free_space()
fclose() Closes an open file
feof() Tests for end-of-file on an open file
fflush() Flushes buffered output to an open file
fgetc() Returns a character from an open file
fgetcsv() Parses a line from an open file, checking for CSV fields
fgets() Returns a line from an open file
fgetss() Returns a line, with HTML and PHP tags removed, from an open file
file() Reads a file into an array
file_exists() Checks whether or not a file or directory exists
file_get_contents() Reads a file into a string
file_put_contents Writes a string to a file
fileatime() Returns the last access time of a file
filectime() Returns the last change time of a file
filegroup() Returns the group ID of a file
fileinode() Returns the inode number of a file
filemtime() Returns the last modification time of a file
fileowner() Returns the user ID (owner) of a file
fileperms() Returns the permissions of a file
filesize() Returns the file size
filetype() Returns the file type
flock() Locks or releases a file
fnmatch() Matches a filename or string against a specified pattern
fopen() Opens a file or URL
fpassthru() Reads from an open file, until EOF, and writes the result to the output buffer
fputcsv() Formats a line as CSV and writes it to an open file
fputs() Alias of fwrite()
fread() Reads from an open file
fscanf() Parses input from an open file according to a specified format
fseek() Seeks in an open file
fstat() Returns information about an open file
ftell() Returns the current position in an open file
ftruncate() Truncates an open file to a specified length
fwrite() Writes to an open file
glob() Returns an array of filenames / directories matching a specified pattern
is_dir() Checks whether a file is a directory
is_executable() Checks whether a file is executable
is_file() Checks whether a file is a regular file
is_link() Checks whether a file is a link
is_readable() Checks whether a file is readable
is_uploaded_file() Checks whether a file was uploaded via HTTP POST
is_writable() Checks whether a file is writeable
is_writeable() Alias of is_writable()
lchgrp() Changes group ownership of symlink
lchown() Changes user ownership of symlink
link() Creates a hard link
linkinfo() Returns information about a hard link
lstat() Returns information about a file or symbolic link
mkdir() Creates a directory
move_uploaded_file() Moves an uploaded file to a new location
parse_ini_file() Parses a configuration file
parse_ini_string() Parses a configuration string
pathinfo() Returns information about a file path
pclose() Closes a pipe opened by popen()
popen() Opens a pipe
readfile() Reads a file and writes it to the output buffer
readlink() Returns the target of a symbolic link
realpath() Returns the absolute pathname
realpath_cache_get() Returns realpath cache entries
realpath_cache_size() Returns realpath cache size
rename() Renames a file or directory
rewind() Rewinds a file pointer
rmdir() Removes an empty directory
set_file_buffer() Sets the buffer size of an open file
stat() Returns information about a file
symlink() Creates a symbolic link
tempnam() Creates a unique temporary file
tmpfile() Creates a unique temporary file
touch() Sets access and modification time of a file
umask() Changes file permissions for files
unlink() Deletes a file
This PHP filters is used to validate and filter data coming from insecure sources, like user input.

Installation

The filter functions are part of the PHP core. There is no installation needed to use these functions.

PHP Filter Functions

PHP: indicates the earliest version of PHP that supports the function.
Function Description PHP
filter_has_var() Checks if a variable of a specified input type exist 5
filter_id() Returns the ID number of a specified filter 5
filter_input() Get input from outside the script and filter it 5
filter_input_array() Get multiple inputs from outside the script and filters them 5
filter_list() Returns an array of all supported filters 5
filter_var_array() Get multiple variables and filter them 5
filter_var() Get a variable and filter it 5


PHP Filters

ID Name Description
FILTER_CALLBACK Call a user-defined function to filter data
FILTER_SANITIZE_STRING Strip tags, optionally strip or encode special characters
FILTER_SANITIZE_STRIPPED Alias of "string" filter
FILTER_SANITIZE_ENCODED URL-encode string, optionally strip or encode special characters
FILTER_SANITIZE_SPECIAL_CHARS HTML-escape '"<>& and characters with ASCII value less than 32
FILTER_SANITIZE_EMAIL Remove all characters, except letters, digits and !#$%&'*+-/=?^_`{|}~@.[]
FILTER_SANITIZE_URL Remove all characters, except letters, digits and $-_.+!*'(),{}|\\^~[]`<>#%";/?:@&=
FILTER_SANITIZE_NUMBER_INT Remove all characters, except digits and +-
FILTER_SANITIZE_NUMBER_FLOAT Remove all characters, except digits, +- and optionally .,eE
FILTER_SANITIZE_MAGIC_QUOTES Apply addslashes()
FILTER_UNSAFE_RAW Do nothing, optionally strip or encode special characters
FILTER_VALIDATE_INT Validate value as integer, optionally from the specified range
FILTER_VALIDATE_BOOLEAN Return TRUE for "1", "true", "on" and "yes", FALSE for "0", "false", "off", "no", and "", NULL otherwise
FILTER_VALIDATE_FLOAT Validate value as float
FILTER_VALIDATE_REGEXP Validate value against regexp, a Perl-compatible regular expression
FILTER_VALIDATE_URL Validate value as URL, optionally with required components
FILTER_VALIDATE_EMAIL Validate value as e-mail
FILTER_VALIDATE_IP Validate value as IP address, optionally only IPv4 or IPv6 or not from private or reserved ranges
The FTP functions give client access to file servers through the File Transfer Protocol (FTP).
The FTP functions are used to open, login and close connections, as well as upload, download, rename, delete, and get information on files from file servers. Not all of the FTP functions will work with every server or return the same results. The FTP functions became available with PHP 3.
These functions are meant for detailed access to an FTP server. If you only wish to read from or write to a file on an FTP server, consider using the ftp:// wrapper with the Filesystem functions.

Installation

The windows version of PHP has built-in support for the FTP extension. So, the FTP functions will work automatically.
However, if you are running the Linux version of PHP, you will have to compile PHP with --enable-ftp (PHP 4+) or --with-ftp (PHP 3) to get the FTP functions to work.

PHP FTP Functions

PHP: indicates the earliest version of PHP that supports the function.
Function Description PHP
ftp_alloc() Allocates space for a file to be uploaded to the FTP server 5
ftp_cdup() Changes the current directory to the parent directory on the FTP server 3
ftp_chdir() Changes the current directory on the FTP server 3
ftp_chmod() Sets permissions on a file via FTP 5
ftp_close() Closes an FTP connection 4
ftp_connect() Opens an FTP connection 3
ftp_delete() Deletes a file on the FTP server 3
ftp_exec() Executes a program/command on the FTP server 4
ftp_fget() Downloads a file from the FTP server and saves it to an open file 3
ftp_fput() Uploads from an open file and saves it to a file on the FTP server 3
ftp_get_option() Returns runtime behaviors of the FTP connection 4
ftp_get() Downloads a file from the FTP server 3
ftp_login() Logs on to an FTP connection 3
ftp_mdtm() Returns the last modified time of a specified file 3
ftp_mkdir() Creates a new directory on the FTP server 3
ftp_nb_continue() Continues retrieving/sending a file (non-blocking) 4
ftp_nb_fget() Downloads a file from the FTP server and saves it to an open file (non-blocking) 4
ftp_nb_fput() Uploads from an open file and saves it to a file on the FTP server (non-blocking) 4
ftp_nb_get() Downloads a file from the FTP server (non-blocking) 4
ftp_nb_put() Uploads a file to the FTP server (non-blocking) 4
ftp_nlist() Lists the files in a specified directory on the FTP server 3
ftp_pasv() Turns passive mode on or off 3
ftp_put() Uploads a file to the FTP server 3
ftp_pwd() Returns the current directory name 3
ftp_quit() Alias of ftp_close() 3
ftp_raw() Sends a raw command to the FTP server 5
ftp_rawlist() Returns a detailed list of files in the specified directory 3
ftp_rename() Renames a file or directory on the FTP server 3
ftp_rmdir() Removes a directory on the FTP server 3
ftp_set_option() Sets runtime options for the FTP connection 4
ftp_site() Sends a SITE command to the server 3
ftp_size() Returns the size of the specified file 3
ftp_ssl_connect() Opens a secure SSL-FTP connection 4
ftp_systype() Returns the system type identifier of the FTP server 3


PHP FTP Constants

PHP: indicates the earliest version of PHP that supports the constant.
Constant Description PHP
FTP_ASCII   3
FTP_TEXT   3
FTP_BINARY   3
FTP_IMAGE   3
FTP_TIMEOUT_SEC   3
FTP_AUTOSEEK   4
FTP_AUTORESUME Determine resume position and start position for get and put requests automatically 4
FTP_FAILED Asynchronous transfer has failed 4
FTP_FINISHED Asynchronous transfer has finished 4
FTP_MOREDATA Asynchronous transfer is still active 4



The HTTP functions let you manipulate information sent to the browser by the Web server, before any other output has been sent.

Installation

The directory functions are part of the PHP core. There is no installation needed to use these functions.

PHP HTTP Functions

PHP: indicates the earliest version of PHP that supports the function.
Function Description PHP
header() Sends a raw HTTP header to a client 3
headers_list() Returns a list of response headers sent (or ready to send) 5
headers_sent() Checks if / where the HTTP headers have been sent 3
setcookie() Sends an HTTP cookie to a client 3
setrawcookie() Sends an HTTP cookie without URL encoding the cookie value 5

Tuesday 12 November 2013

PHP libxml Introduction

The libxml functions and constants are used together with SimpleXML, XSLT and DOM functions.

Installation

These functions require the libxml package. Download at xmlsoft.org

PHP libxml Functions

PHP: indicates the earliest version of PHP that supports the function.
Function Description PHP
libxml_clear_errors() Clear libxml error buffer 5
libxml_get_errors() Retrieve array of errors 5
libxml_get_last_error() Retrieve last error from libxml 5
libxml_set_streams_context() Set the streams context for the next libxml document load or write 5
libxml_use_internal_errors() Disable libxml errors and allow user to fetch error information as needed 5


PHP libxml Constants

Function Description PHP
LIBXML_COMPACT Set small nodes allocation optimization. This may improve the application performance 5
LIBXML_DTDATTR Set default DTD attributes 5
LIBXML_DTDLOAD Load external subset 5
LIBXML_DTDVALID Validate with the DTD 5
LIBXML_NOBLANKS Remove blank nodes 5
LIBXML_NOCDATA Set CDATA as text nodes 5
LIBXML_NOEMPTYTAG Change empty tags (e.g. <br/> to <br></br>), only available in the DOMDocument->save() and DOMDocument->saveXML() functions 5
LIBXML_NOENT Substitute entities 5
LIBXML_NOERROR Do not show error reports 5
LIBXML_NONET Stop network access while loading documents 5
LIBXML_NOWARNING Do not show warning reports 5
LIBXML_NOXMLDECL Drop the XML declaration when saving a document 5
LIBXML_NSCLEAN Remove excess namespace declarations 5
LIBXML_XINCLUDE Use XInclude substitution 5
LIBXML_ERR_ERROR Get recoverable errors 5
LIBXML_ERR_FATAL Get fatal errors 5
LIBXML_ERR_NONE Get no errors 5
LIBXML_ERR_WARNING Get simple warnings 5
LIBXML_VERSION Get libxml version (e.g. 20605 or 20617) 5
LIBXML_DOTTED_VERSION Get dotted libxml version (e.g. 2.6.5 or 2.6.17) 5

PHP Mail Introduction

The mail() function allows you to send emails directly from a script.

Requirements

For the mail functions to be available, PHP requires an installed and working email system. The program to be used is defined by the configuration settings in the php.ini file.

Installation

The mail functions are part of the PHP core. There is no installation needed to use these functions.

Runtime Configuration

The behavior of the mail functions is affected by settings in the php.ini file.
Mail configuration options:
Name Default Description Changeable
SMTP "localhost" Windows only: The DNS name or IP address of the SMTP server PHP_INI_ALL
smtp_port "25" Windows only: The SMTP port number. Available since PHP 4.3 PHP_INI_ALL
sendmail_from NULL Windows only: Specifies the "from" address to be used in email sent from PHP PHP_INI_ALL
sendmail_path NULL Unix systems only: Specifies where the sendmail program can be found (usually /usr/sbin/sendmail or /usr/lib/sendmail) PHP_INI_SYSTEM


PHP Mail Functions

PHP: indicates the earliest version of PHP that supports the function.
Function Description PHP
ezmlm_hash() Calculates the hash value needed by the EZMLM mailing list system 3
mail() Allows you to send emails directly from a script 3

PHP Math Introduction

The math functions can handle values within the range of integer and float types.

Installation

The PHP math functions are part of the PHP core. No installation is required to use these functions.

PHP 5 Math Functions

Function Description
abs() Returns the absolute (positive) value of a number
acos() Returns the arc cosine of a number
acosh() Returns the inverse hyperbolic cosine of a number
asin() Returns the arc sine of a number
asinh() Returns the inverse hyperbolic sine of a number
atan() Returns the arc tangent of a number in radians
atan2() Returns the arc tangent of two variables x and y
atanh() Returns the inverse hyperbolic tangent of a number
base_convert() Converts a number from one number base to another
bindec() Converts a binary number to a decimal number
ceil() Rounds a number up to the nearest integer
cos() Returns the cosine of a number
cosh() Returns the hyperbolic cosine of a number
decbin() Converts a decimal number to a binary number
dechex() Converts a decimal number to a hexadecimal number
decoct() Converts a decimal number to an octal number
deg2rad() Converts a degree value to a radian value
exp() Calculates the exponent of e
expm1() Returns exp(x) - 1
floor() Rounds a number down to the nearest integer
fmod() Returns the remainder of x/y
getrandmax() Returns the largest possible value returned by rand()
hexdec() Converts a hexadecimal number to a decimal number
hypot() Calculates the hypotenuse of a right-angle triangle
is_finite() Checks whether a value is finite or not
is_infinite() Checks whether a value is infinite or not
is_nan() Checks whether a value is 'not-a-number'
lcg_value() Returns a pseudo random number in a range between 0 and 1
log() Returns the natural logarithm of a number
log10() Returns the base-10 logarithm of a number
log1p() Returns log(1+number)
max() Returns the highest value in an array, or the highest value of several specified values
min() Returns the lowest value in an array, or the lowest value of several specified values
mt_getrandmax() Returns the largest possible value returned by mt_rand()
mt_rand() Generates a random integer using Mersenne Twister algorithm
mt_srand() Seeds the Mersenne Twister random number generator
octdec() Converts an octal number to a decimal number
pi() Returns the value of PI
pow() Returns x raised to the power of y
rad2deg() Converts a radian value to a degree value
rand() Generates a random integer
round() Rounds a floating-point number
sin() Returns the sine of a number
sinh() Returns the hyperbolic sine of a number
sqrt() Returns the square root of a number
srand() Seeds the random number generator
tan() Returns the tangent of a number
tanh() Returns the hyperbolic tangent of a number


PHP 5 Predefined Math Constants

Constant Value Description PHP Version
INF INF The infinite PHP 4
M_E 2.7182818284590452354 Returns e PHP 4
M_EULER 0.57721566490153286061 Returns Euler constant PHP 4
M_LNPI 1.14472988584940017414 Returns the natural logarithm of PI: log_e(pi) PHP 5.2
M_LN2 0.69314718055994530942 Returns the natural logarithm of 2: log_e 2 PHP 4
M_LN10 2.30258509299404568402 Returns the natural logarithm of 10: log_e 10 PHP 4
M_LOG2E 1.4426950408889634074 Returns the base-2 logarithm of E: log_2 e PHP 4
M_LOG10E 0.43429448190325182765 Returns the base-10 logarithm of E: log_10 e PHP 4
M_PI 3.14159265358979323846 Returns Pi PHP 4
M_PI_2 1.57079632679489661923 Returns Pi/2 PHP 4
M_PI_4 0.78539816339744830962 Returns Pi/4 PHP 4
M_1_PI 0.31830988618379067154 Returns 1/Pi PHP 4
M_2_PI 0.63661977236758134308 Returns 2/Pi PHP 4
M_SQRTPI 1.77245385090551602729 Returns the square root of PI: sqrt(pi) PHP 5.2
M_2_SQRTPI 1.12837916709551257390 Returns 2/square root of PI: 2/sqrt(pi) PHP 4
M_SQRT1_2 0.70710678118654752440 Returns the square root of 1/2: 1/sqrt(2) PHP 4
M_SQRT2 1.41421356237309504880 Returns the square root of 2: sqrt(2) PHP 4
M_SQRT3 1.73205080756887729352 Returns the square root of 3: sqrt(3) PHP 5.2
NAN NAN Not A Number PHP 4
PHP_ROUND_HALF_UP 1 Round halves up PHP 5.3
PHP_ROUND_HALF_DOWN 2 Round halves down PHP 5.3
PHP_ROUND_HALF_EVEN 3 Round halves to even numbers PHP 5.3
PHP_ROUND_HALF_ODD 4 Round halves to odd numbers PHP 5.3

The misc. functions were only placed here because none of the other categories seemed to fit.

Installation

The misc. functions are part of the PHP core. No installation is required to use these functions.

Runtime Configuration

The behavior of the misc. functions is affected by settings in the php.ini file.
Misc. configuration options:
Name Description Default Changeable
ignore_user_abort FALSE indicates that scripts will be terminated as soon as they try to output something after a client has aborted their connection "0" PHP_INI_ALL
highlight.string Color for highlighting a string in PHP syntax "#DD0000" PHP_INI_ALL
highlight.comment Color for highlighting PHP comments "#FF8000" PHP_INI_ALL
highlight.keyword Color for syntax highlighting PHP keywords (e.g. parenthesis and semicolon) "#007700" PHP_INI_ALL
highlight.bg Removed in PHP 5.4.0. Color for background "#FFFFFF" PHP_INI_ALL
highlight.default Default color for PHP syntax "#0000BB" PHP_INI_ALL
highlight.html Color for HTML code "#000000" PHP_INI_ALL
browscap Name and location of browser-capabilities file (e.g. browscap.ini) NULL PHP_INI_SYSTEM


PHP Miscellaneous Functions

Function Description
connection_aborted() Checks whether the client has disconnected
connection_status() Returns the current connection status
connection_timeout() Deprecated in PHP 4.0.5. Checks whether the script has timed out
constant() Returns the value of a constant
define() Defines a constant
defined() Checks whether a constant exists
die() Prints a message and exits the current script
eval() Evaluates a string as PHP code
exit() Prints a message and exits the current script
get_browser() Returns the capabilities of the user's browser
__halt_compiler() Halts the compiler execution
highlight_file() Outputs a file with the PHP syntax highlighted
highlight_string() Outputs a string with the PHP syntax highlighted
ignore_user_abort() Sets whether a remote client can abort the running of a script
pack() Packs data into a binary string
php_check_syntax() Deprecated in PHP 5.0.5
php_strip_whitespace() Returns the source code of a file with PHP comments and whitespace removed
show_source() Alias of highlight_file()
sleep() Delays code execution for a number of seconds
sys_getloadavg() Gets system load average
time_nanosleep() Delays code execution for a number of seconds and nanoseconds
time_sleep_until() Delays code execution until a specified time
uniqid() Generates a unique ID
unpack() Unpacks data from a binary string
usleep() Delays code execution for a number of microseconds


PHP Misc. Constants

PHP: indicates the earliest version of PHP that supports the constant.
Constant Description PHP
CONNECTION_ABORTED
CONNECTION_NORMAL
CONNECTION_TIMEOUT
__COMPILER_HALT_OFFSET__ 5

Thursday 7 November 2013

PHP MySQLi = PHP MySQL Improved!
The MySQLi functions allows you to access MySQL database servers.
Note: The MySQLi extension is designed to work with MySQL version 4.1.13 or newer.

Installation / Runtime Configuration

For the MySQLi functions to be available, you must compile PHP with support for the MySQLi extension.
The MySQLi extension was introduced with PHP version 5.0.0. The MySQL Native Driver was included in PHP version 5.3.0.
For installation details, go to: http://www.php.net/manual/en/mysqli.installation.php
For runtime configuration details, go to: http://www.php.net/manual/en/mysqli.configuration.php

PHP 5 MySQLi Functions

Function Description
mysqli_affected_rows() Returns the number of affected rows in the previous MySQL operation
mysqli_autocommit() Turns on or off auto-committing database modifications
mysqli_change_user() Changes the user of the specified database connection
mysqli_character_set_name() Returns the default character set for the database connection
mysqli_close() Closes a previously opened database connection
mysqli_commit() Commits the current transaction
mysqli_connect_errno() Returns the error code from the last connection error
mysqli_connect_error() Returns the error description from the last connection error
mysqli_connect() Opens a new connection to the MySQL server
mysqli_data_seek() Adjusts the result pointer to an arbitrary row in the result-set
mysqli_debug() Performs debugging operations
mysqli_dump_debug_info() Dumps debugging info into the log
mysqli_errno() Returns the last error code for the most recent function call
mysqli_error_list() Returns a list of errors for the most recent function call
mysqli_error() Returns the last error description for the most recent function call
mysqli_fetch_all() Fetches all result rows as an associative array, a numeric array, or both
mysqli_fetch_array() Fetches a result row as an associative, a numeric array, or both
mysqli_fetch_assoc() Fetches a result row as an associative array
mysqli_fetch_field_direct() Returns meta-data for a single field in the result set, as an object
mysqli_fetch_field() Returns the next field in the result set, as an object
mysqli_fetch_fields() Returns an array of objects that represent the fields in a result set
mysqli_fetch_lengths() Returns the lengths of the columns of the current row in the result set
mysqli_fetch_object() Returns the current row of a result set, as an object
mysqli_fetch_row() Fetches one row from a result-set and returns it as an enumerated array
mysqli_field_count() Returns the number of columns for the most recent query
mysqli_field_seek() Sets the field cursor to the given field offset
mysqli_field_tell() Returns the position of the field cursor
mysqli_free_result() Frees the memory associated with a result
mysqli_get_charset() Returns a character set object
mysqli_get_client_info() Returns the MySQL client library version
mysqli_get_client_stats() Returns statistics about client per-process
mysqli_get_client_version() Returns the MySQL client library version as an integer
mysqli_get_connection_stats() Returns statistics about the client connection
mysqli_get_host_info() Returns the MySQL server hostname and the connection type
mysqli_get_proto_info() Returns the MySQL protocol version
mysqli_get_server_info() Returns the MySQL server version
mysqli_get_server_version() Returns the MySQL server version as an integer
mysqli_info() Returns information about the most recently executed query
mysqli_init() Initializes MySQLi and returns a resource for use with mysqli_real_connect()
mysqli_insert_id() Returns the auto-generated id used in the last query
mysql_kill() Asks the server to kill a MySQL thread
mysqli_more_results() Checks if there are more results from a multi query
mysqli_multi_query() Performs one or more queries on the database
mysqli_next_result() Prepares the next result set from mysqli_multi_query()
mysqli_num_fields() Returns the number of fields in a result set
mysqli_num_rows() Returns the number of rows in a result set
mysqli_options() Sets extra connect options and affect behavior for a connection
mysqli_ping() Pings a server connection, or tries to reconnect if the connection has gone down
mysqli_prepare() Prepares an SQL statement for execution
mysqli_query() Performs a query against the database
mysqli_real_connect() Opens a new connection to the MySQL server
mysqli_real_escape_string() Escapes special characters in a string for use in an SQL statement
mysqli_real_query() Executes an SQL query
mysqli_reap_async_query() Returns the result from async query
mysqli_refresh() Refreshes tables or caches, or resets the replication server information
mysqli_rollback() Rolls back the current transaction for the database
mysqli_select_db() Changes the default database for the connection
mysqli_set_charset() Sets the default client character set
mysqli_set_local_infile_default() Unsets user defined handler for load local infile command
mysqli_set_local_infile_handler() Set callback function for LOAD DATA LOCAL INFILE command
mysqli_sqlstate() Returns the SQLSTATE error code for the last MySQL operation
mysqli_ssl_set() Used to establish secure connections using SSL
mysqli_stat() Returns the current system status
mysqli_stmt_init() Initializes a statement and returns an object for use with mysqli_stmt_prepare()
mysqli_store_result() Transfers a result set from the last query
mysqli_thread_id() Returns the thread ID for the current connection
mysqli_thread_safe() Returns whether the client library is compiled as thread-safe
mysqli_use_result() Initiates the retrieval of a result set from the last query executed using the mysqli_real_query()
mysqli_warning_count() Returns the number of warnings from the last query in the connection