PHP Introduction
PHP
Three letters that together constitutes the name of one of the
world’s most popular programming languages for Web development, the
PHP Hypertext Preprocessor.
Advantage of PHP
-
Performance
-
Portability(Platform Independent)
-
Ease Of Use
-
Open Source
-
Third-Party Application Support
-
Community Support
PHP Environment Start – End
syntax
is a way to representation of PHP script.
Basically
it gives the primary idea to specify the code format.
It also
specify the area of a written code.
The most commonly and effective PHP syntax:
<?php
echo
"Welcome to the world of php";
?>
In the
given Example
It
begin with (< ?php) and End with(? >).
echo
statement is used to print the given string. Mandatory closing in(“my
statement”)double quotes.
Terminate
the script with semicolon because semicolon is known as terminator.
Short or short-open tags look like this:
<?
echo
"welcome to the world of php";
?>
HTML script tags:
<script
language="PHP">
echo "welcome to the world of php";
</script>
PHP Variables
Variable
is nothing it is just name of the memory location.
A
Variable is simply a container i.e used to store both numeric and
non-numeric information.
Rules for Variable declaration
-
Variables in PHP starts with a dollar($) sign, followed by the name of the variable.
-
The variable name must begin with a letter or the underscore character.
-
A variable name can only contain alphanumeric characters and underscores (A-z, 0-9, and _ )
-
A variable name should not contain space
Assigning Values to Variables
Assigning
a value to a variable in PHP is quite east: use the equality(=)
symbol, which also to the PHP’s assignment operators.
This
assign value on the right side of the equation to the variable on the
left.
A
variable is created the moment you assign a value to it:
<?php
$myCar = "K S Ford";
echo
$myCar;
?>
Output: K
S Ford
PHP Concatenation
<?php
$myCar = "Honda City";
echo
$myCar." is riding";
?>
Output:
Honda
City is riding
In the
above example
Variable($mycar)
hold value=”honda city”. Now we wants to concatenate variable
with string.
pass
this variable($mycar) inside echo statement.
To
concatenate this with a string(“is riding”) use dot(.) between
variable name and string.
The
output will be displayed : Honda City is riding.
Constant in PHP
-
Constants are PHP container that remain constant and never change
-
Constants are used for data that is unchanged at multiple place within our program.
-
Variables are temporary storage while Constants are permanent.
-
Use Constants for values that remain fixed and referenced multiple times.
Rules for defining constant
-
Constants are defined using PHP’s define( ) function, which accepts two arguments:
-
The name of the constant, and its value.
-
Constant name must follow the same rules as variable names, with one exception the “$” prefix is not required for constant names.
<?php
define('ConstName',
'value');
?>
Example:-
<?php
define('ONE',
100);
define('TWO',
100);
define('SUM',ONE+TWO);
print
"Sum of two constant=".SUM;
?>
Output:
Sum of
two constant = 200
PHP data types
Data
types specify the size and type of values that can be stored.
Variables
does not need to be declared ITS DATA TYPE adding a value to it.
PHP is
a Loosely Typed Language so here no need to define data type.
To
check only data type use gettype( ) function.
To
check value, data type and size use var_dump( ) function.
<?php
$num=100;
$fnum=100.0;
$str="Hello";
var_dump($num,$fnum,$str);
?>
Output
int(100)
float(100) string(5) “Hello”
Data types in PHP
There
are 3 types of DATA TYPE
-
Scalar(predefined)
-
Compound(user-defined)
-
Special type
Scalar(It holds only single value)
-
Integer
-
Float/double
-
String
-
Boolean
Compound(Multiple values in single variable)
-
Array
-
Object
Array Data type
<?php
$arr=array(10,20,30,40,50);
var_dump($arr);
?>
Output
array(5)
{ [0]=> int(10) [1]=> int(20) [2]=> int(30) [3]=> int(40)
[4]=> int(50) }
Object Data type
<?php
class
Demo
{
public
function show()
{
echo
"You Are In method<br/>";
}
}
$obj=
new Demo();
$obj->show();
?>
Output
You Are
In method
Special Data types
-
Null
-
Resource
Null Data type
The
special Data type “NULL” represents a variable with no value
Resource Data Type
The
special resource type is not an actual data type. It is the storing
of a reference to functions and resources external to PHP.
PHP Form Example
PHP
form is used to take input from users. in PHP if you want to take
input from keyboard and display the output according to input, in
that case you have to use html form.
html
form’s have a property : form method in which you have to set
either get or post method.
<html>
<head>
<title>form
method</title>
</head>
<body>
<form
method="post">
<h2>Select
Your car</h2>
<table
border="1" align="center">
<tr>
<td>Select
Your car</td>
<td>
<Selct
name="selType">
<option
value="porsche 911">Porsche 911</option>
<option
value="Volkswagen Beetle">Volkswagen Beetle</option>
<option
value="Ford Taurus">Ford Taurus</option>
</select>
</td>
</tr>
<tr>
<td>Color:</td>
<td><input
type="text" name="txtColor"/>
</td>
</tr>
<tr>
<td><input
type="submit"/>
</td>
</tr>
</table">
</form>
</body>
</html>
<?php
error_reporting(1);
$type=$_POST['selType'];
$color=$_POST['txtColor'];
echo
"<font color='blue'>Your $color $type is ready. safe
driving! </font>";
?>
Output
Run On
Browser
Form GET Method
GET
method is unsecured method because it display all information on
address bar/ url.
By
default method is get method. Using GET method limited data sends.
GET method is faster way to send data.
When to use GET?
Information
sent from a form with the GET method is visible to everyone (all
variable names and values are displayed in the URL). GET also has
limits on the amount of information to send. The limitation is about
2000 characters. However, because the variables are displayed in the
URL, it is possible to bookmark the page. This can be useful in some
cases.
GET may
be used for sending non-sensitive data.
Enter two number and print the sum of given numbers.
<html>
<head>
<title>get_browser</title>
<?php
error_reporting(1);
$x=$_GET['f'];
$y=$_GET['s'];
$z=$x+$y;
echo
"Sum of two number = ".$z;
?>
</head>
<body
bgcolor="sky color">
<form
method="GET" >
<table
border="1" bgcolor="green">
<tr>
<td>Enter
your first number</td>
<td><input
type="text" name="f"/></td>
</tr>
<tr>
<td>Enter
your second number</td>
<td><input
type="text" name="s"/></td>
</tr>
<tr
align="center">
<td
colspan="2" >
<input
type="submit" value="+"/></td>
</tr>
</table>
</form>
</body>
</html>
user
has to enter the first number, second number
after
given the input click on “+” button, and check the output means
the sum of two numbers.
can
also see the input given by him/her displays on address-bar(URL).
Form POST Method
POST
method is secured method because it hides all information.
Using
POST method unlimited data sends . POST method is slower method
comparatively GET method.
When to use POST?
Information
sent from a form with the POST method is invisible to others (all
names/values are embedded within the body of the HTTP request) and
has no limits on the amount of information to send.
Moreover
POST supports advanced functionality such as support for multi-part
binary input while uploading files to server.
<html>
<head>
<?php
echo
$_POST['n'];
?>
<title>get_browser</title>
</head>
<body
bgcolor="sky color">
<form
method="post">
<table
border="1" bgcolor="green">
<tr>
<td>Enter
your name</td>
<td><input
type="text" name="n"/></td>
</tr>
<tr>
<td
colspon="2" align="center">
<input
type="submit" value="show my name"/></td>
</tr>
</table>
</form>
</body>
</html>
user
enters the name inside text box, after entered the name inside text
box click on submit button it will display the name entered by user
like user enters “Phptpoint” inside the text box the output
displays “Phptpoint”.
In this
example we have used Form POST method. So the user’s input doesn’t
display on address-bar.
How to use HTML Form action
Action
is used to give reference/link of another page.
If we
want to separate the business logic (PHP script) from Presentation
layer (HTML script) then use action Property of Form .
It
reduce the complexity of bulk of codes. Because All scripts are
separately define on their own page.
Using
action property HTML script define on a separate page and Business
logic(PHP script) on another separate page.
Create HTML Form with action Property
Save as
demo.php
<body>
<form
method="post" action="Logic.php">
<table
border="1" align="center">
<tr>
<td>Enter
your name</td>
<td><input
type="text" name="n"/></td>
</tr>
<tr>
<td>Enter
your age</td>
<td><input
type="text" name="a"/></td>
</tr>
<tr>
<td
colspan="2" align="center">
<input
type="submit" name="sub" value="SHOW MY
NAME"/>
</td>
</tr>
</table>
</form>
</body>
Save as
Logic.php
<?php
$name=$_POST['n'];
$age =
$_POST['a'];
echo
"Welcome ".$name,"<br>" .$age;
?>
PHP Operators
Operators
are used to perform operations on variables and values.
PHP
divides the operators in the following groups:
-
Arithmetic operators
-
Assignment operators
-
Comparison operators
-
Increment/Decrement operators
-
Logical operators
-
String operators
-
Array operators
Arithmetic Operators
The PHP
arithmetic operators are used with numeric values to perform common
arithmetical operations, such as addition, subtraction,
multiplication etc.
Operator
|
Name
|
Example
|
Result
|
+
|
Addition
|
$x + $y
|
Sum of $x and $y
|
-
|
Subtraction
|
$x - $y
|
Difference of $x and $y
|
*
|
Multiplication
|
$x * $y
|
Product of $x and $y
|
/
|
Division
|
$x / $y
|
Quotient of $x and $y
|
%
|
Modulus
|
$x % $y
|
Remainder of $x divided by $y
|
**
|
Exponentiation
|
$x ** $y
|
Result of raising $x to the $y'th power
(Introduced in PHP 5.6)
|
Assignment Operators
The PHP
assignment operators are used with numeric values to write a value to
a variable.
The
basic assignment operator in PHP is "=". It means that the
left operand gets set to the value of the assignment expression on
the right.
Assignment
|
Same as...
|
Description
|
x = y
|
x = y
|
The left operand gets set to the value of the
expression on the right
|
x += y
|
x = x + y
|
Addition
|
x -= y
|
x = x - y
|
Subtraction
|
x *= y
|
x = x * y
|
Multiplication
|
x /= y
|
x = x / y
|
Division
|
x %= y
|
x = x % y
|
Modulus
|
Comparison Operators
The PHP
comparison operators are used to compare two values (number or
string):
Operator
|
Name
|
Example
|
Result
|
==
|
Equal
|
$x == $y
|
Returns true if $x is equal to $y
|
===
|
Identical
|
$x === $y
|
Returns true if $x is equal to $y, and they are of
the same type
|
!=
|
Not equal
|
$x != $y
|
Returns true if $x is not equal to $y
|
<>
|
Not equal
|
$x <> $y
|
Returns true if $x is not equal to $y
|
!==
|
Not identical
|
$x !== $y
|
Returns true if $x is not equal to $y, or they are
not of the same type
|
>
|
Greater than
|
$x > $y
|
Returns true if $x is greater than $y
|
<
|
Less than
|
$x < $y
|
Returns true if $x is less than $y
|
>=
|
Greater than or equal to
|
$x >= $y
|
Returns true if $x is greater than or equal to $y
|
<=
|
Less than or equal to
|
$x <= $y
|
Returns true if $x is less than or equal to $y
|
Increment / Decrement Operators
The PHP
increment operators are used to increment a variable's value.
The PHP
decrement operators are used to decrement a variable's value.
Operator
|
Name
|
Description
|
++$x
|
Pre-increment
|
Increments $x by one, then returns $x
|
$x++
|
Post-increment
|
Returns $x, then increments $x by one
|
--$x
|
Pre-decrement
|
Decrements $x by one, then returns $x
|
$x--
|
Post-decrement
|
Returns $x, then decrements $x by one
|
Logical Operators
The PHP
logical operators are used to combine conditional statements.
Operator
|
Name
|
Example
|
Result
|
and
|
And
|
$x and $y
|
True if both $x and $y are true
|
or
|
Or
|
$x or $y
|
True if either $x or $y is true
|
xor
|
Xor
|
$x xor $y
|
True if either $x or $y is true, but not both
|
&&
|
And
|
$x && $y
|
True if both $x and $y are true
|
||
|
Or
|
$x || $y
|
True if either $x or $y is true
|
!
|
Not
|
!$x
|
True if $x is not true
|
String Operators
PHP has
two operators that are specially designed for strings.
Operator
|
Name
|
Example
|
Result
|
.
|
Concatenation
|
$txt1 . $txt2
|
Concatenation of $txt1 and $txt2
|
.=
|
Concatenation assignment
|
$txt1 .= $txt2
|
Appends $txt2 to $txt1
|
Array Operators
The PHP
array operators are used to compare arrays.
Operator
|
Name
|
Example
|
Result
|
+
|
Union
|
$x + $y
|
Union of $x and $y
|
==
|
Equality
|
$x == $y
|
Returns true if $x and $y have the same key/value
pairs
|
===
|
Identity
|
$x === $y
|
Returns true if $x and $y have the same key/value
pairs in the same order and of the same types
|
!=
|
Inequality
|
$x != $y
|
Returns true if $x is not equal to $y
|
<>
|
Inequality
|
$x <> $y
|
Returns true if $x is not equal to $y
|
!==
|
Non-identity
|
$x !== $y
|
Returns true if $x is not identical to $y
|
PHP Conditional Statements
In PHP
we have the following conditional statements:
-
if statement - executes some code if one condition is true
-
if...else statement - executes some code if a condition is true and another code if that condition is false
-
if...elseif....else statement - executes different codes for more than two conditions
-
switch statement - selects one of many blocks of code to be executed
The if Statement
The if
statement executes some code if one condition is true.
Syntax
if
(condition) {
code
to be executed if condition is true;
}
The
example below will output "Have a good day!" if the current
time (HOUR) is less than 20:
Example
<?php
$t =
10;
if ($t
< "20") {
echo "Have a good day!";
}
?>
The if...else Statement
The
if....else statement executes some code if a condition is true and
another code if that condition is false.
Syntax
if
(condition) {
code to be executed if condition is true;
} else
{
code to be executed if condition is false;
}
Example
<?php
$t =
10;
if ($t
<20) {
echo "Have a good day!";
} else
{
echo "Have a good night!";
}
?>
The if...elseif....else Statement
The
if....elseif...else statement executes different codes for more than
two conditions.
Syntax
if
(condition) {
code to be executed if this condition is true;
}
elseif (condition) {
code to be executed if this condition is true;
} else
{
code to be executed if all conditions are false;
}
Example
<?php
$t =
10;
if ($t
<10) {
echo "Have a good morning!";
}
elseif ($t < 10) {
echo "Have a good day!";
} else
{
echo "Have a good night!";
}
?>
PHP switch Statement
Use the
switch statement to select one of many blocks of code to be executed.
Syntax
switch
(n) {
case
label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}
Example
<?php
$favcolor
= "red";
switch
($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>
Loops
Often
when you write code, you want the same block of code to run over and
over again in a row. Instead of adding several almost equal
code-lines in a script, we can use loops to perform a task like this.
In PHP,
we have the following looping statements:
-
while - loops through a block of code as long as the specified condition is true
-
do...while - loops through a block of code once, and then repeats the loop as long as the specified condition is true
-
for - loops through a block of code a specified number of times
-
foreach - loops through a block of code for each element in an array
The PHP while Loop
The
while loop executes a block of code as long as the specified
condition is true.
Syntax
while
(condition is true) {
code
to be executed;
}
Example
<?php
$x = 1;
while($x
<= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
do...while Loop
The
do...while loop will always execute the block of code once, it will
then check the condition, and repeat the loop while the specified
condition is true.
Syntax
do {
code to be executed;
} while
(condition is true);
Example
<?php
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while
($x <= 5);
?>
for Loop
The for
loop is used when you know in advance how many times the script
should run.
Syntax
for
(init counter; test counter; increment counter) {
code to be executed;
}
Parameters:
-
init counter: Initialize the loop counter value
-
test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends.
-
increment counter: Increases the loop counter value
Example
<?php
for ($x
= 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
foreach Loop
The
foreach loop works only on arrays, and is used to loop through each
key/value pair in an array.
Syntax
foreach
($array as $value) {
code to be executed;
}
For
every loop iteration, the value of the current array element is
assigned to $value and the array pointer is moved by one, until it
reaches the last array element.
Example
<?php
$colors
= array("red", "green", "blue",
"yellow");
foreach
($colors as $value) {
echo "$value <br>";
}
?>
Functions
The
real power of PHP comes from its functions; it has more than 1000
built-in functions.
PHP User Defined Functions
Besides
the built-in PHP functions, we can create our own functions.
A
function is a block of statements that can be used repeatedly in a
program.
A
function will not execute immediately when a page loads.
A
function will be executed by a call to the function.
Create a User Defined Function in PHP
A
user-defined function declaration starts with the word function:
Syntax
function
functionName() {
code to be executed;
}
Note: A
function name can start with a letter or underscore (not a number).
Example
<?php
function
writeMsg() {
echo "Hello world!";
}
writeMsg();
// call the function
?>
Function Arguments
Information
can be passed to functions through arguments. An argument is just
like a variable.
Arguments
are specified after the function name, inside the parentheses. You
can add as many arguments as you want, just separate them with a
comma.
Example
<?php
function
familyName($fname) {
echo "$fname Chahar.<br>";
}
familyName("pk");
familyName("sk");
familyName("lk");
familyName("vk");
familyName("ak");
?>
function
with two arguments ($fname and $year):
<?php
function
familyName($fname, $year) {
echo "$fname Chahar. Born in $year <br>";
}
familyName("pk",
"1975");
familyName("sk",
"1978");
familyName("lk",
"1983");
?>
Output:
pk
Chahar. Born in 1975
sk
Chahar. Born in 1978
lk
Chahar. Born in 1983
Functions - Returning values
To let
a function return a value, use the return statement:
Example
<?php
function
sum($x, $y) {
$z
= $x + $y;
return $z;
}
echo "5
+ 10 = " . sum(5, 10) . "<br>";
echo "7
+ 13 = " . sum(7, 13) . "<br>";
echo "2
+ 4 = " . sum(2, 4);
?>
Arrays
An
array stores multiple values in one single variable.
An
array is a special variable, which can hold more than one value at a
time.
In PHP,
the array() function is used to create an array:
array();
In PHP,
there are three types of arrays:
-
Indexed arrays - Arrays with a numeric index
-
Associative arrays - Arrays with named keys
-
Multidimensional arrays - Arrays containing one or more arrays
Indexed Arrays
There
are two ways to create indexed arrays:
The
index can be assigned automatically (index always starts at 0), like
this:
$players
= array("Dhoni", "Raina", "Kohali");
or the
index can be assigned manually:
$players[0]
= "Dhoni";
$players[1]
= "Raina";
$players[2]
= "Kohali";
Example
<?php
$players
= array("Dhoni", "Raina", "Kohli");
echo "I
like " . $players[0] . ", " . $players[1] . " and
" . $players[2] . ".";
?>
-
The count() function is used to return the length (the number of elements) of an array:
Example
<?php
$players
= array("Dhoni", "Raina", "Kohli");
echo
count($players);
?>
Associative Arrays
Associative
arrays are arrays that use named keys that you assign to them.
There
are two ways to create an associative array:
$age =
array("Peter"=>"35", "Ben"=>"37",
"Joe"=>"43");
or:
$age['Peter']
= "35";
$age['Ben']
= "37";
$age['Joe']
= "43";
Example
<?php
$age =
array("Peter"=>"35", "Ben"=>"37",
"Joe"=>"43");
echo
"Peter is " . $age['Peter'] . " years old.";
?>
Multidimensional Arrays
A
multidimensional array is an array containing one or more arrays.
PHP
understands multidimensional arrays that are two, three, four, five,
or more levels deep. However, arrays more than three levels deep are
hard to manage for most people.
The
dimension of an array indicates the number of indices you need to
select an element.
-
For a two-dimensional array you need two indices to select an element
-
For a three-dimensional array you need three indices to select an element
Form Validation
The
HTML code of the form looks like this:
<form
method="post" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>">
When
the form is submitted, the form data is sent with method="post".
What is
the $_SERVER["PHP_SELF"] variable?
The
$_SERVER["PHP_SELF"] is a super global variable that
returns the filename of the currently executing script.
So, the
$_SERVER["PHP_SELF"] sends the submitted form data to the
page itself, instead of jumping to a different page. This way, the
user will get error messages on the same page as the form.
What is
the htmlspecialchars() function?
The
htmlspecialchars() function converts special characters to HTML
entities. This means that it will replace HTML characters like <
and > with < and >. This prevents attackers from
exploiting the code by injecting HTML or Javascript code (Cross-site
Scripting attacks) in forms.
Display The Error Messages
Then in
the HTML form, we add a little script after each required field,
which generates the correct error message if needed (that is if the
user tries to submit the form without filling out the required
fields):
Example
<!DOCTYPE
HTML>
<html>
<head>
<style>
.error
{color: #FF0000;}
</style>
</head>
<body>
<?php
//
define variables and set to empty values
$nameErr
= $emailErr = $genderErr = $websiteErr = "";
$name =
$email = $gender = $comment = $website = "";
if
($_SERVER["REQUEST_METHOD"] == "POST") {
if
(empty($_POST["name"])) {
$nameErr = "Name is required";
}
else {
$name = test_input($_POST["name"]);
}
if
(empty($_POST["email"])) {
$emailErr = "Email is required";
}
else {
$email = test_input($_POST["email"]);
}
if
(empty($_POST["website"])) {
$website = "";
}
else {
$website = test_input($_POST["website"]);
}
if
(empty($_POST["comment"])) {
$comment = "";
}
else {
$comment = test_input($_POST["comment"]);
}
if
(empty($_POST["gender"])) {
$genderErr = "Gender is required";
}
else {
$gender = test_input($_POST["gender"]);
}
}
function
test_input($data) {
$data
= trim($data);
$data
= stripslashes($data);
$data
= htmlspecialchars($data);
return $data;
}
?>
<h2>PHP
Form Validation Example</h2>
<p><span
class="error">* required field</span></p>
<form
method="post" action="<?php
echohtmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name:
<input type="text" name="name">
<span
class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email">
<span
class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="website">
<span
class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5"
cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender"
value="female">Female
<input type="radio" name="gender"
value="male">Male
<input type="radio" name="gender"
value="other">Other
<span
class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit"
value="Submit">
</form>
<?php
echo
"<h2>Your Input:</h2>";
echo
$name;
echo
"<br>";
echo
$email;
echo
"<br>";
echo
$website;
echo
"<br>";
echo
$comment;
echo
"<br>";
echo
$gender;
?>
</body>
</html>
Validate Name
The
code below shows a simple way to check if the name field only
contains letters and whitespace. If the value of the name field is
not valid, then store an error message:
$name =
test_input($_POST["name"]);
if
(!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
The
preg_match() function searches a string for pattern, returning true
if the pattern exists, and false otherwise.
PHP - Validate E-mail
The
easiest and safest way to check whether an email address is
well-formed is to use PHP's filter_var() function.
In the
code below, if the e-mail address is not well-formed, then store an
error message:
$email
= test_input($_POST["email"]);
if
(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
PHP - Validate URL
The
code below shows a way to check if a URL address syntax is valid
(this regular expression also allows dashes in the URL). If the URL
address syntax is not valid, then store an error message:
$website
= test_input($_POST["website"]);
if
(!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website))
{
$websiteErr = "Invalid URL";
}
Example
<!DOCTYPE
HTML>
<html>
<head>
<style>
.error
{color: #FF0000;}
</style>
</head>
<body>
<?php
//
define variables and set to empty values
$nameErr
= $emailErr = $genderErr = $websiteErr = "";
$name =
$email = $gender = $comment = $website = "";
if
($_SERVER["REQUEST_METHOD"] == "POST") {
if
(empty($_POST["name"])) {
$nameErr = "Name is required";
}
else {
$name = test_input($_POST["name"]);
//
check if name only contains letters and whitespace
if
(!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if
(empty($_POST["email"])) {
$emailErr = "Email is required";
}
else {
$email = test_input($_POST["email"]);
//
check if e-mail address is well-formed
if
(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if
(empty($_POST["website"])) {
$website = "";
}
else {
$website = test_input($_POST["website"]);
//
check if URL address syntax is valid
if
(!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website))
{
$websiteErr = "Invalid URL";
}
}
if
(empty($_POST["comment"])) {
$comment = "";
}
else {
$comment = test_input($_POST["comment"]);
}
if
(empty($_POST["gender"])) {
$genderErr = "Gender is required";
}
else {
$gender = test_input($_POST["gender"]);
}
}
function
test_input($data) {
$data
= trim($data);
$data
= stripslashes($data);
$data
= htmlspecialchars($data);
return $data;
}
?>
<h2>PHP
Form Validation Example</h2>
<p><span
class="error">* required field</span></p>
<form
method="post" action="<?php
echohtmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name:
<input type="text" name="name">
<span
class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email">
<span
class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="website">
<span
class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5"
cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender"
value="female">Female
<input type="radio" name="gender"
value="male">Male
<input type="radio" name="gender"
value="other">Other
<span
class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit"
value="Submit">
</form>
<?php
echo
"<h2>Your Input:</h2>";
echo
$name;
echo
"<br>";
echo
$email;
echo
"<br>";
echo
$website;
echo
"<br>";
echo
$comment;
echo
"<br>";
echo
$gender;
?>
</body>
</html>
PHP Date() Function
The PHP
date() function formats a timestamp to a more readable date and time.
Syntax
date(format,timestamp)
Parameter
|
Description
|
format
|
Required. Specifies the format of the timestamp
|
timestamp
|
Optional. Specifies a timestamp. Default is the
current date and time
|
Get a Simple Date
The
required format parameter of the date() function specifies how to
format the date (or time).
Here
are some characters that are commonly used for dates:
-
d - Represents the day of the month (01 to 31)
-
m - Represents a month (01 to 12)
-
Y - Represents a year (in four digits)
-
l (lowercase 'L') - Represents the day of the week
Example
<?php
echo
"Today is " . date("Y/m/d") . "<br>";
echo
"Today is " . date("Y.m.d") . "<br>";
echo
"Today is " . date("Y-m-d") . "<br>";
echo
"Today is " . date("l");
?>
Simple Time
Here
are some characters that are commonly used for times:
-
h - 12-hour format of an hour with leading zeros (01 to 12)
-
i - Minutes with leading zeros (00 to 59)
-
s - Seconds with leading zeros (00 to 59)
-
a - Lowercase Ante meridiem and Post meridiem (am or pm)
The
example below outputs the current time in the specified format:
Example
<?php
echo
"The time is " . date("h:i:sa");
?>
Time Zone
If the
time you got back from the code is not the right time, it's probably
because your server is in another country or set up for a different
timezone.
Example
<?php
date_default_timezone_set("America/New_York");
echo
"The time is " . date("h:i:sa");
?>
Date With PHP mktime()
The
optional timestamp parameter in the date() function specifies a
timestamp. If you do not specify a timestamp, the current date and
time will be used (as shown in the examples above).
The
mktime() function returns the Unix timestamp for a date. The Unix
timestamp contains the number of seconds between the Unix Epoch
(January 1 1970 00:00:00 GMT) and the time specified.
Syntax
mktime(hour,minute,second,month,day,year)
<?php
$d=mktime(11,
14, 54, 8, 12, 2014);
echo
"Created date is " . date("Y-m-d h:i:sa", $d);
?>
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)
|
very help full ..
ReplyDelete