Thursday, January 5, 2012

PHP Directory Functions

PHP Directory Introduction

The directory functions allow you to retrieve information about directories and their contents.

Installation

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

PHP Directory Functions

PHP: indicates the earliest version of PHP that supports the function.
Function Description PHP
chdir() Changes the current directory 3
chroot() Changes the root directory of the current process 4
dir() Opens a directory handle and returns an object 3
closedir() Closes a directory handle 3
getcwd() Returns the current directory 4
opendir() Opens a directory handle 3
readdir() Returns an entry from a directory handle 3
rewinddir() Resets a directory handle 3
scandir() Lists files and directories inside a specified path 5


PHP Directory Constants

PHP: indicates the earliest version of PHP that supports the constant.
Constant Description PHP
DIRECTORY_SEPARATOR   3
PATH_SEPARATOR   4


http://www.w3schools.com/php/php_ref_directory.asp
»»  READMORE...

Sunday, January 1, 2012

PHP Date / Time Functions

PHP Date / Time Introduction

The date/time functions allow you to extract and format the date and time on the server.
Note: These functions depend on the locale settings of the server!

Installation

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

Runtime Configuration

The behavior of the date/time functions is affected by settings in php.ini.
Date/Time configuration options:
Name Default Description Changeable
date.default_latitude  "31.7667" Specifies the default latitude (available since PHP 5). This option is used by date_sunrise() and date_sunset() PHP_INI_ALL
date.default_longitude "35.2333" Specifies the default longitude (available since PHP 5). This option is used by date_sunrise() and date_sunset() PHP_INI_ALL
date.sunrise_zenith "90.83" Specifies the default sunrise zenith (available since PHP 5). This option is used by date_sunrise() and date_sunset() PHP_INI_ALL
date.sunset_zenith "90.83" Specifies the default sunset zenith (available since PHP 5). This option is used by date_sunrise() and date_sunset() PHP_INI_ALL
date.timezone "" Specifies the default timezone (available since PHP 5.1) PHP_INI_ALL


PHP Date / Time Functions

PHP: indicates the earliest version of PHP that supports the function.
Function Description PHP
checkdate() Validates a Gregorian date 3
date_default_timezone_get() Returns the default time zone 5
date_default_timezone_set() Sets the default time zone 5
date_sunrise() Returns the time of sunrise for a given day / location 5
date_sunset() Returns the time of sunset for a given day / location 5
date() Formats a local time/date 3
getdate() Returns an array that contains date and time information for a Unix timestamp 3
gettimeofday() Returns an array that contains current time information 3
gmdate() Formats a GMT/UTC date/time 3
gmmktime() Returns the Unix timestamp for a GMT date 3
gmstrftime() Formats a GMT/UTC time/date according to locale settings 3
idate() Formats a local time/date as integer 5
localtime() Returns an array that contains the time components of a Unix timestamp 4
microtime() Returns the microseconds for the current time 3
mktime() Returns the Unix timestamp for a date 3
strftime() Formats a local time/date according to locale settings 3
strptime() Parses a time/date generated with strftime() 5
strtotime() Parses an English textual date or time into a Unix timestamp 3
time() Returns the current time as a Unix timestamp 3


PHP Date / Time Constants

PHP: indicates the earliest version of PHP that supports the constant.
Constant Description PHP
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)



 http://www.w3schools.com/php/php_ref_date.asp
»»  READMORE...

Tuesday, December 27, 2011

PHP Calendar Functions

PHP Calendar Introduction

The calendar functions are useful when working with different calendar formats. The standard it is based on is the Julian day count (Julian day count is a count of days starting from January 1, 4713 B.C.). Note that the Julian day count is not the same as the Julian calendar!
Note: To convert between calendar formats, you must first convert to Julian day count, then to the calendar format.

Installation

The windows version of PHP has built-in support for the calendar extension. So, the calendar functions will work automatically.
However, if you are running the Linux version of PHP, you will have to compile PHP with --enable-calendar to get the calendar functions to work.

PHP Calendar Functions

PHP: indicates the earliest version of PHP that supports the function.
Function Description PHP
cal_days_in_month() Returns the number of days in a month for a specified year and calendar 4
cal_from_jd() Converts a Julian day count into a date of a specified calendar 4
cal_info() Returns information about a given calendar 4
cal_to_jd() Converts a date to Julian day count 4
easter_date() Returns the Unix timestamp for midnight on Easter of a specified year 3
easter_days() Returns the number of days after March 21, on which Easter falls for a specified year 3
FrenchToJD() Converts a French Republican date to a Julian day count 3
GregorianToJD() Converts a Gregorian date to a Julian day count 3
JDDayOfWeek() Returns the day of a week 3
JDMonthName() Returns a month name 3
JDToFrench() Converts a Julian day count to a French Republican date 3
JDToGregorian() Converts a Julian day count to a Gregorian date 3
jdtojewish() Converts a Julian day count to a Jewish date 3
JDToJulian() Converts a Julian day count to a Julian date 3
jdtounix() Converts a Julian day count to a Unix timestamp 4
JewishToJD() Converts a Jewish date to a Julian day count 3
JulianToJD() Converts a Julian date to a Julian day count 3
unixtojd() Converts a Unix timestamp to a Julian day count 4


PHP Calendar Constants

PHP: indicates the earliest version of PHP that supports the constant.
Constant Description PHP
CAL_GREGORIAN Gregorian calendar 3
CAL_JULIAN Julian calendar 3
CAL_JEWISH Jewish calendar 3
CAL_FRENCH French Republican calendar 3
CAL_NUM_CALS   3
CAL_DOW_DAYNO   3
CAL_DOW_SHORT   3
CAL_DOW_LONG   3
CAL_MONTH_GREGORIAN_SHORT   3
CAL_MONTH_GREGORIAN_LONG   3
CAL_MONTH_JULIAN_SHORT   3
CAL_MONTH_JULIAN_LONG   3
CAL_MONTH_JEWISH   3
CAL_MONTH_FRENCH   3
CAL_EASTER_DEFAULT   4
CAL_EASTER_ROMAN   4
CAL_EASTER_ALWAYS_GREGORIAN   4
CAL_EASTER_ALWAYS_JULIAN   4
CAL_JEWISH_ADD_ALAFIM_GERESH   5
CAL_JEWISH_ADD_ALAFIM   5
CAL_JEWISH_ADD_GERESHAYIM   5  
»»  READMORE...

Friday, December 23, 2011

PHP Array Functions

PHP Array Introduction
The array functions allow you to manipulate arrays.
PHP supports both simple and multi-dimensional arrays. There are also specific functions for populating arrays from database queries.

Installation

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

PHP Array Functions

PHP: indicates the earliest version of PHP that supports the function.
Function Description PHP
array() Creates an array 3
array_change_key_case() Returns an array with all keys in lowercase or uppercase 4
array_chunk() Splits an array into chunks of arrays 4
array_combine() Creates an array by using one array for keys and another for its values 5
array_count_values() Returns an array with the number of occurrences for each value 4
array_diff() Compares array values, and returns the differences 4
array_diff_assoc() Compares array keys and values, and returns the differences 4
array_diff_key() Compares array keys, and returns the differences 5
array_diff_uassoc() Compares array keys and values, with an additional user-made function check, and returns the differences 5
array_diff_ukey() Compares array keys, with an additional user-made function check, and returns the differences 5
array_fill() Fills an array with values 4
array_filter() Filters elements of an array using a user-made function 4
array_flip() Exchanges all keys with their associated values in an array 4
array_intersect() Compares array values, and returns the matches 4
array_intersect_assoc() Compares array keys and values, and returns the matches 4
array_intersect_key() Compares array keys, and returns the matches 5
array_intersect_uassoc() Compares array keys and values, with an additional user-made function check, and returns the matches 5
array_intersect_ukey() Compares array keys, with an additional user-made function check, and returns the matches 5
array_key_exists() Checks if the specified key exists in the array 4
array_keys() Returns all the keys of an array 4
array_map() Sends each value of an array to a user-made function, which returns new values 4
array_merge() Merges one or more arrays into one array 4
array_merge_recursive() Merges one or more arrays into one array 4
array_multisort() Sorts multiple or multi-dimensional arrays 4
array_pad() Inserts a specified number of items, with a specified value, to an array 4
array_pop() Deletes the last element of an array 4
array_product() Calculates the product of the values in an array 5
array_push() Inserts one or more elements to the end of an array 4
array_rand() Returns one or more random keys from an array 4
array_reduce() Returns an array as a string, using a user-defined function 4
array_reverse() Returns an array in the reverse order 4
array_search() Searches an array for a given value and returns the key 4
array_shift() Removes the first element from an array, and returns the value of the removed element 4
array_slice() Returns selected parts of an array 4
array_splice() Removes and replaces specified elements of an array 4
array_sum() Returns the sum of the values in an array 4
array_udiff() Compares array values in a user-made function and returns an array 5
array_udiff_assoc() Compares array keys, and compares array values in a user-made function, and returns an array 5
array_udiff_uassoc() Compares array keys and array values in user-made functions, and returns an array 5
array_uintersect() Compares array values in a user-made function and returns an array 5
array_uintersect_assoc() Compares array keys, and compares array values in a user-made function, and returns an array 5
array_uintersect_uassoc() Compares array keys and array values in user-made functions, and returns an array 5
array_unique() Removes duplicate values from an array 4
array_unshift() Adds one or more elements to the beginning of an array 4
array_values() Returns all the values of an array 4
array_walk() Applies a user function to every member of an array 3
array_walk_recursive() Applies a user function recursively to every member of an array 5
arsort() Sorts an array in reverse order and maintain index association 3
asort() Sorts an array and maintain index association 3
compact() Create array containing variables and their values 4
count() Counts elements in an array, or properties in an object 3
current() Returns the current element in an array 3
each() Returns the current key and value pair from an array 3
end() Sets the internal pointer of an array to its last element 3
extract() Imports variables into the current symbol table from an array 3
in_array() Checks if a specified value exists in an array 4
key() Fetches a key from an array 3
krsort() Sorts an array by key in reverse order 3
ksort() Sorts an array by key 3
list() Assigns variables as if they were an array 3
natcasesort() Sorts an array using a case insensitive "natural order" algorithm 4
natsort() Sorts an array using a "natural order" algorithm 4
next() Advance the internal array pointer of an array 3
pos() Alias of current() 3
prev() Rewinds the internal array pointer 3
range() Creates an array containing a range of elements 3
reset() Sets the internal pointer of an array to its first element 3
rsort() Sorts an array in reverse order 3
shuffle() Shuffles an array 3
sizeof() Alias of count() 3
sort() Sorts an array 3
uasort() Sorts an array with a user-defined function and maintain index association 3
uksort() Sorts an array by keys using a user-defined function 3
usort() Sorts an array by values using a user-defined function 3


PHP Array Constants

PHP: indicates the earliest version of PHP that supports the constant.
Constant Description PHP
CASE_LOWER Used with array_change_key_case() to convert array keys to lower case  
CASE_UPPER Used with array_change_key_case() to convert array keys to upper case  
SORT_ASC Used with array_multisort() to sort in ascending order  
SORT_DESC Used with array_multisort() to sort in descending order  
SORT_REGULAR Used to compare items normally  
SORT_NUMERIC Used to compare items numerically  
SORT_STRING Used to compare items as strings  
SORT_LOCALE_STRING Used to compare items as strings, based on the current locale 4
COUNT_NORMAL    
COUNT_RECURSIVE    
EXTR_OVERWRITE    
EXTR_SKIP    
EXTR_PREFIX_SAME    
EXTR_PREFIX_ALL    
EXTR_PREFIX_INVALID    
EXTR_PREFIX_IF_EXISTS    
EXTR_IF_EXISTS    
EXTR_REFS    



 http://www.w3schools.com/php/php_ref_array.asp
»»  READMORE...

Wednesday, December 21, 2011

PHP Example - AJAX Poll

AJAX Poll

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

Do you like PHP and AJAX so far?

Yes:
No:

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 type="text/javascript">
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).

http://www.w3schools.com/php/php_ajax_poll.asp
»»  READMORE...

Monday, December 19, 2011

PHP Example - AJAX RSS Reader

An RSS Reader is used to read RSS Feeds.

AJAX RSS Reader

The following example will demonstrate an RSS reader, where the RSS-feed is loaded into a webpage without reloading:

RSS-feed will be listed here...

Example Explained - The HTML Page

When a user selects an RSS-feed in the dropdown list above, a function called "showResult()" is executed. The function is triggered by the "onchange" event:
<html>
<head>
<script type="text/javascript">
function showRSS(str)
{
if (str.length==0)
  {
  document.getElementById("rssOutput").innerHTML="";
  return;
  }
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("rssOutput").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","getrss.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>

<form>
<select onchange="showRSS(this.value)">
<option value="">Select an RSS-feed:</option>
<option value="Google">Google News</option>
<option value="MSNBC">MSNBC News</option>
</select>
</form>
<br />
<div id="rssOutput">RSS-feed will be listed here...</div>
</body>
</html>
The showResult() function does the following:
  • Check if an RSS-feed is selected
  • 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 (q) is added to the URL (with the content of the dropdown list)

The PHP File

The page on the server called by the JavaScript above is a PHP file called "getrss.php":
<?php
//get the q parameter from URL
$q=$_GET["q"];

//find out which feed was selected
if($q=="Google")
  {
  $xml=("http://news.google.com/news?ned=us&topic=h&output=rss");
  }
elseif($q=="MSNBC")
  {
  $xml=("http://rss.msnbc.msn.com/id/3032091/device/rss/rss.xml");
  }

$xmlDoc = new DOMDocument();
$xmlDoc->load($xml);

//get elements from "<channel>"
$channel=$xmlDoc->getElementsByTagName('channel')->item(0);
$channel_title = $channel->getElementsByTagName('title')
->item(0)->childNodes->item(0)->nodeValue;
$channel_link = $channel->getElementsByTagName('link')
->item(0)->childNodes->item(0)->nodeValue;
$channel_desc = $channel->getElementsByTagName('description')
->item(0)->childNodes->item(0)->nodeValue;

//output elements from "<channel>"
echo("<p><a href='" . $channel_link
  . "'>" . $channel_title . "</a>");
echo("<br />");
echo($channel_desc . "</p>");

//get and output "<item>" elements
$x=$xmlDoc->getElementsByTagName('item');
for ($i=0; $i<=2; $i++)
  {
  $item_title=$x->item($i)->getElementsByTagName('title')
  ->item(0)->childNodes->item(0)->nodeValue;
  $item_link=$x->item($i)->getElementsByTagName('link')
  ->item(0)->childNodes->item(0)->nodeValue;
  $item_desc=$x->item($i)->getElementsByTagName('description')
  ->item(0)->childNodes->item(0)->nodeValue;

  echo ("<p><a href='" . $item_link
  . "'>" . $item_title . "</a>");
  echo ("<br />");
  echo ($item_desc . "</p>");
  }
?>
When an RSS-feed is sent from the JavaScript, the following happens:
  • Check which feed was selected
  • Create a new XML DOM object
  • Load the RSS document in the xml variable
  • Extract and output elements from the channel element
  • Extract and output elements from the item element
http://www.w3schools.com/php/php_ajax_rss_reader.asp
»»  READMORE...

Saturday, December 17, 2011

PHP Example - AJAX Live Search

AJAX can be used to create more user-friendly and interactive searches.

AJAX Live Search

The following example will demonstrate a live search, where you get search results while you type.
Live search has many benefits compared to traditional searching:
  • Results are shown as you type
  • Results narrow as you continue typing
  • If results become too narrow, remove characters to see a broader result
Search for a W3Schools page in the input field below:
The results in the example above are found in an XML file (links.xml). To make this example small and simple, only six results are available.

Example Explained - The HTML Page

When a user types a character in the input field above, the function "showResult()" is executed. The function is triggered by the "onkeyup" event:
<html>
<head>
<script type="text/javascript">
function showResult(str)
{
if (str.length==0)
  {
  document.getElementById("livesearch").innerHTML="";
  document.getElementById("livesearch").style.border="0px";
  return;
  }
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("livesearch").innerHTML=xmlhttp.responseText;
    document.getElementById("livesearch").style.border="1px solid #A5ACB2";
    }
  }
xmlhttp.open("GET","livesearch.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>

<form>
<input type="text" size="30" onkeyup="showResult(this.value)" />
<div id="livesearch"></div>
</form>

</body>
</html>
Source code explanation:
If the input field is empty (str.length==0), the function clears the content of the livesearch placeholder and exits the function.
If the input field is not empty, the showResult() function executes 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 (q) is added to the URL (with the content of the input field)

The PHP File

The page on the server called by the JavaScript above is a PHP file called "livesearch.php".
The source code in "livesearch.php" searches an XML file for titles matching the search string and returns the result:
<?php
$xmlDoc=new DOMDocument();
$xmlDoc->load("links.xml");

$x=$xmlDoc->getElementsByTagName('link');

//get the q parameter from URL
$q=$_GET["q"];

//lookup all links from the xml file if length of q>0
if (strlen($q)>0)
{
$hint="";
for($i=0; $i<($x->length); $i++)
  {
  $y=$x->item($i)->getElementsByTagName('title');
  $z=$x->item($i)->getElementsByTagName('url');
  if ($y->item(0)->nodeType==1)
    {
    //find a link matching the search text
    if (stristr($y->item(0)->childNodes->item(0)->nodeValue,$q))
      {
      if ($hint=="")
        {
        $hint="<a href='" .
        $z->item(0)->childNodes->item(0)->nodeValue .
        "' target='_blank'>" .
        $y->item(0)->childNodes->item(0)->nodeValue . "</a>";
        }
      else
        {
        $hint=$hint . "<br /><a href='" .
        $z->item(0)->childNodes->item(0)->nodeValue .
        "' target='_blank'>" .
        $y->item(0)->childNodes->item(0)->nodeValue . "</a>";
        }
      }
    }
  }
}

// Set output to "no suggestion" if no hint were found
// or to the correct values
if ($hint=="")
  {
  $response="no suggestion";
  }
else
  {
  $response=$hint;
  }

//output the response
echo $response;
?>
If there is any text sent from the JavaScript (strlen($q) > 0), the following happens:
  • Load an XML file into a new XML DOM object
  • Loop through all <title> elements to find matches from the text sent from the JavaScript
  • Sets the correct url and title in the "$response" variable. If more than one match is found, all matches are added to the variable
  • If no matches are found, the $response variable is set to "no suggestion"
http://www.w3schools.com/php/php_ajax_livesearch.asp
»»  READMORE...