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

Chapter 5

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

Chapter 5

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

Chapter Five

Server- Side Scripting - PHP

By: Behayilu M.
Faculty of Computing and Software Eng.,
Arba Minch Institute of Technology(AMiT),
Arba Minch University 1
Web design and Programming
Contents
• Introduction to server-side programming
• Server-side Languages
• PHP Basics
• What is PHP?
• Common uses of PHP
• PHP Pros and Cons
• Elements of PHP
• Installing
• Patterns for processing HTML forms
• Understanding $_GET, $_POST, $_SESSION and other PHP super-arrays
• Dynamically generating HTML
• Manipulating MySQL Databases with PHP
Web design and Programming 2
Introduction to Server-Side Scripting
• Is a technique used in web development which involves employing scripts on a web server
which produce a response customized for each user's (client's) request to the website.
• Is the general name for the kinds of programs which are run on the Server.
• Uses
• Process user input.
• Display pages.
• Structure web applications.
• Interact with permanent storage (SQL, files).
Server-side Languages

PHP
ASP
Ruby
Python
Java …

Web design and Programming 4


What is PHP?
• PHP == ‘PHP: Hypertext Preprocessor’ –recursive acronym

• Open-source, server-side scripting language

• Used to generate dynamic web-pages

• PHP is an interpreted language, i.e. there is no need for compilation.

• PHP is simple and easy to learn language.

• PHP scripts reside between reserved PHP tags


• This allows the programmer to embed PHP scripts within HTML
Web design and Programming 5
Common uses of PHP
• PHP can handle forms, i.e. gather data from files, save data to a file,
through email you can send data, return data to the user.
• PHP performs system functions, i.e. from files on a system it can create,
open, read, write, and close them.
• You add, delete, and 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.
Web design and Programming 6
PHP Advantages
• It’s open source and free from cost.
• It is platform independent
• Application can easily be loaded which are based on PHP and connected to database.

• It’s mainly due to its faster rate of loading over slow internet speed than another

programming language.
• It has less learning curve - easy
• Supports OOP
• Built-in database support minimizes dev time
• Very popular and huge community for support
• Flexible – can be combined with different languages
7
PHP Disadvantages
• It is not that secure due to its open-source, because the ASCII text file are often easily
available.

• It is not suitable for giant content-based web applications.

• Using more features of PHP framework and tools cause poor performance of online
applications.

• PHP don’t allow change or modification in core behavior of online applications.

• The PHP frameworks aren’t equivalent in behavior so does their performance and features.

• While PHP may be a powerful tool supported by an outsized community and plentiful
reference documentation, there are easier programming languages for web apps.
8
Installing PHP
• To install PHP, AMP (Apache, MySQL, PHP) software stack is suggested.

• It is available for all operating systems.

• WAMP for Windows

• LAMP for Linux

• MAMP for Mac

• SAMP for Solaris

• FAMP for FreeBSD

• XAMPP (Cross, Apache, MySQL, PHP, Perl) for Cross Platform: It includes some other
components too such as FileZilla, OpenSSL, Webalizer, Mercury Mail etc.
Web design and Programming 9
Web servers- xampp control panel

Web design and Programming


10
Elements of PHP : Tags and Syntax
• Each PHP script must be enclosed in the reserved PHP tag

• Php script is embedded in html code or included as external file


• Use <?php as a start tag for php and ?> as a closing tag
<?php
//php code goes here
?>

• Can be embedded anywhere in the html code, head ,body or inline with html tags depending on the need
of the programmer
• All PHP statements end with a semi-colon

• Use include(‘phpfile.php’) or require(‘phpfile.php’) functions to include external php code to html


file.
11
• Php script can also be attached to forms action attribute.
Elements of PHP: Tags and Syntax

<?php
if($condition){
?>
<b> This is True </b> Comments in PHP
// C++ and Java-style comment
<?php
# Shell-style comments
} else {
?> /* C-style comments
These can span multiple lines */
<b> This is False </b>
<?php
}
?> 12
Elements of PHP : Variables and Datatypes
• Variables in php are start with a dollar($) symbol followed by valid identifier name

• Variable names are case sensitive

• Variables should be initialized before use – no declaration or type

• PHP is a Loosely Typed Language

• we did not have to tell PHP which data type the variable is.

• PHP automatically converts the variable to the correct data type, depending on its value.

• PHP supports the following data types:

integer float boolean string array object NULL


13
Elements of PHP : Variables and Datatypes
<?php
$age = 25; // Numerical variable
$name = "Sami"; // String variable
$salary = 2543.6; // Float variable
$isMale = true; // Boolean variable

echo $name .“ is ".$age." years old";

$txt = "W3Schools.com";// valid identifier


echo "I love " . $txt . "!";// displaying variable values

$x = 5;
$y = 4; var_dump($x);//int(5) returns the data type of a variable
echo $x + $y;
?> 14
PHP Variables Scope
• Local Variables: Any variable used inside a user-defined function, however, has its scope
limited to the local function.

• Global variables are not available inside local functions unless declared with
the global keyword: <?php
<?php $x = 5;
$x = 5; // global scope $y = 10;

function myTest() { function myTest() {


// using x inside this function will generate an error global $x, $y;
echo "<p>Variable x inside function is: $x</p>"; $y = $x + $y;
} }
myTest();
myTest();
echo "<p>Variable x outside function is: $x</p>"; echo $y; // outputs 15
?> ?> 15
PHP echo and print Statements
• In PHP there are two basic ways to get output: echo and print.

• echo has no return value while print has a return value of 1 so it can be used in expressions.

• echo can take multiple parameters (although such usage is rare) while print can take one
argument. echo is marginally faster than print.

• The echo and print statement can be used with or without parentheses: echo or echo().
<?php
<?php
echo "<h2>PHP is Fun!</h2>";
print "<h2>PHP is Fun!</h2>";
echo "Hello world!<br>";
print "Hello world!<br>“;
echo("Hello world!”);
echo "This ", "string ", "was ", "made ", "with multiple parameters."; Print("I'm about to learn PHP!“);
$txt1 = "Learn PHP";
$txt1 = "Learn PHP";
echo "<h2>" . $txt1 . "</h2>";
echo "<h2>" . $txt1 . "</h2>";
?>
?> 16
PHP Constants
• Constants are like variables except that once they are defined they cannot be changed or undefined.

• Syntax define(name, value, case-insensitive) Parameters:


• The example below creates a constant with name: Specifies the name of the constant
value: Specifies the value of the constant
a case-insensitive name: case-insensitive: Specifies whether the constant
<?php name should be case-insensitive. Default is false
define("GREETING", "Welcome to W3Schools.com!", true);
echo GREETING;
<?php
?>
define("GREETING", "Welcome to W3Schools.com!");
• Constants are automatically global and can be used
function myTest() {
• across the entire script. echo GREETING;
• The example below uses a constant inside a function, }
myTest();
• even if it is defined outside the function: ?>
• const MAX_SIZE=56; // possible // case- insensitive is no longer used 17
PHP Arrays
• An array is a special variable, which can hold more than one value at a time.

• In PHP, there are three types of arrays:

• Indexed arrays - Arrays with a numeric index

• Associative arrays - Arrays with named keys

• Multidimensional arrays - Arrays containing one or more arrays

PHP Indexed Arrays

• $cars = array("Volvo", "BMW", "Toyota");

• The count() function is used to return the length (the number of elements) of an array:
18
• echo count($cars); // 3 echo $cars[1]; // BMW
…cont’d
• Loop Through an Indexed Array • Loop Through an Associative Array

<?php <?php
$cars = array("Volvo", "BMW", "Toyota"); $age = array("Peter"=>"35", "Ben"=>"37",
$arrlength = count($cars); "Joe"=>"43");
for($x = 0; $x < $arrlength; $x++) { foreach($age as $x => $x_value) {
echo $cars[$x]; echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>"; echo "<br>";
} }
?> ?>

PHP Associative Arrays


• Associative arrays are arrays that use named keys that you assign to them.

• $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

• echo "Peter is " . $age['Peter'] . " years old."; 19


Elements of PHP: Conditionals
• if: if (expr) statement;

• if-else: if (expr) statement1; else statement2;

• if-elseif: if (expr) statement1;


elseif (expr) statement2;
else statement3;
switch: switch($var) {
case 0: statements;
break;
case "n": statements;
break;
default: statements;
}
20
Elements of PHP: Loops
• for: for (expr1; expr2; expr3) statements; Same as C++ syntax

• while: while (expr) statements;

• do...while:
do { statements; } while (expr);

• foreach:

• Loops through a block of code for each element in an array;

• On each iteration, the value of the current element is assigned to $value and the internal
array pointerforeach
is advanced byasone.
($array $value) {
code to be executed;
}

• break
21
• continue
Loops - example
$value=array(“html", “css", “js", “php"", “mysql");
for ($j = 0; $j < 5; $j++) {
echo "Value is $array[$j] <br>"; for ($x = 0; $x < 10; $x++) {
} if ($x == 4) {
break;
$i = 1; }
do {
echo "The number is: $x
echo "This will execute at least once.";
$i++; <br>";
} while ($i < 10); }

$i = 0;
Elements of PHP

$num = 50; for ($x = 0; $x < 10; $x++) {


while( $i < 10) { if ($x == 4) {
$num--; continue;
$i++; }
} echo "The number is: $x <br>";
echo("Loop stopped at i = $i and num=$num" }
);
$colors?>}
= array("red", "green", "blue", "yellow");
$colors = array("r"=>"red",
foreach ($colors as $value) {
echo "$value <br>"; "g"=>"green");
} foreach ($colors as $key=>$value)
22
{
echo "$key = $value <br>";
PHP functions
• A user-defined function declaration starts with the word function:
Syntax <?php
function writeMsg() {
function functionName() { echo "Hello world!";
code to be executed; }
writeMsg(); // call the function
} ?>
• The following example has a function with two arguments ($fname and $year):

<?php
function familyName($fname, $year) {
echo "$fname . Born in $year <br>";
} Abebe kebede. Born in 1975
familyName(“Abebe kebede", "1975"); Selam Dawit. Born in 1978
familyName(“Selam Dawit", "1978"); Belay Syum. Born in 1983
familyName(“Belay Syum", "1983");
?>
23
PHP Include Files
• The include (or require) statement takes all the text/code/markup that exists in the specified file and copies it into the

file that uses the include statement.


Syntax include 'filename'; or require 'filename';
• Assume we have a standard footer file called "footer.php", that looks like this:
<?php
echo "<p>Copyright &copy; 1999-" . date("Y") . " W3Schools.com</p>";
?>
• To include the footer file in a page, use the include statement:
Assume we have a file called "vars.php", with
<html> some variables defined:
<body> <?php
<h1>Welcome to my home page!</h1> $color='red';
$car='BMW';
<p>Some text.</p> ?>
<p>Some more text.</p>
<?php include 'footer.php';?> <?php include 'vars.php';
echo "I have a $color $car.";
</body>
?> 24
</html>
Patterns for processing HTML forms
• The PHP super-globals $_GET and $_POST are used to collect form-data.

e .html
om
welc welc
om e.ph
p

25
Patterns for processing HTML forms
• The PHP super-globals $_GET and $_POST are used to collect form-data.
• $_GET is used to collect form data sent with Get method
• $_POST is used to collect form data via Post method
• $_SESSION is used to perform session tracking in php
• $_FILES is an associate double dimension array and keeps all the information related
to uploaded file
• NB: - we should use PHP super-globals in capital letters only
• E.g : for a form control with a name attribute value of name we can write php code to
retrieve value entered as follows:
$_POST[‘name’] or $_GET[‘name’]
• When we have the following code in html
<input type=“text” name=“name” >
26
How to check form submission in PHP ?
• <input type = "submit" name = "submit" value = "Submit">
Syntax:
• if (!empty($_POST)) <form method="post">
• if (isset($_POST['submit']))
Enter value1 :<input type="text" name="str1"><br/>
• Use these two statements to check whether the form
Enter value2 :<input type="text" name="str2"><br/>
submitted successfully or not. <input type="submit" value="Sum"
• PHP isset() function is used to check if a variable has name="Submit1"><br/><br/>
been set or not.
<?php
if(isset($_POST["Submit1"]))
{
$sum=$_POST["str1"] + $_POST["str2"];
echo "The sum = ". $sum;

}
?>
27
Difference between GET and POST
GET vs POST Method in PHP
GET is a method that sends information by appending POST is a method that transfers information via HTTP
them to the page request. header.
URL
The form information is visible in the URL The form information is not visible in the URL
Information Amount
Limited amount of information is sent. It is less than
Unlimited amount of information is sent.
1500 characters.
Usage

Helps to send sensitive data (passwords), binary data


Helps to send non-sensitive data
(word documents, images)and uploading files

Security
Not very secure. More secure.
Bookmarking the Page
Possible to bookmark the page Not possible to bookmark the page 28
Form

<form action="file_uploader.php" method="post"


enctype="multipart/form-data">
<input type="text" name="username"
HTML Code placeholder="username">
<input type="file" name="filename" /><br /><br />
<input type="submit" value="Upload File” name="upload"/>
</form>
if(isset($_POST["upload"]))
{
$user=$_POST["username"];
$filename=$_FILES["filename"]["name"];
PHP Code $filesize=$_FILES["filename"]["size"];
$filetemp=$_FILES["filename"]["tmp_name"];
$filetype=$_FILES["filename"]["type"]; file_uploader.ph
echo "your name is "<br>"; p
echo "file name is ".$filename."<br>";
echo "file size is ".$filesize."<br>";
echo "file temp is ".$filetemp."<br>";
echo "file type is ".$filetype."<br>"; 29
}
Dynamically generating HTML
• Php can dynamically generate html content
• For example : - create a heading tag with php
• <?php echo”<h1> Hello world </h1>”; ?>
• More example : - Create a table
<?php echo”<table border=‘1’>”
echo”<tr>”;
echo”<td> Table data </td> “;
echo”</tr>”;
….
echo”</table>”;
?>
• We can create any html code as we like with php
30
PHP MySQL database functions
What is MySQL?
• MySQL is a database system used on the web DBMS EXAMPLES
• Microsoft access
• Oracle database
• MySQL is a database system that runs on a server • MYSQL
• PostgreSQL
• MySQL is very fast, reliable, and easy to use • MongoDB
• SQLite
• MySQL uses standard SQL

• MySQL compiles on a number of platforms

• MySQL is free to download and use

The data in a MySQL database are stored in tables. A table is a collection of related data, and it consists of
columns and rows.

• With PHP, you can connect to and manipulate databases.


31
• MySQL is the most popular database system used with PHP.
PHP Connect to MySQL
• PHP 5 and later can work with a MySQL database using:

• MySQLi extension (the "i" stands for improved)

• PDO (PHP Data Objects)

• Earlier versions of PHP used the MySQL extension. However, this extension was deprecated
in 2012.

• There are three ways of working with PHP and MYSQL

MySQLi (procedural)

MySQLi (object-oriented) (read)

PDO (PHP Data Objects) (read) 32


Open a Connection to MySQL
• PHP mysqli_connect()
• The PHP mysqli_connect() function is used to connect to a MySQL database server.
<?php
$servername = "localhost";
$username = "username"; Save as
Connection.php
$password = "password";

// Create connection
$conn = mysqli_connect($servername, $username, $password);

// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
Web design and Programming 33
?>
PHP Create a MySQL Database
• PHP mysqli_query() function performs a query against database.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
f (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Create database
$sql = "CREATE DATABASE myDB";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully";
} else {
echo "Error creating database: " . mysqli_error($conn);
}
mysqli_close($conn);
?> Web design and Programming 34
PHP Create MySQL Tables
• A database table has its own unique name and consists of columns and rows.
<?php $conn = mysqli_connect($servername, $username, $password,”myDB”);
include “Connection.php”;
Connection.php
// sql to create table
$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
)";
if (mysqli_query($conn, $sql)) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}

mysqli_close($conn);
?> Web design and Programming 35
PHP insert data into MySQL
• After a database and a table have been created, we can start adding data in them.
<?php
include “Connection.php”;

$sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', '[email protected]')";

if (mysqli_query($conn, $sql))
{
echo "New record created successfully";
}
else
{
echo "Error inserting data” . mysqli_error($conn);
}
mysqli_close($conn);
?> Web design and Programming 36
PHP insert multiple records into MySQL
• Multiple SQL statements must be executed with the mysqli_multi_query() function.

<?php
include “Connection.php”;
$sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', '[email protected]');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Mary', 'Moe', '[email protected]');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Julie', 'Dooley', '[email protected]')";
if (mysqli_multi_query($conn, $sql))
{
echo "New records created successfully";
} else {
echo "Error inserting data”. mysqli_error($conn);
}
mysqli_close($conn);
Web design and Programming 37
?>
PHP prepared statements
• A prepared statement is a feature used to execute the same (or similar) SQL statements repeatedly
with high efficiency.

Prepared statements basically work like this:

• Prepare: An SQL statement template is created and sent to the database. Certain values are left
unspecified, called parameters (labeled "?"). Example: INSERT INTO MyGuests VALUES(?, ?, ?)

• The database parses, compiles, and performs query optimization on the SQL statement template,
and stores the result without executing it.

• Execute: At a later time, the application binds the values to the parameters, and the database
executes the statement. The application may execute the statement as many times as it wants with
different values.
Web design and Programming 38
PHP prepared statements
<?php
include "Connection.php";
$sql="insert into student(fname,lname,sex) values (?,?,?)"; sss(string,string,string)
$stmt=mysqli_prepare($con,$sql); (fname,lname,sex)
mysqli_stmt_bind_param($stmt,"sss",$fname,$lname,$sex);
$fname="Berihu";
$lname="Adane";
$sex="male";

if(mysqli_stmt_execute($stmt))
{
echo "Another student is inserted";
}
else
{
echo "error inserting table student".mysqli_error($con);
}
mysqli_stmt_close($stmt);
mysqli_close($con);
?> Web design and Programming 39
PHP select data from MySQL
• The SELECT statement is used to select data from one or more tables:
<?php
include "Connection.php";
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}mysqli_close($conn);
Web design and Programming 40
?>
PHP update data in MySQL
• The UPDATE statement is used to update existing records in a table:

<?php
include "Connection.php";
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";

if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);
?> Web design and Programming 41
PHP delete data from MySQL
• The DELETE statement is used to delete records from a table:

<?php
include "Connection.php"; How to delete a table
// sql to delete a record  DROP MyGuests;
$sql = "DELETE FROM MyGuests WHERE id=3"; How to delete a database
 DROP DATABASE mydb;
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}mysqli_close($conn);
?> Web design and Programming 42
Selecting the database
• The mysqli_select_db() function is used to select a database.

<?php
$con=mysqli_connect("localhost","root","");
$db=mysqli_select_db($con,"dbstudent");
if(!$con)
{
die("Connection failed").mysqli_connect_errno();
}
else
{
echo "dbDB is selected";
}

?>
Web design and Programming 43
Practical Examples
• Assume that database is created with name: my_personal_contacts having a table named:
my_contacts which contain attributes (ID, Full Names, Gender, Contact No, Email, City,
Country)

1.Database Connection (dbconnection.php)

<?php
$dbh = mysqli_connect("localhost", "root'') or
die("Unable to connect to MySQL: " . mysqli_error($dbh));
if (!mysqli_select_db($dbh, ‘my_personal_contacts'))
die("Unable to select database: " . mysqli_error($dbh));
?>
10/26/2024
practical examples
2. Inserting new records

<?php
include “dbconnection.php”;
$sql_stmt = "INSERT INTO `my_contacts`(`full_names`,`gender`,`contact_no`,`email`,`city`,`country`)";
$sql_stmt .= " VALUES('Peter','Male','541',' peter @ gmail.com ','AA','Ethiopia')";
$result = mysqli_query($dbh,$sql_stmt); //execute SQL statement
if (!$result)
die("Adding record failed: " . mysqli_error($dbh));
else
echo "Peter has been successfully added to your contacts list";
mysqli_close($dbh);
?>

10/26/2024
PHP Cookies
What is a Cookie?
• 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.

• A cookie is often used to identify a user.

Create Cookies With PHP

• With PHP, you can both create and retrieve cookie values.

• A cookie is created with the setcookie( ) function.

Syntax

• setcookie(name, value, expire, path, domain, secure, httponly);


46
• Only the name parameter is required. All other parameters are optional.
PHP Create/Retrieve a Cookie
<?php
$cookie_name = "user";
$cookie_value = “abebe kebede";
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>
• The setcookie() function must appear BEFORE the <html> tag.
47
Modify a Cookie Value
• To modify a cookie, just set (again) the cookie using the setcookie() function:
<?php
$cookie_name = "user";
$cookie_value = “hellen getachew";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<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>
48
</html>
Delete a Cookie Check if Cookies are Enabled

• To delete a cookie, use the setcookie() • The following example creates a small script that
checks whether cookies are enabled. First, try to create
function with an expiration date in the past:
a test cookie with the setcookie() function, then count
<?php
the $_COOKIE array variable:
// set the expiration date to one hour ago <?php
setcookie("user", "", time() - 3600); setcookie("test_cookie", "test", time() + 3600, '/');
?> ?>
<html> <html>
<body> <body>

<?php <?php
echo "Cookie 'user' is deleted."; if(count($_COOKIE) > 0) {
?> echo "Cookies are enabled.";
} else {
</body> echo "Cookies are disabled.";
</html> }
?> 49
PHP 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 users computer.

• Session variables hold information about one single user, and are available to all pages in
one application.

• Sessions allow you to easily


• create multipage forms (such as shopping carts),

• save user authentication information from page to page, and

• store persistent user preferences on a site

50
Start a PHP Session
• Creating, accessing, or deleting a session begins with the session_start( ) function.

• This function will attempt to send a cookie the first time a session is started, so it absolutely
must be called prior to any HTML or white space being sent to the Web browser.

• Therefore, on pages that use sessions, you should call the session_start() function as one of
the very first lines in your script.

• 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:

51
Start a PHP Session
<?php
// Start the session saves as
session_start(); demo_session1.php
?>
<!DOCTYPE html>
<html>
<body>

<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat"; Session variables are set.
echo "Session variables are set.";
?>

</body>
</html>
52
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").
<?php
session_start(); saves as
?> demo_session2.php
<!DOCTYPE html>
<html>
<body>
<?php
// Echo session variables that were set on previous page Favorite color is green
Favorite animal is cat
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
</body>
53
</html>
Modify a PHP Session Variable Destroy a PHP Session
• To change a session variable, just overwrite it: • To remove all global session variables and destroy the session,
use session_unset() and session_destroy():
<?php
<?php
session_start();
session_start();
?>
?>
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>

<body> <body>
<?php
<?php
// remove all session variables
// to change a session variable, just overwrite it session_unset();
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION); // destroy the session
session_destroy();
?>
?>
</body>
</body> 54
</html>
Exercise : create a signup page – with backend

55
56

You might also like