Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
0 views

WEB php_PROGRAMMIN2 SWE2

Uploaded by

borel nbonou
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

WEB php_PROGRAMMIN2 SWE2

Uploaded by

borel nbonou
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

IUC DOUALA-CAMEROON

WEB PROGRAMMING II
HND, Software Engineering
Year II / Semester II

COURSE FACILITATOR : TATSOPTEU E. ENDELLY


tatsopt@gmail.com
2020/2021 Academic Year
THE WEB
WWW (also called as Web) is a large scale, online store of information. It is a
system of creating, organizing, and linking of documents. Information is stored
on WWW as a collection of documents that are interconnected with each other
via links. The interconnected documents may be located on one or more than one
computer, worldwide, thus, the name world wide web. The features of WWW and
terms linked to WWW are given below:
 The documents on web are created in hypertext format. Hypertext
facilitates linking of documents.
 The language used to create a hypertext format document is HyperText
Markup Language (HTML). HTML allows the designer of the document to
include text, pictures, video, images, sound, graphics, movies etc., and also
to link contents on the same document or different documents using a
hyperlink.
 The hypertext format document is transferred on the Web using HyperText
Transfer Protocol (HTTP).
 A single hypertext document is called a Web page.
 A group of related web pages is called a Web site. A web site displays
related information on a specific topic.
Request to a Static Site

Request to a Dynamic Site


The server must respond dynamically if it needs to provide different client-side
code depending on the situation:
 Date and time
 Specifics of the user’s request
 Database contents: forms and authentication

COURSE FACILITATOR : TATSOPTEU E. ENDELLY


1
tatsopt@gmail.com
Contents of the HTTP request/response

What is FTP?
File Transfer Protocol, Transfers files between server and client
Its two Basic operations: Downloading and Uploading

How do Web Servers work?


 Client specifies document at a specific web address that is desired
(specified by a URL) Ex: http://www.just.edu.jo/
 If the document is HTML or text, the server simply forwards it back to the
client
– If it is text, it is shown unaltered in the browser

COURSE FACILITATOR : TATSOPTEU E. ENDELLY


2
tatsopt@gmail.com
– If it is HTML it is rendered in the client's browser
 html tags are interpreted and result is shown to the user
 However, the requested document may be an executable script, or it may
be HTML with an embedded script
– The script could be written in any of many different web scripting
Languages
 In these cases, the server executes the script
– If the entire document was a script, the server simply sends the output back
to the client
– If the document had an embedded script, the script sections are replaced
with the output and the modified document is then sent to the client
 Note that the client never sees the server side script code
– This is important – typically client should not see code that the server
executes to process requests
– The server may be accessing files whose names should not be seen, or
preprocessing data that it does not want the client to see
INTRANET, INTERNET AND EXTRANET
Internet
Internet is a global network that connects millions of computers across the world.
It uses standard internet protocol suite (TCP/IP) to connect billions of computer
users worldwide. Every computer in internet is identified by a unique IP address.
It is set up by using electronic, wireless and networking technologies. It is the
fastest mean of sending or exchanging information and data between computers
across the world.

COURSE FACILITATOR : TATSOPTEU E. ENDELLY


3
tatsopt@gmail.com
Internet advantages
Internet covers almost every aspect of life, one can think of.

Internet disadvantages
However, Internet has proved to be a powerful source of information in almost
every field, yet there exists many disadvantages.

Intranet
Intranet is defined as a private network that belongs to a particular organization.
It is designed for the exclusive use of an organization and its associates such as
employees, customers and other authorized people. So, it is like a private internet
that is operating within an organization.
It is based on the internet protocols (TCP/IP) and is protected from unauthorized
access with firewalls and other security systems. So, users on the intranet can
access the internet but the internet users can't access the intranet if they are not
authorized for it. Each computer in Intranet is also identified by a IP Address,
which is unique among the computers in that Intranet.

COURSE FACILITATOR : TATSOPTEU E. ENDELLY


4
tatsopt@gmail.com
Benefits
Intranet is very efficient and reliable network system for any organization. It is
beneficial in every aspect such as collaboration, cost-effectiveness, security,
productivity and much more.

Internet vs. Intranet


Apart from similarities there are some differences between the two. Following are
the differences between Internet and Intranet:

Extranet
Extranet refers to network within an organization, using internet to connect to the
outsiders in controlled manner. It is a communication network that is based on
internet protocols (TCP/IP). It helps to connect businesses with their customers
and suppliers and therefore allows working in a collaborative manner.

COURSE FACILITATOR : TATSOPTEU E. ENDELLY


5
tatsopt@gmail.com
Implementation
Extranet is implemented as a Virtual Private Networks (VPN) because it uses
internet to connect to corporate organization and there is always a threat to
information security. VPN offers a secure network in public infrastructure
(Internet).

Benefits
Extranet proves to be a successful model for all kind of businesses whether small
or big. Here are some of the advantages of extranet for employees, suppliers,
business partners, and customers:

COURSE FACILITATOR : TATSOPTEU E. ENDELLY


6
tatsopt@gmail.com
WEB DEVELOPMENT TOOLS
Web development refers to building website and deploying on the web. Web
development requires use of scripting languages both at the server end as well
as at client end.
Web development tools helps the developer to test and debug the web sites.
Now a days the web development tools come with the web browsers as add-ons.
All web browsers have built in tools for this purpose. These tools allow the
web developer to use HTML, CSS and JavaScript etc. . These are accessed by
hovering over an item on a web page and selecting the “Inspect Element” from
the context menu.

Skills Required
For being a successful web developer, one should possess the following skills:
 Understanding of client and server side scripting.
 Testing cross browser inconsistencies.
 Conducting observational user testing.
 Testing for compliance to specified standards such as accessibility
standards in the client region.
 Programming interaction with javaScript, PHP, and Jquery etc.

SERVER-SIDE WEB PROGRAMMING


URLs and web servers
 Usually when you type a URL in your browser:

COURSE FACILITATOR : TATSOPTEU E. ENDELLY


7
tatsopt@gmail.com
- your computer looks up the server's IP address using DNS
- your browser connects to that IP address and requests the given file
- the web server software (e.g. Apache) grabs that file from the server's
local file system, and sends back its contents to you
 Some URLs actually specify programs that the web server should run, and
then send their output back to you as the result: http://server/path/file
Server-side pages are programs written using one of many web programming
languages/frameworks. Examples: PHP, Java/JSP, Ruby on Rails, ASP.NET,
Python, Perl.
The web server contains software that allows it to run those programs and send
back their output as responses to web requests.
We use PHP for server-side programming in this course.
Principle of server side script

 Pages are generated by a program


 A html document at the server side includes the code to be executed (script)
 The code is delimited via special escape characters
 The web server extracts the script part from the document
 A script engine runs the code
 Web server replaces the script with the output of the execution
 Client sees pure html (no way to access the code)
PHP Fundamentals
What is PHP?
 PHP stands for "PHP Hypertext Pre-processor"
 a server-side scripting language (PHP scripts are executed on the server)
 used to make web pages dynamic:
- provide different content depending on context
- interface with other services: database, e-mail, etc
- authenticate users
- process form information

COURSE FACILITATOR : TATSOPTEU E. ENDELLY


8
tatsopt@gmail.com
 PHP code can be embedded in HTML code
 The default file extension for PHP files is ".php".
Features of PHP
 PHP can generate dynamic page content
 PHP can create, open, read, write, delete, and close files on the server
 PHP can collect form data
 PHP can send and receive cookies
 PHP can add, delete, modify data in your database
 PHP can be used to control user-access.
 PHP can encrypt data.
 PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
 PHP is compatible with almost all servers used today (Apache, IIS, etc.)
 PHP supports a wide range of databases.
Evaluation of PHP
PHP was introduced by Rasmus Lerdorf in 1994. It was developed to track visitor
of his resume. When PHP was developed Full form of PHP was “Personal Home
Page”. PHP is useful to implement a service in the cloud, develop web side and
web applications.
Lifecycle of a PHP web request

 browser requests a .html file (static content): server just sends that file
 browser requests a .php file (dynamic content): server reads it, runs any
script code inside it, then sends result across the network
- script produces output that becomes the response sent back
So in Server side execution,
 Code is scattered inside a html document
COURSE FACILITATOR : TATSOPTEU E. ENDELLY
9
tatsopt@gmail.com
 The web server executes the code and produces a simple html page

PHP + MySQL
PHP combined with MySQL are cross-platform (you can develop in Windows
and serve on a Unix platform). The graphic below shows a basic workflow of
dynamic content being passed to and from the client using PHP combined with
database.

PHP Dynamic Content Interaction

Why PHP?
There are many other options for server-side languages: Ruby on Rails, JSP,
ASP.NET, etc. Why choose PHP?
 free and open source: anyone can run a PHP-enabled server free of charge
 compatible: supported by most popular web servers
 simple: lots of built-in functionality; familiar syntax
 available: installed on UW's servers (Dante, Webster) and most commercial
web hosts

COURSE FACILITATOR : TATSOPTEU E. ENDELLY


10
tatsopt@gmail.com
Installation and configuration of a Web server (WAMP / XAMP server)
XAMPP Setup
XAMPP is a free and open source cross-platform web server solution developed
by Apache Friends, consisting mainly of the Apache HTTP Server, MariaDB
database, and interpreters for scripts written in the PHP and Perl programming
languages. In order to make your PHP code execute locally, first install XAMPP.
 Download XAMPP
 Install the program (check the technologies you want during installation)
 Open XAMPP and click on "Start" on Apache and MySQL (when working
with databases)

XAMPP window after a successful installation with Apache and MySQL enabled
 Place your web project inside the htdocs directory. In the common case, if
you installed XAMPP directly inside the C: drive of your PC, the path to
this folder would be: C:xampphtdocs
 To test the services are up and running you can just enter localhost in your
address bar and expect the welcoming page.
 To see information about how PHP is configured, version information, and
the settings of all environment variables (e.g., HTTP_USER_AGENT and
QUERY_STRING), call the phpinfo()function in any script.
 The php.ini file is the main configuration file for PHP. It can be edited by
the system administrator to change any of the configuration settings. A
change to this file requires the web server be restarted since the file is only
read once when the web server starts up. (The phpinfo()function reports the
location of php.ini on the server.)
PHP Basic Syntax
A PHP script can be placed anywhere in the document.
A PHP script starts with <?php and ends with ?>
Hello, World! Program
The following contents could go into a file hello.php:

COURSE FACILITATOR : TATSOPTEU E. ENDELLY


11
tatsopt@gmail.com
 A block or file of PHP code begins with <?php and ends with ?>
 PHP statements, function declarations, etc. appear between these endpoints
 you can't view your .php page on your local hard drive; you'll either see
nothing or see the PHP source code
 if you upload the file to a PHP-enabled web server, requesting the .php file
will run the program and send you back its output
Input/Output
 print and echo are used to print to the browser.
echo"Go Bisons";
echo("Go Bisons"); // same thing
print("Go Bisons"); // same thing
 print can only accept one argument, and echo can accept any number of
arguments. Print returns a value that indicates if the print statement
succeeded.
 Variables are interpolated inside of strings unless single quotes are used.
$a = "guts";
echo "You have $a."; // prints "You have guts."
echo 'You have $a.'; // prints "You have $a."
 Escape sequences: \n (newline), \r (carriage-return), \t (tab), \$ ($), \” (“), \\ (\)
echo "a\\b\tc\$d"; // prints "a\b c$d"
echo 'a\\b\tc\$d'; // prints "a\b\tc\$d". Only \\ is converted.
 printf works like C’s counter-part.
$title = "X-Men";
$amount = 54.235;
printf("The movie <b>%s</b> made %2.2f million.", $title,$amount);
// prints "The movie <b>X-Men</b> made 54.23 million."
 Output shortcut from within HTML:
Hello, <b><?= $name ?></b> is the same as Hello, <b><?php echo $name ?></b>
Comments
A comment in PHP code is a line that is not read/executed as part of the
program. It is only purpose is to be read by someone who is looking at the code.

COURSE FACILITATOR : TATSOPTEU E. ENDELLY


12
tatsopt@gmail.com
Variables
A variable can have a short name (like x and y) or a more descriptive
name (age, carname, total_volume).
Rules for PHP variables:
 A variable starts with the $ sign (on both declaration and usage), followed
by the name of the variable
 A variable name must start with a letter or the underscore character
 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
 Variable names are case-sensitive ($age and $AGE are two different
variables)
 always implicitly declared by assignment (type is not written)
 a loosely typed language (like JavaScript or Python)

PHP Constant
A constant is an identifier (name) for a simple value. The value cannot be changed
during the script. A valid constant name starts with a letter or underscore (no $
sign before the constant name). Constants are defined using define and by
convention are usually named in ALL CAPITALS.

COURSE FACILITATOR : TATSOPTEU E. ENDELLY


13
tatsopt@gmail.com
define("PI", 3.14);
define("HEADING", "<h1>My Web Site</h1>");
$area = PI * $radius * $radius;
print(HEADING);

PHP Data Types


PHP supports the following data types:
 String: A string can be any text inside quotes.
Ex. $fname = “piyush”; $lname = “Gupta”;
 Integer: negative and positive whole number
 Float: Value with decimal point ex. – 0.5, 1.0
 Boolean: A Boolean represents two possible states: TRUE or FALSE.
 Array: An array stores multiple values in one single variable.
Ex. $number = array(45, 60, 55, 25);
 Object: Instance of class
Ex. $obj = new mysqli();
 NULL: A variable of data type NULL is a variable that has no value
assigned to it.
 Resource: It is the storing of a reference to functions and resources external
to PHP.
Ex. connection to database, mail server

 Int for integers and float for reals


 division between two int values can produce a float
bool (Boolean) type

COURSE FACILITATOR : TATSOPTEU E. ENDELLY


14
tatsopt@gmail.com
 the following values are considered to be FALSE(all others are TRUE):
- 0 and 0.0 (but NOT 0.00 or 0.000)
- " ", "0", and NULL(includes unset variables)
- arrays with 0 elements
 can cast to boolean using (bool)
 FALSE prints as an empty string (no output); TRUE prints as a 1
 TRUE and FALSE keywords are case insensitive
NULL

 a variable is NULL if
- it has not been set to any value (undefined variables)
- it has been assigned the constant NULL
- it has been deleted using the unset function
 can test if a variable is NULL using the isset function
 NULL prints as an empty string (no output)
String type

 zero-based indexing using bracket notation


 string concatenation operator is .(period), not +
- 5 + "2 turtle doves" === 7
- 5 . "2 turtle doves" === "52 turtle doves"
 can be specified with " "or ' '
Some PHP string functions
 Concatenation: $full_name = $first_name . " " . $last_name; // results in
"Bob Smith"
 int strlen($str): Returns string length.
 int strcmp($str1, $str2): Returns < 0 if str1 is less than str2; > 0 if str1 is
greater than str2, and 0 if they are equal. (strcasecmp for case-insensitive
comparison.) The < > == operators can also be used if both arguments are
strings. strcmp is useful if an argument may not be a string and has to be
converted into one.

COURSE FACILITATOR : TATSOPTEU E. ENDELLY


15
tatsopt@gmail.com
 string strstr($text, $search): Returns first occurrence of $search in $text,
FALSEif not found. (stristr for case-insensitive search.)
 string str_replace($find, $replace, $text): Replaces all occurrences of $find
with $replace in $text.
 string chop($str): Removes all white space at end of string.
 string ltrim($str) Removes all white space at beginning of string.
 string trim($str) Removes all white space at beginning and end of string.

OPERATORS
Operators are special symbols to perform specific arithmetic logical operations

COURSE FACILITATOR : TATSOPTEU E. ENDELLY


16
tatsopt@gmail.com
Arithmetic operators

Assignment Operators

Comparison Operator

COURSE FACILITATOR : TATSOPTEU E. ENDELLY


17
tatsopt@gmail.com
Increment/decrement Operator

String Operator

Logical Operator

COURSE FACILITATOR : TATSOPTEU E. ENDELLY


18
tatsopt@gmail.com
CONTROL STRUCTURES
Conditional control structure
Choice structures

1. if ($x > 0)
$y = 5; // {} not required for only one statement

2. if ($a) { // tests if $a is true or non-zero or anon-empty string


print($b);
$b++;
}
else
print($c);

3. if ($a > $b)


print "a is bigger than b";
elseif ($a == $b) // use "elseif" or "else if"
print "a is equal to b";
else
print "a is smaller than b";

4. switch ($vehicle_type) { // works for integers, floats, or strings


case "car": $car++; break;
case "truck": $truck++; break;
case "suv": $suv++; break;
default: $other++;}
loop control structures
while loop

1. while ($n < 10) {


print("$n ");
$n++;
}

COURSE FACILITATOR : TATSOPTEU E. ENDELLY


19
tatsopt@gmail.com
2. do {
print("$n ");
$n++;
} while ($n < 10);

for loop

1. for ($n = 1; $n < 10; $n++)


print("$n ");

4. foreach ($myarray as $item)


print("$item ");
EMBEDDING CODE IN WEB PAGES
 most PHP programs actually produce HTML as their output
- dynamic pages; responses to HTML form submissions; etc.
 an embedded PHP program is a file that contains a mixture of HTML and
PHP code
Syntax for embedded PHP

 any contents of a .php file that are not between <?php and ?> are output as
pure HTML
 can switch back and forth between HTML and PHP "modes"

COURSE FACILITATOR : TATSOPTEU E. ENDELLY


20
tatsopt@gmail.com
 the above code would be saved into a file such as count.php
 How many lines of numbers will appear? (View Source!)
Embedded PHP + print = bad
 best PHP style is to use as few print/echo statements as possible in
embedded PHP code
 But without print, how do we insert dynamic content into the page?
PHP expression blocks

COURSE FACILITATOR : TATSOPTEU E. ENDELLY


21
tatsopt@gmail.com
COURSE FACILITATOR : TATSOPTEU E. ENDELLY
22
tatsopt@gmail.com
FUNCTIONS
 Functions may be declared anywhere in the source code (i.e., they do not
need to be defined before they are called as C++ requires).
 Function names are case-insensitive, though it is usually good form to call
functions as they appear in their declaration.
 Defining and calling
1. General form:

COURSE FACILITATOR : TATSOPTEU E. ENDELLY


23
tatsopt@gmail.com
function func_name ($param_1, $param_2, ..., $param_n) {
// code
return $retval; // optional: can return a scalar or an array
}
2. Call: $result = func_name ($arg1, $arg2, ..., $argn);

 Parameter passing and returning values


1. Arguments may be passed by value (default) or byreference (using &).
Default argument values can also be used which must be initialized in
the parameter list. Variable-length argument lists are also supported but
are not covered here.
// Pass by value
function sum ($a, $b) {
return$a + $b;
}
// Pass by reference
function swap (&$a, &$b) {
$temp = $a;
$a = $b;
$b = $temp;
}
// Default arguments must be on right side
function say_greeting ($name, $greeting="Hello") {
print "$greeting, $name!";
}
say_greeting ("Susan"); // Hello, Susan!
say_greeting ("Rita", "Hola"); // Hola, Rita!

COURSE FACILITATOR : TATSOPTEU E. ENDELLY


24
tatsopt@gmail.com
2. Passing an array by value and by reference
// Pass by value
function sum_array ($values) {
$sum = 0;
foreach ($values as $num)
$sum += $num;
return $sum;
}
$nums = array(1, 2, 3);
print "Sum of array = " . sum_array($nums); // 6
// Pass by reference
function randomize (&$nums) {
for ($i = 0; $i < 10; $i++)
$nums[$i] = rand(0, 100); // 0-100
}
$n = array();
randomize($n); // Place 10 random nums in $n
3. Return an array
// Return an array list($pi, $euler, $phi) = special_nums();
function special_nums() {
return array(3.142, 2.718, 1.618);
}

COURSE FACILITATOR : TATSOPTEU E. ENDELLY


25
tatsopt@gmail.com
Including files: include()

Arrays
 Arrays can have any size and contain any type of value. No danger of going
beyond array bounds.
$my_array[0] = 25;
$my_array[1] = "Bisons";
 PHP arrays are associative arrays which allow element values to be stored
in relation to a key value rather than a strict linear index order.
$capitals["CO"] = "Denver";
$capitals["AR"] = "Little Rock";
 Initialize an array:
$colors = array("red", "green", "blue");
print("The 2nd color is $colors[1]."); // prints green
$capitals = array("CO" => "Denver", "AR" => "Little Rock");
print("$capitals[CO]"); // prints Denver, no quotes around key inside ""
 Print contents of an array for debugging:
print_r($colors);
produces:

COURSE FACILITATOR : TATSOPTEU E. ENDELLY


26
tatsopt@gmail.com
Array (
[0] => red
[1] => green
[2] => blue
)
print_r($capitals);
produces:
Array (
[CO] => Denver
[AR] => Little Rock
)
 Pull values out of an array:
$colors = array("red", "green", "blue");
list($c1, $c2) = $colors;
print("$c1 and $c2"); // prints "red and green"
 Delete from an array:
unset($colors[1]); // $colors now contains red and blueat indexes 0 and 2.
 Extracting array keys and values:
$states = array_keys($capitals); // $states is ("CO", "AR")
$cities = array_values($capitals); // $cities is ("Denver", "Little Rock")
 Iterating through an array:
$heroes = array('Spider-Man', 'Hulk', 'Wolverine');
foreach($heroes as $name)
print("$name<br />"); // prints all three in order
foreach($capitals as $state => $city)
print("$city is the capital of $state.<br />");
 Treat an array like a stack:
array_push($heroes, 'Iron Man'); // Pushed onto end of array
$heroes[] = 'Captain America'; // Same thing as array_push
$h = array_pop($heroes); // Pops off last element (Iron Man)
 Size of an array:
$num_items = count($heroes); // returns 3
 Sort an array:
sort($heroes); // Heroes are now in alphabetical order (lowest to highest)
rsort($heroes); // Reverse alphabetical order (highest to lowest)

COURSE FACILITATOR : TATSOPTEU E. ENDELLY


27
tatsopt@gmail.com
COURSE FACILITATOR : TATSOPTEU E. ENDELLY
28
tatsopt@gmail.com
The foreach loop

COURSE FACILITATOR : TATSOPTEU E. ENDELLY


29
tatsopt@gmail.com
FORM DATA HANDLING
Web Form Input
 Data from web forms can be accessed using the superglobal arrays $_GET
and $_POST.
 $_GET: for accessing data in the query string– the key=value pairs that
appear in the URL after the “?” character. All values are unescaped (+ is
converted to space, etc.).
Example:
http://www.example.com/myscript.php?custname=Bob+Smith&custage=21
$name = $_GET["custname"]; // $name is "Bob Smith"
$age = $_GET["custage"]; // $age is 21
 $_POST: for accessing posted for data from standard input (values are
unescaped).
Example STDIN: custname=Bob+Smith&custage=21
$name = $_POST["custname"]; // $name is "Bob Smith"
$age = $_POST["custage"]; // $age is 21
 It’s always a good idea to use isset to check if the variable exists in $_POST
and $_GET before accessing to avoid PHP warnings:
if (!isset($_POST["custname"]) || trim($_POST["custname"]) =="")
echo "The customer's name was left blank.";
 Shortcut to accessing variables in $_GET and $_POST: extract puts all
key/value pairs in identically named variables. Warning: collisions occur
between identically named variables.
extract($_POST);
if (isset($custname))
echo "Hello, $custname!";

Managing variables
 isset ( ): determines whether a certain variable has already been declared
by PHP.
 unset( ): “undeclares” a previously set variable, and frees any memory that
was used by it if no other variable references its value.
 empty ( ): empty( ) may be used to check if a variable has not been declared
or its value is false.
Predefined System "Superglobals"
 Provide access to key runtime data elements.
 Set by and managed through web server run-time environment and
available to the script.

COURSE FACILITATOR : TATSOPTEU E. ENDELLY


30
tatsopt@gmail.com
 Superglobals are key to form processing, cookies, and other techniques.
Some Superglobal
The PHP superglobals $_GET and $_POST and $_REQUEST are used to collect
form data.
 $_GET[ ]: An array that includes all the GET variables that PHP received
from the client browser.
 $_POST[ ]: An array that includes all the POST variables that PHP
received from the client browser.
 $_COOKIE[ ]: An array that includes all the cookies that PHP received
from the client browser.
 $_SERVER[ ]: An array with the values of the web-server variables.
 $_SESSION[ ]: Array with values concerning a ‘session’
1. GET Method
 Information sent from a form with the GET method is visible to everyone
(all variable names and values are displayed in the URL).
 GET also has limits on the amount of information to send. The
limitation is about 2000 characters.
 GET may be used for sending non-sensitive data.
 GET should NEVER be used for sending passwords or other sensitive
information!
 $_GET superglobal Array is used to access data.
2. Post Method
 Information sent from a form with the POST method is invisible to others.
 has no limits on the amount of information to send.
 POST method is secure than GET Method.
 POST is used for sensitive data.
 $_POST superglobal Array is used to access data.
3. Request Method
 $_REQUEST is a super global variable which is widely used to collect data
after submitting html forms.
 It is used to access data sent through get and post method.

COURSE FACILITATOR : TATSOPTEU E. ENDELLY


31
tatsopt@gmail.com
COURSE FACILITATOR : TATSOPTEU E. ENDELLY
32
tatsopt@gmail.com
When creating a form
Key elements:
 Input fields must be contained inside a form tag.
 All input fields must have a name.
 Names cannot have spaces in them. Fields should be named well for clear
identification.
 Form action should be URL to PHP processing script.
 Appropriate form transmission method selected: GET or POST.

Maintaining State
 To keep track of data between HTTP requests, data can be stored in cookies
using the $_COOKIE array, or it can be stored on the web server via
session variables in the $_SESSION array.
 setcookie() and session_start() functions below must be called before any
other output is produced unless output_buffering is turned on in php.ini.
 $_COOKIE: for accessing HTTP cookies which are stored on the client
and are transmitted back to the web server in every HTTP request.
1. By default, cookies expire with the session. Closing the browser (not
just the tab) ends the session. setcookie ("age", "21");
2. Cookies can be given expiration dates so they persist even after the
browser is closed:
// Cookie expires in 24 hours
setcookie ("name", "Betty", time() + 60 * 60 * 24);
3. Getting the value of a cookie:
echo $_COOKIE["name"]; // Print contents of name cookie
Note that $_COOKIE will not have values set from setcookie() until the
php script is requested after a call to setcookie.
4. Deleting a cookie:
setcookie("name", FALSE);
5. Warning: Since cookies are stored on the client, they should not be used
to store sensitive data.
 $_SESSION: for accessing session variables which are stored on the web
server. Variables are associated with a unique session ID which is stored in
a cookie or passed in the URL if cookies are disabled. This technique is
ideal for storing sensitive data since the data is not stored on the client.
1. Create a session (and a session ID) if one doesn’t already exist:
session_start();
2. If you are curious what the session ID looks like: echo session_id();

COURSE FACILITATOR : TATSOPTEU E. ENDELLY


33
tatsopt@gmail.com
3. Set a session variable that is stored on the webserver and tied to the
user’s session ID: $_SESSION["name"] = "Betty";
4. Get the value of a session variable that is tied to the user’s session ID:
$auto = $_SESSION["name"];
5. Session variables are cleared when the browser is closed or when
destroying the session explicitly: session_destroy();

Cookie Handling
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.
 A cookie is often used to identify a user.
 A cookie is created with the setcookie() function.
 The setcookie() function must appear BEFORE the <html> tag.
Setting Cookie

COURSE FACILITATOR : TATSOPTEU E. ENDELLY


34
tatsopt@gmail.com
Deleting Cookie

Session Management
A session is a way to store information (in variables) to be used across multiple
pages.
 By default, session variables last until the user closes the browser.
 Session variables hold information about one single user, and are available
to all pages in one application.
 Session data is stored on web server.
Start Session
A session is started with the session_start() function. Session variables are
set with the PHP global variable: $_SESSION.
The session_start() function must be the very first thing in your document.
Before any HTML tags.
let's create a new page called "demo_session1.php". In this page, we start
a new PHP session and set some session variables:

COURSE FACILITATOR : TATSOPTEU E. ENDELLY


35
tatsopt@gmail.com
Accessing Session 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").

Destroy PHP Session


To remove all global session variables and destroy the session, use
session_unset() and session_destroy().

COURSE FACILITATOR : TATSOPTEU E. ENDELLY


36
tatsopt@gmail.com
DATABASE HANDLING
 Recall the basic reason for server-side programming
- We need to store client data or look up data stored on the server
 Databases give us an easy way to issue “commands” to insert, select,
organize, and remove data
 MySQL: open-source database, relatively easy to set up, easy to use with
PHP

With PHP, you can connect to and manipulate databases. MySQL is the most
popular database system used with PHP.

COURSE FACILITATOR : TATSOPTEU E. ENDELLY


37
tatsopt@gmail.com
Connecting to MySQLi Databases
The MySQLi stands for MySQL improved. The syntax for connecting to a
database using MySQLi extension is:

Insert data

COURSE FACILITATOR : TATSOPTEU E. ENDELLY


38
tatsopt@gmail.com
Updating data

COURSE FACILITATOR : TATSOPTEU E. ENDELLY


39
tatsopt@gmail.com
Deleting data

COURSE FACILITATOR : TATSOPTEU E. ENDELLY


40
tatsopt@gmail.com
Fetching data

SQL injection
 Attacker guesses the format of a query, then exploits
- If the attacker is able to form a valid SQL query using one of the input
fields, then there may be unintended results

PROJECT

COURSE FACILITATOR : TATSOPTEU E. ENDELLY


41
tatsopt@gmail.com

You might also like