DOC-20250213-WA0018.
DOC-20250213-WA0018.
PHP Introduction
PHP is an open-source, interpreted, and object-
oriented scripting language that can be executed
at the server-side..
MySQL
Informix
Oracle
Sybase,
PostgreSQL,
Generic ODBC,
PHP Introduction
<?php
<?php
/*
Anything placed
within comment
will not be displayed
on the browser;
*/
echo "Welcome to PHP multi line comment";
?>
PHP Case Sensitivity
In PHP, keyword (e.g., echo, if, else,
while), functions, user-defined
functions, classes are not case-
sensitive.
all variable names are case-sensitive
Hello world using echo Hello world using ECHO Hello world using EcHo
Example
<html>
<body>
<?php
echo "Hello world using echo </br>";
ECHO "Hello world using ECHO </br>";
EcHo "Hello world using EcHo </br>";
?>
</body>
</html>
Look at the below example that the variable
names are case sensitive
<html>
<body>
<?php
$color = "black";
echo "My car is ". $ColoR ."</br>";
echo "My dog is ". $color ."</br>";
echo "My Phone is ". $COLOR ."</br>";
?>
</body>
</html>
PHP Variables
> Variables are used for storing values, like text
strings, numbers or arrays.
> When a variable is declared, it can be used
over and over again in your script.
> All variables in PHP start with a $ sign symbol.
some important points to know about
variables:
As PHP is a loosely typed language, so we do not
need to declare the data types of the variables. It
automatically analyzes the values and makes
conversions to its correct data type.
After declaring a variable, it can be reused
throughout the code.
Assignment Operator (=) is used to assign the
value to a variable.
PHP Variables
echo $lang;
?>
Global variable
The global variables are the variables that are
declared outside the function.
These variables can be accessed anywhere in the
program
To access the global variable within a function,
use the GLOBAL keyword before the variable.
These variables can be directly accessed or used
outside the function without any keyword
Example:
<?php
$name = "Sanaya Sharma"; //Global Variable
function global_var()
{
global $name;
echo "Variable inside the function: ". $name;
echo "</br>";
}
global_var();
echo "Variable outside the function: ". $name;
?>
Example:2
<?php
$name = "Sanaya Sharma"; //global variable
function global_var()
{
echo "Variable inside the function: ". $name;
echo "</br>";
}
global_var();
?>
Using $GLOBALS instead of global
Another way to use the global variable inside the
function is predefined $GLOBALS array.
<?php
$num1 = 5; //global variable
$num2 = 13; //global variable
function global_var()
{
$sum = $GLOBALS['num1'] + $GLOBALS['num2'];
echo "Sum of global variables is: " .$sum;
}
global_var();
?>
What Happen
If two variables, local and global, have the
same name,
then the local variable has higher priority than
the global variable inside the function.
<?php
$x = 5;
function mytest()
{
$x = 7;
echo "value of x: " .$x;
}
mytest();
?>
Static variable
It is a feature of PHP to delete the variable,
once it completes its execution and memory is
freed. Sometimes we need to store a variable
even after completion of function execution.
Therefore, another important feature of
variable scoping is static variable
We use the static keyword before the variable
to define a variable, and this variable is called
as static variable.
Static variables exist only in a local function,
but it does not free its memory after the
program execution leaves the scope.
Example
<?php
function static_var()
{
static $num1 = 3; //static variable
$num2 = 6; //Non-static variable
$num1++; //increment in non-static variable
$num2++; //increment in static variable
echo "Static: " .$num1 ."</br>";
echo "Non-static: " .$num2 ."</br>";
}
static_var(); //first function call
static_var(); //second function call
?>
PHP Concatenation
> The concatenation operator (.) is used to put
two string values together.
> To concatenate two string variables together,
use the concatenation operator:
PHP Concatenation
<?php
const MESSAGE="Hello const by JavaTpoint PHP";
echo MESSAGE;
?>
Magic Constants
Magic constants are the predefined constants in PHP.
They start with double underscore (__) and ends with double
underscore.
They are similar to other predefined constants but as they
change their values with the context, they are called magic
constants.
There are nine magic constants in PHP. In which eight magic
constants start and end with double underscores (__).
1) _ _LINE_ _ 2) __FILE__ 3) __DIR__
Syntax:
if(condition)
{
//code to be executed
}
Example
<?php
$num=12;
if($num<100)
{
echo "$num is less than 100";
}
?>
PHP Conditional Statements
Use the if....else statement to execute some code if a condition is
true and another code if a condition is false.
Syntax
if(condition)
{
//code to be executed if true
}
Else
{
//code to be executed if false
}
Example
<?php
$num=12;
if($num%2==0)
{
echo "$num is even number";
}
else
{
echo "$num is odd number";
}
?>
If-else-if Statement
The PHP if-else-if is a special statement used to combine multiple if?.else
statements. So, we can check multiple conditions using this statement.
Syntax:
if (condition1)
{
//code to be executed if condition1 is true
}
elseif (condition2)
{
//code to be executed if condition2 is true
} elseif (condition3)
{
//code to be executed if condition3 is true
....
}
else
{
//code to be executed if all given conditions are false
}
PHP nested if Statement
The nested if statement contains the if block inside another if block.
The inner if statement executes only when specified condition in outer if
statement is true.
Syntax
if (condition)
{
//code to be executed if condition is true
if (condition)
{
//code to be executed if condition is true
}
}
Example
<?php
$age = 23;
$nationality = "Indian";
//applying conditions on nationality and age
if ($nationality == "Indian")
{
if ($age >= 18)
{
echo "Eligible to give vote";
}
else
{
echo "Not eligible to give vote";
}
}
?>
PHP Conditional Statements
PHP switch
PHP switch statement is used to execute one statement from multiple conditions.
It works like PHP if-else-if statement.
Important points to be noticed about switch case:
The default is an optional statement. Even it is not important, that default
must always be the last statement.
There can be only one default in a switch statement. More than one default
may lead to a Fatal error.
Each case can have a break statement, which is used to terminate the
sequence of statement.
The break statement is optional to use in switch. If break is not used, all the
statements will execute after finding matched case value.
PHP allows you to use number, character, string, as well as functions in switch
expression.
Nesting of switch statements is allowed, but it makes the program more
complex and less readable.
You can use semicolon (;) instead of colon (:). It will not generate any error.
Switch Flowchart
Loops in PHP
for Loop
PHP for loop can be used to traverse set of code for the
specified number of times.
Syntax:
for(initialization; condition;
increment/decrement)
{
//code to be executed
}
initialization -
Initialize the loop counter value.
The initial value of the for loop is done only
once.
This parameter is optional.
condition -
The loop execution depend on condition.
If TRUE, the loop execution continues,
otherwise the execution of the loop ends.
Increment/decrement -
It increments or decrements the value of
the variable.
Example
<?php
for($n=1;$n<=10;$n++)
{
echo "$n<br/>";
}
?>
foreach loop
The foreach loop is used to traverse the array elements.
It works only on array and object.
It will issue an error if you try to use it with the variables of
different datatype.
The foreach loop works on elements basis rather than index.
It provides an easiest way to iterate the elements of an array.
In foreach loop, we don't need to increment the value.
Syntax:
<?php
foreach( $array as $var )
{
//code to be executed
}
?>
Example
<?php
$season=array("summer","winter","spring","autumn");
foreach( $season as $arr )
{
echo "Season is: $arr<br />";
}
?>
While Loop
PHP while loop can be used to traverse set of code like for loop.
The while loop executes a block of code repeatedly until the condition is
FALSE.
Once the condition gets FALSE, it exits from the body of loop.
The while loop is also called an Entry control loop because the condition is
checked before entering the loop body. This means that first the condition is
checked. If the condition is true, the block of code will be executed.
while(condition) while(condition):
{
//code to be executed
//code to be executed
}
endwhile;
<?php
$i = 'A';
while ($i < 'H')
{
echo $i;
$i++;
echo "</br>";
}
?>
While Loop Example
<?php
$n=1;
while($n<=10)
{
echo "$n<br/>";
$n++;
}
?>
do-while loop
PHP do-while loop can be used to traverse set of code like php while loop.
The PHP do-while loop is guaranteed to run at least once.
The PHP do-while loop is used to execute a set of code of the program
several times
It executes the code at least one time always because the condition is
checked after executing the code.
Syntax
do
{
//code to be executed
}while(condition);
Example
<?php
$x = 1;
do {
echo "1 is not greater than 10.";
echo "</br>";
$x++;
} while ($x > 10);
echo $x;
?>
PHP Arrays
1. Indexed Array
2. Associative Array
3. Multidimensional Array
PHP Indexed Array/Numeric Arrays
$season=array("summer","winter","spring","autumn");
2nd way:
$season[0]="summer";
$season[1]="winter";
$season[2]="spring";
$season[3]="autumn";
Example
<?php
$season[0]="summer";
$season[1]="winter";
$season[2]="spring";
$season[3]="autumn";
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
Output:
Season are: summer, winter, spring and autumn
PHP Associative Arrays
With an associative array, each ID key is
associated with a value.
We can associate name with each array
elements in PHP using => symbol.
Two ways to define associative array:
1st way:
$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
2nd way:
$salary["Sonoo"]="350000";
$salary["John"]="450000";
$salary["Kartik"]="200000";
Example
<?php
$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
echo "John salary: ".$salary["John"]."<br/>";
echo "Kartik salary: ".$salary["Kartik"]."<br/>";
?>
<?php
$salary["Sonoo"]="350000";
$salary["John"]="450000";
$salary["Kartik"]="200000";
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
echo "John salary: ".$salary["John"]."<br/>";
echo "Kartik salary: ".$salary["Kartik"]."<br/>";
?>
PHP Multidimensional Arrays
$emp = array
(
array(1,"sonoo",400000),
array(2,"john",500000),
array(3,"rahul",300000)
);
Example
<?php
$emp = array
(
array(1,"sonoo",400000),
array(2,"john",500000),
array(3,"rahul",300000)
);
Syntax
array array ([ mixed $... ] )
<?php
$season=array("summer","winter","spring","autumn");
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
2) PHP array_change_key_case() function
PHP array_change_key_case() function changes the
case of all key of an array.
Syntax
Example
<?php
$salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
print_r(array_change_key_case($salary,CASE_UPPER));
?>
Output:
Array ( [SONOO] => 550000 [VIMAL] => 250000 [RATAN] => 200000 )
3) PHP array_chunk() function
PHP array_chunk() function splits array into chunks. By using
array_chunk() method, you can divide array into many parts.
Syntax
Example
<?php
$salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
print_r(array_chunk($salary,2));
?>
4) PHP count() function
PHP count() function counts all elements in an array.
Syntax
int count ( mixed $array_or_countable [, int $mode = COUNT_NORMAL ] )
Example
<?php
$season=array("summer","winter","spring","autumn");
echo count($season);
?>
Output: 4
a 5) PHP sort() function
PHP sort() function sorts all the elements in an
array.
Syntax
sort ( array &$array [, int $sort_flags = SORT_REGULAR ] )
Example
<?php
season=array("summer","winter","spring","autumn");
sort($season);
foreach( $season as $s )
{
echo "$s<br />";
}
?>
Output:
mn spring summer winter
6) PHP array_reverse() function
PHP array_reverse() function returns an
array containing elements in reversed order.
Syntax
Example
<?php
$season=array("summer","winter","spring","autumn");
$reverseseason=array_reverse($season);
foreach( $reverseseason as $s )
{
echo "$s<br />";
}
?>
7) PHP array_search() function
PHP array_search() function searches the specified
value in an array. It returns key if search is successful.
Syntax
Example
<?php
$season=array("summer","winter","spring","autumn");
$key=array_search("spring",$season);
echo $key;
?>
Output:
2
8) PHP array_intersect() function
PHP array_intersect() function returns the intersection of two
array. In other words, it returns the matching elements of two array.
Syntax
Example
<?php
$name1=array("sonoo","john","vivek","smith");
$name2=array("umesh","sonoo","kartik","smith");
$name3=array_intersect($name1,$name2);
foreach( $name3 as $n )
{
echo "$n<br />";
}
?>
Traversing an array
To traverse an array means to access each element
(item) stored in the array so that the data can be
checked or used as part of a process.
There are several ways to traverse arrays in PHP, and
the one you choose will depend on your data and the
task you're performing.
1. The foreach Construct. ...
2. The Iterator Functions. ...
3. Using a for Loop. ...
4. Calling a Function for Each Array Element. ...
5. Reducing an Array. ...
6. Searching for Values.
The implode() function
The implode() function returns a string from the elements of an array.
Syntax
implode(separator,array)
Parameter Description
Parameter Description
separator Required. Specifies where to break the string
string Required. The string to split
limit Optional. Specifies the number of array elements to
return.Possible values:
•Greater than 0 - Returns an array with a maximum of limit
element(s)
•Less than 0 - Returns an array except for the last -limit
elements()
•0 - Returns an array with one element
Example
Example
array_flip() function
This function is used to flip the array with the
keys and values.
It takes one parameter that is an array.
The returned array will contain the flipped
elements.
The values will be the keys, and the keys will
be the values.
This function was introduced in PHP 4.0.
Syntax
?>
EXAMPLE 2
<?php
$fruits= array('oranges', 'apples', 'banana');
$flipped= array_flip($fruits);
print_r($flipped);
?>
EXAMPLE 3
<?php
function Flip($array)
{
$result = array_flip($array);
return($result);
}
$array = array("amitabh" => "jaya", "raj" => "nargis", "akshay" => "katrina",
"aamir" => "juhi");
print_r(Flip($array));
?>
PHP Functions
PHP function is a piece of code
that can be reused many times.
It can take input as argument list
and return value.
User define and system define
function is types of function
There are thousands of built-in
functions in PHP.
PHP Functions
Syntax:
function functionname()
{
//code to be executed
}
Note: Function name must be start with letter and underscore only like other labels in
PHP. It can't be start with numbers or special symbols.
PHP Functions calling
<?php
function sayHello()
{
echo "Hello PHP Function";
}
sayHello(); //calling function
?>
Output:
Hello PHP Function
PHP Functions - Parameters
PHP Functions - Parameters
example to pass single argument in PHP function.
<?php
function sayHello($name)
{
echo "Hello $name<br/>";
}
sayHello("Sonoo");
sayHello("Vimal");
sayHello("John");
?>
PHP Functions - Parameters
<?php
function sayHello($name,$age)
{
echo "Hello $name, you are $age years old<br/>";
}
sayHello("Sonoo",27);
sayHello("Vimal",29);
sayHello("John",23);
?>
PHP Call By Reference
Value passed to the function doesn't modify
the actual value by default (call by value).
But we can do so by passing value as a
reference.
By default, value passed to the function is call
by value.
To pass value as a reference, you need to use
ampersand (&) symbol before the argument
name.
Example
<?php
function adder(&$str2)
{
$str2 .= 'Call By Reference';
}
$str = 'Hello ';
adder($str);
echo $str;
?>
PHP Function: Default Argument Value
<?php
function sayHello($name="Sonoo")
{
echo "Hello $name<br/>";
}
sayHello("Rajesh");
sayHello();//passing no value
sayHello("John");
?>
Variable function
If name of a variable has parentheses (with or without
parameters in it) in front of it, PHP parser tries to find
a function whose name corresponds to value of the
variable and executes it.
Such a function is called variable function. This
feature is useful in implementing callbacks, function
tables etc.
Variable functions can not be built eith language
constructs such as include, require, echo etc. One can
find a workaround though, using function wrappers.
<?php
function add($x, $y)
{
echo $x+$y;
}
$var="add";
$var(10,20);
?>
PHP Anonymous functions
Anonymous function is a function without any
user defined name.
Such a function is also called closure or
lambda function. Sometimes, you may want a
function for one time use.
Closure is an anonymous function which
closes over the environment in which it is
defined.
You need to specify use keyword in it.Most
common use of anonymous function to create
an inline callback function.
Syntax
variable’s name.
•When passed to another function that can then call it later, it is
known as a callback.
•Return it from within an outer function so that it can access the
2) str_word_count()
-The PHP str_word_count() function counts the number of words in a
string.
<?php
echo str_word_count("Hello world!"); // outputs 2
?>
PHP String Function
3) strrev() -
The PHP strrev() function reverses a string.
<?php
echo strrev("Hello world!"); // outputs !dlrow olleH
?>
4) strpos()
The PHP strpos() function searches for a specific text within a
string. If a match is found, the function returns the character position of the
first match. If no match is found, it will return FALSE.
<?php
echo strpos("Hello world!", "world"); // outputs 6
?>
PHP String Function
5) str_replace()
Syntax
string strtolower ( string $string
)
Example
<?php
$str="My name is KHAN";
$str=strtolower($str);
echo $str;
?>
7) PHP strtoupper() function
The strtoupper() function returns string in uppercase letter.
Syntax
string strtoupper ( string $string )
Example
<?php
$str="My name is KHAN";
$str=strtoupper($str);
echo $str;
?>
8) PHP ucwords() function
The ucwords() function returns string converting first character
of each word into uppercase.
Syntax
string ucwords ( string $str )
Example
<?php
$str="my name is Sonoo jaiswal";
$str=ucwords($str);
echo $str;
?>
PHP string strcmp() Function
String comparison is one of the most common
tasks in programming and development.
strcmp() is a string comparison function in PHP.
It is a built-in function of PHP, which is case
sensitive, means it treats capital and the small
case separately.
It is used to compare two strings from each
other.
This function compares two strings and tells
whether a string is greater, less, or equal to
another string.
strcmp() function is binary safe string
comparison.
Syntax:
strcmp($str1, $str2);
Syntax
In PHP, imagecreate( ) function follows the following
syntax.
use imagettftext().
Scaling image
use imagescale() function
Creation of PDF Document
FPDF is a PHP class which allows generating
PDF
FPDF has following features
Choice of measure unit, page format and margins
Page header and footer management
Automatic page break
Automatic line break and text justification
Image support(JPEG,PNG and GIF)
Color and links
TrueType,Type1 and encoding support
Page compression.
FPDF is free and downloaded from hhtps://www.fpdf.org)
<?php
require(‘fpdf.php’);
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont(‘Arial’,’B’,16);
$pdf->Cell(80,10,’Prof.Patil A.D’);
$pdf->Output(‘my_file.pdf’,’I’);
?>
PHP with OOP
1) Object-oriented programming (OOP)
2)classes and objects are important.
3) OOP models complex things as reproducible,
4) simple structures
5) Reusable,
6) OOP objects can be used across programs
7) Allows for class-specific behavior through polymorphism
8) Easier to debug, classes often contain all applicable information
to them
9)Secure, protects information through encapsulation
PHP - What are Classes and Objects?
1) Classes and objects are the two main aspects of object-
oriented programming.
2) Define a Class
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
echo $apple->get_name();
echo "<br>";
echo $banana->get_name();
?>
PHP - The __construct Function
1) A constructor allows you to initialize an
object's properties upon creation of the object.
2) you create a constructor using __construct()
function,
3) PHP will automatically call this function when
you create an object from a class.
4) Notice that the construct function starts with
two underscores (__)!
Example
<?php
class Fruit {
public $name;
public $color;
function __construct($name)
{
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
function __construct($name)
{
$this->name = $name;
}
function __destruct() {
echo "The fruit is {$this->name}.";
}
}
Syntax
Syntax:
$yes_no=class_exists(classname);
<?php
class cwipedia
{
//decl
}
if(class_exists('cwipedia'))
{ $ob=new cwipedia();
echo "This is cwipedia.in";
}
else
{ echo "Not exist";
}
?>
2) get_class_methods()
This function return an array of class methods
name
Syntax:
$method =get_class_methods(classname);
<? Php
class myclass
{
function myclass() { }
function myfun1() { }
}
$my_class=new myclass();
$class_methods =get_class_methods(‘myclass’);
print_r($class_methods)
?> Output:
Array([0]=>myclass [1] => myfun)
3)get_class_vars()
• This function return an array of defaults properties of the class.
• It return an associative array with property’s name value pairs
Syntax
$properties = get_class_vars(classname)
<? Php
class myclass Out Put
{
Array(size=2)’v1’=>null ‘v2’=> int 100
var $v1;
var $v2=100;
}
$my_class = new myclass();
$class_vars= get_class_vars(‘myclass’);
var_ump($class_vars);
?>
4) get_parent_class()
Parameterize function accept either an object or
class name as parameter.
It return the name of the parent class
Or false if there is no parent class
Syntax:
$superclass=get_parent_class(classname)
Examining an object
Serialization in PHP:
Serialization is a technique used by programmers
to preserve their working data in a format that
can later be restored to its previous form.
Serializing an object means converting it to a byte
stream representation that can be stored in a file.
Serialization in PHP is mostly automatic, it
requires little extra work from you, beyond calling
the
serialize()
unserialize() functions.
serialize():
The serialize() converts a storable representation of a
value.
The serialize() function accepts a single parameter
which is the data we want to serialize and returns a
serialized string
A serialize data means a sequence of bits so that it can
be stored in a f il e, a memory buffer, or transmitted
across a network connection link.
It is useful for storing or passing PHP values around
without losing their type and structure.
Syntax: serialize(value);
unserialize():
unserialize():
unserialize() can use string to recreate the
original variable values i.e. converts actual data from
serialized data.
Syntax:
unserialize(string);
Introduction
PHP becoming standard in the world of web
programming
Because of simplicity, performance , reliability ,
flexibility & Speed.
Form are essential parts in web development.
Form are used to get input from user and
submit it into the web server for processing.
Form are used to communicate between users
and server.
Process of form handling
GET method
The GET method is used to submit the HTML
form data.
This data is collected by the predef ined $_GET
variable for processing.
The information sent from an HTML form using
the GET method is visible to everyone in the
browser's address bar, which means that all the
variable names and their values will be displayed
in the URL.
Therefore, the get method is not secured to
send sensitive information.
PHP Forms - $_GET Function
When using method="get" in HTML forms, all
variable names and values are displayed in the
URL.
This method should not be used when sending
passwords or other sensitive information!
However, because the variables are displayed in
the URL, it is possible to bookmark the page. This
can be useful in some cases.
The get method is not suitable for large variable
values; the value cannot exceed 1024 chars.
Some other notes on GET requests:
13-Feb-25
What are forms?
<form> is just another kind of HTML tag
HTML forms are used to create (rather primitive) GUIs on
Web pages
1. Usually the purpose is to ask the user for information
2. The information is then sent back to the server
A form is an area that can contain form elements
The syntax is: <form parameters> ...form elements...
</form>
Form elements include: buttons, checkboxes, text fields
, radio buttons, drop-down menus, etc
A form usually contains a Submit button to send the
information in he form elements to the server
177
The <form> tag
The <form arguments> ... </form> tag encloses form elements
(and probably other HTML as well)
The arguments to form tell what to do with the user input
action="url" (required)
Specifies where to send the data when the Submit button is clicked
method="get" (default)
Form data is sent as a URL with ?form_data info appended to the end
Can be used only if data is all ASCII and not more than 100 characters
method="post"
Form data is sent in the body of the URL request
Cannot be bookmarked by most browsers
target="target"
Tells where to open the page sent as a result of the request
target= _blank means open in a new window
178
target= _top means use the same window
The <input> tag
Most, but not all, form elements use the input tag, with a
type="..." argument to tell which kind of element it is
type can be text, checkbox, radio, password, hidden, submit, reset,
button, file, or image
Other common input tag arguments include:
name: the name of the element
value: the “value” of the element; used in different ways for different
values of type
readonly: the value cannot be changed
disabled: the user can’t do anything with this element
Other arguments are defined for the input tag but have meaning only
for certain values of type
179
Text input
A text field:
<input type="text" name="textfield" value="with an initial value">
A password field:
<input type="password" name="textfield3" value="secret">
• Note that two of these use the input tag, but one uses textarea
180
Buttons
A submit button:
<input type="submit" name="Submit" value="Submit">
A reset button:
<input type="reset" name="Submit2" value="Reset">
A plain button:
<input type="button" name="Submit3" value="Push Me">
submit: send data
type: "checkbox"
name: used to reference this form element from PHP
value: value to be returned when element is checked
Note that there is no text associated with the
checkbox—you have to supply text in the surrounding
HTML
182
Radio buttons
Radio buttons:<br>
<input type="radio" name="radiobutton" value="myValue1">
male<br>
<input type="radio" name="radiobutton" value="myValue2" checked>
female
If two or more radio buttons have the same name, the user can
only select one of them at a time
This is how you make a radio button “group”
If you ask for the value of that name, you will get the value
specified for the selected radio button
As
183 with checkboxes, radio buttons do not contain any text
Drop-down menu or list
A menu or list:
<select name="select">
<option value="red">red</option>
<option value="green">green</option>
<option value="BLUE">blue</option>
</select>
Additional arguments:
size: the number of items visible in the list (default is "1")
multiple: if set to "true", any number of items may be selected
(default is "false")
184
Hidden fields
<input type="hidden" name="hiddenField" value="nyah">
<-- right there, don't you see it?
185
A complete example
<html>
<head>
<title>Get Identity</title>
<meta http-equiv="Content-Type" content="text/html;
charset=iso-8859-1">
</head>
<body>
<p><b>Who are you?</b></p>
<form method="post" action="">
<p>Name:
<input type="text" name="textfield">
</p>
<p>Gender:
<input type="radio" name="gender" value="m">Male
<input type="radio" name="gender" value="f">Female</p>
</form>
</body>
</html>
186
By inserting value in a form we can check that inserted
value is even or odd.
<html>
<body>
<form method="post">
Enter a number:
<input type="number" name="number">
<input type="submit" value="Submit">
</form>
</body>
</html>
<?php
if($_POST)
{
$number = $_POST['number'];
if(($number % 2) == 0)
{
echo "$number is an Even number";
}
else
{
echo "$number is Odd number";
}
}
?>
Prime Number using Form in PHP
<form method="post">
Enter a Number: <input type="text" name="input"><br>
<br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
if($_POST)
{
$input=$_POST['input'];
for ($i = 2; $i <= $input-1; $i++)
{
if ($input % $i == 0)
{
$value= True;
}
}
if (isset($value) && $value)
{
echo 'The Number '. $input . ' is not prime';
} else
{
echo 'The Number '. $input . ' is prime';
}
}
?>
What is a Cookie?
PHP cookie is a small piece of information which
is stored at client browser.
It is used to recognize the user.
Cookie is created at server side and saved to
client browser.
Each time when client sends request to the
server, cookie is embedded with request.
Such way, cookie can be received at the server
side.
Each cookie be used to store up to 4kB of data.
A maximum of 20 cookies can be stored on a
user’s PC per domain.
Set a cookie
setcookie(name [,value [,expire [,path [,domain [,secure]]]]])
or
$variable = $HTTP_COOKIE_VARS[‘cookie_name’];
e.g.
$age = $_COOKIE[‘age’]
Storing an array..
Only strings can be stored in Cookie files.
To store an array in a cookie, convert it to a string
by using the serialize() PHP function.
The array can be reconstructed using the
unserialize() function once it had been read
back in.
Remember cookie size is limited!
Delete a cookie
To remove a cookie, simply overwrite the cookie
with a new one with an expiry time in the past…
setcookie(‘cookie_name’,’’,time()-6000)
Cookie Session
•Cookies are client-side files that contain user •Sessions are server-side files which contain user
information information
•Cookie ends depending on the lifetime you set for it •A session ends when a user closes his browser
•You don't need to start cookie as it is stored in your local •In PHP, before using $_SESSION, you have to write
machine session_start(); Likewise for other languages
•The official maximum cookie size is 4KB •Within-session you can store as much data as you like.
The only limits you can reach is the maximum memory a
script can consume at one time, which is 128MB by
default
•There is no function named unsetcookie() •Session_destroy(); is used to destroy all registered data
or to unset some