Saturday, October 17, 2009

Prevent Duplicate Form Submission

Today Learn PHP Online will give you some basic tips on how to preventing duplicate form submission.

Duplicate Form Submissions

When a web form is submitted to a server through an HTTP POST request, a web user that attempts to refresh the server response in certain user agents can cause the contents of the original HTTP POST request to be resubmitted, possibly causing undesired results, such as a duplicate web purchase.

To avoid this problem, many web developers use the PRG pattern — instead of returning a web page directly, the POST operation returns a redirection command (using the HTTP 303 response code [sometimes 302] together with the HTTP "Location" response header), instructing the browser to load a different page using an HTTP GET request. A web user can then safely refresh the server response without causing the initial HTTP POST request to be resubmitted.

The PRG pattern cannot solve every way of duplicate form submission. Some known duplicate form submissions that PRG cannot solve are:

  • If a web user goes back to the web form and resubmits it.
  • If a web user clicks a submission button multiple times before the server response loads.
  • If a web user refreshes before the initial submission has completed because of server lag, resulting in a duplicate HTTP POST request in certain user agents.

Another way to prevent users from submitting forms twice (e.g. by double clicking a button) is to use Javascript to disable the button after the first click.

2 Ways to Prevent Duplicate Form Submissions

1) Using PHP sessions to prevent duplicate form submission.

<?php
session_start();

$_PG = (!empty($_POST)) ? array_merge($_POST, $_GET) : $_GET;
if(!empty($_PG)) {
 //Retrieve the value of the hidden field
 $form_secret=$_PG['form_secret'];
 if(isset($_SESSION['FORM_SECRET'])) {
  if(strcasecmp($form_secret,$_SESSION['FORM_SECRET'])===0) {
   echo "<br />Valid Key... Data was successfully saved.";
   unset($_SESSION['FORM_SECRET']);
  }else {
   //Invalid secret key
   echo "<br />Invalid Secret Key";
  }
 }else {
  //Secret key missing
  echo 'Form data has already been processed!';
 }
}
else
{
 $_SESSION['FORM_SECRET']=md5(uniqid(rand(), true));
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Prevent Duplicate Submission</title>
</head>

<body>

<form action="<?=$_SERVER['PHP_SELF']?>" >
    <input type="hidden" name="form_secret" value="<?php echo $_SESSION['FORM_SECRET'];?>" />
    <input type="submit" value="Submit" />
</form>

</body>
</html>

2) Using header() redirection technique. Suppose you have a form.php & action.php.

form.php
...
<form action="action.php" >
    <input type="submit" value="Submit" />
</form>
....

action.php
<?php

 // Your Logic function here example
 // mysql_query("INSERT ... values('{$_POST[0]}', ...)");

 // send back to the form.php page
 header("location: form.php");

?>

So, the flow would look like below.

FORM.PHP ---[submit form to]--> ACTION.PHP ---[submit back to]---> FORM.PHP


Source: http://en.wikipedia.org/wiki/Post/Redirect/Get

Thursday, October 15, 2009

PHP Date Time Function

Here's useful function that calculates the difference between two dates. You can get the result in seconds, minutes, hours, days, weeks, and year. :)

dateDiff() function

//function like dateDiff Microsoft
//not error in year Bissesto
function dateDiff($interval,$dateTimeBegin,$dateTimeEnd) {
    //Parse about any English textual datetime
    //$dateTimeBegin, $dateTimeEnd
    $dateTimeBegin=strtotime($dateTimeBegin);
    if($dateTimeBegin === -1) {
      return("..begin date Invalid");
    }
    
    $dateTimeEnd=strtotime($dateTimeEnd);
    if($dateTimeEnd === -1) {
      return("..end date Invalid");
    }
    
    $dif=$dateTimeEnd - $dateTimeBegin;
    switch($interval) {
      case "s"://seconds
          return($dif);
      case "n"://minutes
          return(floor($dif/60)); //60s=1m
      case "h"://hours
          return(floor($dif/3600)); //3600s=1h
      case "d"://days
          return(floor($dif/86400)); //86400s=1d
      case "ww"://Week
          return(floor($dif/604800)); //604800s=1week=1semana
      case "m": //similar result "m" dateDiff Microsoft
          $monthBegin=(date("Y",$dateTimeBegin)*12)+
            date("n",$dateTimeBegin);
          $monthEnd=(date("Y",$dateTimeEnd)*12)+
            date("n",$dateTimeEnd);
          $monthDiff=$monthEnd-$monthBegin;
          return($monthDiff);
      case "yyyy": //similar result "yyyy" dateDiff Microsoft
          return(date("Y",$dateTimeEnd) - date("Y",$dateTimeBegin));
      default:
          return(floor($dif/86400)); //86400s=1d
    }
}

Usage


// Get DateTime difference in seconds
$seconds = dateDiff('s', $dateTimeBefore, $dateTimeNow);
echo $seconds;

// Get DateTime difference in minutes
$minutes = dateDiff('n', $dateTimeBefore, $dateTimeNow);
echo $minutes;

// Get DateTime difference in hours
$hours = dateDiff('h', $dateTimeBefore, $dateTimeNow);
echo $hours;

// Get DateTime difference in days
$days = dateDiff('d', $dateTimeBefore, $dateTimeNow);
echo $days;

// Get DateTime difference in Week
$Week = dateDiff('ww', $dateTimeBefore, $dateTimeNow);
echo $Week;

// Get DateTime difference in similar result "m" dateDiff Microsoft
$m = dateDiff('m', $dateTimeBefore, $dateTimeNow);
echo $m;

// Get DateTime difference in similar result "yyyy" dateDiff Microsoft
$yyyy = dateDiff('yyyy', $dateTimeBefore, $dateTimeNow);
echo $yyyy;

Wednesday, October 14, 2009

PHP Regular Expression Tutorial

PHP regular expression tutorial

PHP Regular Expressions seems to be a quite complicated. Regular Expressions can easy find a pattern in a string and/or as a replacer.

Basic Syntax of Regular Expressions

Meta-characters
The power of regular expressions comes from the ability to include alternatives and repetitions in the pattern. These are

encoded in the pattern by the use of meta-characters, which do not stand for themselves but instead are interpreted in some special way.

There are two different sets of meta-characters: those that are recognized anywhere in the pattern except within square

brackets, and those that are recognized in square brackets. Outside square brackets, the meta-characters are as follows:

\   -  general escape character with several uses
^  -  assert start of subject (or line, in multiline mode)
$  -  assert end of subject (or line, in multiline mode)
.   -  match any character except newline (by default)
[   -  start character class definition
]   - end character class definition
|   -  start of alternative branch
(  - start subpattern
)   - end subpattern
?  - extends the meaning of (, also 0 or 1 quantifier, also quantifier minimizer
*  - 0 or more quantifier
+  - 1 or more quantifier
{  - start min/max quantifier
} - end min/max quantifier
Part of a pattern that is in square brackets is called a "character class". In a character class the only meta-characters are:

\     -  general escape character
^    -  negate the class, but only if the first character
-     -  indicates character range
]     -  terminates the character class
The following sections describe the use of each of the meta-characters.

Backslash
The backslash character has several uses. Firstly, if it is followed by a non-alphanumeric character, it takes away any special

meaning that character may have. This use of backslash as an escape character applies both inside and outside character classes.

For example, if you want to match a "*" character, you write "\*" in the pattern. This applies whether or not the following

character would otherwise be interpreted as a meta-character, so it is always safe to precede a non-alphanumeric with "\" to

specify that it stands for itself. In particular, if you want to match a backslash, you write "\\".

If a pattern is compiled with the PCRE_EXTENDED option, whitespace in the pattern (other than in a character class) and

characters between a "#" outside a character class and the next newline character are ignored. An escaping backslash can be used to include a whitespace or "#" character as part of the pattern.

A second use of backslash provides a way of encoding non-printing characters in patterns in a visible manner. There is no restriction on the appearance of non-printing characters, apart from the binary zero that terminates a pattern, but when a pattern is being prepared by text editing, it is usually easier to use one of the following escape sequences than the binary character it represents:

\a     -    alarm, that is, the BEL character (hex 07)
\cx   -   "control-x", where x is any character
\e    -   escape (hex 1B)
\f     -   formfeed (hex 0C)
\n    -   newline (hex 0A)
\r    -   carriage return (hex 0D)
\t    -  tab (hex 09)
\xhh  -  character with hex code hh
\ddd  -  character with octal code ddd, or backreference
The precise effect of "\cx" is as follows: if "x" is a lower case letter, it is converted to upper case. Then bit 6 of the

character (hex 40) is inverted. Thus "\cz" becomes hex 1A, but "\c{" becomes hex 3B, while "\c;" becomes hex 7B.

After "\x", up to two hexadecimal digits are read (letters can be in upper or lower case). In UTF-8 mode, "\x{...}" is allowed, where the contents of the braces is a string of hexadecimal digits. It is interpreted as a UTF-8 character whose code number is the given hexadecimal number. The original hexadecimal escape sequence, \xhh, matches a two-byte UTF-8 character if the value is greater than 127.

After "\0" up to two further octal digits are read. In both cases, if there are fewer than two digits, just those that are present are used. Thus the sequence "\0\x\07" specifies two binary zeros followed by a BEL character. Make sure you supply two digits after the initial zero if the character that follows is itself an octal digit.

The handling of a backslash followed by a digit other than 0 is complicated. Outside a character class, PCRE reads it and any following digits as a decimal number. If the number is less than 10, or if there have been at least that many previous capturing left parentheses in the expression, the entire sequence is taken as a back reference. A description of how this works is given later, following the discussion of parenthesized subpatterns.

Inside a character class, or if the decimal number is greater than 9 and there have not been that many capturing subpatterns, PCRE re-reads up to three octal digits following the backslash, and generates a single byte from the least significant 8 bits of the value. Any subsequent digits stand for themselves. For example:

\040  -  is another way of writing a space
\40   - is the same, provided there are fewer than 40 previous capturing subpatterns
\7    -  is always a back reference
\11  -  might be a back reference, or another way of writing a tab
\011 -  is always a tab
\0113 -  is a tab followed by the character "3"
\113  -  is the character with octal code 113 (since there can be no more than 99 back references)
\377  -  is a byte consisting entirely of 1 bits
\81  -  is either a back reference, or a binary zero followed by the two characters "8" and "1"
Note that octal values of 100 or greater must not be introduced by a leading zero, because no more than three octal digits are ever read.

All the sequences that define a single byte value can be used both inside and outside character classes. In addition, inside a character class, the sequence "\b" is interpreted as the ackspace character (hex 08). Outside a character class it has a different meaning (see below).

The third use of backslash is for specifying generic character types:

\d   -  any decimal digit
\D   -  any character that is not a decimal digit
\s   -   any whitespace character
\S  -  any character that is not a whitespace character
\w  -  any "word" character
\W  -  any "non-word" character
Each pair of escape sequences partitions the complete set of characters into two disjoint sets. Any given character matches one, and only one, of each pair.

A "word" character is any letter or digit or the underscore character, that is, any character which can be part of a Perl "word". The definition of letters and digits is controlled by PCRE's character tables, and may vary if locale-specific matching is taking place. For example, in the "fr" (French) locale, some character codes greater than 128 are used for accented letters,
and these are matched by \w.

These character type sequences can appear both inside and outside character classes. They each match one character of the appropriate type. If the current matching point is at the end of the subject string, all of them fail, since there is no character to match.

The fourth use of backslash is for certain simple assertions. An assertion specifies a condition that has to be met at a particular point in a match, without consuming any characters from the subject string. The use of subpatterns for more complicated assertions is described below. The backslashed assertions are

\b  -  word boundary
\B  -  not a word boundary
\A  -  start of subject (independent of multiline mode)
\Z  -  end of subject or newline at end (independent of multiline mode)
\z  -  end of subject (independent of multiline mode)
\G  -  first matching position in subject
These assertions may not appear in character classes (but note that "\b" has a different meaning, namely the backspace character, inside a character class).

A word boundary is a position in the subject string where the current character and the previous character do not both match \w or \W (i.e. one matches \w and the other matches \W), or the start or end of the string if the first or last character matches \w, respectively.

The \A, \Z, and \z assertions differ from the traditional circumflex and dollar (described below) in that they only ever match at the very start and end of the subject string, whatever options are set. They are not affected by the PCRE_MULTILINE or PCRE_DOLLAR_ENDONLY options. The difference between \Z and \z is that \Z matches before a newline that is the last character of
the string as well as at the end of the string, whereas \z matches only at the end.

The \G assertion is true only when the current matching position is at the start point of the match, as specified by the offset argument of preg_match(). It differs from \A when the value of offset is non-zero. It is available since PHP 4.3.3. \Q and \E can be used to ignore regexp metacharacters in the pattern since PHP 4.3.3. For example: \w+\Q.$.\E$ will match one or more word characters, followed by literals .$. and anchored at the end of the string.

Examples :
^Quit           -          Matches any string that starts with "Quit"
^ouch$        -          String that starts and ends with "ouch"
foo              -          Matches a string "foo"
foo$            -          "foo" at the end of a string
^foo$          -          "foo" when it is alone on a string
[abc]           -          a, b, or c
[a-z]            -          Any lowercase letter
[^A-Z]        -          Any character that is not a uppercase letter
(gif|jpg)        -          Matches either "gif" or "jpeg"
[a-z]+          -          One or more lowercase letters
[0-9\.\-]       -          Аny number, dot, or minus sign
^[a-zA-Z0-9_]{1,}$          -         Any word of at least one letter, number or _
([wx])([yz])          -         wy, wz, xy, or xz
[^A-Za-z0-9]      -         Any symbol (not a number or a letter)
([A-Z]{3}|[0-9]{4})         -         Matches three letters or four numbers
apple*         -       Matches a string like ("apple", "appleee", "appl" etc..) - 0 or more e's
apple+         -       Matches a string like ("apple", "appleee", etc..) - 1 or more e's
apple?         -       Matches a string like ("apple", "appl") - 0 or 1
we{3}         -       Matches a string that has an a followed by exactly three e's ("weee")
we{,3}        -      Matches a string at least three e's ("weee", "weeee", etc)
we{3,5}      -      Matches a string from three to five e's ("weee", "weeee", etc)


For more info refer to http://www.php.net/ site. Click here.

Thursday, October 8, 2009

How do I get local date & time with the PHP date & time function?

PHP's int time() function returns the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT). The string date ( string format [, int timestamp] ) returns a string formatted according to the given format string using the given integer timestamp or the current time if no timestamp is given. In other words, timestamp is optional and defaults to the value of time(). If you want to have a manual date timezone convertion see the code below.

Example

<?php 
    $gmt_timezone_offset = +8;
    $time = time();
    $my_gmt_timezone = $time + ($gmt_timezone_offset * 60 * 60);
    echo date("Y-m-d H:i:s", $my_gmt_timezone);
?>

Or Simply, you can do this:
<?php 
    // put this code at the very top of your file
    ini_set('date.timezone', "Asia/Taipei");
    ...
?>

Or you can modify php.ini.

...
date.timezone = "Asia/Taipei"
...

Or you can modify .htaccess
...
php_value date.timezone Asia/Taipei
# or
php_value date.timezone UTC
...

The following table indicates each timezone and its location. Below are the list of timezone reference:

http://php.net/manual/en/timezones.php

OR

Time Zone Location
UM12 (UTC - 12:00) Enitwetok, Kwajalien
UM11 (UTC - 11:00) Nome, Midway Island, Samoa
UM10 (UTC - 10:00) Hawaii
UM9 (UTC - 9:00) Alaska
UM8 (UTC - 8:00) Pacific Time
UM7 (UTC - 7:00) Mountain Time
UM6 (UTC - 6:00) Central Time, Mexico City
UM5 (UTC - 5:00) Eastern Time, Bogota, Lima, Quito
UM4 (UTC - 4:00) Atlantic Time, Caracas, La Paz
UM25 (UTC - 3:30) Newfoundland
UM3 (UTC - 3:00) Brazil, Buenos Aires, Georgetown, Falkland
Is.
UM2 (UTC - 2:00) Mid-Atlantic, Ascention Is., St Helena
UM1 (UTC - 1:00) Azores, Cape Verde Islands
UTC (UTC) Casablanca, Dublin, Edinburgh, London, Lisbon, Monrovia
UP1 (UTC + 1:00) Berlin, Brussels, Copenhagen, Madrid, Paris,
Rome
UP2 (UTC + 2:00) Kaliningrad, South Africa, Warsaw
UP3 (UTC + 3:00) Baghdad, Riyadh, Moscow, Nairobi
UP25 (UTC + 3:30) Tehran
UP4 (UTC + 4:00) Adu Dhabi, Baku, Muscat, Tbilisi
UP35 (UTC + 4:30) Kabul
UP5 (UTC + 5:00) Islamabad, Karachi, Tashkent
UP45 (UTC + 5:30) Bombay, Calcutta, Madras, New Delhi
UP6 (UTC + 6:00) Almaty, Colomba, Dhaka
UP7 (UTC + 7:00) Bangkok, Hanoi, Jakarta
UP8 (UTC + 8:00) Beijing, Hong Kong, Perth, Singapore, Taipei
UP9 (UTC + 9:00) Osaka, Sapporo, Seoul, Tokyo, Yakutsk
UP85 (UTC + 9:30) Adelaide, Darwin
UP10 (UTC + 10:00) Melbourne, Papua New Guinea, Sydney, Vladivostok
UP11 (UTC + 11:00) Magadan, New Caledonia, Solomon Islands
UP12 (UTC + 12:00) Auckland, Wellington, Fiji, Marshall Island

Tuesday, September 29, 2009

Introduction - Learn PHP

Learn PHP


Before we start, we have to know first more about PHP. PHP stands for PHP Hypertext Preprocessor is a server-side scripting language, and server-sidescripts are special commands you must place in Web pages. Those commands are processed before the pages are sent from your Server to the Web browser of your visitor. A typical PHP files will content commads to be executed in the server in addition to the usual mixture of text and HTML (Hypertext Markup Language) tags.

What Can You Do with PHP?


Anything. PHP is mainly focused on server-side scripting, so you can do anything any other CGI program can do, such as collect form data, generate dynamic page content, or send and receive cookies. But PHP can do much more.

There are three main areas where PHP scripts are used.

Server-side scripting. This is the most traditional and main target field for PHP. You need three things to make this work. The PHP parser (CGI or server module), a web server and a web browser. You need to run the web server, with a connected PHP installation. You can access the PHP program output with a web browser, viewing the PHP page through the server. All these can run on your home machine if you are just experimenting with PHP programming. See the installation instructions section for more information.


Command line scripting. You can make a PHP script to run it without any server or browser. You only need the PHP parser to use it this way. This type of usage is ideal for scripts regularly executed using cron (on *nix or Linux) or Task Scheduler (on Windows). These scripts can also be used for simple text processing tasks. See the section about Command line usage of PHP for more information.

Writing desktop applications. PHP is probably not the very best language to create a desktop application with a graphical user interface, but if you know PHP very well, and would like to use some advanced PHP features in your client-side applications you can also use PHP-GTK to write such programs. You also have the ability to write cross-platform applications this way. PHP-GTK is an extension to PHP, not available in the main distribution. If you are interested in PHP-GTK, visit » its own website.

PHP can be used on all major operating systems, including Linux, many Unix variants (including HP-UX, Solaris and OpenBSD), Microsoft Windows, Mac OS X, RISC OS, and probably others. PHP has also support for most of the web servers today. This includes Apache, Microsoft Internet Information Server, Personal Web Server, Netscape and iPlanet servers, Oreilly Website Pro server, Caudium, Xitami, OmniHTTPd, and many others. For the majority of the servers, PHP has a module, for the others supporting the CGI standard, PHP can work as a CGI processor.

So with PHP, you have the freedom of choosing an operating system and a web server. Furthermore, you also have the choice of using procedural programming or object oriented programming, or a mixture of them. Although not every standard OOP feature is implemented in PHP 4, many code libraries and large applications (including the PEAR library) are written only using OOP code. PHP 5 fixes the OOP related weaknesses of PHP 4, and introduces a complete object model.

With PHP you are not limited to output HTML. PHP's abilities includes outputting images, PDF files and even Flash movies (using libswf and Ming) generated on the fly. You can also output easily any text, such as XHTML and any other XML file. PHP can autogenerate these files, and save them in the file system, instead of printing it out, forming a server-side cache for your dynamic content.

One of the strongest and most significant features in PHP is its support for a wide range of databases. Writing a database-enabled web page is incredibly simple. The following databases are currently supported:







* Adabas D
* dBase
* Empress
* FilePro (read-only)
* Hyperwave
* IBM DB2
* Informix
* Ingres
* InterBase
* FrontBase
* mSQL
* Direct MS-SQL
* MySQL
* ODBC
* Oracle (OCI7 and OCI8)
* Ovrimos
* PostgreSQL
* SQLite
* Solid
* Sybase
* Velocis
* Unix dbm
We also have a database abstraction extension (named PDO) allowing you to transparently use any database supported by that extension. Additionally PHP supports ODBC, the Open Database Connection standard, so you can connect to any other database supporting this world standard.

PHP also has support for talking to other services using protocols such as LDAP, IMAP, SNMP, NNTP, POP3, HTTP, COM (on Windows) and countless others. You can also open raw network sockets and interact using any other protocol. PHP has support for the WDDX complex data exchange between virtually all Web programming languages. Talking about interconnection, PHP has support for instantiation of Java objects and using them transparently as PHP objects. You can also use our CORBA extension to access remote objects.

PHP has extremely useful text processing features, from the POSIX Extended or Perl regular expressions to parsing XML documents. For parsing and accessing XML documents, PHP 4 supports the SAX and DOM standards, and you can also use the XSLT extension to transform XML documents. PHP 5 standardizes all the XML extensions on the solid base of libxml2 and extends the feature set adding SimpleXML and XMLReader support.

At last but not least, we have many other interesting extensions, the mnoGoSearch search engine functions, the IRC Gateway functions, many compression utilities (gzip, bz2, zip), calendar conversion, translation...

As you can see this page is not enough to list all the features and benefits PHP can offer. Read on in the sections about installing PHP, and see the function reference part for explanation of the extensions mentioned here.

What you should know

Before starting this tutorial it is important that you have a basic understanding and experience in the following:

* HTML - Know the syntax and especially HTML Forms.
* Basic programming knowledge - This isn't required, but if you have any traditional programming experience it will make learning PHP a great deal easier.

Source: http://us.php.net/manual/en/intro-whatcando.php