You are on page 1of 62

WEB PROGRAMMING

USING PHP

Rameela Ravindran K

Department of Computer Science

St. Thomas College, Thrissur

INTRODUCTION TO PHP
Web development language
stands for :- Hypertext Preprocessor
server-side scripting language- can be embedded in
HTMLons to love
Reasons to love Php

Cost

Open source software


Php license

Ease of use (easy to learn and write :- a little bit of


experience in a C-syntaxed programming language and
little more involved than HTML
Html embedness (ordinary HTML pages that
escape into PHP mode only when necessary)

Cross-platform compatibility (Apahe unix, iis


windows, Netscape Enterprise Server)
Not tag based
Stability

Server

need not be rebooted often


Software doesn't change radically

Speed (compared to Jsp CGI)


Many extensions (supports ODBC, SQL, access etc:supports major protocols also)
Fast feature development
team will accept every random contribution into the
official distribution without community buy-in, but
independent developers can and do distribute their
own extensions which may be
later folded into the main PHP package in more or
less unitary form.

Popularity
Not proprietary (not tied to any one server
operating)

SERVER SIDE WEB SCRIPTING


On the client, it can mean multimedia
presentations, scrolling headlines, pages that
update themselves automatically, or elements that
appear and disappear. On the server, the term
generally denotes content assembled on the fly, at
the time the page is requested. If you display the
current date and time on a page, for example, the
content will change from one occasion to another
and thus will be dynamic.
Client-Side

anything

to do with layout or browser events happens on

the client
client-side technologies cannot do anything that requires
connecting to a back end server. JavaScript cannot
assemble a customized drop-down list on the fly from
user preferences stored in a database

Server-side Web scripting is mostly about


connecting Web sites to back end servers, such as
databases. This enables the following types of
two-way communication:
Server

to client: Web pages can be assembled


from back end-server output
Client to server: Customer-entered information
can be acted upon.

Common examples of client-to-server interaction


are online forms with some drop-down lists

handle many of the crucial technical and


administrative details necessary to keep a site
running, such as:
Hardware
Software

upgrades
InterNIC registration, IP addressing, DNS
Mail servers (POP/IMAP and SMTP)
Bandwidth
Power supply
Backups
Security

INSTALLING PHP
A server or workstation with enough RAM for OS
Unix, Mac OS X, or Windows operating system
Working, dedicated Internet connection
Install PHP on Windows:

Working

PHP-supported Web server. Under previous


versions of PHP, IIS/PWS was the easiest choice
because a module version of PHP was available for it;
but PHP now has added a much wider selection of
modules for Windows.
correctly installed PHP-supported database
PHP Windows binary distribution
utility to unzip files

Extract the binary archive using unzip utility; C:\PHP -common location.
Copy .dll files from PHP directory to systems directory (usually
C:\Winnt\System32). php5ts.dll , Web server moduleC:\PHP\Sapi\
php5isapi.dll., dlls subfolder are the necessary to be copied to the system
Copy either php.ini-dist or php.ini-recommended to Windows
directory (C:\Winnt or C:\Winnt40), and rename it php.ini. Open this file in
a text editor. Edit this file to get configuration directives. Set error reporting
to E_ALL on their development machines at this point. For now, the most
important thing is the doc_root directive under the Paths and Directories
sectionmake sure this matches your IIS Inetpub folder
Stop and restart the WWW service. Go to the Start menu Settings
Control Panel Services. Scroll down the list to IIS Admin Service.
Select it and click Stop. After it stops, select World Wide Web Publishing
Service and click Start. Stopping and restarting the service from within
Internet Service Manager.
5. Open a text editor Type: <?php phpinfo(); ?>. Save this file in your
Web servers document root as info.php. Start any Web browser and browse
the fileyou must always use an HTTP request (
http://www.testdomain.com/info.php or http://localhost/info.php or
http://127.0.0.1/info.php) rather than a filename
(C:\inetpub\wwwroot\info.php) for the file to be parsed correctly. You
should see a long table of information about your new PHP5 installation.

BEGINNING WITH PHP

Canonical PHP tags


The most universally effective PHP tag style is <?
php ?>
Short-open (SGML-style) tags
Short or short-open tags <? ?>
do one of two things to enable PHP to recognize the
tags:

Choose the --enable-short-tags configuration option


when youre building PHP.
Set the short_open_tag setting in your php.ini file to
on.
ASP-style tags

ASP-style

tags mimic the tags used by Microsoft Active


Server Pages to delineate code blocks : <% %>

HTML script tags


<SCRIPT LANGUAGE=PHP> </SCRIPT>

SYNTAX AND VARIABLES


PHP syntax is relevant only within PHP
PHPs Syntax Is C-Like
PHP is whitespace insensitive
Statements are expressions terminated by
semicolons

$greetings

=Welcome to PHP;

Expressions are combinations of tokens


Expressions are evaluated
Expressions mathematical, boolean, string,
assignment expression
Precedence, associatively, and evaluation order

COMMENTS

Portion of a program that exists only for human


readers
Multiline

comments: starts with the character


pair /* and terminates with */
They cannot be nested
Single line comments: # and // are the commenting
to a given line

VARIABLES
denoted with a leading dollar sign ($).
value of a variable is the value of its most recent
assignment.
need not to be declared before assignment.
no intrinsic type other than the type of their
current value.
have default values.
Variable = value

After the initial $, variable names must be


composed of letters (uppercase or lowercase),
digits (09), and underscore characters (_).
first character after the $ may not be a number.
types are associated with values rather than
variables
no declaration is necessary
Reassigning variables
IsSet that tests a variable to see whether it has
been assigned a value.
unset() will restore a variable to an unassigned
state (for example, unset($set_var); will make
$set_var into an unbound variable, regardless of
its previous assignments).

Variable Scope
Global
Local

Defined Constants

Define(variablename,

Pre-defined variables
$_GET

$_POST

$_COOKIE
$_FILES
$_ENV
$_SESSION

value);

DATA TYPES
PHP has a total of eight types: .
Integers are whole numbers, without a decimal point, like
495. range -231-1 to 231-1
Doubles are floating-point numbers, like 3.14159 or 49.0.
Booleans have only two possible values: TRUE and FALSE.
NULL is a special type that only has one value: NULL.
Strings are sequences of characters, like PHP 4.0 supports
string operations.
Arrays are named and indexed collections of other values.
Objects are instances of programmer-defined classes, which
can package up both other kinds of values and functions that
are specific to the class.
Resources are special variables that hold references to
resources external to PHP (such as database connections).

Strings can be enclosed in either single or double


quotation marks, with different behavior at read
time.
Singly quoted strings are treated almost literally,
doubly quoted strings replace variables with their
values as well as specially interpreting certain
character sequences.

Output:
The

two most basic constructs for printing to output


are echo and print
The simplest use of echo is to print a string as
argument, for example:
echo This will print in the users browser window.;

Or equivalently:

echo(This will print in the users browser window.);


multiple arguments to the unparenthesized version of
echo, separated by commas, as in:

echo This will print in the , users browser


window.;

Print

print

can accept only one argument.


print returns a value, which represents whether the
print statement succeeded.
$animal = antelope;
$animal_heads = 1;
$animal_legs = 4;
print(The $animal has $animal_heads head(s).
<BR>);
print(the $animal has $animal_legs leg(s).<BR>);

Break
Continue
Alternate control syntaxes

alternate to start and end if switch for while


construct
If (expression)
if(expression):
{
statement1
Statement1
statement2
statement2
}
endif;

FUNCTION

{
}

Function function_name($argument_1,$argument_1)

Call by value
Call by reference
Default argument
Return by value
Function &function_name($argument_1,$argument_1)
{
Return $variable;
}
$variable= &function_name;

OPERATORS
Arithmetic operators
Increment decrement operators
Comparison operators
Logical operators
String operators
Bitwise operators
Assignment operators

PASSING INFORMATION BETWEEN


PAGES
Passing variables between pages using URL
Passing variables between pages using Cookies
Passing variables between pages using sessions

PHP will catch the variable tossed from one page


to the next and make it available for further use.
PHP happens to be unusually good at this type of
data-passing function, which makes it fast and
easy to employ for a wide variety of Web site
tasks.

GET ARGUMENTS
The GET method passes arguments from one
page to the next as part of the Uniform Resource
Indicator query string.
When used for form handling, GET appends the
indicated variable name(s) and value(s) to the
URL designated in the ACTION attribute with a
question mark separator and submits the whole
thing to the processing agent- a Web server

<HTML>
<HEAD>
<TITLE>A GET method example, part 1</TITLE>
</HEAD>
<BODY>
<FORM ACTION=http://localhost/baseball.php METHOD=GET>
<P>Root, root, root for the:<BR>
<SELECT NAME=Team SIZE=2>
<OPTION VALUE=Cubbies>Chicago Cubs (National
League)</OPTION>
<OPTION VALUE=Pale Hose>Chicago White Sox (American
League)</OPTION>
</SELECT>
<P><INPUT TYPE=submit NAME=Submit VALUE=Select>
</P>
</FORM>
</BODY>
</HTML>

When the user makes a selection and clicks the Submit button,
the browser agglutinates these elements in this order, with no
spaces between the elements:
The URL in quotes after the word ACTION (
http://localhost/baseball.php)

A question mark (?) denoting that the following characters


constitute a GET string.
A variable NAME, an equal sign, and the matching VALUE
(Team=Cubbies)
An ampersand (&) and the next NAME-VALUE pair
(Submit=Select); further name-value pairs separated by
ampersands can be added as many times as the server
querystring-length limit allows.
The browser thus constructs the URL string:
http://localhost/baseball.php?
Team=Cubbies&Submit=Select

It then forwards this URL into its own address space as a new
request. The PHP script to which the preceding form is submitted
(baseball.php) will grab the GET variables from the end of the
request string, stuff them into the $_GET superglobal array.
The following code sample shows the PHP form handler for the
preceding HTML form:
<HTML>
<HEAD>
<TITLE>A GET method example, part 2</TITLE>
<STYLE>
</HEAD>
<BODY>
<P>Go,
<?php echo $_GET[Team]; ?>
!</P>
</BODY>
</HTML>

Advantages of GET over POST


It constructs an actual new and differentiable URL
query string. Users can now bookmark this page. The
result of forms using the POST method is not
bookmarkable.
Disadvantages:
The GET method is not suitable for logins because
the username and password are fully visible
onscreen as well as potentially stored in the client
browsers memory as a visited page.
Every GET submission is recorded in the Web server
log, data set included.
Because the GET method assigns data to a server
environment variable, the length of the URL is
limited. (Maximum 300-word chunk of HTMLformatted prose using GET method)

HTTP POST METHOD

HTTP COOKIES

HTTP SESSION

ARRAY

Create array
By

assigning a value into one

$my_array= the first thing;

By

using array()

$my_array=array();
$my_array= array(apple, orange, pear);
$my_array[0]= apple;
$my_array[1]=pear;
$my_array= array(1,1,52,73);

By

calling a function that happens to return an array


as its value
$my_array= range(1,5);
$my_array=fun(4);

RETRIEVING VALUE

Index

Echo

List()

$my_array[1];

$my_array=

array(apple, orange, pear);


list($f1,$f2,$f3)=$my_array;

MULTIDIMENSIONAL ARRAY

Using array() construct


$my_array= array(breakfast array(idly,
dosa, appam),lunch(rice, bread);
$my_array= array(array(a,b), array(c, d),
array(f, g));

Deleting from array


Use

unset()

Iteration

Hidden

pointer system built into array


Each index value points to the next
Foreach loop

Foreach($a as $v)

traversing using list() and each()

While(list($key,$val)=each($array)

Array functions

Is_array($myarray)
Count($myarray)
Sizeof()

// nonempty elements

In_array($myarray,

a)
Isset($myarray[$key] // key is valid or not

ARRAY OPERATIONS
Union (+)
Equality(==) // same key value pair
Identity (===)// same key value pair in the same
order and of same type
Inequality (!= <>)
Non identity (!==)

ARRAY FUNCTION
Is_array()
Array_fill($startindex,$num,$value)
Array_key_exists($key, $array)
Array_sum($myarray)
Array_count_values // array using the values of
the input as key and their frequency as values
Array_unique()

Sort(&$my_array[,$sort_flag=______)
Sort_regular

Sort_numeric
sort_string

Asort(&$my_array[,$sort_flag= -------------)
Rsort((&$my_array[,$sort_flag= -------------)
arsort (&$my_array[,$sort_flag= -------------)
ksort (&$my_array[,$sort_flag= -------------) //sort
by key
krsort (&$my_array[,$sort_flag= -------------)
natsort (&$my_array[,$sort_flag= -------------)
natcasesort (&$my_array[,$sort_flag= -------------)

In_array($value,$array)
Each($array) // return each key value pair
List()
Current($array) // return current element
Next()
Pre()
End() // sets the pointer to the last element
Reset()
count()

STRINGS IN PHP
Sequence of characters
Accessed using index
concatenation using .
Heredoc syntax <<<

$string_value= <<<identifier
Text
Identifier;

STRING FUNCTIONS
Strlen($string)
Strops()

strpos($mystring,$findme[,offset=0])
Mystring

string to be searched in
Findme item to be searched
Offset which character to start searching
$pos= strpos($mystring,$findme)

Strrpos()

Postion

of the last occurrence of the substring

Stripos()
Strripos()
str

DATABASE
Collection of data with regular and predictable
structure
Examples :

postgreSQL
MySQL
SQL

Server
Oracle

MYSQL
Freeware
Stable no crashing
Lightweight require no

You might also like