Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

Features

As a programming lanouage for the Web, PHP 1s · hard to ·ignore. Clean


· s}·ntax,
. .
object-oriented fundam~ntals, an extensible architecture that encourages innovation,
support for both current and upcoming technologies and protoc~ls. ~nd excellent
database integration are just some of the reasons for the popularity it currently
enjoys in the developer community.

Simplicity
Because PHP uses a consistent and logical syntax, and because it comes with
a clearly written manual, even novices find it easy to learn. In fact, the quickest
way to learn PHP is to step through the manual's introductory tutorial, and then
start looking at code samples off the Web. Within a few hours, you' II havr! learned
the basics and will be confident enough to begin writing your own scripts. This
adherence to the KISS (Keep It Simple, Stupid) principle has made PHP popular
as a prototyping and rapid application development tool for web applications. PHP
can even access C libraries and take advantage of program code written for this
language, and the language is renowned for the tremendous flexibility it allows
programmers in accomplishing specific tasks.

Portability
With programming languages, portability-the ease with which a program can
be made to work on different platfonns-is an important factor. PHP users have
littl~ to fear here, bec_ause cross-platfonn devel~pment has been an imponant .
design goal of PHP since PHP 3.0. Today, PHP 1s available for a wide variety f
platfonns, including UNIX, Microsoft Windows, Mac OS, and 0S12. Add't'~
because PHP code is inte~reted and not compiled, PHP scripts written on•~- i~
platfonn usually work as 1s on any other platform for which an interpr'ete ,..
This means that developers can code on Windows and deploy on UYJX r _ex
any major difficulties. ,. · -
Speed .
Out of the box, PHP scripts run faster than most other scripting languages, widt
numerous independent benchmarks putting the language ahead of compelinJ ·
alternatives like JSP, ASP.NET, and Perl. When PHP 4.0 was first released, ii ·
raised the perfonnance bar with its completely new parsing engine. PHP 5.0
improves perfonnance even further through the use of an optimized memorf ·
manager, and the use of object handles that reduce memory consumption and
help applications run faster.

Open Source
Poss ~bly the best thi ng about PHP is that it's free-its source code is freely
avaibble on the Web, and developers can install and us.e it without paying licensing
fees or investing in expensive hardware or software. Using PHP can thus significantly
reduce the development costs of a software.application, without compromising on
either reliability or performance. The open-source approach also ensures faster bug
fixes and quicker integration of new technologies into the core language, simply
due to the much larger base of involved developers.

Extensible
Keeping future growth in mind, PHP's creators built an extensible architect'Jre
that enables developers to easily add support for new technologies to the language
throLgh modular extensions. This extensibility keeps PHP fresh and always at
the cutting edge of new technology. To illustrate this, consider what PHP lets you
do through its add-on modules: dynamically create image, PDF, and SWF files;
connect to IMAP and POP3 servers; interface with MySQL, Oracle, PostgreSQL,
and SQ Lite databases; handle electronic payments; parse XML documents; and
execute Perl, Java, and COM code through a PHP script. And as if all that wasn't
enough, there's also an on line repository of free PHP classes called PEAR, the
EHP Extension and Application Repository, which provides a source of reusable,
bug-:ree PHP components.

XML and Database Support


Regardless of whether your web application sources its data from an
or a database, PHP has you covered. PHP 5.0 comes with an impro
extension that enables you to take advantage of new features in the
RDBMS (including subqueries, transactions, and referential im •
language also suppons D82, PostgreSQL, Oracle, mSQL.
Storing Values in Variables
Variables are the building blocks of any programming language. A variable can b
thought of as a programming construct used to store both numeric and nonnume
data. The contents of a variable can be altered during program exec ution , and
variables can be compared and manipulated using operators.
64 Bow lo Do Everything with PHP & MySQL

PHP supports n number of different variable types- Booleans, integers,


floating point numbers, strings,·arrays, objects, resources, and NULLs-and die
language can automatically determine variable type by the context in whicb :t ii
being used. Every variable has a name, which is preceded by a dollar($) ~
and it must begin with a letter or underscore character, optionally followed t,J
more letters, numbers, and underscores. For example, $popeye, $one_day.,
and $I NCOME are all valid PHP variable names, while $123 and $481-h
in valid variable names.
11
~i.~--~~)'..
• s¼, Va riable names in Pl-IP are case-sensitive; $count is diR'ere
~J•
~~~~~-{ $Count or $COUNT.
'

To see PHP's vari ables in action, try out the following script:

<ht ml >
<head>c::basefont face ="Arial">< /he ad>
<bcdy>

<h2>~: This creature has tusks made of ivory. J


What is its name?</h2>

<?php
// define variable
$a~swer = 'Elephant';

// print output
echo "<h2><i>Sanswer< /i >< /h 2> ";

</bc dy >
</html>

Here, the variable $answer is first defined with a string value,


subs tituted in the echo () function call. The echo () function~
p ri nt () function, is commonly used to print data to the stan1dnlt,i
(here, the browser). Notice that l've included HTML tags within the
and they have been rendered by the browser in its output.
CHAPTER 3: Using Variables, Statements, and Operators 65

Assigning and Using Variable Values


To assign a value to a vari~ble, use the assignment operator, the equality (=) symbol.
This operator assigns a va.lue (the right side of the equation) to a variable (the left
side). The value beir:g assigned need not always be fixed; it could also be another
variable, an expression, er even an expression involving other variables, as here:

<? php
$age= $doh + 15;

To use a variable vake in your script, simply call the variable by name, and
PHP will substitute its value at run ti me. For example:

<?php
$today= "Ja~ 05 200~";
echo "Today is $today" ;
?>

Saving Fonn Input in Variables


fonns have always been :me of the quickest and easiest ways to add interactivity
to your web si te. A fonn !nables you to ask customers if they like your products
and casual visitors for comments. PHP can simplify the task of processing web-
based fo rms substantially, by providing a simple mechanism to read user data
submitted through a fonn into PHP variables. Consider the following sample fonn:

<httnl>
<head> </head>
<body>

<fo::-m ac t ion="messaqe.php" method="post">


Enter your message : .:: input type="text" name="msg " size•" 30">
<inp·:1t type = 11 subnit 11 val ue= "Send ">
</form>

</body >
</html>
Th~ most critical line in this entire page is the <form> tag:

cform methcd= "post" action=" message . php">

c/fcrm>

As yo-J probab~y already know, the method attribute of the< form:> tag
the manner in which fonn data will be submitted (POST), while the action
specifies ~he name-. of the server-side script (messag e. php) that will process 1111
inforrnation entered into the fonn. Here is what messag e. php looks like:

<?php
// retrieve fonn data in a variable
$ i nput= $_POST ['msg '] ;

// print it
ecr.o 11 \'o·J said: <i>$inp ut</i>";
?>

To 5ee how L'lis works, enter some data into the fonn ( "boo") and submit iL
The form processoc should read it and display it back to you ( "you said: bo0:1;
Thus, whenever a fonn is POST-ed to a PHP script, all variable-value pairs •
that form auton1atically become available for use within the script through a
PHP container variable,$_ POST. To then access the value of the form
its nam-2 inside the $_POST container, as in the previous script. If the
GET instead of POST, simply retrieve values from $_GET instead of$
104 How to Do Everything with PHP & MySQL

Using Array Functi~ns


If you're using an associative array, the array_keys () and array ~alues{t
die
functions come in handy to get a list of all the keys and values within ara,_,
The following example illustrates this: · ·

<?php
// define an array
$menu= array('breakfast' => 'bacon and eggs', J
'lunch'=> 'roast beef', 'dinner'=> 'lasagna');

// returns the array ('breakfast', 'lunch', 'dinner')


$result= array_keys($menu);

// returns the array ('bacon and eggs', 'roast beef',


$result= array_values ($menu);
?>

To check if a variable is an array, use the is_array() function, as in


following:

<?php
// create array
$desserts= array('chocolate mousse', 'tiramisu');

// returns 1 (true)
echo is_array($desserts);

You can convert array elements into regular PHP variables with•
and extract () functions. The list () function assigns array e
variables, as in the following example: ·

<?php
// define an array
$flavors: array('strawberry', 'grape',

// extract values into variables .


list (Sflavorl, $flavor2, $flavor3)

// returns "strawberry"
echo $flavorl;

t
i CHAPTER 5: Using Arrays and Qasaom
, - . , . .-

, conve . . . .
ugh a hash
function iterates thro the key-value
. T~e e x tr a c t { )_ variable-value pairs. Here's how: rung
ing
paus into correspond

<? ph p
ia ti v e ar ra y
II je f in e a ss o c le ', •y el lo w '= > 'ban
ana•, J
'a p p
y (' re d ' =>
S fr u i : s = a rr a 'g ra p e ') ;
le ' = > 'p lu m ', 'g re e n '= >
•p u rp

in to v ar ia b le s
II ex : ra ct v al u es
s) ;
ex tr a c t ($ fr u it
an a"
I I re : u rn s "b an
ec h.::, .$ ye ll ow ;
?>
Sli
d of an ex isting array with the arrayJ)U
en t to th e en interestingly named
Yoo can add an elem th e en d w ith th e
e an element from t off the top of the llll"P
!aiii¼•~
fun ction , and remov to po p an el em en
a rr a y_ p o p () fu
ncti on . If you need hi le the a rr a y _ u n sh if t ()
tio n, w
a y _ s h if t () func array. The folio ·
you can use the a rr the be gi nn in g of th e
nc tion takes care o f adding elements to
fu
ple de m onstrate s all these functions:
exam

<? ph p
II de :: in e ar ra y ' 1
J1"l l ' , 'H ar ry ') ,·
$ st ~ d en ts = ar ra y ( 'T om ,
in g
el em en t fr om th e be gi nn
I/ re □ove an
t• Jd en ts ) ;
ar ra y _ sh i f t ( $ s
en d
m en t from th e
II re no ve a n e le
d e n ts );
ar ra y_ pop ($ st u

ad d an el em en
t to th e en d
/I 'J oh n' > i
u d en ts ,
a rr a y_p us h ($ st
n in g
t to th e b eg in
II ad d an el em en 'R on al d '> ;
if t ($ st u d en ts ,
a r ra y _ u n sh
'J il l' '
no w lo o k s 1 ik e (' R o n al d ,,
I I a rr ay
ts );
p ri n t r{ $ st u d en
?>
106 How to Do Evel'}thing \\ith PHP & MySQL

The exp 1ode ( } function splits a string into smaller componeac:s • :B


blsis of a user-specified pattern, and then returns these elements • •
function is particullrly handy if you need to take a string containinc a
{for example. a comma-delim ited list) and separate each elemen! oflhe
further processing. Here's an example:

<?p'::.?
// define string
Sstri~g = ' Engli s h Latin Greek Spanish ' ;

// spl i t on whi tespace


Sla~gua9es = exp l ode ( ' ' $string );

// Slangua5 e s r.ow contai ns (' English'. 'Latin', 'Gre~k•. •


?>

Obviously, you can also do the reverse: the implode () fJnctioa


a single string from all the elements of an array. joining them together willlt
defined sepe!I"ator. Re,·ising the previous example. you have :he followiag:

<?php
// define string
$string= ' Eng l i sh Latin Greek Spanish';

// split en wh itespace
$languages = expl ode(• • $string);

// create new string


// returns •Engli sh and Lat i n and Greek and Spaaia•
SnewString = implode(• and•• $languages) ;
?>
Reading and Writing Files
pffPcomes wit~ apowerful and flexible file manipulation APt
develope~ ~o view and modify file attributes, read and list di.~ ~'11\w.
file pennisstons, retrieve file contents into a variety of native data
search ~~r files based on specific patterns. The following sectons cLCCUII
and wntmg files, and retrieving file infonnation.

Reading Data from a File


To begin with, let's consider the process of opening a file and rea.d:r.g its contents.
Create and run the following PHP script (remember to alter U",e vi!.h:.e of the $file
variable to an actual file on your system that is readable by t'1e wet server):

<?phP
// set file to read
$f De = '/home/web/projects. txt';
CHAPTER 6: Using Files, Sessions, Cookies, and External Programs

// c,pen f:.le
Sfh = foper :.($fi le, 'r') or die('C ould not open file! '):

// read file conte nts


$data = fread ($fh, files ize($ file) ) or die('C ould not
read file! ');

/ / close file
fclos e($fh );

// ~rint file conte nts


echo $data ;

A review of the previous script will reveal the three basic steps to reading data
from a file:

1. Open the file and assign it a file handle: PHP needs a file handle to
read
data from a file. This file handle can be created with the f open () function,
which accepts two arguments: the name and path to the file, and a string
indica:ing the mode in which the file is to be opened (' r' for read).
2. Interact with the file via its handle and extract its contents into a PHP
variable. If the f open () function is successful, it returns a file handle-
$ fh-w hich can be used for further interaction with the file. This file
handle is used by the f_re_ad~ _n_S:~i9_~_,_ ~_~kh. r~~9$.Jh~ file and.places
its cottents into a variable.

The second argument to f read () is the number of bytes to be read. You


can usually obtain this infonnation through the file s i ze () function,
which returns the size. of the file in bytes.
3. Close the file. Once you' re done with the file, it's a good idea to close
iL
with fclo se (), to avoid using up memory. This last step is not '
. ~

t necessary, but it's a good habit to develop.


Ar_ alternative method of reading data from a file is the file


r! ca.a
which reads t.1e entire file into an array with a single function
i
f of the array then contains one hne from thenle.Tc>aiip ay
'
f simply iterate over the array in a f orea ch () looe Jl'Jd '
fI
I
t
// deiniti a:ize variabl e
unset {$T,e) ;
II check type again
I I returris nrLL
echo gettype ($me);
?>

7 1Jsing Operators to Manipulate


and Compare Variables
If variables are the building blocks of a programming language, o~
the glue that 1e~ you do something useful with them. PHP comes w·
15 operators, including operators for assignment, arithmetic, string,
and logical operations. Table 3-3 has a list.

/ Using Arithmetic Operators


To perform mathematical operations on variables, use the standard ari
operators. as illustrated in the follo wing example:

<?php
II defi~e variabl es
$numl = 101;
$num2 = 5;

// add
$sum= $numl + $num2;

/I subtrac t
$diff = $numl - $num2;

// multipl y
$produc t= $~uml • $num2;
CHAPTER 3: Using Variables, Statements, and 0pmJ0rS 7

// divide
$quotient = $numl / $nurn2;

/ / modulus
$remainder = $numl ~ $num2;

To perform an arithmetic operation simultaneou 5Jy wi:h an assignment, use the


two operators together. The following two code snippets are equivalent:

<?php <?ph?
$a = $a + 1 O; Sa + = l•J:

Operator What It Doe-s


= Assign men~
+ Add ition
Subtraction
* Multiplication
I Division; returns q:Jotiem
% Division; returns rr.odulu.s
String concllenatic,n
-- Equal to
-- - Equal to an.j of the same type
! ::: = Not equal to or not of the same type
<> aka ! = Not equal to
< Less than
<= Less than o· equal :o
> Greater than
>::: Greater than or eql:al to
&& Logical ANJ
II Logical OR
xor Logical XO~
Logical NOT
++ . Addition b) l
Subtraction by I
]6 How to Do Everything with PHP & MySQL

which operators have precedence over others. The following list illlUStl•fj
irr:portant PHP precedence rules. (Operators on the same line have the I ■ I
of precedence.)


I
.
I I '++ ' I
-- I

■ I* t I I' I% I

+
■ '-' .
I I I I

■ I< I
' <=' I> I
'>='
__ , I _ __ I , __ ,
■ .I -- .--
I I I I

■ ' &&'


I
II I


I
I ? I I
.

1f in doubt, remember that you can-in fact, should-override these mid


parentheses, as some of the examples in this chapter do. This reduces am·n·
and ensures that operators are evaluated in the order that you specify. For ·
the expression 10 * 10 + 1 would return 101, while the expression 10
( 1 o + 1) would return 11 o. The difference lies in the fact that the second
uses parentheses to clearly indicate the order in which operations are to l'e

Summary
This chapter focused on getting you started with PHP, by teaching
thjngs you need to know about PHP scripting. It showed you how ll
code inside HTML documents using the special <?php .•. ? >
taught you the basic syntactical rules for statements, comments,
It showed you how to assign values to variables and use PHP
input from an HTML fonn in one or more PHPvariableLI
some of PHP's data types and operators, illustratinc Ml~~
to perfonn calculations, comparisons, and ~
finallyt it wrapped · witll;.t
How to Do Everything with PHP & MySQL

itoring Data in Cookies


Cookies allow web sites to store client-specific information in a file on the
system, and re v 1s 1n ormatlon on an as-needed as1s. oo
used to bypass the stateless nature of the HTTP protocol. by using tJrei
disk as a storage area for persistent data; however, they're dependent 00
browse r being configured to accept cookies.
PHP has included support for cookie generation and retrieval since
Using PHP's built- in functions, you can create client-side cookies, store Vi
them, and delete them after a specifi ed period has passed.
When dealing with cookies, you should be aware of some ground rule&::

~ - Because cookies are used to record information about your activities ~


a particular site, they can only be read by the site that created them.
Jc. A single domain cannot set more than 20 cookieit and each cookie ~
limited to a maximum size of 4KB.
~ - A cookie usually possesses five types of attributes. Table 6-2 lists
;t(. Of all the five attributes, only the first is not optional.

fiti~EfC~l;V6t• Because cookies are stored on the user's h~rd drive, you as th~ d
·~\;~\·>,. ~ii~~~ have little control over them. If a user decides to tum off cookie
his or her browser, your cookies will simply not be saved. The11
persistence is an important feature of your web site, have a be
(such as server•side cookies or sessions) ready as well.

Attribute What It Does


Name , Sets the name and v
Expire s Sets the date ..
CHAPTER 6: Using Files , Sessions, Cookies, and Extern

ow ing se:tions discuss the PHP functions for setting cooti


The foU
cookie data, and deleting cookies.

Setting Cookies
P, cookies are set with the se tc oo ki e () function, which ace
In PH es
vaJue, its expiry date (in UNIX tim
arg uments: the cookie name, its
doma in, an d a Bo olean flag indicating its security status . On
jt; path and s,
areoptional. To better understand thi
argwnen t is required! all the rest
following example script:

<? ph p th va lue 'ad mi n' ,


et a ~o ok .ie ca lle d 'us ern ame' wi
/,'6
da y ~t 2- co nc:L S
// ex pi rin g a£ te r 1
mi n', mk tim e ( J +8 64 00 , 'I'
J;
S
etc oo ki e ( 'us ern al! 'le , , 'ad -~ cJ1'Yll.
?> C, .'Y 12 at f1 ~ co ot <! lt2 . .
ie () fun cti on ret urn s true if successful. By checJjng ~
Th e se t co ok
you can verify i~ the ccolde wa
s sent to the browser or not.

· h va lue •ad mi n'


<?. ph p k" c c- lle d ' u s ern arn e' w1 t
; 1 se t a co o 1e · e () +8 64 00 , '/' );
1 y . ,
/ / ex pi rin g af te r(, u.s da
e r n a me ', 'ad m1 n , mk tim
tcc o:- cie
$r et = Se
set
II ch ec k i f co ok ie wa s
II di sp la y er ro r if no t
if (!$ re t)
k . e" .
co ol . ,
ec ho " Un ab l e t o se t

J b cailing se t co ok ie () once
lot
. .
~ y ~i ch sets three cookies for
the •
can set mu ltif le co ~k ies , s1m
Yo u
coDkie. Co ns ide r the foIJowt mg ~xamp e,_
. h ex pir y dates.
.th differen
dom am , ea c WJ
'/' , '.
. , mJctime C, +8 64 00 ,
< ?ph p
'ad m~ n •,) 18 00 • '/s ec ur
e/t 1e b/, JI
:co ok ie { ' use rna cne . ..
se , ,~• mJct1me + J ;
, • , o ' I'
se- : co ok ie { 'ro le
' •UK_ '• _ ,
'- '-'-_,•c..,,.,o~u::;:;.;...n t;.__ry:_,_
_ _ _____ .- .;. L~ ~
28 How to Do Everything with PHP & MySQL

.2PM by Any Other Name ...


~ ·

inkt-±i~:{i·Junction a~~~Pi _a series


. Th~ of date and time parameters. and t

._. ~ ..,.,,.
converts tJiem\ntp'aUNI){ tfoies~mp. · .
• • • :· •• • • ••• : : : / ~ • .: ,. , • j •

Retrieving Cookie Data


Once a cookie has been set for a domain, it becomes available in the special
$_COOK IE associativ e array, and its value may be accessed using ;tandard 81TIJ
notation. Here!s an example:

<?php
// if cookie present , use it
// else display generic mes sage
if ($_COOK IE('usern ame'))
{
echo "Welcome back, " . $_COOK IE['usern ame'];
}
else

echo "IE this your first time here? Take our guided tour!";

· . ~ To ch€ck whether your cookies are working correctly. use :he state.
< ?php print_ r ($_COOKIE); ?> to look inside PHP'sm dd
$_ CO~KIE array.

Deleting Cookies
To ~elete a coolcie, simply use setcook ie () with its name to;
expiry date to a value in the past.

<?php
setcooki e('userna me',
?>

You might also like