0% found this document useful (0 votes)
27 views

WPPM Unit-1

The document discusses a unit-1 syllabus for PHP that covers introduction to open source software and PHP, including its history and features. It also discusses PHP variables, statements, operators, conditional statements like if-else and switch statements, loops like while, do-while and for loops. The document also talks about arrays in PHP, functions, files, sessions, cookies and how to create sample PHP applications.

Uploaded by

Amit Pollai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

WPPM Unit-1

The document discusses a unit-1 syllabus for PHP that covers introduction to open source software and PHP, including its history and features. It also discusses PHP variables, statements, operators, conditional statements like if-else and switch statements, loops like while, do-while and for loops. The document also talks about arrays in PHP, functions, files, sessions, cookies and how to create sample PHP applications.

Uploaded by

Amit Pollai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

PRESENTED BY-

SOUMYA RANJAN MISHRA


DEPT.OF CSE
GIET UNIVERSITY
GUNUPUR

Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR


UNIT-1 Syllabus
UNIT: 1 (10 Hours)
Introduction- open source-PHP – history- features-variables-
statements, operators-conditional statements-if-switch-nesting
conditions-merging forms with conditional statements-
loopswhile-do-for – loop iteration with break and continue.
Arrays: Creating an array- modifying array-processing array-
grouping form with arrays- using array functions- creating user
defined functions- using files- sessions- cookies- executing
external programs- Creating sample applications using PHP.

Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR


What is PHP?
 PHP is an recursive acronym for „„PHP: Hypertext
Preprocessor‟‟.
 PHP (Hypertext Preprocessor) is a widely-used server-side
scripting language designed for web development.
 It is an open-source (free to download, use, modify and
rerelease) scripting language that can be embedded in
HTML, and it is particularly well-suited for web
development and creating dynamic web pages.
 PHP scripts are executed on the server, generating dynamic
content that is then sent to the client's browser.
Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR
PHP History :-
 PHP (1995): PHP was developed by Rasmus
Lerdorf for monitoring his online resume in 1995. It slowly
became popular. This first version PHP/F1 has some basic
functions.
 Personal Home Page/Forms Interpreter (PHP/FI 2.0)
(1997): PHP/F1 2.0 was released and it was quickly replaced
by PHP 3.0 in 1998.
 PHP 3 (1998): PHP 3.0 was interesting. It was developed by
and Andi Gutmans and Zeev suraski. It includes support for
wider range of data bases (Oracle and My SQL). This version
had greater portability. It was used by thousands of web
servers.
Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR
PHP History :-
 PHP 4.0 was released in 2003. It used a new engine and
provided better performance, greater reliability and scalability
and support for web servers other than Apache. It also
supports OOP features and built-in session management.
 PHP 5.0 offers a complete object oriented program models. It
also includes better exception handling, a more consistent
XML tool kit, improved My SQL support and a better memory
manager. PHP 5.0 was the best in the languages 10 year
history. A survey was conducted by net craft in April 2004. It
showed that PHP was in use for over 15 million websites.

Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR


PHP History :-
 PHP 6 (Not Released): PHP 6 was planned to include native
support for Unicode, but the project was eventually
abandoned due to various technical challenges and delays.
The features intended for PHP 6 were eventually incorporated
into future PHP versions.
 PHP 7 (2015): PHP 7, released in 2015, was a major leap
forward in terms of performance and resource usage. It
introduced the Zend Engine 3, which significantly improved
speed and efficiency. PHP 7 also included new language
features and enhancements.
 PHP 8 (2020): PHP 8, released in 2020, brought numerous
improvements, including the Just-In-Time (JIT) compiler for
further performance boosts, named arguments, union types,
and more. PHP 8 continued to evolve the language and
enhance its capabilities.

Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR


Features Of PHP:-
 PHP‟s main competitors are Python, Ruby (on Rails or
otherwise), Node.js, Perl, Microsoft .NET, and Java. In
comparison to these products, PHP has many strengths,
including the following:
1. Performance
2. Scalability
3. Interfaces to many different database systems
4. Built-in libraries for many common web tasks
5. Low cost
6. Ease of learning and use
7. Strong object-oriented support
8. Portability
9. Flexibility of development approach
10. Availability of source code
11. Availability of support and documentation

Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR


Features Of PHP:-
1. Performance
 PHP is very fast. Using a single inexpensive server, you can
serve millions of hits per day.
 It scales down to the smallest email form and up to sites such
as Facebook .
2. Scalability
 PHP has what Rasmus Lerdorf frequently refers to as a
“shared-nothing” architecture.
 This means that you can effectively and cheaply implement
horizontal scaling with large numbers of commodity servers.
3. Database Integration
 PHP has native connections available to many database
systems. In addition to MySQL, you can directly connect to
PostgreSQL, Oracle, MongoDB, and MySQL, among others.
 PHP 5 and PHP 7 also have a built-in SQL interface to flat
files, called SQLite.
Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR
Features Of PHP:-
 Using the Open Database Connectivity (ODBC) standard, you
can connect to any database that provides an ODBC driver.
 This includes Microsoft products and many others. In addition
to native libraries, PHP comes with a database access
abstraction layer called PHP Database Objects (PDOs), which
allows consistent access and promotes secure coding
practices.
4. Built-in Libraries
 Because PHP was designed for use on the Web, it has many
built-in functions for performing many useful web-related
tasks.
 We can generate images on the fly, connect to web services
and other network services, parse XML, send email, work with
cookies, and generate PDF documents, all with just a few lines
of code.

Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR


Features Of PHP:-
5. Low Cost
 PHP is free.
 We can download the latest version at any time from
http://www.php.net for no charge.
6. Ease of Learning and use
 The syntax of PHP is based on other programming languages,
primarily C and Perl.
 If we already know C or Perl, or a C-like language such as
C++ or Java, we will be productive using PHP almost
immediately.
7. Portability
 PHP is available for many different operating systems.
 We can write PHP code on free UNIX-like operating systems
such as Linux and FreeBSD, commercial UNIX versions,
OSX, or on different versions of Microsoft Windows. Well-
written code will usually work without modification on a
different system running PHP.
Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR
Features Of PHP:-
8. Object-Oriented Support
 PHP version 5 had well-designed object-oriented features,
which continued to be refined and improved in PHP version 7.
 If we learned to program in Java or C++, we will find the
features (and generally the syntax) that you expect, such as
inheritance, private and protected attributes and methods,
abstract classes and methods, interfaces, constructors, and
destructors. You will even find some less common features
such as iterators and traits.
9. Flexibility of Development Approach
 PHP allows us to implement simple tasks simply, and equally
easily adapts to implementing large applications using a
framework based on design patterns such as Model-View-
Controller (MVC).

Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR


Features Of PHP:-
10. Source Code
 We have access to PHP‟s source code. With PHP, unlike
commercial, closed-source products.
 If we want to modify something or add to the language, we are
free to do so we do not need to wait for the manufacturer to
release patches.
 We also don‟t need to worry about the manufacturer going out
of business or deciding to stop supporting a product.
11. Availability of Support and Documentation
 Zend Technologies (http://www.zend.com), the company
behind the engine that powers PHP, funds its PHP
development by offering support and related software on a
commercial basis.
 The PHP documentation and community are mature and rich
resources with a wealth of information to share.

Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR


Operators:-
 Operators are symbols that we can use to manipulate values
and variables by performing an operation on them.
 In general, operators can take one, two, or three arguments,
with the majority taking two. For example, the assignment
operator takes two: the storage location on the left side of the
= symbol and an expression on the right side. These
arguments are called operands—that is, the things that are
being operated upon.
Arithmetic operators
 Arithmetic operators are straightforward; they are just the
normal mathematical operators. PHP‟s arithmetic operators
are shown in Table 1.1.

Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR


Operators:-

 Addition, subtraction, multiplication and division work as we would


expect. The result of these operators is to add or subtract,
respectively, the values stored in the $a and $b variables.
 We can also use the subtraction symbol (-) as a unary operator—
that is, an operator that takes one argument or operand—to indicate
negative numbers, as in this example: $a = -1;
 The modulus operator returns the remainder calculated by dividing
the $a variable by the $b variable. Consider this code fragment: $a =
27; $b = 10; $result = $a%$b;
 The modulus operator returns the remainder calculated by dividing
the $a variable by the $b variable.
 Consider this code fragment: $a = 27; $b = 10; $result = $a%$b;
Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR
Operators:-
.

Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR


Operators:-
.

Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR


Operators:-
.

Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR


Loop :-
 A loop is a control structure that able us to provide repetition of
set statements based upon set of conditionals.
 There are three loops in PHP 1. While loop 2. Do While loop
3. For loop
Q. Write a script for displaying multiplication table as shown.
<?php
//define number and limits for multiplication tables
$num=1
$upperlimit=10;
$lowerlimit=12;
//loop and multiply to create table
do
{
echo”$num x$lowerlimit=”($num*$lowerlimit);
$lowerlimit ++;
}
while ($lowerlimit <=$upperlimit)
?>
Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR
Loop :-
Write a PHP script for printing ever number between any two limits.
<?
$lower limit=10;
$upper limit =50;
for ($ lower limit -1.2 1==0)
$ lower limit++;
for($i=lower limit;$i=$upper limit;$i++) echo $i;
?>
<?
<form action=PHP-SELF method=post>
Enter lower limit:<input type=“text”name=“lower”size=”30”> Enter
upper limit:<input type=“text”name=“lower”size=”30”>
<input type=“submit” value=“send”>
</form>
$lower limit=$_post [“Lower”];
$lower limit i$i <=$upper limit,Bi++)
{
echo $; } ?>
Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR
Array :-
 Array is complex variable that allowed us to store multiple values
in a single variable. We use this to store related information.
 This value can have same name and similar action performing
and them.
 An array is defined as following
<?php
//define array
$fruits={„apple‟,„mango‟,„orange‟}
$fruits[0]={„grapes‟}
?>
 Here $ fruits is an array variable. It contains 3 values" grapes,
orange, mango". The elements of the array are accessed using an
index. The index number of first element is zero, the index
number of second element is one and soon.
So $fruits[0]=' grapes'
Suppose if we want to add new element to this array. We can write
statement
$fruits[3]=' banana‟;
Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR
Array :-
 In PHP we have a different type of Array which
relates key and value. This type of array is also known
as hash or associative array.
Example of this array is given below. Position as key value.
<? php
$fruits={ yellow=' mango'
Purple=' grapes' Orange=' orange'
}
?>
 Here $fruits is an array variable type of key values. We access
element by using the key instead of position number.
$fruits[yellow]=‟mango‟. We are using the key yellow instead of
position 0. Creating an array:
Method 1:
$ Fruits=array{'strawberry';„grape‟;„vanilla';„caramel'}

Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR


Array :-
Method 2:
$ fruits[0]=' strawberry';
$ fruits[1]=' grapes';
Method 3:
$ fruits[' red']=' apple';
$ fruits[' yellow']=' mango';
Modifying an array element:
 To add an element to the array we can write the statement
$fruit[5] ='lemon‟. Suppose if we don‟t know the last position to add
a new element in array we can simply write
$ fruit[]=' strawberry';
Deleting an array element:
 To remove an element we can use array_ push or array_ pop().
These two functions are built-in array functions in PHP.
Processing array with loop:
 In PHP we can process arrays using loops like for, while, etc..
 We also have a special loop in PHP known as for each loop
for array processing.
Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR
Array :-
Example for array processing with loop
<html>
<head></head>
<body>
Today shopping list;
<ul>
<?php
$shoppinglist=array(„sugar‟,„redchilli‟,‟rice‟);
for($x=0;$x< sizeof($shoppinglist);x++)
{
echo<li>$shoppinglist[$x];
}
?>
</ul>
</body>
</html>

Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR


Array :-
 In this example for loop is used to interact with the array. This
loops extract elements from the array and prints in the screen
one after another as an order list. The sizeof() function returns
the number of elements in the array.
foreach loop()
 This loop runs for each element of the array moving through
the element of array on each increment/decrement.
 In for loop, we have condition statement and
iteration(increment/decrement) statement.
 Condition statement and iteration statement are not needed in
foreach() loop.
The syntax of foreach() loop is
foreach (array variable as loop variable)
{
// loop statement
}

Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR


Array :-
Example using foreach() loop
<html>
<head></head>
<body>
Today‟s shopping list;
<ul>
<?php
$shoppinglist=array („sugar‟, „redchilli‟, „rice‟);
foreach($shoppinglist as $ item)
{
echo”<li>$item”;
}
?>
</ul>
</body>
</html>

Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR


Array :-
For each loop for an associative array:
< html>
< head></ head>
< body>
$ can see
<ul>
<?php
// define associative array
$ animals=array(' dog'='Tripsy',' cat'=>‟Tabitha‟, 'parrot'='polly)';
//iterate over it
foreach($ animal as $ key=$ value)
{
echo"</ u>A $ key name $ value";
}
?>
</ul>
</ body>
</ html>
Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR
Using Array Functions :-
There are many built-in array functions in PHP that we can use along with array.
 is_array()
This function check whether the variable in PHP is a array variable or not. It
returns Boolean value as output
 array_key()
This function returns the list of key in associative array for example this function
will return
'dog', cat', 'parrot’ from the array $animals.
 array_value()
This function will return only the array element in an associative array. For
example, this function returns 'Tripsy', 'Tabitha', 'polly' from the animals array,
 list()
This list function assigns array elements to array variable. ex:
$flavours=array(' strawberry', 'grape', 'vanilla'); list($f1, $f2, $f3) =
$flavours;
$f1 will have strawberry
$f2 will have grape and so on
Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR
Using Array Functions :-
 extract()
The extract() function iterates through (associative array)
converting the key value pairs into corresponding variable value
pairs.
$ fruits= array('red'= „apple‟, ' yellow'=' banana', 'purple'= „grapes‟);
Extract ($ fruits):
$red will have 'apple'
$yellow will have' banana'
$purple will have' grapes'
 array_push() function:
It adds an element from the end of the array.
array_push($student, 'John');
The element John is added to the $students array.
 array_pop() :
This function removes an element from the end of the array.
ex:- array-pop($students)

Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR


Using Array Functions :-
 array-shift ()
This function is used to pop element at the beginning of the array.
array-shift ($student)
 array-unshift:
This function adds element at the beginning of the array. array-
unshift ($students, „Ronald');
 Explode ()
The explode function splits a string into smaller components on the
basis of a user defined character and then returns those element in
an array.
ex:-
$string=' this is a book';
$words = explode („$string‟, „ „);
This function returns an array variable $words will contain („this‟,
„is‟, „book‟)

Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR


Using Array Functions :-
 implode ()
The implode function create a single string from all the element
of an array joining them together with user defined separator.
EX:-
$words=array(„This‟,‟ is‟, „a‟, „book‟, „of‟, ‟hindi‟);
$string=implode(„ ‟,$words);
$string=‟This is a book of hindi‟;

Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR


Function :-
 A function is a set of program statements that perform a
specific task. Functions can be called or executed from
anywhere in the program.
 All the programming languages have built-in functions and
also allow us to create user defined function. For example we
can use the function with name from c library math.h or we
can define our own function.

Usage of function:-
i. Reducing repetition:
User defined function enables developer to extract commonly
used pieces of code as separate package. So it reduces
unnecessary code repetition and redundancies also makes the
code easier to understand and debug.

Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR


Function :-
ii. Easy maintenance:-
Because functions are defined once and used many times, they
are used to maintain the code. During code maintenance if we
want to change from values in calculation, we need to change
only in the function. We need not traverse the whole program for
making change in one value.
iii. Improves abstraction:
Function forces programmer to think in abstract terms. We need
not worry about implementation of the function. It is enough
that we know the function name, number of arguments and
return type of the function.

Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR


Creating user defined function:-
 In PHP functions are defined with the function keyword
following by name of the function.
 The name of function should follow the rule for naming
variables.
 After function name list of arguments enclosed in
parenthesis() should be present.
 It is optional and can be omitted if no argument is present.
 After the first line of the function the body of the function
should be present in between the curly brackets { }.
 The function code can contain any valid PHP statements,
which includes loops conditional statements and call to other
function.
 Invoking a function is done by calling a function with its
name.
 If the function had arguments we have to specify the
arguments during invoking.

Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR


Creating user defined function:-
 In PHP functions are defined with the function keyword
following by name of the function.
 The name of function should follow the rule for naming
variables.
 After function name list of arguments enclosed in
parenthesis() should be present.
 It is optional and can be omitted if no argument is present.
 After the first line of the function the body of the function
should be present in between the curly brackets { }.
 The function code can contain any valid PHP statements,
which includes loops conditional statements and call to other
function.
 Invoking a function is done by calling a function with its
name.
 If the function had arguments we have to specify the
arguments during invoking.

Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR


Creating user defined function:-
Consider the example below which define a function for
displaying Shakespeare quote in a webpage.
<?php
//define a function
function displayShakesphearQuote()
{
Echo „some are born great, some achieve greatness and some
have greatness through upon them‟;.
}

invoking function
<?php
….
….
displayShakesphearQuote();
?>

Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR


Creating user defined function:-
Example of PHP script for function with argument.
<?php
//define a function
function triangle_area ($base,$height)
{
$area=$base*$height*0.5 return $area;
}
//invoke a function
$ta=triangle_area(10,50); echo‟the area of a triangle is $ta‟;
?>

Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR


Creating user defined function:-
Using arrays as function arguments and a return value
PHP fully supports passing arrays to function. Ex:-
<?php
//define a function with array as argument function
addDomainToUsername($u,$d)
{
//great empty result array
$result_array=array(); forreach($u as $element)
{
$result array[]=$element,‟@‟,$d;
}
return $result_array;
}
$users=array(„John‟, „jim‟ ,‟harry‟);
$newusers=addDomainToUsername($users, „guese.me.domain‟);
?>

Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR


Creating user defined function:-
Q. Write a PHP script for calculation of ncr value using
recursive factorial function
<?php
function fact($F);
{
If f==o return 1;
else
return f*fact f-1;
}
$n=5
$r=3
$RES=fact ($n/(fact $r*fact$n-$r)
echo “The result of ncr calculation”;
echo $RES
?>php

Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR


Sessions :-
 A session is a way to store information (in variables) to be
used across multiple pages. Unlike a cookie, the information
is not stored on the user‟s computer.
What is a PHP Session?
 When you work with an application, you open it, do some
changes, and then you close it. This is much like a Session.
The computer knows who you are. It knows when you start
the application and when you end. But on the internet there is
a problem: the web server does not know who you are or what
you do, because the HTTP address doesn't maintain state.
 Session variables solve this problem by storing user
information to be used across multiple pages (e.g. username,
favorite color, etc). By default, session variables last until the
user closes the browser.

Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR


Sessions :-
 So; Session variables hold information about one single user,
and are available to all pages in one application.
 If you need a permanent storage, you may want to store the
data in a database.
Start a PHP Session
 A session is started with the session_start() function.Session
variables are set with the PHP global variable:
$_SESSION.Now, let's create a new page called
"demo_session1.php".
 In this page, we start a new PHP session and set some session
variables:
<?php
// Start the session session_start();
?>
<!DOCTYPE html>
<html>

Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR


Sessions :-
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>
Get PHP Session Variable Values
 Next, we create another page called "demo_session2.php".
From this page, we will access the session information we set
on the first page ("demo_session1.php").
 Notice that session variables are not passed individually to
each new page, instead they are retrieved from the session we
open at the beginning of each page (session_start()).

Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR


Sessions :-
Also notice that all session variable values are stored in the global
$_SESSION variable:
Example
<?php
session_start();
?>

<!DOCTYPE html>
<html>
<body>
<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
</body>
</html>
Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR
Sessions :-
Another way to show all the session variable values for a user
session is to run the following code:
<?php
session_start();
?>

<!DOCTYPE html>
<html>
<body>
<?php
print_r($_SESSION);
?>
</body>
</html>

Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR


Sessions :-
 How does it work? How users are identified?
Most sessions set a user-key on the user's computer. Then,
when a session is opened on another page, it scans the
computer for a user-key. If there is a match, it accesses that
session, if not, it starts a new session.
Modify a PHP Session Variable
To change a session variable, just overwrite it by using the
following statement
$_SESSION["favcolor"] = "yellow";
Destroy a PHP Session
To remove all global session variables and destroy the session,
use session_unset() and session_destroy()

Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR


Cookie :-
What is a Cookie?
A cookie is often used to identify a user. A cookie is a small file
that the server embeds on the user's computer. Each time the
same computer requests a page with a browser, it will send the
cookie too. With PHP, you can both create and retrieve cookie
values.
Create Cookies With PHP
A cookie is created with the setcookie() function.
Syntax
setcookie(name, value, expire, path, domain, secure, httponly);
Only the name parameter is required. All other parameters are
optional.

Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR


Cookie :-
What is a Cookie?
A cookie is often used to identify a user. A cookie is a small file that
the server embeds on the user's computer. Each time the same
computer requests a page with a browser, it will send the cookie
too. With PHP, you can both create and retrieve cookie values.
Create Cookies With PHP
A cookie is created with the setcookie() function.
Syntax
setcookie(name, value, expire, path, domain, secure, httponly);
Only the name parameter is required. All other parameters are
optional.
PHP Create/Retrieve a Cookie
The following example creates a cookie named "user" with the value
"John Doe". The cookie will expire after 30 days (86400 * 30). The
"/" means that the cookie is available in entire website (otherwise,
select the directory you prefer).
We then retrieve the value of the cookie "user" (using the global
variable $_COOKIE).
Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR
We also use the isset() function to find out if the cookie is set:
Example
<?php
$cookie_name = "user";
$cookie_value = "Jegan Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
// 86400 = 1 day
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR
Cookie :-
Note: The setcookie() function must appear before the <html>
tag.
Note: The value of the cookie is automatically URLencoded when
sending the cookie, and automatically decoded when received (to
prevent URLencoding, use setrawcookie() instead).
Modify a Cookie Value
To modify a cookie, just set (again) the cookie using the
setcookie() function:

Example
<?php
$cookie_name = "user";
$cookie_value = "Atul Kailash";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30),
"/");
?>

Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR


<html>
<body>
<?php if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
Delete a Cookie
To delete a cookie, use the setcookie() function with an
expiration date in the past:
Example
<?php
// set the expiration date to one hour ago setcookie("user", "",
time() - 3600);
?>
Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR
Cookie :-
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>
Check if Cookies are Enabled
The following example creates a small script that checks whether
cookies are enabled. First, try to create a test cookie with the
setcookie() function, then count the $_COOKIE array variable:
Example
<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
<html>
<body>
Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR
Cookie :-
<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
?>
</body>
</html>

Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR


Cookie :-
What is a Cookie?
A cookie is often used to identify a user. A cookie is a small file
that the server embeds on the user's computer. Each time the
same computer requests a page with a browser, it will send the
cookie too. With PHP, you can both create and retrieve cookie
values.
Create Cookies With PHP
A cookie is created with the setcookie() function.
Syntax
setcookie(name, value, expire, path, domain, secure, httponly);
Only the name parameter is required. All other parameters are
optional.

Sunday, 21 January 2024 GIET UNIVERSITY, GUNUPUR

You might also like