Title: Dynamic Web Sites with PHP
1Dynamic Web Sites with PHP MySQL
- Introduction - Features
- Syntax with examples
- Database handling with example
- Useful hints
- How to get help
2Introduction
- PHP is a tool that lets you create dynamic web
pages - PHP-enabled web pages are treated just like
regular HTML pages and you can create and edit
them the same way you normally create regular
HTML pages - PHP stands for 'Hypertext Pre-Processor'
- PHP is script embedded in HTML file, which can
generate dynamic HTML contents - It is a server side HTML object-oriented
scripting/programming language - Client transparent
3What is PHP?
- At the most basic level, PHP can do anything any
other CGI program can do, such as - collect form data
- generate dynamic page content, or
- send and receive cookies
- PHP also has support for talking to other
services using protocols such as - IMAP
- SNMP
- NNTP
- POP3
- HTTP
- PHP can also
- open network sockets and
- interact using other protocols
4Functions Features
- Built in support for
- Email, FTP, XML, PDF
- Extensive database support
- Fully support to all data base products
- Over 1000 functions and 50 Modules!
- HTTP authentication with PHP
- GIF creation with PHP - GD library
- File upload support
- HTTP cookie support
- Error connection handling
- PHP source viewer
- Provide easy and powerful hypertext manipulation
- High performance ( 400,000 visitors per day)
5History of PHP (Part 1)
- PHP is a powerful server side web scripting
solution - 1994 Personal project of Rasmus Lerdorf
- He combined his Personal Home Page tools scripts
with the Form Interpreter, added mSQL support,
which resulted the PHP/FI - PHP/FI grew at an amazing pace and people started
contributing code to it - By late 1996 PHP/FI was in use on at least 15,000
web sites around the world - By mid-1997 this number had grown to over 50,000
- 1997 New parser (PHP 3.0) from Zeev Suraski
Andi Gutmans - In the PHP 4 the parser is the Zend Engine
6History of PHP (Part 2)
- It has quickly grown in popularity and according
to the February 2001 usage stats PHP is
installed on 19.8 of all web sites - in 2000 it was 7, only
- The goal of the language is to allow web
developers to write dynamically generated pages
quickly - CGI is more powerful in general, while PHP is
more convenience to use and write - A lot of possibility of joining to the PHP
community...
7Grow of PHP Usage I
8Grow of PHP Usage II
9Why use PHP?
- Today Version 4 powerful language
- Cross-platform, extensible, FAST
- Very easy to learn / teach
- Cheap
- Great online community support
- It had become the most well-known and most widely
used scripting language for - Web, Internet, e-commerce, business-to-business
projects - Speed
- PHP runs 5 to 20 times faster than Java
- It is extremely easy to use and you can develop
very complex web/e-commerce applications very
rapidly in a very short period of time
10Database Support
- The strongest and most significant feature in PHP
is its support for a wide range of databases - Writing a database-enabled web page is incredibly
simple - The following databases are currently supported
- Adabas D Ingres Oracle
- dBase InterBase Ovrimos Informix
- Empress FrontBase PostgreSQL ODBC
- FilePro mSQL Direct MS-SQL dbm
- Solid Hyperwave Sybase IBM DB2
- MySQL Velocis Unix dbm
11Platforms
- The power of PHP is that it is cross-platform and
runs everywhere - It runs on many web-servers like
- Apache (built-in)
- Microsoft IIS, others (as CGI binary)
- It runs on
- Linux
- Windows 95/98/NT
- Windows 2000
- Solaris
- HPUX and
- all flavors of Unix
- PHP is write once and deploy anywhere and
everywhere
12What do I need?
- The server has to have support for PHP activated
and that all files ending in .php3 are handled by
PHP - On most servers this is the default extension for
PHP files, but ask your server administrator to
be sure - If your server supports PHP then you don't need
to do anything - Just create your .php3 files and put them in your
web directory and the server will magically parse
them for you - There is no need to compile anything nor do you
need to install any extra tools - Think of these PHP-enabled files as simple HTML
files with a whole new family of magical tags
that let you do all sorts of things
13The Configuration File
- The configuration file (called php.ini) is read
when PHP starts up - For the server module versions of PHP, this
happens only once when the web server is started - For the CGI version, it happens on every
invocation - When using PHP as an Apache module, you can also
change the configuration settings using
directives in Apache configuration files and
.htaccess files - You can view the settings of the configuration
values in the output of phpinfo()
14Syntax
- Much of its syntax is borrowed from C, Java and
Perl with some unique PHP-specific features
thrown in - Control structures
- if, else, for, do while, switch etc
- Types
- Integers, strings, arrays, objects
- Classes (OOP) and Functions
- Syntax of PHP is similar to the basic syntax used
by the C language - All the string and memory manipulation issues in
C have been eliminated in PHP, but the basic
syntax remains - PHP can be compiled and optimized to make it run
even faster by using the Zend Optimizer - Zend optimizer is integrated with PHP in PHP
version 4.0
15Instruction Separation
- Instructions are separated the same as in C or
perl - terminate each statement with a semicolon - The closing tag (?gt) also implies the end of the
statement, so the following are equivalent - lt?php
- echo "This is a test"
- ?gt
- lt?php echo "This is a test" ?gt
16Hello World Example I
- lthtmlgt
- ltheadgt
- lttitlegtPHP Example Ilt/titlegt
- lt/headgt
- ltbodygt
- lt?php
- print Hello World!"
- ?gt
- lt/bodygt
- lt/htmlgt
17Another Hello World Example I
- Create a file named hello.php3 and in it put the
following lines - lthtmlgt
- ltheadgt
- lttitlegtPHP Example IIlt/titlegt
- lt/headgt
- ltbodygt
- lt?php echo "Hello WorldltPgt" ?gt
- lt/bodygt
- lt/htmlgt
- The file does not need to be executable or
special in any way - Think of it as a normal HTML file which happens
to have a set of special tags available to you
that do a lot of interesting things
18Another Hello World Example II
- This program is extremely simple and you really
didn't need to use PHP to create a page like this - All it does is display
- Hello World
- If it didn't output anything, chances are that
the server you are on does not have PHP enabled - Ask your administrator to enable it for you
- The point of the example is to show the special
PHP tag format - In this example lt?php was used to indicate the
start of a PHP tag - Then the PHP statement and left PHP mode was put
by adding the closing tag, ?gt - You may jump in and out of PHP mode in an HTML
file like this all you want
19Architecture of a PHP-based DBM Application
20First Steps in the MySQL Usage
- Let the name of the database is mydata_dbuse
mydata_dbcreate table student (name
VARCHAR(30), supervisor VARCHAR(30), birthdate
DATE)insert into student (name, supervisor,
birthdate) values ("John Little","Andreas Big",
"1979-10-20")insert into student (name,
supervisor, birthdate) values ("Erica
Knight","Andreas Big", "1980-11-22")select
from student where supervisor like "Big"update
student set supervisor "Edward Teller" where
name"Erica Knight"commitquit - The home page of the mysql documentationhttp//w
ww.mysql.com/documentation/mysql/bychapter/index.h
tml
21Checking the User Agent
- E.g. we are going to check what sort of browser
the person viewing the page is using - In order to do that we check the user agent
string that the browser sends as part of its
request - This information is stored in a variable
- Variables always start with a dollar-sign in PHP
- The variable we are interested in is
HTTP_USER_AGENT - To display this variable we can simply do
- lt?php echo HTTP_USER_AGENT ?gt
- For the browser that you are using right now to
view this page, this displays - Mozilla/4.0 (compatible MSIE 5.0 Windows
98 DigExt)
22Function Names
- They are case insensitive
- Even all of the built in PHP functions are case
insensitive - function foo ()
- return 'foo'
-
- function FOO ()
- return 'FOO'
-
- // error function foo() already declared
23Variables
- Variables are case sensitive
- foo 'foo'
- FOO 'FOO'
- echo "fooFOO"
- // prints fooFOO
24Other Variables
- There are many other variables that are
automatically set by your web server - You can get a complete list of them by creating a
file that looks like this - lt?php phpinfo()?gt
- Then load up this file in your browser and you
will see a page full of information about PHP
along with a list of all the variables available
to you
25Usage of the Variables
- In PHP, a variable does not require formal
declaration - It will automatically be declared when a value is
assigned to it - Variables are prefixed by a dollar sign
(VariableName) - In the following example, four variables are
automatically declared by assigning a value to
them - lt?php
- number 5
- string1 "this is a string\n"
- string2 'this is another "string"'
- real 37.2
- ?gt
26Variables
- Variables that have not been set are defined as
NULL - If you use a variable that has not been set then
PHP will treat the NULL like it is an empty
string - But, don't depend on your variables being empty
unless you have explicitly set them to be so - Users can pass arbitrary variable values into
your script using the GET and POST HTTP methods
27Types
- For the most part, types are hidden from the
developer in PHP - 99 of the time you don't know or care about the
type of a variable since PHP is so good at doing
automatic conversions - There are times however when the type of your
variables does become important
28Types of the PHP4
- array
- boolean
- double
- integer
- null
- variables that are not set
- object
- resource
- variables that represent resources such as file
or database handles - string
- unknown type
29Converting Types
- PHP4 has introduced a concept of identity to the
language - Two values are identical if they have the same
content and the same type - Equality is based on two values having the same
content after they have been converted to the
same type - Equality () of two variables is not the same as
identity () - You can explicitly cast and convert between types
in PHP when necessary - The main time you need to think about doing this
is when you are trying to do comparisons between
variables of unknown or different types
30Example of Types
- A good example of where types can get tricky is
with database operations - Any return value from a database will always be
represented in PHP as a string - The type in the database is irrelevant,
immediately upon its return to PHP the value will
be a string - Implicit conversion will treat this string as an
integer, but it is still a string - There is one notable exception however
- If you get a NULL return value from the database
then PHP will create a variable of type NULL - ie. effectively the variable is not set
31References
- All variable assignments in PHP are done by
copying values - Every time you assign a value to a variable you
are creating a copy - Most of the time this doesn't really matter and
in fact protects programmers from themselves
since they can't destroy their precious data - Sometimes however copying by value can be a
burden if your data is large and the copy isn't
really necessary - To get around this problem PHP lets you create
references to data - E.g., you can make b reference the same data as
a with this command - b a
32Arrays I
- PHP arrays are a cross between numbered arrays
and associative arrays - This means that you can use the same syntax and
functions to deal with either type of array,
including arrays that are - Indexed from 0
- Indexed by strings
- Indexed with non-continuous numbers
- Indexed by a mix of numbers and strings
- In the next example, three literal arrays are
declared as follows - 1.A numerically indexed array with indices
running from 0 to 4 - 2.An associative array with string indices
- 3.A numerically indexed array, with indices
running from 5 to 7
33Arrays II
- lt?php
- array1 array(2, 3, 5, 7, 11)
- array2 array("one" gt 1, "two" gt 2, "three"
gt 3) - array3 array(5 gt "five", "six", "seven")
- printf("7 d, 1 d, 'six' s\n", array13,
array2"one", array36) - ?gt
- From the above example, the indices in the array1
are implicit, while the indices in array2 are
explicit - When specifically setting the index to a number N
with the gt operator, the next value has the
index N1 by default - Explicit indices do not have to be listed in
sequential order - You can also mix numerical and string indexes,
but it is not recommended
34Conditionals and Looping Constructs I
- PHP includes if and elseif conditionals, as well
as while and for loops, all with syntax similar
to C - The example below introduces these four
constructs - lt?php
- // Conditionals
- if (a)
- print "a is trueltBRgt\n"
- elseif (b)
- print "b is trueltBRgt\n"
- else
- print "neither a or b is trueltBRgt\n"
-
35Conditionals and Looping Constructs II
- // Loops
- do
- c test_something()
- while (c)
- while (d)
- print "okltBRgt\n"
- d test_something()
-
- for (i 0 i lt 10 i)
- print "iiltBRgt\n"
-
- ?gt
36Architecture FOR Loop
- Build-in module in Apache web server
- Example
Apache httpd
request
PHP module Proxy module GIF module DB module
html
lthtmlgtltbodygt lt?php for(t1tlt5t)
echo "ltpgthello ".t."times" ?gt lt/bodygtlt/htmlgt
hello 1 times hello 2 times hello 3 times hello 4
times hello 5 times
37Usage of Functions I
- PHP parses one file at a time
- Thus, you can use any function that has already
been declared or is declared as part of the
current file - So, this is valid
- foo()
- function foo ()
- echo 'foo'
-
38Usage of Functions II
- If we move the foo() function into an include
file the above ordering will no longer work
regardless of whether we use include() or
require() since PHP will attempt to run that step
after the call to the function foo() - So, this will not work
- foo()
- include('./foo.inc')
39If Statement
- You can put
- multiple PHP statements inside a PHP tag
- create little blocks of code (that do more than
just a single echo) - E.g., if we wanted to check for Internet Explorer
we could do something like this - lt?php if(strstr(HTTP_USER_AGENT,"MSIE"))
-
- echo "You are using Internet
Explorerltbrgt" -
- ?gt
40The strstr() Funcion Call I
- strstr() is a function built into PHP which
searches a string for another string - In this case we are looking for "MSIE" inside
HTTP_USER_AGENT - If the string is found the function returns true
and if it isn't, it returns false - If it returns true the following statement is
executed
41The strstr() Funcion Call II
- We can take this a step further and show how you
can jump in and out of PHP mode even in the
middle of a PHP block - lt?php
- if(strstr(HTTP_USER_AGENT,"MSIE"))
- ?gt
- ltCENTERgtltBgtYou are using Internet
Explorerlt/Bgtlt/CENTERgt - lt?
- else
- ?gt
- ltCENTERgtltBgtYou are not using Internet
Explorerlt/Bgtlt/CENTERgt - lt?
-
- ?gt
42The strstr() Funcion Call III
- Instead of using a PHP echo statement to output
something, we jumped out of PHP mode and just
sent straight HTML - The important and powerful point to note here is
that the logical flow of the script remain intact - Only one of the HTML blocks will end up getting
sent to the viewer - Running this script right now results in
- You are using Internet Explorer
43Dealing with Forms
- One of the most powerful features of PHP is the
way it handles HTML forms - The basic concept that is important to understand
is thatany form element in a form will
automatically result in a variable with the same
name as the element being created on the target
page - By default, any form entry creates a global PHP
variable of the same name - One of PHP's oldest features is the ability to
make HTML form and cookie data available directly
to the programmer
44Web Application Features
- In the followings, a user name is retrieved and
assigned to a variable - The name is then printed by the sub-routine
"submit.php" - ltFORM METHOD"GET" ACTION"submit.php"gt
- What's your name?
- ltINPUT NAME"myname" SIZE3gt
- lt/FORMgt
- submit.php
- lt?php
- print "Hello, myname!"
- ?gt
- From the above example, note that variables can
also be referenced from within double quoted
strings
45Simple Example for Forms
- Assume you have a page with a form like this on
it - ltFORM ACTION"action.php3" METHOD"POST"gt
- Your name ltINPUT TYPEtext NAMEnamegt
- You age ltINPUT TYPEtext NAMEagegt
- ltINPUT TYPEsubmitgt
- lt/FORMgt
- There is nothing special about this form
- It is a straight HTML form with no special tags
of any kind - When the user fills in this form and hits the
submit button, the action.php3 page is called - In this file you would have something like this
- Hi lt?php echo name?gt. You are lt?php echo
age?gt years old - It should be obvious what this does
- The name and age variables are automatically
set for you by PHP
46Debugging
- The classic debugging technique for PHP (and many
other languages) is through echo statements - Just dump out information or the contents of your
variables at various points in the script - There are some tricks that you can use to make
debugging more effective - log messages to file rather than printing so you
don't affect HTTP headers - your HTML output use print_r or var_dump to
examine the contents of any variable - There are some PHP debuggers coming onto the
market that allow you to step through PHP code
line by line
47Comments
- PHP supports 'C', 'C' and Unix shell-style
comments - E.g.
- lt?php
- echo "This is a test" // This is a one-line
c style comment - / This is a multi line comment
- yet another line of comment /
- echo "This is yet another test"
- echo "One Final Test" This is shell-style
style comment - ?gt
48Usage of Comments
- The "one-line" comment styles actually only
comment to the end of the line or the current
block of PHP code, whichever comes first - lth1gtThis is an lt? echo "simple"?gt example.lt/h1gt
- ltpgtThe header above will say 'This is an
example'. - You should be careful not to nest 'C' style
comments, which can happen when commenting out
large blocks - lt?php
- /
- echo "This is a test" / This comment will
cause a problem / - /
- ?gt
49Built-in Variables
- PHP has a number of built-in variables that give
you access to your Web server's CGI environment,
form/cookie data and PHP internals. Here are some
of the most useful variables - PHP internal variables
- The GLOBALS and PHP_SELF variables shown in the
table below are specific to PHP - Variable Name Description
- GLOBALS An associative array of all global
variables - You can access it anywhere without declaring
it - as a global first
- PHP_SELF This is the current script
50HTTP Request Variables
- HTTP request variables are derived from their
corresponding HTTP headers - E.g., HTTP_USER_AGENT is derived from the
User-Agent header, presented in the table below - HTTP_HOST
- Host name in the browser's "location" field
- HTTP_USER_AGENT
- User agent (browser) being used
- HTTP_REFERER
- URL of the referring page
51Database Handling
- Communication with MySQL
- PHP and MySQL are often referred to as the
"dynamic duo" of dynamic Web scripting - PHP and MySQL work very well together, in
addition to the speed and features of each
individual tool - The following is a simple example of how to dump
the contents of a MySQL table using PHP - The example assumes you have a MySQL user called
"nobody" who can connect with an empty password
from localhost - In this example, PHP implements the following
procedure - Connect to MySQL
- Send a query
- Print a table heading
- Print table rows until end of the table has been
reached
52MySQL Example I
- lt?php
- //Connect to the database on the server's machine
as - //user "Nobody".
- conn mysql_connect("localhost", "nobody", "")
- res mysql_query("SELECT FROM mytable",
conn) - header_printed false
- print "ltTABLEgt\n"
- do
- data mysql_fetch_array(res)
- // Retrieve the next row of data.
- if (!is_array(data))
- break
-
53MySQL Example II
- // This part is done only on the first loop. It
prints - // out the names of the fields as table headings.
This - // ensures that the headings will only be printed
if the - // database returns at least one row
- if (!header_printed)
- print " ltTRgt"
- reset(data)
- while (list(name, value) each(data))
- print " ltTHgtnamelt/THgt\n"
-
- print " lt/TRgt\n"
- header_printed true
-
- print " ltTRgt\n"
- print " ltTDgt"
54MySQL Example III
- // Instead of looping through the returned data
fields, - // we use implode to create a string of all data
items - // with the required HTML between them.
- print implode("lt/TDgt\n ltTDgt", data)
- print " lt/TRgt\n"
- while (data)
- print "lt/TABLEgt\n"
- ?gt
55Communication with Other Databases
- Unlike other scripting languages for Web page
development, PHP is - open-source
- cross-platform, and
- offers excellent connectivity to most of today's
common databases including - Oracle
- Sybase
- MySQL
- ODBC (and others)
- PHP also offers integration with various external
libraries which enable the developer to do
anything - from generating PDF documents to parsing XML
56Code Reusage
- Use existing code when it is available, just
integrate it into your standards and project - Develop a library of helpful functions
- A good advice Web gurus know that speed of
coding is much more important than speed of code - PHP was born and raised in an open source
environment - The community holds open source ideals close to
its heart - As a result there are thousands of people on the
mailing list willing to share their knowledge and
code - PHP has a huge user base and a large developer
base as it runs on both Window95/NT and all
flavors of Unixes - Not suggested to spend all day asking people to
write code for you - But through clever use of resources (next
slide), mailing list archives and PHP projects
you can save yourself a lot of time
57Useful Codes
- There are a number of useful code modules you can
use - PHP Resources
- PHP Code Exchange
- PHP Classes Repository
- PHP Knowledge Base
- PHP Mailing List Archive
- Address (e.g.)
- http//www.e-gineer.com/clickthrough/
- They include things like
- database abstraction layer
- session management
- debugging libraries
- logging functions
- timing code
58Problems FAQ Bug Reports
- Read the FAQ
- Some problems are more common than others
- The most common ones are listed in the PHP FAQ,
found at - http//www.php.net/FAQ.php3
- Bug reports
- If you think you have found a bug in PHP, please
report it - The PHP developers probably don't know about it,
and unless you report it, chances are it won't be
fixed - You can report bugs using the bug-tracking system
at - http//www.php.net/bugs.php3
59Archives Downloadingthe Latest Version
- If you are still stuck, someone on the PHP
mailing list may be able to help you - You should check out the archive first, in case
someone already answered someone else who had the
same problem as you - The archives are available from the support page
on - http//www.php.net/
- The source code, and binary distributions for
some platforms (including Windows), can be found
at - http//www.php.net/
60Mailing list for Discussing the Problems
- To subscribe to the PHP mailing list, send an
empty mail to - php3-subscribe_at_lists.php.net
- The mailing list address is
- php3_at_lists.php.net
- If you want to get help on the mailing list,
please - try to be precise and give the necessary details
about your environment - which operating system
- what PHP version
- what web server if you are running PHP as CGI or
a server module, etc. - and preferably enough code to make others able to
reproduce and test your problem