Introduction to PHP Programming Basics
Introduction to PHP Programming Basics
Unit - 1
Introduction to PHP
PHP started out as a small open source project that evolved as more and more people found out how
useful it was. Rasmus Lerdorf released the first version of PHP way back in 1994. Initially, PHP was
supposed to be an abbreviation for "Personal Home Page", but it now stands for the recursive
initialism "PHP: Hypertext Preprocessor".
Lerdorf began PHP development in 1993 by writing several Common Gateway Interface (CGI)
programs in C, which he used to maintain in his personal homepage. Later on, He extended them to
work with web forms and to communicate with databases. This implementation of PHP was
"Personal Home Page/Forms Interpreter" or PHP/FI.
Today, PHP is the world’s most popular server-side programming language for building web
applications. Over the years, it has gone through successive revisions and versions.
PHP performs system functions. It can create, open, read, write, and close the files.
PHP can handle forms. It can gather data from files, save data to a file, through email you can
send data, return data to the user.
You add, delete, modify elements within your database through PHP.
Access cookies variables and set cookies.
Using PHP, you can restrict users to access some pages of your website.
It can encrypt data.
PHP provides a large number of reusable classes and libraries are available on "PEAR" and
"Composer". PEAR (PHP Extension and Application Repository) is a distribution system for
reusable PHP libraries or classes. "Composer" is a dependency management tool in PHP.
DYNAMIC WEBSITE
Dynamic Website is a website containing data that can be mutable or changeable. It uses client-
side or server scripting to generate mutable content. Like a static website, it also contains HTML
data.
Dynamic websites are those websites that changes the content or layout with every request to the
webserver. These websites have the capability of producing different content for different visitors
from the same source code file. There are two kinds of dynamic web pages i.e. client side scripting
and server side scripting. The client-side web pages changes according to your activity on the web
page. On the server-side, web pages are changed whenever a web page is loaded.
Example: login & signup pages, application & submission forms, inquiry and shopping cart pages.
A Typical Architecture of dynamic website
There are different languages used to create dynamic web pages like PHP, ASP, .NET and JSP.
Whenever a dynamic page loads in browser, it requests the database to give information depending
upon user’s input. On receiving information from the database, the resulting web page is applied to
the user after applying the styling codes.
Facebook
Twitter
LinkedIn
Online booking website.
Social media
SCOPE OF PHP
Dynamic Typing: PHP is dynamically typed, meaning you don’t need to declare the data type
of a variable explicitly.
Cross-Platform: PHP runs on various platforms, making it compatible with different operating
systems.
Database Integration: PHP provides built-in support for interacting with databases, such as
MySQL, PostgreSQL, and others.
Server-Side Scripting: PHP scripts are executed on the server, generating HTML that is sent
to the client’s browser.
PHP is versatile and can be used in a variety of web development scenarios, including:
Dynamic Web Pages: Generating dynamic content based on user interaction or other
conditions.
Content Management Systems (CMS): Many popular CMSs like WordPress, Joomla, and
Drupal are built with PHP.
E-commerce Platforms: PHP is commonly used to develop e-commerce websites due to its
database integration capabilities.
Web Applications: PHP is used for creating feature-rich web applications such as social media
platforms, forums, and customer relationship management (CRM) systems.
API Development: PHP can be used to create APIs for web and mobile applications.
WAMP
WAMP is an acronym for Windows, Apache, MySQL, and PHP, it’s used as a Web development
platform that insists the users manage web apps using PHP, MySQL, and Apache. It is free and an
open-source web server solution stack package. It uses virtual hosts and provides top services.
XAMPP
XAMPP is an acronym for (X) cross-platform (Windows, Linux, Mac OS), (A)Apache, (M)Maria
DB or MySQL, (P)PHP and Perl. Like WAMP, XAMPP is also a free and open-source platform used
for web development.
NOTE: UNLIKE WAMP, XAMPP IS DESIGNED FOR WINDOWS, MAC OS AND LINUX. SO
IT CAN BE INSTALLED IN ALL OPERATING SYSTEMS
STEP 1- Open any web browser and visit [Link] On the home
page, you can find the option to download XAMPP for three platforms- Windows, MAC, and Linux.
Click on XAMPP for Windows. The latest version available on the website is 7.4.5.
As soon as you click on it, a message displaying the automatic start of download appears on the
screen.
STEP 2- After the download is completed, double click the .exe extension file to start the process of
installation.
STEP 3- A pop-up screen with the message asking you to allow to make changes on your desktop
appears. Click "YES" to continue the process.
STEP 4- Click to Allow access or deactivate the firewall and any other antivirus software because it
can hamper the process of installation. Thus, it is required to temporarily disable any antivirus
software or security firewall till the time all the XAMPP components have been installed completely.
STEP 5- Just before the installation, a pop-up window appears with a warning to disable UAC. User
Account Control (UAC) interrupts the XAMPP installation because it restricts the access to write to
the C: drive. Therefore, it is suggested to disable it for the period of installation.
STEP 6- After clicking the .exe extension file, the XAMPP setup wizard opens spontaneously. Click
on "NEXT" to start the configuration of the settings.
STEP 7- After that, a 'Select Components' panel appears, which gives you the liberty to choose
amongst the separate components of the XAMPP software stack for the installation. To get a
complete localhost server, it is recommended to install using the default options of containing all
available components. Click "NEXT" to proceed further.
STEP 8- The setup is now ready to install, and a pop-up window showing the same appears on the
screen. Click "NEXT" to take the process forward.
STEP 9- Select the location where the XAMPP software packet needs to be installed. The original
setup creates a folder titled XAMPP under C:\ for you. After choosing a location, click "NEXT".
STEP 10- After choosing from all the previously mentioned preferences (like language and learn
more bitnami dialogue box) click to start the installation. The setup wizard will unpack and install the
components to your system. The components are saved to the assigned directory. This process may
takes a few minutes to complete. The progress of the installation in terms of percentage is visible on
the screen.
STEP 11- After the successful installation of the XAMPP setup on your desktop, press the "FINISH"
button.
On clicking the FINISH button, the software automatically launches, and the CONTROL PANEL is
visible. The image below shows the appearance of the final result.
UNIT – 2
Syntax of PHP
PHP, a powerful server-side scripting language used in web development. It’s simplicity and ease
of use makes it an ideal choice for beginners and experienced developers. This article provides an
overview of PHP syntax. PHP scripts can be written anywhere in the document within PHP tags
along with normal HTML.
Output
Hello, world!
PHP is a server-side scripting language. We need to handle some logic by server-side in PHP web
applications, allowing developers to embed HTML directly within PHP code and generate dynamic
content for web applications.
Basic Embedding
Basic Embedding
The simplest way to embed HTML in PHP is by mixing PHP tags () with HTML code. Let’s take a
simple example:
In the above code, We have encapsulated dynamic content in PHP tags. The echo statement outputs
text or variables to the HTML.
PHP also supports short tags () to embed HTML in PHP. This provides a more concise way to embed
HTML. Some servers may have short tags disabled for security or compatibility reasons. Please verify
and enable it on the server.
we can also use heredoc or nowdoc syntax to embed larger HTML blocks or templates.
Encapsulating HTML within PHP variables enables a more organized structure of code. You can
include longer HTML blocks with heredoc and nowdoc without having to perform a lot of
concatenation.
Heredoc Syntax:
Nowdoc Syntax:
The Template Engine is the most popular way to integrate HTML into PHP for complex web
applications. This helps to create a clean separation of HTML presentation and PHP logic in the web
application, making it easier to manage and maintain code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Blade Templating Example</title>
</head>
<body>
<h1>{{ "Welcome to Blade Templating" }}</h1>
</body>
</html>
o 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 datatype.
o After declaring a variable, it can be reused throughout the code.
o Assignment Operator (=) is used to assign the value to a variable.
1. $variablename=value;
Rules for declaring PHP variable:
o A variable must start with a dollar ($) sign, followed by the variable name.
o It can only contain alpha-numeric character and underscore (A-z, 0-9, _).
o A variable name must start with a letter or underscore (_) character.
o A PHP variable name cannot contain spaces.
o One thing to be kept in mind that the variable name cannot start with a number or special
symbols.
o PHP variables are case-sensitive, so $name and $NAME both are treated as different variable.
Let's see the example to store string, integer, and float values in PHP variables.
File: [Link]
1. <?php
2. $str="hello string";
3. $x=200;
4. $y=44.6;
5. echo "string is: $str <br/>";
6. echo "integer is: $x <br/>";
7. echo "float is: $y <br/>";
8. ?>
Output:
File: [Link]
1. <?php
2. $x=5;
3. $y=6;
4. $z=$x+$y;
5. echo $z;
6. ?>
Output:
11
PHP Variable: case sensitive
In PHP, variable names are case sensitive. So variable name "color" is different from Color, COLOR,
COLor etc.
File: [Link]
1. <?php
2. $color="red";
3. echo "My car is " . $color . "<br>";
4. echo "My house is " . $COLOR . "<br>";
5. echo "My boat is " . $coLOR . "<br>";
6. ?>
Output:
My car is red
Notice: Undefined variable: COLOR in C:\wamp\www\[Link] on line 4
My house is
Notice: Undefined variable: coLOR in C:\wamp\www\[Link] on line 5
My boat is
File: [Link]
1. <?php
2. $a="hello";//letter (valid)
3. $_b="hello";//underscore (valid)
4.
5. echo "$a <br/> $_b";
6. ?>
Output:
hello
hello
File: [Link]
1. <?php
2. $4c="hello";//number (invalid)
3. $*d="hello";//special symbol (invalid)
4. echo "$4c <br/> $*d";
5. ?>
Output:
Parse error: syntax error, unexpected '4' (T_LNUMBER), expecting variable (T_VARIABLE)
or '$' in C:\wamp\www\[Link] on line 2
PHP is a loosely typed language, it means PHP automatically converts the variable to its correct data
type.
Output
704
int(704)
2. Float (Double)
Can hold numbers containing fractional or decimal parts including positive and negative numbers
or a number in exponential form. By default, the variables add a minimum number of decimal
places. The Double data type is the same as a float as floating-point numbers or real numbers.
<?php
$val1 = 50.85;
$val2 = 654.26;
$sum = $val1 + $val2;
echo $sum;
echo "\n\n";
//returns data type and value
var_dump($sum)
?>
Output
705.11
float(705.11)
3. String
Hold letters or any alphabets, even numbers are included. These are written within double quotes
during declaration. The strings can also be written within single quotes, but they will be treated
differently while printing variables. To clarify this look at the example below.
<?php
$name = "Krishna";
echo "The name of the Geek is $name \n";
echo 'The name of the geek is $name ';
echo "\n\n";
//returns data type, size and value
var_dump($name)
?>
Output
string(7) "Krishna"
4. Boolean
Boolean data types are used in conditional testing. Hold only two values, either TRUE(1) or
FALSE(0). Successful events will return true and unsuccessful events return false. NULL type
values are also treated as false in Boolean. Apart from NULL, 0 is also considered false in boolean.
If a string is empty then it is also considered false in boolean data type.
<?php
if(TRUE)
echo "This condition is TRUE";
if(FALSE)
echo "This condition is not TRUE";
?>
Output
<?php
$intArray = array( 10, 20 , 30);
echo "First Element: $intArray[0]\n";
echo "Second Element: $intArray[1]\n";
echo "Third Element: $intArray[2]\n\n";
//returns data type and value
var_dump($intArray);
?>
Output
First Element: 10
Second Element: 20
Third Element: 30
array(3) {
[0]=>
int(10)
[1]=>
int(20)
[2]=>
int(30)
<?php
$nm = NULL;
echo $nm; // this will return no output
// return data type
var_dump($nm);
?>
Output
NULL
2. Resources
Resources in PHP are not an exact data type. These are basically used to store references to some
function call or to external PHP resources. For example, consider a database call. This is an
external resource. Resource variables hold special handles for files and database connections.
Note:
To check the type and value of an expression, use the var_dump() function which dumps
information about a variable.
PHP allows the developer to cast the data type.
PHP Operator is a symbol i.e used to perform operations on operands. In simple words, operators are
used to perform operations on variables or values.
o Arithmetic Operators
o Assignment Operators
o Bitwise Operators
o Comparison Operators
o Incrementing/Decrementing Operators
o Logical Operators
o String Operators
o Array Operators
o Type Operators
o Execution Operators
o Error Control Operators
Arithmetic Operators:
The arithmetic operators are used to perform simple mathematical operations like addition,
subtraction, multiplication, etc. Below is the list of arithmetic operators along with their syntax and
operations in PHP.
Logical
and $x and $y True if both the operands are true else false
AND
Logical True if either of the operands is true and false if both are
xor $x xor $y
XOR true
Logical $x &&
&& True if both the operands are true else false
AND $y
!= Not Equal To $x != $y Returns True if both the operands are not equal
<> Not Equal To $x <> $y Returns True if both the operands are unequal
$x === Returns True if both the operands are equal and are
=== Identical
$y of the same type
Greater Than or
>= $x >= $y Returns True if $x is greater than or equal to $y
Equal To
If the condition is true? then $x : or else $y. This means that if the condition
?: Ternary is true then the left result of the colon is accepted otherwise the result is on
right
Assignment Operators:
These operators are used to assign values to different variables, with or without mid-operations.
Here are the assignment operators along with their syntax and operations, that PHP provides for the
operations.
$x +=
+= Add then Assign Simple Addition same as $x = $x + $y
$y
Array Operators:
These operators are used in the case of arrays. Here are the array operators along with their syntax
and operations, that PHP provides for the array operation.
Operator Name Syntax Operation
$x === Returns True if both have the same key-value pair in the
=== Identity
$y same order and of the same type
Non- $x !==
!== Returns True if both are not identical to each other
Identity $y
Increment/Decrement Operators:
These are called the unary operators as they work on single operands. These are used to increment
or decrement values.
String Operators:
This operator is used for the concatenation of 2 or more strings using the concatenation operator
(‘.’). We can also use the concatenating assignment operator (‘.=’) to append the argument on the
right side to the argument on the left side.
Operator Name Syntax Operation
Spaceship Operators:
PHP 7 has introduced a new kind of operator called spaceship operator. The spaceship operator or
combined comparison operator is denoted by “<=>“. These operators are used to compare values
but instead of returning the boolean results, it returns integer values. If both the operands are equal,
it returns 0. If the right operand is greater, it returns -1. If the left operand is greater, it returns 1.
The following table shows how it works in detail:
$x <= $y $x <=> $y Identical to -1 (right is greater) or identical to 0 (if both are equal)
$x >= $y $x <=> $y Identical to 1 (if left is greater) or identical to 0 (if both are equal)
PHP allows us to perform actions based on some type of conditions that may be logical or
comparative. Based on the result of these conditions i.e., either TRUE or FALSE, an action would
be performed as asked by the user. It’s just like a two- way path. If you want something then go
this way or else turn that way. To use this feature, PHP provides us with four conditional
statements:
if statement
if…else statement
if…elseif…else statement
switch statement
Let us now look at each one of these in details:
if Statement: This statement allows us to set a condition. On being TRUE, the following block
of code enclosed within the if clause will be executed.
Syntax :
if (condition){
// if TRUE then execute this code
}
Example:
<?php
$x = 12;
if ($x > 0) {
echo "The number is positive";
}
?>
Output:
The number is positive
if…else Statement: We understood that if a condition will hold i.e., TRUE, then the block of
code within if will be executed. But what if the condition is not TRUE and we want to perform an
action? This is where else comes into play. If a condition is TRUE then if block gets executed,
otherwise else block gets executed.
Syntax:
if (condition) {
// if TRUE then execute this code
}
else{
// if FALSE then execute this code
}
Example :
<?php
$num=12;
if($num%2==0){
echo "$num is even number";
}else{
echo "$num is odd number";
}
?>
Output:
12 is even number
if…elseif…else Statement: This allows us to use multiple if…else statements. We use this
when there are multiple conditions of TRUE cases.
Syntax:
if (condition) {
// if TRUE then execute this code
}
elseif {
// if TRUE then execute this code
}
elseif {
// if TRUE then execute this code
}
else {
// if FALSE then execute this code
}
Example:
<?php
$x = "August";
if ($x == "January") {
echo "Happy Republic Day";
}
elseif ($x == "August") {
echo "Happy Independence Day!!!";
}
else{
echo "Nothing to show";
}
?>
Output:
Happy Independence Day!!!
SWITCH STATEMENT
The switch statement is similar to the series of if-else statements. The switch statement performs in
various cases i.e. it has various cases to which it matches the condition and appropriately executes
a particular case block. It first evaluates an expression and then compares it with the values of each
case. If a case matches then the same case is executed.
To use the switch, we need to get familiar with two different keywords namely, break and default.
break: The break statement is used to stop the automatic control flow into the next cases and
exit from the switch case.
default: The default statement contains the code that would execute if none of the cases match.
Syntax
switch (expression) {
case label1:
//code block
break;
case label2:
//code block;
break;
case label3:
//code block
break;
default:
//code block
Example
$favcolor = "red";
switch ($favcolor) {
case "red":
break;
case "blue":
break;
case "green":
break;
default:
}
WHILE LOOP
The while loop is the simple loop that executes nested statements repeatedly while the expression
value is true. The expression is checked every time at the beginning of the loop, and if the
expression evaluates to true then the loop is executed otherwise loop is terminated.
Syntax:
while (if the condition is true) {
// Code is executed
}
<?php
// Declare a number
$num = 10;
// While Loop
$num += 2;
?>
Output
10
12
14
16
18
FOR LOOP
The for loop is the most complex loop in PHP that is used when the user knows how many times
the block needs to be executed. The for loop contains the initialization expression, test condition,
and update expression (expression for increment or decrement).
Syntax:
for (initialization expression; test condition; update expression) {
// Code to be executed
Loop Parameters:
Initialization Expression: In this expression, we have to initialize the loop counter to some
value. For example: $num = 1;
Test Condition: In this expression, we have to test the condition. If the condition evaluates to
“true” then it will execute the body of the loop and go to the update expression otherwise it will
exit from the for loop. For example: $num <= 10;
Update Expression: After executing the loop body, this expression increments/decrements the
loop variable by some value. For example: $num += 2;
Example 1: The following code shows a simple example using for loop.
<?php
?>
Output
0
5
10
15
UNIT – 3
PHP | Functions
A function is a block of code written in a program to perform some specific task. We can relate
functions in programs to employees in a office in real life for a better understanding of how
functions work. Suppose the boss wants his employee to calculate the annual budget. So how will
this process complete? The employee will take information about the statistics from the boss,
performs calculations and calculate the budget and shows the result to his boss. Functions works in
a similar manner. They take informations as parameter, executes a block of statements or perform
operations on this parameters and returns the result.
PHP provides us with two major types of functions:
Built-in functions : PHP provides us with huge collection of built-in library functions. These
functions are already coded and stored in form of functions. To use those we just need to call
them as per our requirement like, var_dump, fopen(), print_r(), gettype() and so on.
User Defined Functions : Apart from the built-in functions, PHP allows us to create our own
customised functions called the user-defined functions.
Using this we can create our own packages of code and use it wherever necessary by simply
calling it.
CREATING AN ARRAY
An array can hold more than one value. In PHP, they’re stored as value pairs that in other languages
would be called a dictionary or a hashtable. Keys can be strings or integers.
Syntax
There are several methods of declaring an array in PHP. The array() function can be used, either with
key-value pairs, or with values alone. Single brackets, [...] can also be used in place of
the array() keyword. If any key value is omitted, the key will be found by incrementing the largest
prior integer key. If a key is repeated, the new value will overwrite the prior key.
Example
$cars = array("Volvo", "BMW", "Toyota");
Example
$cars = [
"Volvo",
"BMW",
"Toyota",
];
You can declare an empty array first, and add items to it later:
Example
$cars = [];
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
Example
Change the second array item from "BMW" to "Ford":
$cars[1] = "Ford";
OUTPUT
array(3) {
[0]=>
string(5) "Volvo"
[1]=>
string(4) "Ford"
[2]=>
string(6) "Toyota"
}
The while loop executes a block of code as long as the specified condition is true.
Example
$i = 1;
echo $i;
$i++;
The do...while loop will always execute the block of code at least once, it will then check the
condition, and repeat the loop while the specified condition is true.
Example
$i = 1;
do {
echo $i;
$i++;
Syntax
// code block
Example
The most common use of the foreach loop, is to loop through the items of an array. For every loop
iteration, the value of the current array element is assigned to the variable $x. The iteration continues
until it reaches the last array element.
Example:
<!DOCTYPE html>
<html>
<body>
<?php
?>
</body>
</html>
Output:
red
green
blue
yellow
Groups an array into arrays by a given $key, or set of keys, shared between all array members. Array
variables allow you to group related PHP data values together in a list using a single variable name.
You can then either reference the values as a whole by referencing the variable name or handle each
data value individually within the array by referencing its place in the list.
Parameters
Return Values
Returns a multidimensional array, with each dimension containing elements grouped by the passed
key(s).
Errors/Exceptions
If $key is not one of the accepted types E_USER_ERROR will be thrown and NULL returned.
Examples
$records = [
[
"state" => "IN",
"city" => "Indianapolis",
"object" => "School bus"
],
[
"state" => "IN",
"city" => "Indianapolis",
"object" => "Manhole"
],
[
"state" => "IN",
"city" => "Plainfield",
"object" => "Basketball"
],
[
"state" => "CA",
"city" => "San Diego",
"object" => "Light bulb"
],
[
"state" => "CA",
"city" => "Mountain View",
"object" => "Space pen"
]
];
Array
(
[IN] => Array
(
[Indianapolis] => Array
(
[0] => Array
(
[state] => IN
[city] => Indianapolis
[object] => School bus
)
)
)
PHP Arrays are a data structure that stores multiple elements of a similar type in a single variable.
The arrays are helpful to create a list of elements of similar type. It can be accessed using their
index number or key. The array functions are allowed to interact and manipulate the array elements
in various ways. The PHP array functions are used for single and multi-dimensional arrays.
Installation: The array functions have not required any installation. These are part of PHP core
concepts.
Function Description
array_combine() Creates an array by using the elements from one "keys" array and one
"values" array
array_diff() Compare arrays, and returns the differences (compare values only)
array_diff_assoc() Compare arrays, and returns the differences (compare keys and values)
array_diff_key() Compare arrays, and returns the differences (compare keys only)
array_shift() Removes the first element from an array, and returns the value of the removed
element
In PHP, reading from and writing to files is a common task in web development, especially for
tasks such as reading configuration files, processing data files, or logging
information. PHP provides built-in functions for handling file operations, making it straightforward
to perform file read and write operations.
o fread()
o fgets()
o fgetc()
The PHP fread() function is used to read data of the file. It requires two arguments: file resource and
file size.
Syntax
Example
<?php
$filename = "c:\\[Link]";
$fp = fopen($filename, "r");//open file in read mode
$contents = fread($fp, filesize($filename));//read file
echo "<pre>$contents</pre>";//printing data of file
fclose($fp);//close file
?>
Output
The PHP fgets() function is used to read single line from the file.
Syntax
Example
<?php
$fp = fopen("c:\\[Link]", "r");//open file in read mode
echo fgets($fp);
fclose($fp);
?>
Output
The PHP fgetc() function is used to read single character from the file. To get all data using fgetc()
function, use !feof() function inside the while loop.
Syntax
<?php
$fp = fopen("c:\\[Link]", "r");//open file in read mode
while(!feof($fp)) {
echo fgetc($fp);
}
fclose($fp);
?>
Output
UNIT – V
MANAGING SESSIONS AND USING SESSION VARIABLES
In general, session refers to a frame of communication between two medium. A PHP session is
used to store data on a server rather than the computer of the user. Session identifiers or SID is a
unique number which is used to identify every user in a session based environment. The SID is
used to link the user with his information on the server like posts, emails etc.
Starting a PHP Session: The first step is to start up a session. After a session is started, session
variables can be created to store information. The PHP session_start() function is used to begin
a new [Link] also creates a new session ID for the user.
Below is the PHP code to start a new session:
<?php
session_start();
?>
Storing Session Data: Session data in key-value pairs using the $_SESSION[] superglobal
[Link] stored data can be accessed during lifetime of a session.
Below is the PHP code to store a session with two session variables Rollnumber and Name:
<?php
session_start();
$_SESSION["Rollnumber"] = "11";
$_SESSION["Name"] = "Ajay";
?>
Accessing Session Data: Data stored in sessions can be easily accessed by firstly
calling session_start() and then by passing the corresponding key to
the $_SESSION associative array.
The PHP code to access a session data with two session variables Rollnumber and Name is
shown below:
<?php
session_start();
?>
Output:
The Name of the student is :Ajay
Destroying Certain Session Data: To delete only a certain session data,the unset feature can
be used with the corresponding session variable in the $_SESSION associative array.
The PHP code to unset only the “Rollnumber” session variable from the associative session
array:
<?php
session_start();
if(isset($_SESSION["Name"])){
unset($_SESSION["Rollnumber"]);
?>
<?php
session_start();
session_destroy();
?>
cookie in PHP is a small file with a maximum size of 4KB that the web server stores on the client
computer. They are typically used to keep track of information such as a username that the site can
retrieve to personalize the page when the user visits the website next time. A cookie can only be
read from the domain that it has been issued from. Cookies are usually set in an HTTP header but
JavaScript can also set a cookie directly on a browser.
Setting Cookie In PHP: To set a cookie in PHP, the setcookie() function is used. The setcookie()
function needs to be called prior to any output generated by the script otherwise the cookie will not
be set.
Syntax:
setcookie(name, value, expire, path, domain, security);
Parameters: The setcookie() function requires six arguments in general which are:
Name: It is used to set the name of the cookie.
Value: It is used to set the value of the cookie.
Expire: It is used to set the expiry timestamp of the cookie after which the cookie can’t be
accessed.
Path: It is used to specify the path on the server for which the cookie will be available.
Domain: It is used to specify the domain for which the cookie is available.
Security: It is used to indicate that the cookie should be sent only if a secure HTTPS
connection exists.
Below are some operations that can be performed on Cookies in PHP:
Creating Cookies: Creating a cookie named Auction_Item and assigning the value Luxury Car
to it. The cookie will expire after 2 days(2 days * 24 hours * 60 mins * 60 seconds).
Example: This example describes the creation of the cookie in PHP.
PHP
<!DOCTYPE html>
<?php
?>
<html>
<body>
<?php
?>
<p>
<strong>Note:</strong>
</p>
</body>
</html>
Note: Only the name argument in the setcookie() function is mandatory. To skip an argument, the
argument can be replaced by an empty string(“”).
Output:
SETTING COOKIES
Checking Whether a Cookie Is Set Or Not: It is always advisable to check whether a cookie is
set or not before accessing its value. Therefore to check whether a cookie is set or not, the PHP
isset() function is used. To check whether a cookie “Auction_Item” is set or not, the isset() function
is executed as follows:
Example: This example describes checking whether the cookie is set or not.
PHP
<!DOCTYPE html>
<?php
?>
<html>
<body>
<?php
if (isset($_COOKIE["Auction_Item"]))
else
?>
<p>
<strong>Note:</strong>
</p>
</body>
</html>
Output: