You are on page 1of 43

Introduction to PHP

Origin and Uses Of PHP


Overview of PHP
General Syntactic characteristics of
PHP
Primitives,operations and Expressions
Output, Control statements
Arrays, Functions,Pattern matching,
Form handling
Files, Cookies, Session tracking
Database access with PHP and MySQL.

Origin and Uses Of PHP

PHP was developed by RASMUS LERDORF , a


member of Apaches Group in 1994.

Initial purpose was to help Lerdorf track visitors to


his personal web site

In 1995 he developed a package called Personal


Home Page tools which became the first version of
PHP

PHP was an acronym for Personal Home Page

Within 2 years of release PHP was being used at a


large number of websites.

PHP is now developed ,distributed and supported as


an open source product.

PHP processor is now resident on most web servers.

PHP is a server side XHTML embedded scripting


language

Used for form handling and database access

It has driver support for 15 different database


systems.

Supports the common electronic mail protocol POP3


and IMAP

Also supports distributed object architectures COM


and CORBA

OVERVIEW OF PHP

PHP is a server side XHTML embedded scripting language.

Alternative to CGI,microsofts ASP and ASP.net(Active


Server Pages)Sunss JSP (Java Server Pages) and Allaires
ColdFusion.

The way how it is interpreted is related to client side side


javascript.

Like javascript, When a browser requests an XHTML


document that includes PHP script, the web server that
provides the document calls PHP processor.

The server identifies the PHP script by their filename


extension. Ex .php,.php3 or .phtml

Overview contd..

PHP processor has two modes of operations


copy mode
Interpret mode
If a processor finds xhtml code in i/p file it simply copies
it into o/p file.

If it finds PHP script in i/p file then it interprets it and


sends any o/p of the script into o/p file

The output from a PHP script must be a XHTML or


embedded client side script.

This new file is sent to the requesting browser.(The


client never sees a script.(even view source shows the
xhtml code not the php script)

Recent PHP implementation performs some


precompilation on complex scripts which increases
speed.

The syntax and semantics of PHP is closely related to Perl and


Javascript.

PHP uses dynamic typing like javascript.

Variables are not type declared and no intrinsic type.

The type of variable is set every time it is assigned a value.

PHP arrays are merge of the arrays of common programming lang and
associative arrays and having characteristics of both.

There are large collection of functions for creating and manipulating


PHP arrays.

Supports both procedural and object oriented programming.

PHP has an extensive library of funs. Making it more flexible and more
powerful tool for server side s/w development.Many predefined
functions are used to provide the interfaces to other s/w systems such
as mails and DBs

Web site for official infm on PHP is http://www.php.net

General syntactic characteristics


PHP scripts are either embedded in xhtml doc. Or in the files that
are referenced by xhtml doc. Eg. <?php and ?> tags
If a PHP is stored in a different file it can be brought into the doc
by include construct. Eg. Include(table2.inc);
The PHP interpreter changes from interpret to copy mode when an
include encounters.
All variable names begins with $ dollar sign. The name after the $
is like variable name in other prog.lang.(letter or no or
underscore).Variable names are case sensitive.
Comments can be specified in single line either with # or with // or
in multiple line with /* and*/.
Perl style comments are mostly used.
Statements are terminated with semicolon.
Braces are used to form compound statements for control
constructs..

Variables names are case sensitive but reserved


words are not.

PHP RESERVED WORDS

and

contin
ue

elseif

foreac
h

includ or
e

switc virtua
h
l

break

default

extend
s

Functio
n

list

requir
e

this

xor

case

do

false

global

new

return

true

while

class

else

for

If

not

static

var

There is no difference between not,NOT or Not

Primitives
PHP has 8 primitive data types.(fundamental)
PHP has 4 scalar types.(single)
Boolean
integer
double
string
Two compound types
Array and
objects
And Two special types
Resources (used to link)and
NULL

VARIABLES
Dynamically typed and no type declaration.
The type is set every time it is assigned a value.
An unassigned variables is called unbound variables which has the value NULL.
If an unbound variable is used in an expression and uses a number then NULL is
0.,If it is a string then NULL is empty string.
IsSet function is used to test whether a variable is currently has a value or not.
Eg. IsSet($fruit) returns true if it has a value. False otherwise.
A variable retains it value until either it is assigned a new value or it is set back
to the unassigned state by unset function.
Error reporting function is used to inform about the reference of unbound
variable
Place this statement at the beginning of script
error_reporting(15);
The default error repoting is 7 which will not report the use of unbound
variables.

Integer Type:

Corresponds to long type of C and its successors. i.e


its size is that of the word size of the machine.

Most cases this is 32 bit or a bit less than 10 decimal


digits.

Double type :
Corresponds to double type of C

Includes decimal points,exponent (E or e)or both


followed by signed integer

No need of any digits before or after decimal points.


E.g .345 and 345. are legal

String type :

Characters are single byte.

No character type. Single character data value is represented


by the length of 1.

Defined either with single quote or double quote.

In single quote escape sequence is not recognized e.gThe sum


is :$sum will be displayed as it is .no value will be substituted
for sum.

But in double quoted interpolation(value substitution) is


possible.
e.g The sum is :$sum is The sum is 10.2

If the variable in the double quoted does not want to be


interpolated then use back(\)slash to escape the meaning

Double quoted strings can include embedded new line


characters that are created by enter key

Boolean type

Two possible values TRUE or FALSE.

If an integer expression is used in boolean context,it


evaluates to FALSE if it is zero, otherwise it is TRUE.

If string is used, it evaluates to FALSE if it is empty


string or the 0 otherwise it is TRUE.

But 0.0 is TRUE.

If it is double ,it evaluates to FALSE ,if it is 0.0.Becoz of


rounding errors and string 0.0 is true ,its not an
good idea to use expression of type double in boolean
context.

A value can be very close to zero,but becoz it is not


exactly zero ,it is evaluated to true.

ARITHMETIC OPERATORS AND


EXPRESSIONS

PHP has usual collection of arithmetic operators with


usual meanings.
+ ,- , *, / ,% , ++ and
In case of + ,-, * ,if both operands are integers, the
operation is integer and an integer result is produced.
If either operand is double ,the operation is double
and a double result is produced.
But for division if integer division is done ,then the
result is not the integer value but it returns the
double value.
Any operation on integer that results in integer
overflow also produces a double.
The operands of the modulus operators (%) are
expected to be integers.

PREDEFINED FUNCTIONS
FUNCTION

PARAMETER
TYPE

RETURNS

floor

double

Rounds it to the nearest


integer below its current
value.

ceil

double

Rounds it to the nearest


integer above its current
value.

round

double

Nearest integer

srand

integer

Initializes a random number


generator with parameter

rand

Two
numbers

Pseudo randam number


greater than the first
parameter and smaller than
the second

abs

number

Absolute value of the


parameter

min

One or more

smallest

EXAMPLE FOR floor and ceil


<?php
$val = 4.9;
$ceiled = ceil($val);
$floored = floor($val);
?>
Out put
Ceiled =5 and floored = 4

String operations

Only string operator is the catenation operator, specified


with a period(.)
String variables can be treated like arrays for access to
individual characters.
For e.g if $str has the value apple
The $str{3} is l
PHP includes many functions that operate on strings.Some
commonly used string function are
strlen
strcmp
strpos
substr
chop
trim
itrim
strtolower
strtoupper

Functio
n

Parameter
type

Returns

strlen

A string

The number of character in the string

strcmp

Two strings

Zero if the two strings are identical,


Negative if first string2 is greater than string
1or
Positive if string1 is greater than string2

strpos

Two strings

Finds the position of the first occurance of a


string inside another string

substr

A string and
an integer

Substring of the string parameter starting from


the position indicated by the second
parameter.If third parameter is given it
specifies the length of the returned substring.

chop

A string

The parameter with all whitespace characters


removed from its end

trim

A string

The parameter with all whitespace characters


removed from both the ends

itrim

A string

The parameter with all whitespace characters


removed from its beginning

strtolow
er

A string

The parameter with all uppercase letters


convertedto lowercase letters.

Ex for strpos
<?php
Echo strpos(I love PHP,PHP);
?>
output 7

Ex for substr
$ str = apples are good;
$sub = substr($str,7,1);
Output
$sub = a

SCALAR TYPE CONVERSION


PHP includes both implicit and explicit type conversions
Implicit type conversions are called coercion.
In most cases context of an expression determines the
type that is required.
There are frequent coercions between numeric and
string types.
Whenever the numeric value appears in string
context,the numeric value is coerced to a string.
Whenever a string value appears in numeric context,the
string value is coerced to a numeric value.
If the string contains a period(.) an e or an E,it is
converted to a double. Otherwise it is converted to an
integer.

If the string does not begin with a sign or a digit,the


conversion fails and zero is used.

Non numeric characters following the number in the


string are ignored.

Explicit type conversions can be specified in three


different ways.
* By using the syntax of C , an expression can be
cast to a
different type
* Using the functions intval , doubleval or strval.
* Using the set type function

By using the syntax of C , an expression can be cast to a different


type.The cast is a type name in parantheses preceding the
expression.
For E.g If $sum = 4.777
(int)$sum produces 4
Another way of explicit conversion
For E.g If $sum = 4.777
intval($sum) this function call returns 4
The settype function takes 2 parameters - a variable and a string
that specifies the type name.
For E.g If $sum =4.777
settype($sum, integer);
The type of the variable can be detrmined in 2 ways.
By using gettype function
By using the type testing function.

gettype function

The gettype function takes a variable as its parameter and


returns a string that has the name of the type of the current
value of the variable.

One possible return type is unknown.

Type testing function.

Type testing function takes a variable name as parameter


and returns a Boolean value.
is_int , is_integer , is_long are used for testing integer type.
is_float , is_double , is_real are used for testing double
type.
is_bool tests for Boolean type.
is_string test for string type.

Assignment operators:

PHP has the assignment operators as C and perl,including


the compound assignment operators such as += , /= etc..

OUTPUT
Any output from a PHP scripts becomes part of the
document the PHP procesor is building .So all the output
must be in the form of Xhtml which may include embedded
client script.

The print function used to create a simple unformated


output.It can be called with or with out parantheses
around its parameter
E.g print APPLES ARE RED<br /> They are good for
health<br />

Print expects a string parameter,if some other type is


given ,the PHP interpreter will coerce it to a string .
print(47) will produce 47.

Variables that appear in double quoted string is interpolated.

print The result is : $result <br />;


will be taken.

PHP uses the printf function from C. It is used when complete


control over the format of specified data is required

The general form of a call to printf is

Printf(literal_string , param1 ,param2,..)

The literal string can include labeling information about the


parameter whose values are to be displayed.
Also contains the format codes for those values.
The form of format code is % sign followed by a field width
and a type specifier.( e.g s for strings ,d for integer and f for
float or doubles
The field width is either an integer or or two integer literals
separated by a decimal point for float and doubles.

---The value of result

%10s -------a character string field of 10 characters

%6d

%5.2f ------a float or double field of 8 spaces with 2


digits to the right of the decimal point ,the decimal
point and 5 digits to the left.

Consider $day is Friday

printf(Today is 6s :,$day);

Today is Friday will be printed.

-------an integer field of 6 digits.

then

CONTROL STATEMENTS
PHP control statements are similar to those of C and its
descendants.
PHP uses the 8 relational operators of javascript.
< ,<= , > , >= , != , == , === and !==
The === produces true only if both operands are of the same
type and have same value and !== ,the opposite of===.
If the type of operands of the other 6 relational operators are
not the same ,one is coerced into other type.
If a string is compared to a number , the string can be converted
to the number and the numeric comparision will be done.
Ther are 6 boolean operators.
and , or , xor , ! , && , ||
The precedence of and , or is lower than the && and ||

SELECTION STATEMENTS :
The control statement can be either an individual
statement or a compound statement .An if statement
can include any number of elseif classes.
Ex.
if ($day == Saturday || $day == Sunday)
$today = weekend;
else {
$today = weekday ;
$work = true;
}

The switch statement has the form and semantics of


javascripts.
The type of control expression and case expression is either
integer double or string.
If necessary the value of case expression is coerced to the
type of control expression for the comparision.
A default case can be included.
Break statement should follow the each selectable case
segment.
Ex
switch ($ bordersize){
case 0 : print <table>;
break;
case1 : print <table border = 1>;
break;
case4:print<table borde = 4 >;
break;
default:printerror;

LOOP STATEMENTS:
while , do-while , for , foreach are similar to javascript

EX for finding factorial


while loop do while loop
$fact = 1;
$fact = 1;
$count = 1; $count = 1;
While ( $count < $n) { do {
$count++; $count++;
$fact *= $count; $fact *= $count;
} }while ( $count < $n) ;
for loop
for ($count = 1 , $fact = 1 ; $count <$n;){
$count++;
$fact *= $count;

ARRAYS

Arrays in php are combination of any other programming


language and associative arrays or hashes.

Each array elemant consists of 2 parts , a key and a value.

If an array has an logical structure similar to that of


common programming language then the key will be a
non negative integers and are always in ascending order.

If it is similar to hash, its key are strings and the order of


the element is determined with system designed hashing
functions.

The string keys are some times a people name or days of


the week etc.
Arrays can have some elements with integer keys and
some with string keys.

Ther are 2 ways to create an array.


By assigning a value to an element of an array or
By using array construct.
1st method
$list[0] =17;
If $list is already used in the script then after this
assignment $list becomes array
For E.g
$list[1] = today is a good day;
And if an empty brackets are used in the array then
$list[] = 40;
Then the list subscript becomes 2.
The elements of the array need not be of same type.

2nd method:

$list = array(10,20,25,45,34)
This assignments create the array of 5 elements with keys 0
,1, 2, 3,4

If u want to specify different keys then,


$list = array(1 => 10 , 2 => 20 , 3 => 25 , 4 => 45 , 5 =>
34 );

An array construct with empty parantheses creates an


empty array with no elements.
$list = array ();

The following creates the array that has a form of hash


$ages = array(joe =>35 , mary =>36, ben =>15);

PHP array can be mixture of traditional array and hash.

For E.g
$stuff = array(make => cessna , model => c20 ,
2 =>sold);
Array elements can accessed by subscripting. The value in
the subscript is the key of the value being referenced,
Ex :
$ages[mary] = 36;
The value of the element whose key is mary in the ages
array is set to 36
Multiple elements of an array can be assigned to scalar
variables in one assignment
$trees = array(oak , pine , binary);
$list($hardwood , $softwood, $datastructures) = $trees;
Now, $hardwood = oak $softwood = pine and
$datastructures=binary

FUNCTION FOR DEALING WITH ARRAYS


A whole array can be deleted with unset and individual array
element can also be removed with unset.
EX:

$list = array(2 , 4 ,6 , 8);


unset($list[2]);

Now $list contains 3 elements with keys 0 ,1, 3 and elements 2 ,


4 ,8.
The collection of keys and collection of values can be
extracted by built in functions.
Array_keys takes array as parameter and returns the array of
keys of the given array. The returned arrray uses 0 , 1 , 2 etc
as keys
EX:
$high = array (mon => 70 , tue => 65 ,wed =>60 )
$days = array_keys($high);
$temp = array_values($high);
Now
$days = (mon ,tue ,wed) and $temp = (70 ,65 , 60)
In both the cases the keys are 0 , 1 ,2

The array_key_exists function is used for determining the


existance of a key and this function returns a boolean value.

The is_array function is used to check wheteher it is an array


or not.It takes a variable as its parameter and returns true if
the variable is an array and false otherwise.

The elment in an array can be determined by sizeoffunction

EX: $list = array (bob ,mary ,ben);


$len = sizeof($list);
Now , $len=3.
The explode function explodes a string into substrings and
returns them in an array. The delimiters are defined in th
first parameter and the second parameter is the string to be
converted.
Ex :
$str = have a good day;
$words =explode( , $str)
Now,
$words contains(have , a , good ,day).

The implode function does the reverse of explode. Given


a separate character or strings it catenates the elements
of the array together.
EX:

$words = array (are, you ,fine);


$str = implode( ,$words);

Now,
$str has are you fine
Internally the elements of the array are stored in a linked
list of cells where each cell includes both the key and the
value of the element.
The cells themselves are stored in memory through a
hashing functions so that they are randomly distributed.
String keys are implemented through the hashing
function.

LOGICAL INTERNAL STRUCTURE OF ARRAYS

Key based
access
function

Hash
fun

Key value

Sequenti
next al access
fun

Key value

next

Key value

next

Current function is initialized refer


the first element of the array.

You might also like