Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
What is PHP
PHP was originally an abbreviation
of Personal Home Page (tools). The
language was initially developed by
Rasmas Lerdorf.
What is MySQL
MySQL is a relational database system that is used to
store information. MySQL can store many types of data
from something as tiny as a single character to as large
as complete files or graphics. Although it can be accessed
by most programing languages, it is often coupled with
PHP because they work together with ease. Information
stored in a MySQL database hosted on a web server can
be accessed from anywhere in the world with a computer.
This makes it a good way to store information that needs
the ability to change over time, but also needs to be
accessed over the net. Some examples that can utilize
MySQL are a web message board or a customer's shipping
status.
<!DOCTYPE html>
<html>
<body>
<?php
echo "My first PHP script!";
?>
</body>
</html>
What is PHP?
PHP is an acronym for "PHP:
Hypertext Preprocessor"
PHP is a widely-used, open source
scripting language
PHP scripts are executed on the
server
PHP is free to download and use
Why PHP?
PHP runs on various platforms (Windows, Linux,
Unix, Mac OS X, etc.)
PHP is compatible with almost all servers used
today (Apache, IIS, etc.)
PHP supports a wide range of databases
PHP is free. Download it from the official PHP
resource:www.php.net
PHP is easy to learn and runs efficiently on the
server side
What Do I Need?
To start using PHP, you can:
Find a web host with PHP and MySQL
support
Install a web server on your own PC,
and then install PHP and MySQL
PHP 5Syntax
A PHP script is executed on the
server, and the plain HTML result is
sent back to the browser.
Basic PHP Syntax
A PHP script can be placed anywhere
in the document.
A PHP script starts with<?phpand
ends with?>:
<?php
// PHP code goes here
?>
The default file extension for PHP
files is ".php".
A PHP file normally contains HTML
tags, and some PHP scripting code.
Below, we have an example of a simple PHP file, with a PHP script that
uses a built-in PHP function "echo" to output the text "Hello World!" on a
web page:
Example
<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>
Note:PHP statements end with a semicolon (;).
Comments in PHP
A comment in PHP code is a line that is not
read/executed as part of the program. Its only
purpose is to be read by someone who is looking at
the code.
Comments can be used to:
Let others understand what you are doing
Remind yourself of what you did - Most
programmers have experienced coming back to
their own work a year or two later and having to refigure out what they did. Comments can remind you
of what you were thinking when you wrote the code
In the example below, only the first statement will display the value of
the $color variable (this is because $color, $COLOR, and $coLOR are
treated as three different variables):
Example
<!DOCTYPE html>
<html>
<body>
<?php
$color = "red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";
?>
</body>
</html>
PHP Variables
A variable can have a short name (like x and y) or a
more descriptive name (age, carname, total_volume).
Rules for PHP variables:
A variable starts with the $ sign, followed by the name
of the variable
A variable name must start with a letter or the
underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric
characters and underscores (A-z, 0-9, and _ )
Variable names are case-sensitive ($age and $AGE are
two different variables)
Remember that PHP variable names are casesensitive!
Output Variables
The PHP echo statement is often used to
output data to the screen.
The following example will show how to
output text and a variable:
Example
<?php
$txt = "W3Schools.com";
echo "I love $txt!";
?>
Example
<?php
$txt = "W3Schools.com";
echo "I love " . $txt . "!";
?>
Destroying Variables
PHP 5Constants
Constants are like variables except that once
they are defined they cannot be changed or
undefined.
A constant is an identifier (name) for a simple
value. The value cannot be changed during the
script.
A valid constant name starts with a letter or
underscore (no $ sign before the constant
name).
Note:Unlike variables, constants are
automatically global across the entire script.
function myTest() {
echo GREETING;
}
myTest();
?>
Output :Welcome to W3Schools.com!
PHP - Functions
PHP functions are similar to other programming
languages. A function is a piece of code which
takes one more input in the form of parameter and
does some processing and returns a value.
You already have seen many functions
likefopen()andfread()etc. They are built-in
functions but PHP gives you option to create your
own functions as well.
There are two parts which should be clear to you
Creating a PHP Function
Calling a PHP Function
<html>
<head>
<title>Writing PHP Function</title>
</head>
<body>
<?php
/* Defining a PHP Function */
function writeMessage() {
echo "You are really a nice person, Have a nice time!";
}
/* Calling a PHP Function */
writeMessage();
?>
</body>
</html>
This will display following result
You are really a nice person, Have a nice time!
<html>
<head>
<title>Writing PHP Function with Parameters</title>
</head>
<body>
<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>
</body>
</html>
This will display following result
Sum of the two numbers is : 30
<html>
<head>
<title>Passing Argument by Reference</title>
</head>
<body>
<?php
function addFive($num) {
$num += 5;
}
function addSix(&$num) {
$num += 6;
}
$orignum = 10;
addFive( $orignum );
echo "Original Value is $orignum<br />";
addSix( $orignum );
echo "Original Value is $orignum<br />";
?>
</body>
</html>
<html>
<head>
<title>Writing PHP Function which returns value</title>
</head>
<body>
<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10, 20);
echo "Returned value from the function :
$return_value";
?>
</body>
</html>
This will display following result
Returned value from the function : 30
<html>
<head>
<title>Writing PHP Function which returns
value</title>
</head>
<body>
<?php
function printMe($param = NULL) {
print $param;
}
printMe("This is test");
printMe();
?>
</body>
</html>
This will produce following result
This is test
<html>
<head>
<title>Dynamic Function Calls</title>
</head>
<body>
<?php
function sayHello() {
echo "Hello<br />";
}
$function_holder = "sayHello";
$function_holder();
?>
</body>
</html>
This will display following result
Hello
<?php
//globalscope
$x=10;
functionvar_scope()
{
//localscope
$y=20;
echo"Thevalueofxis:$x"."<br/>";
echo"Thevalueofyis:$y"."<br/>";
}
var_scope();
echo"Thevalueofxis:$x"."<br/>";
echo"Thevalueofyis:$y";
?>
The
The
The
The
value
value
value
value
of
of
of
of
x
y
x
y
is
is
is
is
:
: 20
: 10
:
PHP String
A string is a sequence of characters, like "Hello world!".
A string can be any text inside quotes. You can use
single or double quotes:
Example
<?php
$x = "Hello world!";
$y = 'Hello world!';
echo $x;
echo "<br>";
echo $y;
?>
PHP Integer
An integer data type is a non-decimal number
between -2,147,483,648 and 2,147,483,647.
Rules for integers:
An integer must have at least one digit
An integer must not have a decimal point
An integer can be either positive or negative
Integers can be specified in three formats:
decimal (10-based), hexadecimal (16-based prefixed with 0x) or octal (8-based - prefixed
with 0)
PHP Float
A float (floating point number) is a number with
a decimal point or a number in exponential
form.
In the following example $x is a float. The PHP
var_dump() function returns the data type and
value:
Example
<?php
$x = 10.365;
var_dump($x);
?>
PHP Boolean
A Boolean represents two possible
states: TRUE or FALSE.
$x = true;
$y = false;
Booleans are often used in
conditional testing.
<?php
$height=100;
$width=50;
if($width)
{
echo"Theareaoftherectangleis".$height*$width;
}
else
{
echo"Thewidthneedstobeanon-zeronumber";
}
?>
In this example no comparison operator is used. But PHP
automatically converted $width value50 to its Boolean
equivalent true and calculate the area of the rectangle
i.e. execute the commands inside the if() statement.
PHP Object
An object is a data type which stores data and information on how to
process that data.
In PHP, an object must be explicitly declared.
First we must declare a class of object. For this, we use the class
keyword. A class is a structure that can contain properties and
methods:
Example
<?php
class Car {
function Car() {
$this->model = "VW";
}
}
// create an object
$herbie = new Car();
// show object properties
echo $herbie->model;
?>
<?php
// define string variable
$whoami = 'Sarah';
// output: 'string'
echo gettype($whoami);
// assign new integer value to variable
$whoami = 99.8;
// output: 'double'
echo gettype($whoami);
// destroy variable
unset($whoami);
// output: 'NULL'
echo gettype($whoami);
?>
This example introduces PHPs gettype() operator,
which is a handy little tool for finding out the type of
a particular variable.
Type Cast
its possible to explicitly set the type of a PHP
variable by casting a variable to a specific type
before using it.
Casting is a technique commonly used by Java
programmers; to use it, simply specify the
desired data type in parentheses on the right
side of the assignment equation.
Consider the following example, which
illustrates turning a floating-point value into an
integer value:
<?php
// define floating-point variable
$speed = 501.789;
// cast to integer
$newSpeed = (integer) $speed;
// output: 501
echo $newSpeed;
?>
PHP Array
An array in PHP is a collection of
key/value pairs. This means that it
maps values to keys.
Array keys (or indexes) may be either
an integers or a strings whereas
values can be any type. Example
Array() construct
An array can be declared using the array() language
construct, which generally takes the following format.
<p>array(key1=>value1,
key2=>value3,
key3=>value3,
..........)</p>
Key1, key2, key3 may be an integer or string.
value1, value2, value3 may be any value of any type.
As of PHP 5.4 a short array syntax [] is used instead
of array().
<?php
$fruits=array(
fruit1=>"Banana",
fruit2=>"Apple"
);
//declaringtheabovearrayasofPHP5.4
$fruits=[
fruit1=>"Banana",
fruit2=>"Apple"
];
?>
<?php
$fruits=array(
0=>"Banana",
"fruit1"=>"Apple",
11=>"Mango",
-34=>"Coconut",
);
var_dump($fruits);
?>
Output :
<?php
$fruits=array(
"Banana",
11=>"Apple",
"Mango",
"fruit1"=>"Coconut",
);
var_dump($fruits);
?>
Output :
array(4) { [0]=> string(6) "Banana" [11]=> string(5) "Apple"
[12]=> string(5) "Mango" ["fruit1"]=> string(7) "Coconut" }
In the above example the third value "Mango" is assigned the key
12 because the largest integer key before that was 11.
<?php
// define array
$data = array('Monday', 'Tuesday',
'Wednesday');
// get array size
echo 'The array has ' . count($data) . '
elements';
?>
Multidimensional Arrays
A multi-dimensional array each element in the
main array can also be an array. And each
element in the sub-array can be an array, and
so on. Values in the multi-dimensional array are
accessed using multiple index.
Example
In this example we create a two dimensional
array to store marks of three students in three
subjects
Example
<?php
// define array
$cities = array('London', 'Paris', 'Madrid', 'Los
Angeles', 'Bombay', 'Jakarta');
// iterate over array
// print each value
for ($i=0; $i<count($cities); $i++) {
echo $cities[$i] . "\r\n";
}
?>
foreach
With a foreach loop, each time the loop runs, the
current array element is assigned to a temporary
variable, which can then be processed in any
way you pleaseprinted, copied to another
variable, used in a calculation, and so on.
Unlike a for loop, a foreach loop doesnt use a
counter; it automatically knows where it is in
the array, and it moves forward continuously
until it reaches the end of the array, at which
point it automatically halts.
<?php
// define array
$cities = array('London', 'Paris', 'Madrid', 'Los
Angeles', 'Bombay', 'Jakarta');
// iterate over array
// print each value
foreach ($cities as $c) {
echo "$c \r\n";
}
?>
<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>
PHP Resource
The special resource type is not an
actual data type. It is the storing of a
reference to functions and resources
external to PHP.
A common example of using the
resource data type is a database call.
PHP 5Strings
A string is a sequence of characters, like "Hello world!".
Reversing and Repeating Strings
The strlen() function returns the number of characters
in a string. Heres an example
of it in action:
<?php
// calculate length of string
// output: 17
$str = 'Welcome to Xanadu';
echo strlen($str);
?>
PHP also allows you to slice a string into smaller parts with
the substr() function, which accepts three arguments: the
original string, the position (offset) at which to start
slicing, and the number of characters to return from the
starting position. The following
listing illustrates this in action:
<?php
// extract substring
// output: 'come'
$str = 'Welcome to nowhere';
echo substr($str, 3, 4);
?>
NOTE
When using the substr() function, the first character of the string is
treated as offset 0, the second character as offset 1, and so on.
Comparing,
If you need to compare two strings, the strcmp()
function performs a case-sensitive comparison of
two strings, returning a negative value if the first
is less than the second, a positive value if its
the other way around, and zero if both strings are
equal. Here are some examples of how this
works:
<?php
// compare strings
$a = "hello";
$b = "hello";
$c = "hEllo";
// output: 0
echo strcmp($a, $b);
// output: 1
echo strcmp($a, $c);
Formatting Strings
PHPs trim() function can be used to remove
leading or trailing whitespace from a string;
this is quite useful when processing data
entered into a Web form. Heres an
example:
<?php
// remove leading and trailing whitespace
// output 'a b c'
$str = ' a
b
c ';
echo trim($str);
?>
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
<?php
// define variables
$x = 10;
$y = 5;
$z = 3;
// add
$sum = $x + $y;
echo "$x + $y = $sum\n";
// subtract
$diff = $x - $y;
echo "$x - $y = $diff\n";
// multiply
$product = $x * $y;
echo "$x * $y = $product\n";
// divide and get quotient
$quotient = $x / $y;
echo "$x / $y = $quotient\n";
// divide and get modulus
$modulus = $x % $y;
echo "$x % $y = $modulus\n";
?>
<?php
// define variables
$count = 7;
$age = 60;
$greeting = 'We';
// subtract 2 and re-assign new value to variable
// equivalent to $count = $count - 2
// output: 5
$count -= 2;
echo $count;
// divide by 5 and re-assign new value to variable
// equivalent to $age = $age / 5
// output: 12
$age /= 5;
echo $age;
// add new string and re-assign new value to variable
// equivalent to $greeting = $greeting . 'lcome!'
// output: 'Welcome!'
$greeting .= 'lcome!';
echo $greeting;
?>
<?php
// define variables
$p = 10;
$q = 11;
$r = 11.3;
$s = 11;
// test if $q is greater than $p
// returns true
echo ($q > $p);
// test if $q is less than $p
// returns false
echo ($q < $p);
// test if $q is greater than or equal to $s
// returns true
echo ($q >= $s);
// test if $r is less than or equal to $s
// returns false
echo ($r <= $s);
// test if $q is equal to $s
// returns true
echo ($q == $s);
// test if $q is equal to $r
// returns false
echo ($q == $r);
?>
<?php
// define variable
$count = 19;
// increment
$count++;
// output: 20
echo $count;
// now decrement
$count--;
// output: 19
echo $count;
?>
<?php
// define variables
$price = 100;
$size = 18;
// logical AND test
// returns true if both comparisons are true
// returns true here
echo ($price > 50 && $size < 25);
// logical OR test
// returns true if any of the comparisons are true
// returns false here
echo ($price > 150 || $size > 75);
// logical NOT test
// reverses the logical test
// returns false here
echo !($size > 10);
?>
<?php
// define variables
$country = 'England';
$city = 'London';
// combine into single string
// output: 'Welcome to London, the coolest
city in all of England'
echo 'Welcome to ' . $city . ', the coolest city
in all of ' . $country;
?>
PHP 5if...else...elseifStatements
Conditional statements are used to perform different actions
based on different conditions.
PHP Conditional Statements
Very often when you write code, you want to perform different
actions for different conditions. You can use conditional
statements in your code to do this.
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
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
}
?>
<?php
// repeat continuously until counter
becomes 10
// output:
for ($x=1; $x<10; $x++) {
echo "$x ";
}
?>
<?php
// define string
$str = 'tinker,tailor,soldier,spy';
// convert string to array
// output: ('tinker', 'tailor', 'soldier,
'spy')
$arr = explode(',', $str);
print_r($arr);
?>
<?php
// define array
$arr = array(7, 36, 5, 48, 28, 90, 91,
3, 67, 42);
// get min and max
// output: 'Minimum is 3 and
maximum is 91'
echo 'Minimum is ' . min($arr) . ' and
maximum is ' . max($arr);
?>
PHP allows you to slice an array into smaller parts with the
array_slice() function, which accepts three arguments: the
original array, the index position (offset) at which to start
slicing, and the number of elements to return from the
starting offset. The following listing illustrates this in action:
<?php
// define array
$rainbow = array('violet', 'indigo', 'blue', 'green', 'yellow',
'orange', 'red');
// extract 3 central values
// output: ('blue', 'green', 'yellow')
$arr = array_slice($rainbow, 2, 3);
print_r($arr);
?>
<?php
// define array
$movies = array('The Lion King', 'Cars', 'A Bug\'s
Life');
// remove element from beginning of array
array_shift($movies);
// remove element from end of array
array_pop($movies);
// add element to end of array
array_push($movies, 'Ratatouille');
// add element to beginning of array
array_unshift($movies, 'The Incredibles');
// print array
// output: ('The Incredibles', 'Cars', 'Ratatouille')
print_r($movies);
?>
Searching Arrays
The in_array() function looks through an array for a
specified value and returns true if found. Heres an
example, which searches the array $cities for the
string
'Barcelona':
<?php
// define array
$cities = array('London', 'Paris', 'Barcelona', 'Lisbon',
'Zurich');
// search array for value output :1
echo in_array('Barcelona', $cities);
?>
<?php
// define array
$cities = array(
"United Kingdom" => "London",
"United States" => "Washington",
"France" => "Paris",
"India" => "Delhi"
);
// search array for key
echo array_key_exists('India', $cities);
?>
Sorting Arrays
Merging Arrays
PHP lets you merge one array into another with its
array_merge() function, which accepts one or more array
variables. The following listing and output illustrates its use:
<?php
// define arrays
$dark = array('black', 'brown', 'blue');
$light = array('white', 'silver', 'yellow');
// merge arrays
// output: ('black', 'brown', 'blue',
// 'white', 'silver', 'yellow')
$colors = array_merge($dark, $light);
print_r($colors);
?>
Comparing Arrays
Doing Calculus
The log() function calculates the natural or base10 logarithm of a number, while the exp()
function calculates the exponent of a number.
Heres an example of both in action:
<?php
// calculate natural log of 100
// output: 2.30258509299
echo log(10);
// calculate log of 100, base 10
// output: 2
echo log(100,10);
// calculate exponent of 2.30258509299
// output: 9.99999999996
echo exp(2.30258509299);
?>
Generating Random
Numbers
Generating random numbers with PHP is pretty simple
too: the languages built-in rand() function automatically
generates a random integer greater than 0.
You can constrain it to a specific number range by
providing optional limits as arguments. The
following example illustrates:
<?php
// generate a random number
echo rand();
// generate a random number between 10 and 99
echo rand(10,99);
?>
<?php
// convert to binary
// output: 1000
echo decbin(8);
// convert to hexadecimal
// output: 8
echo dechex(8);
// convert to octal
// output: 10
echo decoct(8);
// convert from octal
// output: 8
echo octdec(10);
// convert from hexadecimal
// output: 101
echo hexdec(65);
// convert from binary
// output: 8
echo bindec(1000);
?>
PHPError Handling
The default error handling in PHP is very simple. An error
message with filename, line number and a message describing
the error is sent to the browser.
PHP Error Handling
When creating scripts and web applications, error handling is an
important part. If your code lacks error checking code, your
program may look very unprofessional and you may be open to
security risks.
This tutorial contains some of the most common error checking
methods in PHP.
We will show different error handling methods:
Simple "die()" statements
Custom errors and error triggers
Error reporting
To prevent the user from getting an error message like the one
above, we test whether the file exist before we try to access it:
<?php
if(!file_exists("welcome.txt")){
die("File not found");
} else {
$file=fopen("welcome.txt","r");
}
?>
Now if the file does not exist you get an error like this:
File not found
The code above is more efficient than the earlier code,
because it uses a simple error handling mechanism to stop the
script after the error.
Example
Testing the error handler by trying to output variable that does not
exist:
<?php
//error handler function
function customError($errno, $errstr) {
echo "<b>Error:</b> [$errno] $errstr";
}
//set error handler
set_error_handler("customError");
//trigger error
echo($test);
?>
The output of the code above should be something like this:
Error:[8] Undefined variable: test
Trigger an Error
In a script where users can input data it is useful to trigger errors
when an illegal input occurs. In PHP, this is done by the
trigger_error() function.
Example
In this example an error occurs if the "test" variable is bigger than
"1":
<?php
$test=2;
if ($test>1) {
trigger_error("Value must be 1 or below");
}
?>
The output of the code above should be something like this:
Notice: Value must be 1 or below
inC:\webfolder\test.phpon line6
Example
In this example an E_USER_WARNING occurs if the "test" variable is
bigger than "1". If an E_USER_WARNING occurs we will use our custom
error handler and end the script:
<?php
//error handler function
function customError($errno, $errstr){
echo "<b>Error:</b> [$errno] $errstr<br>";
echo "Ending Script";
die();
}
//set error handler
set_error_handler("customError",E_USER_WARNING);
//trigger error
$test=2;
if ($test>1){
trigger_error("Value must be 1 or below",E_USER_WARNING);
}
?>
The output of the code above should be something like this:
Error:[512] Value must be 1 or below
Ending Script
What is HTTP?
The Hypertext Transfer Protocol (HTTP) is designed to
enable communications between clients and servers.
HTTP works as a request-response protocol between a
client and server.
A web browser may be the client, and an application on
a computer that hosts a web site may be the server.
Example: A client (browser) submits an HTTP request to
the server; then the server returns a response to the
client. The response contains status information about
the request and may also contain the requested
content.
<?php
if( isset($_GET["name"])|| isset( $_GET["age"] ))
{
echo "Welcome ". $_GET['name']. "<br />";
echo "You are ". $_GET['age']. " years old.";
exit();
}
?>
<html>
<body>
<form action = "<?php $_PHP_SELF ?>" method = "GET">
Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>
</body>
</html>
issetDetermine if a variable is set and is notNULL
<?php
if( isset($_POST["name"]) ||isset( $_POST["age"] )) {
if (preg_match("/[^A-Za-z'-]/",$_POST['name'] )) {
die ("invalid name and name should be alpha");
}
echo "Welcome ". $_POST['name']. "<br />";
echo "You are ". $_POST['age']. " years old.";
exit();
}
?>
<html>
<body>
<form action = "<?php $_PHP_SELF ?>" method = "POST">
Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>
</body>
</html>
<?php
if( $_REQUEST["name"] || $_REQUEST["age"] ) {
echo "Welcome ". $_REQUEST['name']. "<br />";
echo "You are ". $_REQUEST['age']. " years old.";
exit();
}
?>
<html>
<body>
<form action = "<?php $_PHP_SELF ?>" method = "POST">
Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>
</body>
</html>
Form Handling
When the user fills out the form above and clicks the submit
button, the form data is sent for processing to a PHP file
named "welcome.php". The form data is sent with the HTTP
POST method.
To display the submitted data you could simply echo all the
variables. The "welcome.php" looks like this:
<html>
<body>
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>
</body>
</html>
The same result could also be achieved using the HTTP GET
method:
Example
<html>
<body>
PHP - Cookies
Cookies are text files stored on the client computer and
they are kept of use tracking purpose. PHP transparently
supports HTTP cookies.
There are three steps involved in identifying returning
users
Server script sends a set of cookies to the browser. For
example name, age, or identification number etc.
Browser stores this information on local machine for
future use.
When next time browser sends any request to web server
then it sends those cookies information to the server and
server uses that information to identify the user.
<head>
<body>
<?php
/* is equivalent to */
/* is equivalent to */
?>
</body>
</html>
<?php
if( isset($_COOKIE["name"]))
else
?>
</body>
</html>
<?php
setcookie( "name", "", time()- 60, "/","", 0);
setcookie( "age", "", time()- 60, "/","", 0);
?>
<html>
<head>
<title>Deleting Cookies with PHP</title>
</head>
<body>
<?php echo "Deleted Cookies" ?>
</body>
</html>
PHP - Sessions
An alternative way to make data accessible across
the various pages of an entire website is to use a
PHP Session.
A session creates a file in a temporary directory on
the server where registered session variables and
their values are stored. This data will be available
to all pages on the site during that visit.
The location of the temporary file is determined by
a setting in the php.inifile
calledsession.save_path. Before using any
session variable make sure you have setup this
path.
Put this code in a test.php file and load this file many times to see the result
<?php
session_start();
$_SESSION['counter'] += 1;
}else {
$_SESSION['counter'] = 1;
}
<head>
<body>
</html>
if (isset($_SESSION['counter'])) {
$_SESSION['counter'] = 1;
}else {
$_SESSION['counter']++;
}
echo ( $msg );
?>
<p>
To continue click following link <br />
<?php
$pattern = '/^[a-zA-Z0-9_.-]{4,20}$/';
$username = "this.is.a-demo_-";
if (preg_match($pattern,$username))
echo "Match";
else
echo "Not match";
?>
$pattern = '/^#(([a-fA-F0-9]{3}$)|([a-fA-F0-9]
{6}$))/';
$color = "#1AA";
if (preg_match($pattern,$color))
echo "Match";
else
echo "Not match";
<? php
$pattern = '/^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]
{2,5}$/';
$email = "john123.demo_.name@demo.info";
if (preg_match($pattern,$email))
echo "Match";
else
echo "Not match";
?>