Professional Documents
Culture Documents
2023 GC.
Introduction
What is a Cookie?
A cookie is a small file that the server embeds on
function.
Cookies and Sessions…
user’s computer after the user leaves your Web site, set your cookie with
an expiration time, as follows:
setcookie(“variable”,”value”,expiretime);
Cookies and Sessions…
The expiretime value sets the time when the cookie expires.
The value for expiretime is usually set by using either the
time or mktime function as follows:
time: This function returns the current time in a format the
computer can understand.
You use the time function plus a number of seconds to set the
expiration time of the cookie:
setcookie(“state”, ”CA”, time()+3600); #expires in one hour
$Name=“three_days”;
setcookie(“Name”, $Name, time()+(3*86400)) #expires 3
days
Cookies and Sessions…
mktime: This function returns a date and time in a
format that the computer can understand. You must
provide the desired date and time in the following
order: hour, minute, second, month, day, and year. If
any value is not included, the current value is used.
It is safest to set the cookie with a date you are sure has already expired:
setcookie("vegetable", "", time()-60);
You should also ensure that you pass setcookie() the same path, domain,
and secure parameters as you did when originally setting the cookie.
Cont.
<!DOCTYPE html>
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
Output
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:
<!DOCTYPE html>
<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
<html>
<body>
<?php
if(count($_COOKIE) > 0) { Output
echo "Cookies are enabled."; Cookies are enabled.
} else {
echo "Cookies are disabled.";
}
?>
</body>
</html>
Cont.
What is a PHP Session?
A session is a way to store information (in variables) to be used
Web page.
A session is started with the Session_start() function, as
follows:
session_start();
The function first checks for an existing session ID number.
$_SESSION.
$_SESSION[‘varname’] = “John Bonson”;
When you open a session on any subsequent Web page, the
If you want to stop storing any variable at any time, you can
unset the variable by using the following statement:
unset($_SESSION[‘varname’]);
Cont.
Now, let's create a new page called "session1.php".
In this page, we start a new PHP session and set some session variables:
Example
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body> Output
<?php Session variables are set.
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
Cont.
Get PHP Session Variable Values
Next, we create another page called
"session2.php". From this page, we will access the
session information we set on the first page
("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()).
Cont.
Example2
<?php
session_start();
?> Output
<!DOCTYPE html> Favorite color is green.
Favorite animal is cat.
<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>
Cont.
Another way to show all the session variable values for a user session is to
run the following code:
Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php Output
print_r($_SESSION); Array ( [favcolor] => green [favanimal] => cat )
?>
</body>
</html>
Destroying a Session
You may want to restrict your site to users
with a valid user ID and password.
For restricted sessions that users log into, you
PHP provides too very simple, yet very useful, statements to allow you to
reuse any type of code.
Using include or require statement, you can load a file into your PHP
script.
The file can contain anything you would normally type in a script
including PHP statements, text, HTML tags, etc
Reusing Code…
The two functions are identical in every way, except how they
handle errors:
include() generates a warning (E_WARNING), but the
<?php
echo “Here is a very simple PHP statement. <br>”;
?>
PHP code.
However, there is one big difference between include and
Example
<?php
<html>
<body>
<h1>Welcome to my home page!</h1> Output
<p>Some text.</p> Welcome to my home page!
<p>Some more text.</p> Some text.
include (“footer.php”); Some more text.
?> Copyright © 1999-2016 W3Schools.com
</body>
Include Vs. Require example
Assume we have a file called "vars.php", with some variables defined:
<?php
$color='red';
$car='BMW';
?>
Then, if we include the "vars.php" file, the variables can be used in the
calling file:
Example
<html>
<body>
<?php
<h1>Welcome to my home page!</h1> Output
include (“vars.php”); Welcome to my home page!
echo "I have a $color $car."; I have a red BMW.
?>
</body>
</html>
Include Vs. Require example
If we require the "vars.php" file, the variables can be used in the calling file:
Example
<html>
<body>
<?php
<h1>Welcome to my home page!</h1>
require (“vars.php”);
echo "I have a $color $car.";
?>
</body> Output
</html> Welcome to my home page!
I have a red BMW.
The output is the same with the previous example, because the purpose of using
both of them are the same but, if the file is not found there will give different out
put
Include Vs. Require example
If the file name not match which reuses on other page by using include() or
require() function, we can observe the output difference when using include
and require reusing functions. Take the file name "vars2.php" file, the
variables can be used in the calling file:
Example
<html>
<body>
<?php
<h1>Welcome to my home page!</h1> Output
require (“vars2.php”); Welcome to my home page!
echo "I have a $color $car.";
?>
</body>
</html>
Here when using required() function the script is stop execution after
Include Vs. Require example
When we use include() instead of require() the out put will be:
Example
<html>
<body>
<?php
<h1>Welcome to my home page!</h1>
require (“vars2.php”); Output
Welcome to my home page!
echo "I have a $color $car.";
I have a
?>
</body>
</html>
class classname
{
//code
}
In order to be useful, our classes need attributes and operations.
The following code will create a class named car with two operations.
Classes in PHP…
class car
{
var $name;
var $speed;
function moveforward() //operation1
{
//code here
}
function reverse($param1, $param2) //operation2
{
//code here
}
}
Classes in PHP…
Constructors
Most classes will have a special type of operation called a constructor.
A constructor is called when an object is created, and
performs useful initialization tasks such as setting attributes to sensible
starting values or
creating other objects needed by this object.
A constructor is declared in the same way as other operations, but has the
same name as the class.
We can manually call the constructor
But its main purpose is to be called automatically when an object is
created.
In PHP 5 and later, constructors are named __construct().
Classes in PHP…
class car
{
function car($param)
{
echo “Constructor called with parameter $param <br>”;
}
function __construct()
{
echo “another constructor”;
}
}
Classes in PHP…
Instantiation of Class
After we have declared a class, we need to create an object to
work with
Object is a particular individual that is a member of the class.
This is also known as creating an instance or instantiating a
class.
We create an object using the new keyword.
We need to specify what class our object will be an instance of,
and provide any parameters required by our constructor.
Classes in PHP…
class person
{
var $name;
function person($param)
{
echo “Constructor called with parameter $param <br>”;
}
}
$a = new person(“First”); //instantiation
$b = new person(“Second”); //another instantiation
$c = new person(); //yet another instantiation
Public means that methods or properties inside the class can be accessed
as shown:
class Car
{
var $gas = 0;
function addGas($amount)
{
$this->gas = $this->gas + $amount;
echo “$amount gallons added to gas tank”;
}
Classes in PHP…
You can prevent access to properties by making them private.
PHP provides two options for making properties and methods private,
as follows:
private: No access from outside the class.
protected: No access from outside except from a class inherits current class.
Example:
class Car {
private $gas = 0;
function addGas($amount)
{
$this->gas = $this->gas + $amount;
echo “$amount gallons added to gas tank”;
}
Classes in PHP…
In the following code, line 2 and 3 generates error because
$gas is private:
$mycar = new Car();
$gas_amount = $mycar->gas;
$mycar->gas = 20;
Classes in PHP…
Implementing Inheritance in PHP
If our class is to be a subclass of another, you can use the extends keyword to specify this.
class A
{
var $attribute1;
function operation1()
{
//code here
}
}
class B extends A
{
var $attribute2;
function operation2()
{
//code here
}
Classes in PHP…
All the following accesses to operations and attributes of an object of
type B would be valid:
$b = new B();
$b->operation1();
$b->attribute1 = 10;
$b->operation2();
$b->attribute2 = 10;