SlideShare a Scribd company logo
1 of 74
ITCS 323
Web Programming Concepts III
COURSE OVERVIEW
What is PHP?
recursive acronym for PHP: Hypertext
Preprocessor
a widely-used open source general-purpose
scripting language
What is PHP?
especially suited for web development and
can be embedded into HTML
is a server-side scripting language
scripts are executed on the server
supports many databases (MySQL, Informix,
Oracle, Sybase, Solid, PostgreSQL, Generic ODBC
What is PHP?
PHP files can contain text, HTML tags and
scripts
 PHP pages contain HTML with embedded code
that does "something"

have a file extension of ".php", ".php3", or
".phtml“
enclosed in special start and end processing
instructions <?php and ?>
 allow you to jump into and out of "PHP mode."
Example
• <!DOCTYPE HTML PUBLIC <html>
<head>
<title>Example</title>
</head>
<body>
<?php
echo “Hello World!";
?>

</body>
</html>
Why PHP?
open source software
free to download and use

runs on different platforms (Windows, Linux,
Unix, Mac OS X, RISC OS, etc.)
compatible with almost all servers used today
(Apache, IIS, etc.)
support for a wide range of databases
with PHP, you have the freedom of choosing
an operating system and a web server
Why PHP?
not limited to output HTML
 PHP's abilities includes outputting images, PDF
files and even Flash movies (using libswf and
Ming) generated on the fly
 can autogenerate files, and save them in the file
system
Why PHP?
1. Easy to Use

Code is embedded into HTML. The PHP code is enclosed in special start
and end tags that allow you to jump into and out of "PHP mode".

•

<html>
<head>
<title>Example</title>
</head>
<body>

<?php
echo "Hi, I'm a PHP script!";
?>
Why PHP?
2. Cross Platform

Runs on almost any Web server on several operating systems.
One of the strongest features is the wide range of supported
databases



Web Servers: Apache, Microsoft IIS, Caudium, Netscape Enterprise
Server
Operating Systems: UNIX (HP-UX,OpenBSD,Solaris,Linux), Mac OSX,
Windows NT/98/2000/XP/2003


Supported Databases: Adabas D, dBase,Empress, FilePro (read-only),
Hyperwave,IBM DB2, Informix, Ingres, InterBase, FrontBase, mSQL, Direct
MS-SQL, MySQL, ODBC, Oracle (OCI7 and OCI8), Ovrimos, PostgreSQL,
SQLite, Solid, Sybase, Velocis,Unix dbm
Why PHP?
3. Cost Benefits

PHP is free. Open source code means that the entire PHP
community will contribute towards bug fixes. There are several
add-on technologies (libraries) for PHP that are also free.

PHP
Software

Free

Platform

Free (Linux)

Development Tools

Free
PHP Coder, jEdit
Difference?
Compare to other client-side program like java
script. PHP code is executed on the server
PHP combined with MySQL are cross-platform
(you can develop in Windows and serve on a
Unix platform)
It is an open source
Three main areas where PHP scripts
are used.

1. Server-side scripting.
2. Command line scripting.
3. Writing desktop applications.
Three main areas where PHP scripts
are used.
1. Server-side scripting.
 most traditional and main target field for PHP
 three things to make this work
1. PHP parser (CGI or server module)
2. web server
3. web browser
Three main areas where PHP scripts
are used.
2. Command line scripting
 run PHP script without any server or browser
 only need the PHP parser to use
 this type of usage is ideal for scripts regularly
executed using cron (on *nix or Linux) or Task
Scheduler (on Windows).
 These scripts can also be used for simple text
processing tasks
Three main areas where PHP scripts
are used.
3. Writing desktop applications.
 One of the advance features of PHP
 have the ability to write cross-platform
applications
 PHP-GTK is an extension to PHP
 not available in the main distribution
What is needed?
Web sever that support php (apache server)
Sql database (MySql)
PHP installer
Assignment
• How to install, configure and use php
• Give different AMP packages
• Give different php functions, give example
code and syntax
Overview to PHP

BRIEF HISTORY
Brief History
PHP (PHP: Hypertext Preprocessor) was created by Rasmus Lerdorf in 1994. It
was initially developed for HTTP usage logging and server-side form
generation in Unix.
PHP 2 (1995) transformed the language into a Server-side embedded scripting
language. Added database support, file uploads, variables, arrays,
recursive functions, conditionals, iteration, regular expressions, etc.
PHP 3 (1998) added support for ODBC data sources, multiple platform
support, email protocols (SNMP,IMAP), and new parser written by Zeev
Suraski and Andi Gutmans .
PHP 4 (2000) became an independent component of the web server for
added efficiency. The parser was renamed the Zend Engine. Many security
features were added.
PHP 5 (2004) adds Zend Engine II with object oriented programming, robust
XML support using the libxml2 library, SOAP extension for interoperability
with Web Services, SQLite has been bundled with PHP
As of August 2004, PHP is used on 16,946,328 Domains,
1,348,793 IP Addresses http://www.php.net/usage.php
This is roughly 32% of all domains on the web.
Introduction

PHP START UP
Objectives
PHP Structure
Variables, operators, and Comments
PHP Arrays
Passing Variables in Links
HTML special Characters
Passing Variables in Forms
Installation Procedure
1. install your selected HTTP (web) server on
your system, and make sure that it works.
2. Run the executable installer and follow the
instructions provided by the installation
wizard.
 Two types of installation are supported –
1. standard, which provides sensible defaults for all the
settings it can,
2. advanced, which asks questions as it goes along.
Installation Procedure
3. The installation wizard gathers enough
information to set up the php.ini file, and
configure certain web servers to use PHP. One of
the web servers the PHP installer does not
configure for is Apache, so you'll need to
configure it manually.
4. Once the installation has completed, the
installer will inform you if you need to restart
your system, restart the server, or just start
using PHP.
PHP Script
• Typically file ends in .php--this is set by the web
server configuration
• Separated in files with the <?php ?> tag
• php commands can make up an entire file, or can
be contained in html--this is a choice….
• Program lines end in ";" or you get an error
• Server recognizes embedded script and executes
• Result is passed to browser, source isn't visible
<P>
<?php $myvar = "Hello World!";
echo $myvar;
?>
</P>
Two ways
• You can embed sections of php inside html:
<BODY>
<P>
<?php $myvar = "Hello World!";
echo $myvar;
</BODY>

• Or you can call html from php:
<?php
echo "<html><head><title>Howdy</title>
…
?>
Variables
• Typed by context (but one can force type), so it's
loose
• Begin with "$" (unlike javascript!)
• Assigned by value
– $foo = "Bob"; $bar = $foo;

• Assigned by reference, this links vars
– $bar = &$foo;

• Some are preassigned, server and env vars
– For example, there are PHP vars, eg. PHP_SELF,
HTTP_GET_VARS
Variables
• Case-sensitive ($Foo != $foo != $fOo)
• Global and locally-scoped variables
– Global variables can be used anywhere
– Local variables restricted to a function or class

• Certain variable names reserved by PHP
– Form variables ($_POST, $_GET)
– Server variables ($_SERVER)
– Etc.
Variable of variable
• Using the value of a variable as the name of
a second variable)
$a = "hello";
$$a = "world";

• Thus:
echo "$a ${$a}";

• Is the same as:
echo "$a $hello";

• But $$a echoes as "$hello"….
Variable usage
<?php
$foo = 25;
$bar = “Hello”;
$foo = ($foo * 7);
$bar = ($bar * 7);
?>

// Numerical variable
// String variable
// Multiplies foo by 7
// Invalid expression
Constant
• You cannot alter the value of constant after
declaration
– -define(CONSTANT, “value”);
– -print CONSTANT;
Magic Constants
• PHP has lot of predefined variables
• Also, predefined Constants:
– _LINE_
– _FILE_
– _FUNCTION_
– _CLASS_
– _METHOD_
Echo
• The PHP command ‘echo’ is used to output
the parameters passed to it
– The typical usage for this is to send data to the
client’s web-browser

• Syntax
– void echo (string arg1 [, string argn...])
– In practice, arguments are not passed in
parentheses since echo is a language construct
rather than an actual function
Echo Example
<?php
$foo = 25;
$bar = “Hello”;
echo
echo
echo
echo
echo
?>

$bar;
$foo,$bar;
“5x5=”,$foo;
“5x5=$foo”;
‘5x5=$foo’;

// Numerical variable
// String variable
//
//
//
//
//

Outputs
Outputs
Outputs
Outputs
Outputs

Hello
25Hello
5x5=25
5x5=25
5x5=$foo

• Notice how echo ‘5x5=$foo’ outputs $foo rather than
replacing it with 25
• Strings in single quotes (‘ ’) are not interpreted or evaluated
by PHP
• This is true for both variables and character escape-sequences
(such as “n” or “”)
Concatenation
• Use a period to join strings into one.
<?php
$string1=“Hello”;
$string2=“PHP”;
$string3=$string1 . “ ” . $string2;
Print $string3;
?>

Hello PHP
Escaping the Characters
• If the string has a set of double quotation
marks that must remain visible, use the 
[backslash] before the quotation marks to
ignore and display them.
<?php
$heading=“”Computer Science””;
Print $heading;
?>

“Computer Science”
Date Display
2009/4/1

Wednesday, April 1, 2009

$datedisplay=date(“yyyy/m/d”);
Print $datedisplay;
# If the date is April 1st, 2009
# It would display as 2009/4/1

$datedisplay=date(“l, F d, Y”);
Print $datedisplay;
# If the date is April 1st, 2009
# Wednesday, April 1, 2009
Month, Day, Date Format Symbol
M
F
m
n
Day of Month
Day of Month
Day of Week
Day of Week

Jan
January
01
1
d
J
l
D

01
1
Monday
Mon
PHPinfo()
• The phpinfo() function shows the php
environment
• Use this to read system and server
variables, setting stored in php.ini, versions,
and modules
• Notice that many of these data are in arrays
• This is the first script you should write…
Operator
• Arithmetic (+, -, *, /, %) and String (.)
• Assignment (=) and combined assignment
$a
$a
$b
$b

= 3;
+= 5; // sets $a to 8;
= "Hello ";
.= "There!"; // sets $b to "Hello There!";

• Bitwise (&, |, ^, ~, <<, >>)
– $a ^ $b(Xor: Bits that are set in $a or $b but not
both are set.)
– ~ $a (Not: Bits that are set in $a are not set,
and vice versa.)

• Comparison (==, ===, !=, !==, <, >, <=, >=)
Arithmetic Operation
<?php
$a=15;
$b=30;
$total=$a+$b;
Print $total;
Print “<p><h1>$total</h1>”;
// total is 45
?>

•
•
•
•

$a - $b
$a * $b
$a / $b
$a += 5

// subtraction
// multiplication
// division
// $a = $a+5 Also works for *= and /=
Coercion
• Just like javascript, php is loosely typed
• Coercion occurs the same way
• If you concatenate a number and string, the
number becomes a string
Operators
• Error Control (@)
– When this precedes a command, errors generated are ignored
(allows custom messages)

• Execution (` is similar to the shell_exec()
function)
– You can pass a string to the shell for execution:
$output = `ls -al`;
$output = shell_exec("ls -al");

– This is one reason to be careful about user set variables!

• Incrementing/Decrementing

++$a (Increments by one, then returns $a.)
$a++ (Returns $a, then increments $a by one.)
--$a (Decrements $a by one, then returns $a.)
$a-- (Returns $a, then decrements $a by one.)
Operators
• Logical
$a and $b
$a or $b
$a xor $b

And
Or
Xor

! $a
$a && $b
$a || $b

Not
And
Or

True if
True if
True if
but not
True if
True if
True if

both $a and $b are
either $a or $b is
either $a or $b is
both.
$a is not true.
both $a and $b are
either $a or $b is

true.
true.
true,
true.
true.

• The two ands and ors have different
precedence rules, "and" and "or" are lower
precedence than "&&" and "||"
• Use parentheses to resolve precedence
problems or just to be clearer
Control Structure
• Wide Variety available
– if, else, elseif
– while, do-while
– for, foreach
– break, continue, switch
– require, include, require_once, include_once

Mostly parallel to what we've covered already in
javascript
if, elseif, else, while, for, foreach, break and continue
Control Structure
 Control Structures: Are the structures within a language that
allow us to control the flow of execution through a program or
script.
 Grouped into conditional (branching) structures (e.g. if/else) and
repetition structures (e.g. while loops).
 Example if/else if/else statement:
if ($foo == 0) {
echo ‘The variable foo is equal to 0’;
}
else if (($foo > 0) && ($foo <= 5)) {
echo ‘The variable foo is between 1 and 5’;
}
else {
echo ‘The variable foo is equal to ‘.$foo;
}
If….Else
• If (condition)
{
Statements;
}
Else
{
Statement;
}

<?php
If($user==“John”)
{
Print “Hello John.”;
}
Else
{
Print “You are not John.”;
}
?>
Alternative Syntax
• Applies to if, while, for, foreach, and switch
• Change the opening brace to a colon
• Change the closing brace to an endxxx
<?php
statement
<?php if ($a == 5):
?>
A is equal to 5
<?php endif; ?>

if ($a == 5):
echo "a equals 5";
echo "...";
else:
echo "a is not 5";
endif;
?>
While…loop
• While (condition)
{
Statements;
}

<?php
$count=0;
While($count<3)
{
Print “hello PHP. ”;
$count += 1;
// $count = $count + 1;
// or
// $count++;
?>

hello PHP. hello PHP. hello PHP.
Switch
• Switch, which we've seen, is very useful
• These two do the same
things….
switch ($i) {
if ($i == 0) {
echo "i equals 0";
} elseif ($i == 1) {
echo "i equals 1";
} elseif ($i == 2) {
echo "i equals 2";
}

case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
}
Function
• Functions MUST be defined before then can be called
• Function headers are of the format
function functionName($arg_1, specified
– Note that no return type is $arg_2, …, $arg_n)

• Unlike variables, function names are not case sensitive
(foo(…) == Foo(…) == FoO(…))
Function Example
<?php
// This is a function
function foo($arg_1, $arg_2)
{
$arg_2 = $arg_1 * $arg_2;
return $arg_2;
}
$result_1 = foo(12, 3);
echo $result_1;
echo foo(12, 3);
?>

// Store the function
// Outputs 36
// Outputs 36
Include Files
Include “opendb.php”;
Include “closedb.php”;
This inserts files; the code in files will be inserted into current code. This will
provide useful and protective means once you connect to a database, as
well as for other repeated functions.

Include (“footer.php”);
The file footer.php might look like:
<hr SIZE=11 NOSHADE WIDTH=“100%”>
<i>Copyright © 2008-2010 KSU </i></font><br>
<i>ALL RIGHTS RESERVED</i></font><br>
<i>URL: http://www.kent.edu</i></font><br>
Scope
<?php
$a = “Pekka”;
Print “My Name is “. $a;
?>
<?php
$a = “Pekka”;
Function test() {
Print $a;
}
Print “My Name is “;
Test();
?>
Scope
<?php
$a = “Pekka”;
Function test() {
global $a;
Print $a;
}
Print “My Name is “;
Test();
?>
PHP BASIC
Strings
My First PHP script

PHP FORMS AND SESSION
PHP Forms
•Access to the HTTP POST and GET data is simple in PHP
•The global variables $_POST[] and $_GET[] contain the
request data
<?php
if ($_POST["submit"])
echo "<h2>You clicked Submit!</h2>";
else if ($_POST["cancel"])
echo "<h2>You clicked Cancel!</h2>";
?>
<form action="form.php" method="post">
<input type="submit" name="submit" value="Submit">
<input type="submit" name="cancel" value="Cancel">
</form>

http://www.cs.kent.edu/~nruan/form.php
Why PHP Sessions?
Whenever you want to create a website that allows you to store and display
information about a user, determine which user groups a person belongs to,
utilize permissions on your website or you just want to do something cool on
your site, PHP's Sessions are vital to each of these features.
Cookies are about 30% unreliable right now and it's getting worse every day.
More and more web browsers are starting to come with security and privacy
settings and people browsing the net these days are starting to frown upon
Cookies because they store information on their local computer that they do
not want stored there.
PHP has a great set of functions that can achieve the same results of Cookies
and more without storing information on the user's computer. PHP Sessions
store the information on the web server in a location that you chose in
special files. These files are connected to the user's web browser via the
server and a special ID called a "Session ID". This is nearly 99% flawless in
operation and it is virtually invisible to the user.
PHP Sessions
•Sessions store their identifier in a cookie in the client’s browser
•Every page that uses session data must be proceeded by the
session_start() function
•Session variables are then set and retrieved by accessing the global
$_SESSION[]
•Save it as session.php
<?php
session_start();
if (!$_SESSION["count"])
$_SESSION["count"] = 0;
if ($_GET["count"] == "yes")
$_SESSION["count"] = $_SESSION["count"] + 1;
echo "<h1>".$_SESSION["count"]."</h1>";
?>
<a href="session.php?count=yes">Click here to count</a>

http://www.cs.kent.edu/~nruan/form.php
Avoid Error PHP Sessions
PHP Example: <?php
echo "Look at this nasty error below:<br />";
session_start();
?>

Error!
Warning: Cannot send session cookie - headers already sent by
(output started at session_header_error/session_error.php:2) in
session_header_error/session_error.php on line 3
Warning: Cannot send session cache limiter - headers already sent
(output started at session_header_error/session_error.php:2) in
session_header_error/session_error.php on line 3

PHP Example: <?php
session_start();
echo "Look at this nasty error below:";
?>
Correct
Destroy PHP Sessions
Destroying a Session

why it is necessary to destroy a session when the session will get
destroyed when the user closes their browser. Well, imagine that you had
a session registered called "access_granted" and you were using that to
determine if the user was logged into your site based upon a username
and password. Anytime you have a login feature, to make the users feel
better, you should have a logout feature as well. That's where this cool
function called session_destroy() comes in handy. session_destroy() will
completely demolish your session (no, the computer won't blow up or self
destruct) but it just deletes the session files and clears any trace of that
session.
NOTE: If you are using the $_SESSION superglobal array, you must clear
the array values first, then run session_destroy.
Here's how we use session_destroy():
Destroy PHP Sessions

<?php
// start the session
session_start();
header("Cache-control: private"); //IE 6 Fix
$_SESSION = array();
session_destroy();
echo "<strong>Step 5 - Destroy This Session </strong><br />";
if($_SESSION['name']){
echo "The session is still active";
} else {
echo "Ok, the session is no longer active! <br />";
echo "<a href="page1.php"><< Go Back Step 1</a>";
}
?>

http://www.cs.kent.edu/~nruan/form.php
PHP Script
• Save as sample.php:
<!– sample.php -->
<html><body>

<strong>Hello World!</strong><br />
<?php
echo “<h2>Hello, World</h2>”; ?>

<?php
$myvar = "Hello World";
echo $myvar;
?>
</body></html>
Example – Show data into table
• Function: list all tables in your database. Users
can select one of tables, and show all contents
in this table.
• second.php
• showtable.php
Example – Show data into table
• second.php
<html><head><title>MySQL Table Viewer</title></head><body>
<?php
// change the value of $dbuser and $dbpass to your username and password
$dbhost = 'hercules.cs.kent.edu:3306';
$dbuser = 'nruan';
$dbpass = ‘*****************’;
$dbname = $dbuser;
$table = 'account';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$conn) {
die('Could not connect: ' . mysql_error());
}
if (!mysql_select_db($dbname))
die("Can't select database");
Example – Show data into table
• second.php
<html><head><title>MySQL Table Viewer</title></head><body>
<?php
// change the value of $dbuser and $dbpass to your username and password
$dbhost = 'hercules.cs.kent.edu:3306';
$dbuser = 'nruan';
$dbpass = ‘*****************’;
$dbname = $dbuser;
$table = 'account';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$conn) {
die('Could not connect: ' . mysql_error());
}
if (!mysql_select_db($dbname))
die("Can't select database");
Example – Show data into table
• Showtable.php
<html><head>
<title>MySQL Table Viewer</title>
</head>
<body>
<?php
$dbhost = 'hercules.cs.kent.edu:3306';
$dbuser = 'nruan';
$dbpass = ‘**********’;
$dbname = 'nruan';
$table = $_POST[“table”];
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$conn)
die('Could not connect: ' . mysql_error());
if (!mysql_select_db($dbname))
die("Can't select database");
$result = mysql_query("SELECT * FROM {$table}");
if (!$result) die("Query to show fields from table failed!" . mysql_error());
Example – Show data into table
• Showtable.php (cont)
$fields_num = mysql_num_fields($result);
echo "<h1>Table: {$table}</h1>";
echo "<table border='1'><tr>";
// printing table headers
for($i=0; $i<$fields_num; $i++) {
$field = mysql_fetch_field($result);
echo "<td><b>{$field->name}</b></td>";
}
echo "</tr>n";
while($row = mysql_fetch_row($result)) {
echo "<tr>";
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
foreach($row as $cell)
echo "<td>$cell</td>";
echo "</tr>n";
}
mysql_free_result($result);
mysql_close($conn);
?>
</body></html>
Function Covered
•
•
•
•

mysql_connect()
mysql_select_db()
include()
mysql_query()
mysql_num_rows()
mysql_fetch_array()mysql_close()

More Related Content

What's hot

Php tutorial
Php tutorialPhp tutorial
Php tutorial
Niit
 
Php i basic chapter 3 (mardhiah kamaludin's conflicted copy 2013-04-23)
Php i basic chapter 3 (mardhiah kamaludin's conflicted copy 2013-04-23)Php i basic chapter 3 (mardhiah kamaludin's conflicted copy 2013-04-23)
Php i basic chapter 3 (mardhiah kamaludin's conflicted copy 2013-04-23)
Muhamad Al Imran
 
Php hypertext pre-processor
Php   hypertext pre-processorPhp   hypertext pre-processor
Php hypertext pre-processor
Siddique Ibrahim
 

What's hot (18)

01 Php Introduction
01 Php Introduction01 Php Introduction
01 Php Introduction
 
PHP programmimg
PHP programmimgPHP programmimg
PHP programmimg
 
PHP Function
PHP Function PHP Function
PHP Function
 
Php unit i
Php unit i Php unit i
Php unit i
 
Php Ppt
Php PptPhp Ppt
Php Ppt
 
Php introduction
Php introductionPhp introduction
Php introduction
 
PHP LICTURES ..........
PHP LICTURES ..........PHP LICTURES ..........
PHP LICTURES ..........
 
Php Ppt
Php PptPhp Ppt
Php Ppt
 
Php advance
Php advancePhp advance
Php advance
 
Introduction To PHP
Introduction To PHPIntroduction To PHP
Introduction To PHP
 
Advantages of Choosing PHP Web Development
Advantages of Choosing PHP Web DevelopmentAdvantages of Choosing PHP Web Development
Advantages of Choosing PHP Web Development
 
Web Application Development using PHP Chapter 1
Web Application Development using PHP Chapter 1Web Application Development using PHP Chapter 1
Web Application Development using PHP Chapter 1
 
Php tutorial
Php tutorialPhp tutorial
Php tutorial
 
php
phpphp
php
 
Php i basic chapter 3 (mardhiah kamaludin's conflicted copy 2013-04-23)
Php i basic chapter 3 (mardhiah kamaludin's conflicted copy 2013-04-23)Php i basic chapter 3 (mardhiah kamaludin's conflicted copy 2013-04-23)
Php i basic chapter 3 (mardhiah kamaludin's conflicted copy 2013-04-23)
 
Software Design
Software DesignSoftware Design
Software Design
 
Php hypertext pre-processor
Php   hypertext pre-processorPhp   hypertext pre-processor
Php hypertext pre-processor
 
Php intro
Php introPhp intro
Php intro
 

Viewers also liked

CourseProjectIngramD
CourseProjectIngramDCourseProjectIngramD
CourseProjectIngramD
DanikaIngram
 
EV creation and fall
EV creation and fallEV creation and fall
EV creation and fall
mruploads
 

Viewers also liked (16)

CourseProjectIngramD
CourseProjectIngramDCourseProjectIngramD
CourseProjectIngramD
 
EV creation and fall
EV creation and fallEV creation and fall
EV creation and fall
 
MacIT 2014 - Essential Security & Risk Fundamentals
MacIT 2014 - Essential Security & Risk FundamentalsMacIT 2014 - Essential Security & Risk Fundamentals
MacIT 2014 - Essential Security & Risk Fundamentals
 
Community Career Center: Cyber Security at Home
Community Career Center: Cyber Security at HomeCommunity Career Center: Cyber Security at Home
Community Career Center: Cyber Security at Home
 
Password Playdate 2015
Password Playdate 2015Password Playdate 2015
Password Playdate 2015
 
Burn that notebook! Password management for the masses
Burn that notebook! Password management for the massesBurn that notebook! Password management for the masses
Burn that notebook! Password management for the masses
 
Apps for Academics: MIT Libraries
Apps for Academics: MIT LibrariesApps for Academics: MIT Libraries
Apps for Academics: MIT Libraries
 
ENG 131: Technical Writing Introduction PowerPoint
ENG 131: Technical Writing Introduction PowerPointENG 131: Technical Writing Introduction PowerPoint
ENG 131: Technical Writing Introduction PowerPoint
 
Introduction to IOT & Smart City
Introduction to IOT & Smart CityIntroduction to IOT & Smart City
Introduction to IOT & Smart City
 
Net neutrality: The Basics
Net neutrality: The BasicsNet neutrality: The Basics
Net neutrality: The Basics
 
Introduction to Development for the Internet
Introduction to Development for the InternetIntroduction to Development for the Internet
Introduction to Development for the Internet
 
Creating HTML Pages
Creating HTML PagesCreating HTML Pages
Creating HTML Pages
 
Montreal Girl Geeks: Building the Modern Web
Montreal Girl Geeks: Building the Modern WebMontreal Girl Geeks: Building the Modern Web
Montreal Girl Geeks: Building the Modern Web
 
Testing at Spotify
Testing at SpotifyTesting at Spotify
Testing at Spotify
 
Introduction to Information Architecture
Introduction to Information ArchitectureIntroduction to Information Architecture
Introduction to Information Architecture
 
CSS Grid Layout for Topconf, Linz
CSS Grid Layout for Topconf, LinzCSS Grid Layout for Topconf, Linz
CSS Grid Layout for Topconf, Linz
 

Similar to PHP ITCS 323

PHP
PHPPHP
Learn PHP Lacture1
Learn PHP Lacture1Learn PHP Lacture1
Learn PHP Lacture1
ADARSH BHATT
 

Similar to PHP ITCS 323 (20)

Basics PHP
Basics PHPBasics PHP
Basics PHP
 
Php intro
Php introPhp intro
Php intro
 
Php intro
Php introPhp intro
Php intro
 
Php mysql
Php mysqlPhp mysql
Php mysql
 
PHP
PHPPHP
PHP
 
How PHP works
How PHP works How PHP works
How PHP works
 
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
 
PHP MySQL Workshop - facehook
PHP MySQL Workshop - facehookPHP MySQL Workshop - facehook
PHP MySQL Workshop - facehook
 
1. introduction to php and variable
1. introduction to php and variable1. introduction to php and variable
1. introduction to php and variable
 
PHP Basics
PHP BasicsPHP Basics
PHP Basics
 
Php ppt
Php pptPhp ppt
Php ppt
 
PHP
PHPPHP
PHP
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
Php training100%placement-in-mumbai
Php training100%placement-in-mumbaiPhp training100%placement-in-mumbai
Php training100%placement-in-mumbai
 
PHP Hypertext Preprocessor
PHP Hypertext PreprocessorPHP Hypertext Preprocessor
PHP Hypertext Preprocessor
 
Php tutorial
Php tutorialPhp tutorial
Php tutorial
 
Php tutorial
Php tutorialPhp tutorial
Php tutorial
 
Php tutorial
Php tutorialPhp tutorial
Php tutorial
 
Learn PHP Lacture1
Learn PHP Lacture1Learn PHP Lacture1
Learn PHP Lacture1
 
Php notes
Php notesPhp notes
Php notes
 

Recently uploaded

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
SanaAli374401
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
MateoGardella
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 

Recently uploaded (20)

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 

PHP ITCS 323

  • 3. What is PHP? recursive acronym for PHP: Hypertext Preprocessor a widely-used open source general-purpose scripting language
  • 4. What is PHP? especially suited for web development and can be embedded into HTML is a server-side scripting language scripts are executed on the server supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC
  • 5. What is PHP? PHP files can contain text, HTML tags and scripts  PHP pages contain HTML with embedded code that does "something" have a file extension of ".php", ".php3", or ".phtml“ enclosed in special start and end processing instructions <?php and ?>  allow you to jump into and out of "PHP mode."
  • 6. Example • <!DOCTYPE HTML PUBLIC <html> <head> <title>Example</title> </head> <body> <?php echo “Hello World!"; ?> </body> </html>
  • 7. Why PHP? open source software free to download and use runs on different platforms (Windows, Linux, Unix, Mac OS X, RISC OS, etc.) compatible with almost all servers used today (Apache, IIS, etc.) support for a wide range of databases with PHP, you have the freedom of choosing an operating system and a web server
  • 8. Why PHP? not limited to output HTML  PHP's abilities includes outputting images, PDF files and even Flash movies (using libswf and Ming) generated on the fly  can autogenerate files, and save them in the file system
  • 9. Why PHP? 1. Easy to Use Code is embedded into HTML. The PHP code is enclosed in special start and end tags that allow you to jump into and out of "PHP mode". • <html> <head> <title>Example</title> </head> <body> <?php echo "Hi, I'm a PHP script!"; ?>
  • 10. Why PHP? 2. Cross Platform Runs on almost any Web server on several operating systems. One of the strongest features is the wide range of supported databases  Web Servers: Apache, Microsoft IIS, Caudium, Netscape Enterprise Server Operating Systems: UNIX (HP-UX,OpenBSD,Solaris,Linux), Mac OSX, Windows NT/98/2000/XP/2003  Supported Databases: Adabas D, dBase,Empress, FilePro (read-only), Hyperwave,IBM DB2, Informix, Ingres, InterBase, FrontBase, mSQL, Direct MS-SQL, MySQL, ODBC, Oracle (OCI7 and OCI8), Ovrimos, PostgreSQL, SQLite, Solid, Sybase, Velocis,Unix dbm
  • 11. Why PHP? 3. Cost Benefits PHP is free. Open source code means that the entire PHP community will contribute towards bug fixes. There are several add-on technologies (libraries) for PHP that are also free. PHP Software Free Platform Free (Linux) Development Tools Free PHP Coder, jEdit
  • 12. Difference? Compare to other client-side program like java script. PHP code is executed on the server PHP combined with MySQL are cross-platform (you can develop in Windows and serve on a Unix platform) It is an open source
  • 13. Three main areas where PHP scripts are used. 1. Server-side scripting. 2. Command line scripting. 3. Writing desktop applications.
  • 14. Three main areas where PHP scripts are used. 1. Server-side scripting.  most traditional and main target field for PHP  three things to make this work 1. PHP parser (CGI or server module) 2. web server 3. web browser
  • 15. Three main areas where PHP scripts are used. 2. Command line scripting  run PHP script without any server or browser  only need the PHP parser to use  this type of usage is ideal for scripts regularly executed using cron (on *nix or Linux) or Task Scheduler (on Windows).  These scripts can also be used for simple text processing tasks
  • 16. Three main areas where PHP scripts are used. 3. Writing desktop applications.  One of the advance features of PHP  have the ability to write cross-platform applications  PHP-GTK is an extension to PHP  not available in the main distribution
  • 17. What is needed? Web sever that support php (apache server) Sql database (MySql) PHP installer
  • 18. Assignment • How to install, configure and use php • Give different AMP packages • Give different php functions, give example code and syntax
  • 20. Brief History PHP (PHP: Hypertext Preprocessor) was created by Rasmus Lerdorf in 1994. It was initially developed for HTTP usage logging and server-side form generation in Unix. PHP 2 (1995) transformed the language into a Server-side embedded scripting language. Added database support, file uploads, variables, arrays, recursive functions, conditionals, iteration, regular expressions, etc. PHP 3 (1998) added support for ODBC data sources, multiple platform support, email protocols (SNMP,IMAP), and new parser written by Zeev Suraski and Andi Gutmans . PHP 4 (2000) became an independent component of the web server for added efficiency. The parser was renamed the Zend Engine. Many security features were added. PHP 5 (2004) adds Zend Engine II with object oriented programming, robust XML support using the libxml2 library, SOAP extension for interoperability with Web Services, SQLite has been bundled with PHP
  • 21. As of August 2004, PHP is used on 16,946,328 Domains, 1,348,793 IP Addresses http://www.php.net/usage.php This is roughly 32% of all domains on the web.
  • 23. Objectives PHP Structure Variables, operators, and Comments PHP Arrays Passing Variables in Links HTML special Characters Passing Variables in Forms
  • 24.
  • 25.
  • 26. Installation Procedure 1. install your selected HTTP (web) server on your system, and make sure that it works. 2. Run the executable installer and follow the instructions provided by the installation wizard.  Two types of installation are supported – 1. standard, which provides sensible defaults for all the settings it can, 2. advanced, which asks questions as it goes along.
  • 27. Installation Procedure 3. The installation wizard gathers enough information to set up the php.ini file, and configure certain web servers to use PHP. One of the web servers the PHP installer does not configure for is Apache, so you'll need to configure it manually. 4. Once the installation has completed, the installer will inform you if you need to restart your system, restart the server, or just start using PHP.
  • 28. PHP Script • Typically file ends in .php--this is set by the web server configuration • Separated in files with the <?php ?> tag • php commands can make up an entire file, or can be contained in html--this is a choice…. • Program lines end in ";" or you get an error • Server recognizes embedded script and executes • Result is passed to browser, source isn't visible <P> <?php $myvar = "Hello World!"; echo $myvar; ?> </P>
  • 29. Two ways • You can embed sections of php inside html: <BODY> <P> <?php $myvar = "Hello World!"; echo $myvar; </BODY> • Or you can call html from php: <?php echo "<html><head><title>Howdy</title> … ?>
  • 30. Variables • Typed by context (but one can force type), so it's loose • Begin with "$" (unlike javascript!) • Assigned by value – $foo = "Bob"; $bar = $foo; • Assigned by reference, this links vars – $bar = &$foo; • Some are preassigned, server and env vars – For example, there are PHP vars, eg. PHP_SELF, HTTP_GET_VARS
  • 31. Variables • Case-sensitive ($Foo != $foo != $fOo) • Global and locally-scoped variables – Global variables can be used anywhere – Local variables restricted to a function or class • Certain variable names reserved by PHP – Form variables ($_POST, $_GET) – Server variables ($_SERVER) – Etc.
  • 32. Variable of variable • Using the value of a variable as the name of a second variable) $a = "hello"; $$a = "world"; • Thus: echo "$a ${$a}"; • Is the same as: echo "$a $hello"; • But $$a echoes as "$hello"….
  • 33. Variable usage <?php $foo = 25; $bar = “Hello”; $foo = ($foo * 7); $bar = ($bar * 7); ?> // Numerical variable // String variable // Multiplies foo by 7 // Invalid expression
  • 34. Constant • You cannot alter the value of constant after declaration – -define(CONSTANT, “value”); – -print CONSTANT;
  • 35. Magic Constants • PHP has lot of predefined variables • Also, predefined Constants: – _LINE_ – _FILE_ – _FUNCTION_ – _CLASS_ – _METHOD_
  • 36. Echo • The PHP command ‘echo’ is used to output the parameters passed to it – The typical usage for this is to send data to the client’s web-browser • Syntax – void echo (string arg1 [, string argn...]) – In practice, arguments are not passed in parentheses since echo is a language construct rather than an actual function
  • 37. Echo Example <?php $foo = 25; $bar = “Hello”; echo echo echo echo echo ?> $bar; $foo,$bar; “5x5=”,$foo; “5x5=$foo”; ‘5x5=$foo’; // Numerical variable // String variable // // // // // Outputs Outputs Outputs Outputs Outputs Hello 25Hello 5x5=25 5x5=25 5x5=$foo • Notice how echo ‘5x5=$foo’ outputs $foo rather than replacing it with 25 • Strings in single quotes (‘ ’) are not interpreted or evaluated by PHP • This is true for both variables and character escape-sequences (such as “n” or “”)
  • 38. Concatenation • Use a period to join strings into one. <?php $string1=“Hello”; $string2=“PHP”; $string3=$string1 . “ ” . $string2; Print $string3; ?> Hello PHP
  • 39. Escaping the Characters • If the string has a set of double quotation marks that must remain visible, use the [backslash] before the quotation marks to ignore and display them. <?php $heading=“”Computer Science””; Print $heading; ?> “Computer Science”
  • 40. Date Display 2009/4/1 Wednesday, April 1, 2009 $datedisplay=date(“yyyy/m/d”); Print $datedisplay; # If the date is April 1st, 2009 # It would display as 2009/4/1 $datedisplay=date(“l, F d, Y”); Print $datedisplay; # If the date is April 1st, 2009 # Wednesday, April 1, 2009
  • 41. Month, Day, Date Format Symbol M F m n Day of Month Day of Month Day of Week Day of Week Jan January 01 1 d J l D 01 1 Monday Mon
  • 42. PHPinfo() • The phpinfo() function shows the php environment • Use this to read system and server variables, setting stored in php.ini, versions, and modules • Notice that many of these data are in arrays • This is the first script you should write…
  • 43. Operator • Arithmetic (+, -, *, /, %) and String (.) • Assignment (=) and combined assignment $a $a $b $b = 3; += 5; // sets $a to 8; = "Hello "; .= "There!"; // sets $b to "Hello There!"; • Bitwise (&, |, ^, ~, <<, >>) – $a ^ $b(Xor: Bits that are set in $a or $b but not both are set.) – ~ $a (Not: Bits that are set in $a are not set, and vice versa.) • Comparison (==, ===, !=, !==, <, >, <=, >=)
  • 44. Arithmetic Operation <?php $a=15; $b=30; $total=$a+$b; Print $total; Print “<p><h1>$total</h1>”; // total is 45 ?> • • • • $a - $b $a * $b $a / $b $a += 5 // subtraction // multiplication // division // $a = $a+5 Also works for *= and /=
  • 45. Coercion • Just like javascript, php is loosely typed • Coercion occurs the same way • If you concatenate a number and string, the number becomes a string
  • 46. Operators • Error Control (@) – When this precedes a command, errors generated are ignored (allows custom messages) • Execution (` is similar to the shell_exec() function) – You can pass a string to the shell for execution: $output = `ls -al`; $output = shell_exec("ls -al"); – This is one reason to be careful about user set variables! • Incrementing/Decrementing ++$a (Increments by one, then returns $a.) $a++ (Returns $a, then increments $a by one.) --$a (Decrements $a by one, then returns $a.) $a-- (Returns $a, then decrements $a by one.)
  • 47. Operators • Logical $a and $b $a or $b $a xor $b And Or Xor ! $a $a && $b $a || $b Not And Or True if True if True if but not True if True if True if both $a and $b are either $a or $b is either $a or $b is both. $a is not true. both $a and $b are either $a or $b is true. true. true, true. true. • The two ands and ors have different precedence rules, "and" and "or" are lower precedence than "&&" and "||" • Use parentheses to resolve precedence problems or just to be clearer
  • 48. Control Structure • Wide Variety available – if, else, elseif – while, do-while – for, foreach – break, continue, switch – require, include, require_once, include_once Mostly parallel to what we've covered already in javascript if, elseif, else, while, for, foreach, break and continue
  • 49. Control Structure  Control Structures: Are the structures within a language that allow us to control the flow of execution through a program or script.  Grouped into conditional (branching) structures (e.g. if/else) and repetition structures (e.g. while loops).  Example if/else if/else statement: if ($foo == 0) { echo ‘The variable foo is equal to 0’; } else if (($foo > 0) && ($foo <= 5)) { echo ‘The variable foo is between 1 and 5’; } else { echo ‘The variable foo is equal to ‘.$foo; }
  • 50. If….Else • If (condition) { Statements; } Else { Statement; } <?php If($user==“John”) { Print “Hello John.”; } Else { Print “You are not John.”; } ?>
  • 51. Alternative Syntax • Applies to if, while, for, foreach, and switch • Change the opening brace to a colon • Change the closing brace to an endxxx <?php statement <?php if ($a == 5): ?> A is equal to 5 <?php endif; ?> if ($a == 5): echo "a equals 5"; echo "..."; else: echo "a is not 5"; endif; ?>
  • 52. While…loop • While (condition) { Statements; } <?php $count=0; While($count<3) { Print “hello PHP. ”; $count += 1; // $count = $count + 1; // or // $count++; ?> hello PHP. hello PHP. hello PHP.
  • 53. Switch • Switch, which we've seen, is very useful • These two do the same things…. switch ($i) { if ($i == 0) { echo "i equals 0"; } elseif ($i == 1) { echo "i equals 1"; } elseif ($i == 2) { echo "i equals 2"; } case 0: echo "i equals 0"; break; case 1: echo "i equals 1"; break; case 2: echo "i equals 2"; break; }
  • 54. Function • Functions MUST be defined before then can be called • Function headers are of the format function functionName($arg_1, specified – Note that no return type is $arg_2, …, $arg_n) • Unlike variables, function names are not case sensitive (foo(…) == Foo(…) == FoO(…))
  • 55. Function Example <?php // This is a function function foo($arg_1, $arg_2) { $arg_2 = $arg_1 * $arg_2; return $arg_2; } $result_1 = foo(12, 3); echo $result_1; echo foo(12, 3); ?> // Store the function // Outputs 36 // Outputs 36
  • 56. Include Files Include “opendb.php”; Include “closedb.php”; This inserts files; the code in files will be inserted into current code. This will provide useful and protective means once you connect to a database, as well as for other repeated functions. Include (“footer.php”); The file footer.php might look like: <hr SIZE=11 NOSHADE WIDTH=“100%”> <i>Copyright © 2008-2010 KSU </i></font><br> <i>ALL RIGHTS RESERVED</i></font><br> <i>URL: http://www.kent.edu</i></font><br>
  • 57. Scope <?php $a = “Pekka”; Print “My Name is “. $a; ?> <?php $a = “Pekka”; Function test() { Print $a; } Print “My Name is “; Test(); ?>
  • 58. Scope <?php $a = “Pekka”; Function test() { global $a; Print $a; } Print “My Name is “; Test(); ?>
  • 61. My First PHP script PHP FORMS AND SESSION
  • 62. PHP Forms •Access to the HTTP POST and GET data is simple in PHP •The global variables $_POST[] and $_GET[] contain the request data <?php if ($_POST["submit"]) echo "<h2>You clicked Submit!</h2>"; else if ($_POST["cancel"]) echo "<h2>You clicked Cancel!</h2>"; ?> <form action="form.php" method="post"> <input type="submit" name="submit" value="Submit"> <input type="submit" name="cancel" value="Cancel"> </form> http://www.cs.kent.edu/~nruan/form.php
  • 63. Why PHP Sessions? Whenever you want to create a website that allows you to store and display information about a user, determine which user groups a person belongs to, utilize permissions on your website or you just want to do something cool on your site, PHP's Sessions are vital to each of these features. Cookies are about 30% unreliable right now and it's getting worse every day. More and more web browsers are starting to come with security and privacy settings and people browsing the net these days are starting to frown upon Cookies because they store information on their local computer that they do not want stored there. PHP has a great set of functions that can achieve the same results of Cookies and more without storing information on the user's computer. PHP Sessions store the information on the web server in a location that you chose in special files. These files are connected to the user's web browser via the server and a special ID called a "Session ID". This is nearly 99% flawless in operation and it is virtually invisible to the user.
  • 64. PHP Sessions •Sessions store their identifier in a cookie in the client’s browser •Every page that uses session data must be proceeded by the session_start() function •Session variables are then set and retrieved by accessing the global $_SESSION[] •Save it as session.php <?php session_start(); if (!$_SESSION["count"]) $_SESSION["count"] = 0; if ($_GET["count"] == "yes") $_SESSION["count"] = $_SESSION["count"] + 1; echo "<h1>".$_SESSION["count"]."</h1>"; ?> <a href="session.php?count=yes">Click here to count</a> http://www.cs.kent.edu/~nruan/form.php
  • 65. Avoid Error PHP Sessions PHP Example: <?php echo "Look at this nasty error below:<br />"; session_start(); ?> Error! Warning: Cannot send session cookie - headers already sent by (output started at session_header_error/session_error.php:2) in session_header_error/session_error.php on line 3 Warning: Cannot send session cache limiter - headers already sent (output started at session_header_error/session_error.php:2) in session_header_error/session_error.php on line 3 PHP Example: <?php session_start(); echo "Look at this nasty error below:"; ?> Correct
  • 66. Destroy PHP Sessions Destroying a Session why it is necessary to destroy a session when the session will get destroyed when the user closes their browser. Well, imagine that you had a session registered called "access_granted" and you were using that to determine if the user was logged into your site based upon a username and password. Anytime you have a login feature, to make the users feel better, you should have a logout feature as well. That's where this cool function called session_destroy() comes in handy. session_destroy() will completely demolish your session (no, the computer won't blow up or self destruct) but it just deletes the session files and clears any trace of that session. NOTE: If you are using the $_SESSION superglobal array, you must clear the array values first, then run session_destroy. Here's how we use session_destroy():
  • 67. Destroy PHP Sessions <?php // start the session session_start(); header("Cache-control: private"); //IE 6 Fix $_SESSION = array(); session_destroy(); echo "<strong>Step 5 - Destroy This Session </strong><br />"; if($_SESSION['name']){ echo "The session is still active"; } else { echo "Ok, the session is no longer active! <br />"; echo "<a href="page1.php"><< Go Back Step 1</a>"; } ?> http://www.cs.kent.edu/~nruan/form.php
  • 68. PHP Script • Save as sample.php: <!– sample.php --> <html><body> <strong>Hello World!</strong><br /> <?php echo “<h2>Hello, World</h2>”; ?> <?php $myvar = "Hello World"; echo $myvar; ?> </body></html>
  • 69. Example – Show data into table • Function: list all tables in your database. Users can select one of tables, and show all contents in this table. • second.php • showtable.php
  • 70. Example – Show data into table • second.php <html><head><title>MySQL Table Viewer</title></head><body> <?php // change the value of $dbuser and $dbpass to your username and password $dbhost = 'hercules.cs.kent.edu:3306'; $dbuser = 'nruan'; $dbpass = ‘*****************’; $dbname = $dbuser; $table = 'account'; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if (!$conn) { die('Could not connect: ' . mysql_error()); } if (!mysql_select_db($dbname)) die("Can't select database");
  • 71. Example – Show data into table • second.php <html><head><title>MySQL Table Viewer</title></head><body> <?php // change the value of $dbuser and $dbpass to your username and password $dbhost = 'hercules.cs.kent.edu:3306'; $dbuser = 'nruan'; $dbpass = ‘*****************’; $dbname = $dbuser; $table = 'account'; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if (!$conn) { die('Could not connect: ' . mysql_error()); } if (!mysql_select_db($dbname)) die("Can't select database");
  • 72. Example – Show data into table • Showtable.php <html><head> <title>MySQL Table Viewer</title> </head> <body> <?php $dbhost = 'hercules.cs.kent.edu:3306'; $dbuser = 'nruan'; $dbpass = ‘**********’; $dbname = 'nruan'; $table = $_POST[“table”]; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if (!$conn) die('Could not connect: ' . mysql_error()); if (!mysql_select_db($dbname)) die("Can't select database"); $result = mysql_query("SELECT * FROM {$table}"); if (!$result) die("Query to show fields from table failed!" . mysql_error());
  • 73. Example – Show data into table • Showtable.php (cont) $fields_num = mysql_num_fields($result); echo "<h1>Table: {$table}</h1>"; echo "<table border='1'><tr>"; // printing table headers for($i=0; $i<$fields_num; $i++) { $field = mysql_fetch_field($result); echo "<td><b>{$field->name}</b></td>"; } echo "</tr>n"; while($row = mysql_fetch_row($result)) { echo "<tr>"; // $row is array... foreach( .. ) puts every element // of $row to $cell variable foreach($row as $cell) echo "<td>$cell</td>"; echo "</tr>n"; } mysql_free_result($result); mysql_close($conn); ?> </body></html>