Professional Documents
Culture Documents
CSI4118
Fall 2005
Introduction to PHP
24/4/20
3
WhatisisPHP
What PHP(Cont’d)
(cont’d)
Interpreted language, scripts are parsed at run-
time rather than compiled beforehand
Executed on the server-side
Source-code not visible by client
‘View Source’ in browsers does not display the PHP
code
Plethora of built-in functions allow for fast
development
Compatible with many popular databases
24/4/20
4
What does PHP code look like?
Structurally similar to C/C++
Supports procedural and object-oriented
paradigm (to some degree)
All PHP statements end with a semi-colon
Each PHP script must be enclosed in the
reserved PHP tag
<?php
…
?>
24/4/20
5
Comments in PHP
# Shell-style comments
/* C-style comments
These can span multiple lines */
24/4/20
6
Variables in PHP
24/4/20
7
Variable usage
<?php
$foo = 25; // Numerical variable
$bar = “Hello”; // String variable
24/4/20
8
Echo
24/4/20
9
Echo example
<?php
$foo = 25; // Numerical variable
$bar = “Hello”; // String variable
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 “\\”)
24/4/20
10
Functions
Functions MUST be defined before then can be
called
Function headers are of the format
24/4/20
11
Functions example
<?php
// This is a function
function foo($arg_1, $arg_2)
{
$arg_2 = $arg_1 * $arg_2;
return $arg_2;
}
24/4/20
12
The Big Picture for Assignment 2
24/4/20
13
Saving Data in Text Files
PHP has built in functions for File I/O processing
fopen (..), fwrite(..), fclose(..), fflush(..),
file_get_contents(..)
Using these pre-made functions, File I/O in PHP
is similar to that of C
General Flow:
Open file
Read data
Modify data
Write data
Close file
24/4/20
14
Saving Data in Text Files
Reading from a file
<?php
$file = fopen("sample.txt", "r");
while (!feof($file)) {
echo fgets($file), "<BR>";
}
?>
Reading from a URL
<?php $file = fopen("http://www.php.net/file.txt", "r"); ?>
Writing to a file
<?php
$file = fopen("agent.log", "a");
fputs($file, $HTTP_USER_AGENT."\n");
?>
24/4/20
15
Saving Data in Text Files
Reading from a file
<?php
$file = fopen("sample.txt", "r");
while (!feof($file)) {
echo fgets($file), "<BR>";
}
?>
Reading from a URL
<?php $file = fopen("http://www.php.net/file.txt", "r"); ?>
Writing to a file
<?php
$file = fopen("agent.log", "a");
fputs($file, $HTTP_USER_AGENT."\n");
?>
24/4/20
16
Saving Data in Text Files
Reading a File directly into Array or String
The file() function reads entire file into an array: array file (string filename [, int
use_include_path]) Each element of the array corresponds to a line in the file, with
the newline still attached.
You can use the optional second parameter and set it to "1", if you want to search
for the file in the include_path, too.
24/4/20
17
Saving Data in Text Files: Example
<?php
$filename = 'test.txt'; /* Filename for writing. This is assumed to be in the same directory as
the script */
$somecontent = "Add this to the file\n"; // String to append to the file
fclose($handle);
} else {
echo "The file $filename is not writable";
} ?>
24/4/20
18
For more information…
http://www.php.net/manual/en/
http://www.w3schools.com/php/default.asp
http://www.zend.com/zend/tut/
24/4/20
19
Various Notes on PHP
<?php
// string storing the destination
$url = http://www.uottawa.ca
24/4/20
22
Preventing Browser-caching
24/4/20
23
Anti-caching example
<?php
// Date in the past
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
// always modified
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . "
GMT");
// HTTP/1.1
header("Cache-Control: no-store, no-cache, must-
revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
// HTTP/1.0
header("Pragma: no-cache");
?>
24/4/20
24
Anti-caching example
IE 6 Fix:
24/4/20
25
Anti-caching example
<?php
// start the session
session_start();
header("Cache-control: private"); //IE 6 Fix
http://www.php.net/manual/en/function.
md5.php
RSA MD5 Message Digest Algorithm
http://www.faqs.org/rfcs/rfc1321
24/4/20
28
PHP the [Easy] way
24/4/20
30
[Easy]PHP
http://www.easyphp.org/
Automagically installs and configures Apache,
PHP, and MySQL
Defaults to running from http://localhost/
Installer:
http://www.easyphp.org/telechargements/dn.php?
F=easyphp1-7
English Readme files (Extract to EasyPHP
Installation Directory):
http://www.easyphp.org/telechargements/dn.php?
F=indexUS_1.7
24/4/20
31
Benefits of Web Applications
MySQL (www.mysql.com)
Open source SQL database that is free and extremely powerful
Latest version: 4.1 (though 5.0.1 is testing version)
PHP (www.php.net)
PHP (Hypertext Preprocessor) is mainly focused on server-side
scripting, so you can do anything any other CGI program can do, such as
collect form data, generate dynamic page content, or send and receive
cookies. But PHP can do much more.
Latest version: 4.3 (though 5 is testing)
Software Usage
Development Profiles
Us
er
Apache - Benefits
•Apache is well supported - Most support for Apache is free and
available 24 hours a day via Internet mail or newsgroups.
•Apache is multi-platform - Apache can run on virtually any
hardware platform (from PCs to mainframes), and almost any operating
system, such as Linux, Windows, NetWare, Macintosh, xBSD, etc.
•Apache is secure - security holes are rare but when they exist they
are discovered and fixed quickly
•Apache is extensible - anyone can write modules that easily plug in
to Apache. If Apache doesn't do what you want or need it to do, anyone
with programming skills can write the modules you need.
•Apache is database-friendly - you can interface Apache with
virtually any commercial database, such as Oracle, Sybase, DB2, and
Informix, as well as free databases such as MySQL and Postgres.
•Apache is hardware-friendly - Apache generally consumes far fewer
hardware resources that commercial web servers.
•No Microsoft Viruses - Apache is immune to the Code Red, Nimda,
and other viruses that target at Microsoft Web servers.
24/4/20
40
Installation – Apache (ver 2.0.52)
•Go to http://httpd.apache.org/download.cgi
•Click Download
•Execute setup.exe
• Go to C:\mysql\bin
• Execute winmysqladmin.exe. You will be prompted for
username and password. Type as admin with password as
admin
•You will see the Traffic light signal on the task bar and
also the admin window
Configuration - MySQL
MySQL Control Center
•Graphical administrative interface for MySQL
database(s)
•Download from
http://dev.mysql.com/downloads/other/mysqlc
c.html
Establish connection
to DB server
24/4/20
50
MySQL Control Center - Configuration
in Databases ignore mysql; delete test
in User Administration delete
first two users and assign
password to root users
ignore Server Administration
adapt connection (password)
24/4/20
51
PHP - Benefits
•Easy, powerful, popular
•Server-side scripting language
•Supports many DB’s (not only MySQL)
•Platform Independent
•Web Server Independent
•Free and Open Source
PHP Overtakes Microsoft ASP as the Web’s Number 1
server side Web technology for the Internet.
•An April Netcraft surveys indicate 24 percent of the
37.6 million websites, or are running PHP scripts. PHP
adoption is growing by 6.5 percent each month. (9
million sites)
24/4/20
52
Installation - PHP
Browser: http://localhost:8088/php/sample.php
24/4/20
59
PHP Control Structures
•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;
24/4/20 } 60
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">
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.
24/4/20
62
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>
24/4/20
63
Avoid Error PHP - Sessions
PHP Example: <?php
echo "Look at this nasty error below:<br />";
session_start();
?>
Error!
24/4/20
65
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>";
}
?>
24/4/20
66
MySQL Overview
24/4/20
67
MySQL – Database Basics
•A relational database manager (MySQL) manages databases
which holds tables which has records (rows) with attributes
(columns)
24/4/20
68
MySQL – Create Tables
Table structure for following examples:
CREATE TABLE oscarpool ( CREATE TABLE
uid int(4) auto_increment, bestdirector (
username varchar(255), bdid int(4)
email varchar(255), auto_increment,
bestpicture int(2), name varchar(255),
PRIMARY KEY (uid) PRIMARY KEY (bdid)
) )
Created two tables, ‘oscarpool’ & ‘bestdirector’ using:
(a) use MySQL either in line mode (cd c:\mysql\bin and mysql) or
(b) Use MySQL Control Center
(c) use phpMyAdmin tool which you can get from
http://www.phpmyadmin.net/
phpMyAdmin is a tool written in PHP intended to handle the administration
of MySQL over the Web. Currently it can create and drop databases,
create/drop/alter tables, delete/edit/add fields, execute any SQL
statement, manage keys on fields, manage privileges,export data into
various formats http://localhost:8088/mysql/index.php
24/4/20
69
MySQL – INSERT
Common SQL Statement: INSERT
INSERT INTO
oscarpool
(username,email,bestpicture)
VALUES
(‘dolsen',‘dave@usablecode.com',1)
24/4/20
70
MySQL – SELECT
Common SQL Statement: SELECT
SELECT uid,username
FROM oscarpool
Selects the attributes ‘uid’ and ‘username’ from every
record in ‘oscarpool’
SELECT is how you query the database. You can also:
limit the number of records returned with LIMIT,
limit retrieval to those records that match a condition
with WHERE,
sort the data after the query has been evaluated using
ORDER BY
Tip: To easily select every attribute replace ‘uid’ with ‘*’
24/4/20
71
MySQL – UPDATE
Common SQL Statement: UPDATE
UPDATE oscarpool
SET email = ‘david.olsen@mail.wvu.edu’
WHERE uid = 1
24/4/20
72
MySQL – DELETE
Common SQL Statement: DELETE
24/4/20
73
MySQL – JOIN
SELECT bd.name
FROM oscarpool op, bestdirector bd
WHERE op.uid = 1 and
op.bestdirector = bd.bdid
24/4/20
74
MySQL – ERD
Entity-Relationship (ER) Modeling
ER Modeling is the simple and clear method of expressing the
design (relations) of a database between tables and attributes.
Rectangles – Represent entities.
Diamonds – Represent relationships
between entities
Ellipses – Represent attributes that
describe an entity
Lines – Connect entities to relationships.
Can have annotation.
M = many, 1 = one.
Lines – Connects entities to attributes. No annotation.
Entity = Table, Attributes = Attributes
24/4/20
75
MySQL – DB Access
<html>
<body>
<h1>A List of Users Who Have Signed Up For OscarPool</h1>
<?
$dbh = mysql_connect("localhost","root","")
or die("Couldn't connect to database.");
$db = mysql_select_db("test", $dbh)
or die("Couldn't select database.");
$sql = "SELECT username, email FROM oscarpool";
$result = mysql_query($sql, $dbh)
or die("Something is wrong with your SQL statement.");
Users Table:
Attr: UserID, Password, First Name, Last Name, Email, Addr,
Phone….
Topics Table:
Attr: TopicID, PostedTime, UserID, TopicSubject, TopicBody….
Replies Table:
Attr: ReplyID, PostedTime, TopicID, UserID, ReplySubject,
ReplyBody…
…………………….
24/4/20
78
Basic Use Cases for BBS
Basic Use Cases:
1. User Registers in the bulletin board
(Generated UserID and Password) ….Create SQL Users table
24/4/20
79
Thinking about BBS
1. If a user was authenticated to post a message in name of his userID? How to create a
BBS Administrator?
(DB Driven Authentication)
2. How to implement that a user just logs on successfully from the entrance
page for one-time and the other web pages remember that the user is an
authenticated user without asking the user to do authentication again?
(Session)
3. How to let the browser to remember a userID in the log in Form always?
(Cookie)
5. How to do form validations, from Client Side or Server Side? Pros and cons?
Client Scripts Vs. Server Side Scripts
24/4/20
80
PHP References
•www.php.net <-- php home page
•http://www.phpbuilder.com/
•http://www.devshed.com/
•http://www.phpmyadmin.net/
•http://www.hotscripts.com/PHP/
•http://geocities.com/stuprojects/ChatroomDescription.htm
•http://www.academic.marist.edu/~kbhkj/chatroom/chatroom.htm
•http://www.aspfree.com/c/a/ASP-Code/Free-ASP-Based-Chat-Program/
•http://www.aus-etrade.com/Scripts/php.php
•http://www.codeproject.com/asp/CDIChatSubmit.asp
•www.php.net/downloads <-- php downlad page
•http://www.php.net/manual/en/install.windows.php <-- php
instllation manual
•http://php.resourceindex.com/ <-- PHP resources like sample
programs, text book referencs, etc.
•http://www.daniweb.com/techtalkforums/forum17.html php
forums
24/4/20
81