Professional Documents
Culture Documents
Adobe Scan Aug 01, 2023
Adobe Scan Aug 01, 2023
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.
To see PHP's vari ables in action, try out the following script:
<ht ml >
<head>c::basefont face ="Arial">< /he ad>
<bcdy>
<?php
// define variable
$a~swer = 'Elephant';
// print output
echo "<h2><i>Sanswer< /i >< /h 2> ";
</bc dy >
</html>
<? 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" ;
?>
<httnl>
<head> </head>
<body>
</body >
</html>
Th~ most critical line in this entire page is the <form> tag:
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
<?php
// define an array
$menu= array('breakfast' => 'bacon and eggs', J
'lunch'=> 'roast beef', 'dinner'=> 'lasagna');
<?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',
// returns "strawberry"
echo $flavorl;
1·
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
<?p'::.?
// define string
Sstri~g = ' Engli s h Latin Greek Spanish ' ;
<?php
// define string
$string= ' Eng l i sh Latin Greek Spanish';
// split en wh itespace
$languages = expl ode(• • $string);
<?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! '):
/ / close file
fclos e($fh );
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.
<?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;
<?php <?ph?
$a = $a + 1 O; Sa + = l•J:
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
.
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
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.
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:
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
._. ~ ..,.,,.
converts tJiem\ntp'aUNI){ tfoies~mp. · .
• • • :· •• • • ••• : : : / ~ • .: ,. , • j •
<?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',
?>