You are on page 1of 44

Next Previous Contents

Satheesh Babu, sbabu@tnc.org


v1.0, 22 November 1999

PHP is a very easy to learn and use server-side scripting language. With little know-how
of how to program, one can create really interactive websites using PHP. This material is
not intended to make one know the language fully, but to get one quickly into developing
dynamic websites. Basic knowledge of HTML (or some HTML editor) and some idea of
programming is assumed.

1. Introduction
• 1.1 History
• 1.2 Advantages of PHP
• 1.3 Competition : ASP, mod_perl, JSP

2. Tutorial
• 2.1 Pre-requisites
• 2.2 PHP setup
• 2.3 Syntax
• 2.4 Data Types
• 2.5 Variables & Constants
• 2.6 Operators
• 2.7 Control Structures
• 2.8 Functions
• 2.9 Classes

3. Hands-on
• 3.1 Planning a home page
• 3.2 HTML 2 PHP
• 3.3 Counter
• 3.4 Feedback form
• 3.5 Silly site search engine
4. Database Connectivity
• 4.1 Connecting
• 4.2 Querying
• 4.3 Display Results
• 4.4 Authentication against Oracle

5. Miscellaneous Stuff
• 5.1 Graphics Creation
• 5.2 Cookies
• 5.3 HTTP Authentication
• 5.4 File Uploads
• 5.5 Common Functions
• 5.6 Extending Our Example Homepage

6. Resources
• 6.1 Websites
• 6.2 Mailing Lists
• 6.3 Books
• 6.4 Interesting Projects

Next Previous Contents

Copyright© 2000 V.Satheesh Babu. All rights reserved.

3
Next Previous Contents

1. Introduction
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 means, PHP: Hypertext Preprocessor

PHP costs $0. You can download it from PHP site at http://www.php.net . The license is
GNU Public License (GPL), the same license under which popular software like Linux,
Emacs etc are released. You have complete access to the source code and if you want to,
you can add your own features to PHP.

PHP is available for most Unix platforms, GNU/Linux and Microsoft Windows(TM). How
to install PHP in your Windows(TM) PC or Unix machine is well documented at the PHP
site. It is quite easy to install.

PHP is also Year2000 compliant, if your machine is!

1.1 History
Three years ago, Rasmus Lerdorf, created PHP as Personal Home Page Tools to manage
his online resume. It was a very simple language. People noticed it and started making
suggestions to extend it. Many people contributed and with the source code available
freely, it became a very feature-rich language. And it continues to grow.

PHP, though easy to learn, was slower when compared to mod_perl (perl embedded
into webserver) scripts. Now, there is a new engine called Zend which is almost as
fast as mod_perl and PHP4 will utilize Zend engine completely. PHP4 is still in beta.
Andi Gutmans and Zeev Suraski are the primary authors of Zend. Visit the Zend site at
http://www.zend.com.

From a personal project, PHP usage has shot up quickly. Netcraft reports that in October
1999, 931122 Domains and 321128 IP Addresses deliver pages created by PHP.

1.2 Advantages of PHP


There are lots of advantages of using PHP. Some disadvantages that come to mind are the
facts that being a open source project, so far no commercial support is available, and the
relatively slow speed of execution of PHP (prior to version 4). However, the mailing lists
for PHP are extremely useful and unless you are running a site that is as popular as Yahoo!
or Amazon.com, you probably will not notice the difference in speed at all. I haven't! Let
us see the advantages now.

Learning Curve
Personally, I love PHP's very easy learning curve. Unlike Java or Perl, you just don't need
to sink into 100's of pages of documentation to write a program which does something
useful. With just a few basic syntax and language features, you can be productive. Then,
when you need to do something more specific, check the relevant documentation.

PHP's syntax is very similar to C, Perl, ASP or JSP. For people who know either of these
languages, PHP is too easy. Inversely, if you know PHP, the language features can easily
scale to other languages you want to learn.

To learn the core features, you just need 30 minutes. You already might know HTML very
well, or you really know how to design good looking web sites, either using site builder
tools or using plain HTML coding. Since PHP code can be added in a non-interfering way,
after you design and implement your site, you can add PHP code to make it more dynamic.

Database Integration
PHP can be compiled with functions to interact with lot of databases. PHP with MySQL is
a very popular combination. You can also write your wrap-around functions to indirectly
call database functions. This way, you can easily change your code when you want to
change your database. PHPLIB is a set of libraries written in PHP that provides most
commonly required routines.

Extensibility
Like mentioned before, PHP has been evolving at a rapid pace. For a non-programmer it
might be difficult to extend PHP to support additional functions, but for programmers it
should not be very difficult.

Object Oriented Programming


PHP provides for Classes and Objects. Support for object oriented programming is
sufficient enough for most programming tasks related to the web. PHP supports
constructors, derived classes etc.

Rich Features

5
PHP is just a scripting wrap-around for many popular libraries, with a nice chocolate layer
around it to make it easy to use for web. You can use PHP to connect to many databases
including Oracle, MS-Access, MySQL. You can create graphics on the fly. You can write
programs to download and display e-mail. You can even do network related functions.
And best of all, you can decide what all capabilities your PHP installation should have. To
quote Nissan's Xterra, your PHP can be made to have Everything you need, nothing you
don't!.

Scalability
Traditionally, interactivity in web pages are achieved using CGI programs. CGI programs
do not scale well, because, each run of a program occurs as a separate process. The solution
is to compile the interpreters for languages used to write CGI programs into the webserver
(mod_perl, JSP...). PHP also can be installed like this, though rarely people might want to
use PHP in CGI version too. Embedded PHP installations scale well.

1.3 Competition : ASP, mod_perl, JSP


ASP is quite popular and I've written some applications in ASP since January 2000.
Microsoft's arguments for ASP include availability of tools like Visual Interdev, language
independence and easy learning curve. I have used VIM to code ASP, so I can't say much
about the tools. Language independence is also not that much of an issue, just because
in its default configuration it supports VBScript and JScript. You can also get extensions
which makes it possible to write ASP in PerlScript making it a good choice for folks who
are used to mod_perl and Apache. At least for a simple directory listing code, PHP3.0 on
a P133 with 32MB RAM ran circles around ASP code on an NT4 machine with dual P500
with 600MB RAM! I tend to prefer PHP3. Also, VBScript's string functions are a pain to
use (IMHO) - though it has REGEX capability now.

JSP has a very unique advantage that you need to know Java alone. From what I've seen,
most people would prefer to work in one language and use that for as many purposes
as possible. This, and the training costs involved will make Java an attractive option
for companies. Additionally, there are already a number of tools out there for Java.
Architecture-wise JSP+Servlets are comparable to VBScript+COM. For quick web-site
building JSP may not be worth the trouble. For businesses, this would make more sense,
especially since a number of Java based application servers are already in the market.
From my personal experience, both Java and ASP need elite hardware, whereas PHP3 with
Apache on Linux will perform adequately with your old P133 :-)

mod_perl is as powerful as Perl is. It is also quite fast. PHP4 with Zend engine will
probably be as fast as mod_perl. However, Perl code can get unmaintainable quickly - this
is just my opinion and goes well with Perl's idea of being a language for the lazy.

6
Next Previous Contents

Copyright© 2000 V.Satheesh Babu. All rights reserved.

7
Next Previous Contents

2. Tutorial
The on-line manual at the PHP site is extremely good. There are some additional links
provided there, to different tutorials. This section, however is to just quickly get you
familiar with PHP. It is in no way exhaustive. Just helps you get started writing PHP
scripts.

2.1 Pre-requisites
You must have a working webserver with PHP support. Let us assume that all of your files
with PHP code have an extension .php3.

2.2 PHP setup


Create a file called test.php3 with the contents as below:

<? phpinfo(); ?>

Then point your browser to this file. Study the page and you'll know what options your
PHP installations have.

2.3 Syntax
Like mentioned before, you can put PHP and HTML code in your file. So, you must have
a way to distinguish between PHP and HTML code. We can do this in multiple ways. Pick
one that you like and stick to that!

Escaping from HTML


Here are the possible ways to escape your PHP code from HTML.

• <? ... ?>

• <?php ... ?>

• <script language="php"> ... </script>

• <% ... %>


Statements
In PHP, this is same as in Perl or C. You use the semi-colon (;). The closing tag for your
escape from HTML also implies an end-of-statement.

Comments
PHP supports C, C++ and Unix style comments.

• /* C,C++ style multi-line comment */

• // C++ style single line comment

• # Unix style single line comment

Hello World!
With this basic info, let us create a PHP program which will just print the standard
message!

<HTML>
<HEAD>
<TITLE>
<?
echo "Hello World!";
?>
</TITLE>
</HEAD>
<BODY>
<H1>
First PHP page
</H1>
<HR>
<?
// Single line C++ style comment
/*
printing the message
*/
echo "Hello World!";
# Unix style single line comment
?>
</BODY>
</HTML>
9
2.4 Data Types
PHP supports integers, floats, strings, arrays and objects. The type of the variable is
usually not set by the programmer, but determined by PHP at run-time (good riddance!).
However, types can be expressly changed if necessary, using cast or settype() functions.

Numbers
Numbers can be integers or floating point numbers. You can specify a number using any
of the following syntaxes.

$a = 1234; # decimal number


$a = -123; # a negative number
$a = 0123; # octal number (equivalent to 83 decimal)
$a = 0x12; # hexadecimal number (equivalent to 18
decimal)
$a = 1.234; # floating point number. "double"
$a = 1.2e3; # exponential format for double

Strings
Strings can be defined by using single quotes or double quotes. Whatever is inside single
quotes is taken literally and values inside double quotes will be expanded. Backslash (\)
can be used to escape special characters.

$first = 'Hello';
$second = "World";
$full1 = "$first $second"; # yields Hello World
$full2 = '$first $second';# yields $first $second

You can mix strings and numbers using arithmetic operators. Strings are then converted to
numbers, using the initial portion. PHP manual has examples.

Arrays & Hashes


Arrays and hashes are implemented in the same way. How you use it determines what
you get. You create arrays using list() or array() functions, or by explicitly setting values.
Array index starts from 0. Though not explained here, you can have multi- dimensional
arrays too.

10
$a[0] = "first"; // a two element array
$a[1] = "second";
$a[] = "third"; // easy way to append to the array.
// Now, $a[2] has "third"
echo count($a); // prints 3, number of elements in the
array
// create a hash in one shot
$myphonebook = array (
"sbabu" => "5348",
"keith" => "4829",
"carole" => "4533"
);
// oops, forgot dean! add dean
$myphonebook["dean"] = "5397";
// yeoh! carole's number is not that. correct it!
$myphonebook["carole" => "4522"
// didn't we tell that hashes and arrays are
//implemented alike? let's see
echo "$myphonebook[0]"; // sbabu
echo "$myphonebook[1]"; // 5348

Some functions useful in this context are sort(), next(), prev(), each().

Objects
To create an object, use the new statement.

class foo {
function do_foo () {
echo "Doing foo.";
}
}
$bar = new foo;
$bar->do_foo();

Changing Types
From the PHP manual - "PHP does not require (or support) explicit type definition in
variable declaration; a variable's type is determined by the context in which that variable
is used. That is to say, if you assign a string value to variable var, var becomes a string. If
you then assign an integer value to var, it becomes an integer."

$foo = "0"; // $foo is string (ASCII 48)


$foo++; // $foo is the string "1" (ASCII 49)

11
$foo += 1; // $foo is now an integer (2)
$foo = $foo + 1.3; // $foo is now a double (3.3)
$foo = 5 + "10 Little Piggies"; // $foo is integer (15)
$foo = 5 + "10 Small Pigs"; // $foo is integer (15)

Type casting works just like in C. You can also use settype() function.

2.5 Variables & Constants


As you might've noticed, variables in PHP are prefixed with the dollar sign ($). All
variables have local scope. To make a variable defined outside any function to be seen
inside a function, you've to specify it using global. For values to be retained inside
functions, you can use static variables too.

$g_var = 1 ; // global scope


function test() {
global $g_var; // that's how you specify global
variable
}

Slightly more advanced are variable variables. See the manual. These can be extremely
useful at times.

PHP defines some constants internally. You can define your own constants using the
define function, like define("CONSTANT","value").

2.6 Operators
PHP has all the common operators found in C, C++ or Java. Precedence rules are also
same. Assignment operator is =.

Arithmetic & String


There is only one string operator.

• $a + $b : addition
• $a - $b : subtraction
• $a * $b : multiplication
• $a / $b : division
• $a % $b : modulus (remainder)
• $a . $b : string concatenation

12
Logical & Comparison
Logical operators are :

• $a || $b : Or
• $a or $b : Or
• $a && $b : And
• $a and $b : And
• $a xor $b : EXOR. (True if either $a or $b is true, but not both)
• ! $a : Not

Comparison operators are :

• $a == $b : Equality
• $a != $b : Not Equal
• $a < $b : Less Than
• $a < $b : Less Than or equal to
• $a > $b : Greater Than
• $a > $b : Greater Than or equal to

Like in C, PHP has the ternary operator (?:) too. Bit operators are also available.

Precedence
Just like in C or Java!

2.7 Control Structures


PHP has standard control structures you find in C. We will briefly cover these.

if, else, elseif, if(): endif


if ( expr1 ) {
...
} elseif (expr2) {
} else {
}

// or like in Python
if (expr1) :
...
...
elseif (expr2) :
13
...
else :
...
endif;

Loops. while, do..while, for


while (expr) { ... }
do {...} while (expr);
for (expr1; expr2; expr3) {...}
// or like in Python
while (expr) :
...
endwhile;

switch
Switch is an elegant replacement for multiple if-elseif-else structure.

switch ($i) {
case 0:
print "i equals 0";
case 1:
print "i equals 1";
case 2:
print "i equals 2";
}

break, continue
break breaks out of current looping control-scructures.

continue is used within looping structures to skip the rest of the current loop iteration and
continue execution at the beginning of the next iteration.

require, include
require is just like C's #include pre-processor directive. The file you specify with require
is substituted in place. This means that you can't put require within if statements. To
conditionally include code, we use include() function. It is a good practice to split PHP
code into multiple files and inlcude only the necessary ones.

14
2.8 Functions
You can define your own functions as shown below. Return values can be any of the data
types.

function foo ($arg_1, $arg_2, ..., $arg_n) {


echo "Example function.\n";
return $retval;
}

Any valid PHP code may appear inside a function, even other functions and class
definitions. Functions must be defined before they are referenced.

2.9 Classes
Use the class construct to create classes. See the manual for a good explanation of classes.

class Employee {
var $empno; // employee number
var $empnm; // name

function add_employee($in_num, $in_name){


$this->empno = $in_num;
$this->empnm = $in_name;
}

function show() {
echo "$this->empno, $this->empnm";
return;
}

function changenm($in_name){
$this->empnm = $in_name;
}
}

$sbabu = new Employee;


$sbabu->add_employee(10,"sbabu");
$sbabu->changenm("babu");

$sbabu->show();

Next Previous Contents


15
Copyright© 2000 V.Satheesh Babu. All rights reserved.

16
Next Previous Contents

3. Hands-on
Most of the features of PHP are related to other tools and software. With what we have
seen so far, we will attempt to make a basic site with some interactivity. We will learn more
about PHP on the way. We will concentrate on a typical personal home page.

3.1 Planning a home page


Typically, a personal site has a welcome page, a guest book perhaps, a bookmarks' page,
a counter, contact information, may be a photo gallery, some music files and so on. Let
us say, we start with a front page, a contact information page and a resume page. We also
would like to have standard header and footer portions for each page.

The front page - front.html


Here, we have a very simple html file.

<HTML>
<HEAD>
<TITLE>
My Home Page - Welcome
</TITLE>
</HEAD>
<BODY>
<H1>
My Home Page
</H1>
<H2>
Welcome
</H2>
<HR>
<P>
Welcome to my little home page. There is
nothing at all here now.
</P>
<P>
Soon I hope to have something here.
</P>
<HR>
<P ALIGN="CENTER">
<SMALL> <I>
Copyright © by Me, 1999
</I> </SMALL>
</P>
</BODY>
</HTML>

Contact information page - cont.html


Again, we have a very simple html file.

<HTML>
<HEAD>
<TITLE>
My Home Page - Contact Information
</TITLE>
</HEAD>
<BODY>
<H1>
My Home Page
</H1>
<H2>
Contact Information
</H2>
<HR>
<P>
I am available at 1-800-PHP-INFO.
</P>
<HR>
<P ALIGN="CENTER">
<SMALL> <I>
Copyright by Me, 1999
</I> </SMALL>
</P>
</BODY>
</HTML>

18
3.2 HTML 2 PHP
As you can see, you have a similar looking header section, and a footer section. This is
OK if you have only a handful of pages. What happens if there are 100's of pages and
you want to change the look of headers in all pages? Editing each one by hand can be a
tedious process. So, let us make header and footer files in PHP. We will include these in
our HTML files. We will save these files in a subdirectory called include. Additionally, we
will define our site-wide defaults also in a file.

Site-wide defaults : common.inc

<?
// some sitewide defaults
$MyEmail = "phptalk@tnc.org";
$MyEmailLink = "<a
href=\"mailto:$MyEmail\">$MyEmail</a>";
$MyName = "PHP Talk";
$MySiteName = $MyName."'s Home Page";
?>

Common Header : header.inc

<?
// defines the common header structure
?>
<HTML>
<HEAD>
<TITLE>
<? echo "$MySiteName - $title"; ?>
</TITLE>
</HEAD>
<BODY>
<H1>
<? echo "$MySiteName"; ?>
</H1>
<H2>
<? echo "$title"; ?>
</H2>
<HR>

19
Common Footer :footer.inc

<?
// common footer
?>
<HR>
<P ALIGN="CENTER">
<SMALL> <I>
Copyright © by
<? echo "$MyName ($MyEmailLink)"; ?>
, 1999
</I> </SMALL>
</P>
</BODY>
</HTML>

New front.php3 !

<?
include("include/common.inc");
$title = "Welcome";
include("include/header.inc");
?>
<P>
Welcome to my little home page. There is
nothing at all here now.
</P>
<P>
Soon I hope to have something here.
</P>
<?
include("include/footer.inc");
?>

New cont.php3 !

<?

20
include("include/common.inc");
$title = "Contact Information";
include("include/header.inc");
?>
<P>
I am available at 1-800-PHP-INFO.
</P>
<?
include("include/footer.inc");
?>

By now, you would have guessed the advantages of the new scheme. If you want to make
a change to the header or footer, you just need to change in the corresponding file. If you
need to change you e-mail or even your name, you just change in common.inc. Another
thing to note is that the included files can be of any name or extension. And you can also
include files in some other www site.

3.3 Counter
Let us add a counter to our front page. It is not very sophisticated, but will demonstrate
how you can use PHP to read and write from files, and also on how to write your own
functions. Our counter file contains the following code in counter.inc.

<?
/*
|| a simple counter
*/
function get_hitcount($counter_file){
/* initialize count to zero
so, if the counter file doesn't exist ,
it will be created with content 1
You can initialize this to say 20000,
to cheat people!
*/
$count=0;
// if the counter file is there, read the content
if ( file_exists($counter_file) ) {
$fp=fopen($counter_file,"r");
// we read only 20 characters, hopefully, your
// site isn't wildly popular!
$count=0+fgets($fp,20);
// since the function fgets() returns a string,
21
we
// add it to zero, to convert it to a number.
fclose($fp);
// we are done with the file.
}
// increment the count
$count++;
// write the new count to the file
$fp=fopen($counter_file,"w");
fputs($fp,$count);
fclose($fp);
# return the count
return ($count);
}
?>

And we change the footer section in front.php3 to display the count.

<?
include("include/counter.inc");
// I'll store my counts in the file counter.txt. Get it
and
// print it.
printf ("<CENTER><B>%06d</B></CENTER> <BR> \n",
get_hitcount("counter.txt"));
include("include/footer.inc");
?>

Our new front page.

3.4 Feedback form


Let us add a form where your visitors can fill in a form and that will be mailed to you. We
will implement this in a very simple way, ie., it will have two files, one for displaying the
form and one for capturing the form data and mailing it.

In PHP, it is very easy to read form values. When a form is submitted, each element in the
form has a corresponding variable in PHP. Just use it like a normal variable.

<FORM name="myform" ACTION="process_form.php3"

22
METHOD="POST">
<INPUT TYPE="TEXT" NAME="mytext" VALUE="Some Value">
</FORM>

In process_form.php3, the variable $mytext holds the value user entered! It is that simple.
Similarly, you can use values from list boxes, checkboxes, radio-groups, buttons and other
elements. Only thing to note is that you must define a name for your form element.

With this basic idea, we can create a form, which will have three fields, viz., name, email
and comments. When user submits the form, the processing PHP file (sendfdbk.php3)
reads the data, checks if the name is null, and sends the data by mail.

The form : feedback.php3

<?
include("include/common.inc");
$title = "Feedback";
include("include/header.inc");
?>
<P>
<FORM ACTION="sendfdbk.php3" METHOD="POST">
<INPUT TYPE="text" NAME="name" value="Your
name" SIZE="20" MAXLENGTH="30">
<INPUT TYPE="text" MAXLENGTH="40" WIDTH="20"
value="Your Email" NAME="email">
<BR>
<TEXTAREA ROWS="7" COLS="40" NAME="comment">
Your feedback on my home page.
</TEXTAREA>
<BR>
<INPUT TYPE="submit" VALUE="Send Feedback!">
</FORM>
</P>
<?
include("include/footer.inc");
?>

The form processor : sendfdbk.php3

23
<?
include("include/common.inc");
$title = "Feedback";
include("include/header.inc");
if ( $name == "" ) {
// Now, I hate comments from anonymous people!
echo "Duh ? How come you are anonymous?";
} elseif ($name == "Your name") {
// This person is too dumb!
echo "Hello ? <B>Your name</B> is supposed to be
replaced with
your actual name!</B>";
} else {
// just print a polite acknowledgement
echo "
Hello, $name.
<BR>
Thank you for your feedback. It is greatly
appreciated.
<BR>
Thanking you
<BR>
$MyName <BR>
$MyEmailLink
";
// and mail it
mail($MyEmail, "Feedback.","
Name : $name
E-mail : $email
Comment : $comment
");
}
include("include/footer.inc");
?>

3.5 Silly site search engine


PHP can call external programs. In Unix, we can easily use the command grep to make a
simple search engine. We will add some complexity to this, by having the form to accept
search string and the code to display results, all in the same file.

24
<?
include("include/common.inc");
$title = "Search";
include("include/header.inc");
?>
<P>
<FORM ACTION="<? echo "$PHP_SELF"; ?>"
METHOD="POST">
<INPUT TYPE="text" NAME="searchstr" value="<?
echo "$searchstr"; ?>"
SIZE="20" MAXLENGTH="30">
<INPUT TYPE="submit" VALUE="Search!">
</FORM>
</P>
<?
if ( ! empty($searchstr) ) {
// empty() is used to check if we've any
search string
// if we do, call grep and display the
results.
echo "<HR>\n";
// call grep with case-insensitive search
mode on all files
$cmdstr = "grep -i $searchstr *";
$fp = popen( $cmdstr, "r" ); //open the
output of command as a pipe
$myresult = array(); // to hold my search
results
while( $buffer = fgetss ($fp, 4096)) {
// grep returns in the format
// filename: line
// So, we use split() to split the data
list($fname, $fline) =
split(":",$buffer, 2);
// we take only the first hit per file
if ( !defined($myresult[$fname]))
$myresult[$fname] = $fline;
}
// we have results in a hash. lets walk
through it and print it
if ( count($myresult) ){
echo "<OL>\n";
while(list($fname,$fline) =
each($myresult))

25
echo "<LI>
<A HREF=\"$fname\">$fname</A> :
$fline </LI>\n";
echo "</OL>\n";
} else {
// no hits
echo "Sorry. Search on
<B>$searchstr</B>
returned no results.<BR>\n";
}
pclose($fp);
}
?>
<?
include("include/footer.inc");
?>

Notes :

• PHP_SELF is a variable maintained by PHP. Contains the name of the current file.
• fgets() function reads a line, at the most 4096(specified) characters long.
• fgetss() is just like fgets(), but it will parse the output to have proper HTML.
• split() is called with 2, because we need only a split by two. Further ":" are
ignored.
• each() is an array function which helps to easily walk through an array.
• popen()/pclose() are identical to fopen()/fclose(), but operate on pipes.

Please note that this is not a good way to implement a search engine. It will help us to
learn about PHP, that's all. Ideally, one should build a database of keywords and then use
the search against that.

Next Previous Contents

Copyright© 2000 V.Satheesh Babu. All rights reserved.

26
Next Previous Contents

4. Database Connectivity
With PHP, you can easily connect to a database, query for data , display results in a web
site, modify the data in the database etc. MySQL is a very popular database and there are
lot of tutorials available on the web about using PHP with MySQL. MySQL is free, so it
might be of interest to many people. Since it is widely covered, we will not illustrate the
use of MySQL here. Oracle is widely used in the enterprises and that is the database we'll
use to get an idea about database connectivity. We will not cover principles of database
design with Oracle, since it is beyond the scope of this talk.

PHP provides for two sets of functions to work with Oracle, viz., ora_ and OCI functions.
Functions which start with ora_ are slightly older set. OCI functions are newer and
claimed to be better. There is not much difference in the syntax between these two sets.
As mentioned before, your PHP installation must've support for these functions to be tried
out.

For a paper on obtaining and installing Apache with PHP3 on Microsoft Windows
platform, and to get the basics of working with Oracle, you can check
www.csoft.net/~vsbabu/zope/6tutorials/oraphp.html.

4.1 Connecting
<?
if ($conn=Ora_Logon("user@TNSNAME","password")) {
echo "<B>SUCCESS ! Connected to database<B>\n";
} else {
echo "<B>Failed :-( Could not connect to
database<B>\n";
}
Ora_Logoff($conn);
phpinfo();
?>

The code above just connects to an Oracle database defined by TNSNAME (this entry
is there in your tnsnames.ora file), using the userid user and password password. Upon
successful connection, the function Ora_Logon returns a non-zero connection identifier,
which we store in the variable $conn.

4.2 Querying
Let us assume that the connection step went smoothly. Let us fire some queries against
the database. The following code illustrates a typical page which connects and queries an
Oracle database.

<?
/*
* connect to database and execute a query
*/
function printoraerr($in_cur){
// function to check whether an oracle error occured
// if it did, print the error
// call this after every oracle call when a cursor
is active
if(ora_errorcode($in_cur))
echo "Oracle code - ".ora_error($in_cur)."
\n";
return;
}
/** main */
if (!($conn=ora_logon("user@TNSNAME","password"))) {
echo "Connection to database failed\n";
exit;
}
echo "Connected as connection - <b>$conn</b><br>\n";

echo "Opening cursor ...<br>\n";


$cursor=ora_open($conn); printoraerr($cursor);
echo "Opened cursor - <b>$cursor</b><br>\n";

$qry="select user,sysdate from dual";


echo "Parsing the query <b>$qry</b> ...<br>\n";
ora_parse($cursor,$qry,0); printoraerr($cursor);
echo "Query parsed <br>\n";

echo "Executing cursor ...<br>\n";


ora_exec($cursor); printoraerr($cursor);
echo "Executed cursor<br>\n";

echo "Fetching cursor ...<br>\n";


while(ora_fetch($cursor)){
$user=ora_getcolumn($cursor,0); printoraerr($cursor);
$sysdate=ora_getcolumn($cursor,1);
printoraerr($cursor);
echo " row = <B>$user, $sysdate </B><br>\n";
}
28
echo "Fetched all records<br>\n";
echo "Closing cursor ...<br>\n";
ora_close($cursor);
echo "Closed cursor<br>\n";

echo "Logging off from oracle... <br>\n";


ora_logoff($conn);
echo "Logged off from oracle <br>\n";
?>

4.3 Display Results


The next code section shows how to fire generic queries against the database and display
the results in a tabular form.

<?
function printoraerr($in_cur, $conn){
// function to check whether an oracle error occured
// if it did, print the error
// call this after every oracle call when a cursor
is active
// If it encountered an error, we exit immediately
if(ora_errorcode($in_cur)) {
echo "Oracle code -
".ora_error($in_cur)."<br>n";
ora_logoff($conn);
exit;
}
return;
}

function exequery($w_qry,$conn) {
$cursor=ora_open($conn); printoraerr($cursor,$conn);
ora_parse($cursor,$w_qry,0);
printoraerr($cursor,$conn);
ora_exec($cursor); printoraerr($cursor,$conn);
$numrows=0;
$w_numcols=ora_numcols($cursor);
// print headers
echo "
<TABLE WIDTH=\"100%\" BORDER=\"0\"
CELLSPACING=\"1\" CELLPADDING=\"2\">
<TR>\n";
for ($i=0;$i<$w_numcols;$i++) {
29
$align=(ora_columntype($cursor,$i)=="NUMBER")?"RIGHT":"LEFT";
echo "\t<TH VALIGN=TOP
ALIGN=$align>".ora_columnname($cursor,$i)."</TH>\n";
}
echo "</TR>\n";

while(ora_fetch($cursor)){
echo "<TR>\n";
for ($i=0;$i<$w_numcols;$i++) {

$align=(ora_columntype($cursor,$i)=="NUMBER")?"RIGHT":"LEFT";
if(ora_columntype($cursor,$i)=="LONG")
echo "<TD VALIGN=TOP
ALIGN=$align><PRE>".

ora_getcolumn($cursor,$i)."</PRE></TD>\n";
else
echo "<TD VALIGN=TOP
ALIGN=$align>".ora_getcolumn($cursor,$i)."</TD>\n";
printoraerr($cursor,$conn);
}
$numrows++;
echo "</TR>\n";
}
if ($numrows==0)
echo "<TR><TD COLSPAN=\"$w_numcols\"><B>Query
returned no records
</B></TD></TR>\n";
else {
echo "<TR>\n";
echo "<TH COLSPAN=\"".($w_numcols-1)."\"
ALIGN=RIGHT>Count</TH>\n";
echo "<TH ALIGN=RIGHT>$numrows</TH>\n";
echo "</TR>\n";
}
echo "</TABLE>\n";
ora_close($cursor);
return;
}

// main
if(!($conn=ora_logon("user@SID","password"))) {
echo "Error: Cannot connect to database\n";

30
exit;
}

$qry="SELECT
deptno \"Dept\"
,empno \"Emp\"
,empnm \"Name\"
,salary \"Salary\"
FROM
employee
ORDER BY 1,2";

exequery($qry);

ora_logoff($conn);
?>

4.4 Authentication against Oracle


Add this to the beginning of the code to validate oracle login. You must specify $SID
properly.

<? if(!isset($PHP_AUTH_USER)) {
Header("WWW-authenticate: basic realm=\"$SID\"");
Header("HTTP/1.0 401 Unauthorized");
$title="Login Instructions";
echo "<blockquote>
You are not authorised to enter the site
</blockquote> \n";
exit;
} else {
if
(!($conn=ora_logon("$PHP_AUTH_USER@$SID",$PHP_AUTH_PW)))
{
Header("WWW-authenticate: basic
realm=\"$SID\"");
Header("HTTP/1.0 401 Unauthorized");
$title="Login Instructions";
echo "<blockquote>
You are not authorised to enter
the site
</blockquote> \n";
exit;
}
31
}
?>

Next Previous Contents

Copyright© 2000 V.Satheesh Babu. All rights reserved.

32
Next Previous Contents

5. Miscellaneous Stuff

5.1 Graphics Creation


PHP can manipulate images. If you have GD library installed, you can even create GIF
images.

<?
Header("Content-type: image/gif");
$string=implode($argv," ");
$im = imagecreatefromgif("images/button1.gif");
$orange = ImageColorAllocate($im, 220, 210, 60);
$px = (imagesx($im)-7.5*strlen($string))/2;
ImageString($im,3,$px,9,$string,$orange);
ImageGif($im);
ImageDestroy($im);
?>

This example would be called from a page with a tag like: <img
src="button.php3?text"> The above button.php3 script then takes this "text"
string an overlays it on top of a base image which in this case is "images/button1.gif" and
outputs the resulting image. This is a very convenient way to avoid having to draw new
button images every time you want to change the text of a button. With this method they
are dynamically generated.

5.2 Cookies
PHP supports HTTP cookies. You can refer to a cookie, just like you use a variable,
making it very easy to use. Cookies are little pieces of information the browser stores
in your PC. You can use these to decide whether anybody has visited your site from a
particular PC, how that person progressed and so on. A standard use of cookies is to set
user preferences for your site. Cookies are set using the setcookie() function. Like the
header() function used to send HTTP headers, setcookie() also must be called before any
output is sent to the browser. A simple example is given below.

<?
if (empty($VisitedBefore)) {
// if not set, set the cookie with the value of
current time
// last argument defines how long cookie should
be active, in
// this case it is one year.
// time() function returns the seconds elapsed
since the epoch(1/1/1970)
SetCookie("VisitedBefore",time(),
time()+(60*60*24*365));
} else {
// welcome the user back
echo "Hello there, welcome back<BR>";
// May be here, you can read the cookie value
if ( (time() - $VisitedBefore) >= (60*60*24*7) )
echo "Why did you take a week to come
back. You should be here more often!";
}
?>

5.3 HTTP Authentication


HTTP authentication is not available when PHP runs as a CGI program. Otherwise, we can
use the header() function to send the headers which force an authentication. The browser
will pop-up a window in which you enter the userid and password. These values will be
available in the variables $PHP_AUTH_USER and $PHP_AUTH_PW. You can use these
values to check for validity and then allow entry. Following example verifies a user against
the userid/password pair of tnc/nature .

<?
if(!isset($PHP_AUTH_USER)) {
Header("WWW-Authenticate: Basic realm=\"My
Realm\"");
Header("HTTP/1.0 401 Unauthorized");
echo "Text to send if user hits Cancel button\n";
exit;
} else {
if ( !($PHP_AUTH_USER=="tnc" &&
$PHP_AUTH_PW=="nature") ){
// if wrong userid/password, force
re-authentication
Header("WWW-Authenticate: Basic
realm=\"My Realm\"");
Header("HTTP/1.0 401 Unauthorized");
echo "ERROR :
$PHP_AUTH_USER/$PHP_AUTH_PW is invalid.";
exit;
34
} else {
echo "Welcome tnc!";
}
?>

In reality, you might not be checking against hard-coded strings, but against a database or
an encrypted password file.

5.4 File Uploads


You can write PHP code to handle file uploads with capable browsers like Netscape3+ and
IE3+. Following sample code illustrates this.

( upload.html ):
<HTML>
<HEAD>
<TITLE>Upload Your File</TITLE>
</HEAD>
<BODY>
<FORM ACTION="receiver.php3"
ENCTYPE="multipart/form-data" METHOD=POST>
<INPUT TYPE="HIDDEN"
NAME="MAX_FILE_SIZE" VALUE="2000000">
<INPUT TYPE="FILE"
NAME="uploadfile" SIZE="24" MAXLENGTH="80">
<BR><BR>
<INPUT TYPE="SUBMIT" VALUE="Upload File!"
NAME="sendit">
<INPUT TYPE="SUBMIT" VALUE="Cancel"
NAME="cancelit"><BR>
</FORM>
<I><FONT SIZE="2">(You may notice a slight
delay while we upload your file.)</FONT></I>
</BODY>
</HTML>

=======================================

Here is code for the receiving page


( receiver.php3 ):
<? function do_upload () {
global $uploadfile, $uploadfile_size;
global $local_file, $error_msg;
if ( $uploadfile == "none" ) {
35
$error_msg = "You did not specify a file for
uploading.";
return;
}
if ( $uploadfile_size > 2000000 ) {
$error_msg = "Sorry, your file is too large.";
return;
}
$the_time = time ();
// Wherever you have write permission below...
$upload_dir = "/local/uploads";
$local_file = "$upload_dir/$the_time";
if ( file_exists ( '$local_file' ) ) {
$seq = 1;
while ( file_exists ( "$upload_dir/$the_time$seq" )
) { $seq++; }
$local_file = "$upload_dir/$the_time$seq";
};
rename ( $uploadfile, $local_file );
display_page ();
}
function display_page () {
// Your page content here....
}
<HTML>
<HEAD>
<TITLE>php3 Receiving Script</TITLE>
</HEAD>
<BODY>
<? if ( $error_msg ) { echo
"<B>$error_msg</B><BR><BR>"; }
if ( $sendit ) {
do_import ();
} elseif ( $cancelit ) {
header ( "Location: $some_other_script" );
exit;
} else {
some_other_func ();
}
?>
</BODY>
</HTML>

5.5 Common Functions


36
Here we will briefly see some very commonly needed functions.

Arrays
• array - create an array.
• count - number of elements in an array.
• sort - sort an array. other types of sort are also available.
• list - assign variables as if they were an array.
• each - return next key-value pair
• current - return the current element
• next,prev - navigate the array

Date & Time


• checkdate - validate date/time
• date - format date/time
• time - current timestamp
• strftime - format date/time

Directory, FileSystem
• chdir - change directory
• dir - directory class
• opendir, readdir, closedir - open, read and close directory
• fopen, fclose - open, close file
• fgets, fgetss - read line
• file - read entire file into an array

Regular Expressions
• ereg - match regex
• eregi - case insensitive regex match
• ereg_replace - regex replace
• eregi_replace - case insensitive regex replace
• split - split string into array by regex

String
• AddSlashes - quote string with slashes
• echo - output one or more strings
• join, implode - join array elements to a string
• htmlentities, htmlspecialchars - convert characters with special meaning in

37
HTML to encoded form
• split - split string into array by regex

5.6 Extending Our Example Homepage


We will put to test our new-found tricks to make our home page a little more automated.
We will add a navigation bar on top of each page, with the current page automatically
disabled. We will also add a authenticated form with which we can upload our music files,
pictures etc. to our home page and have it automatically published.

Navigation Bar
This essentially means adding code to our footer.inc file. Let us assume that all files ending
in .php3 in our website should be shown in the navigation bar. Here is the code, saved in
the file include/navbar.inc.

<?
/* prints a navigation bar. links to all php3 files.
current file is
not linked. */
# read directory
$d = dir("./");
echo "<P ALIGN=\"CENTER\"> | \n";
while($entry = $d->read()){
// ignone non-files
if ( !is_file($entry) )
continue;
/* split the filename into name and extension
. is a regex special character. so we escape
it as \. */
list($filenm, $fileext) = split("\.",$entry, 2);
// ignore non-php3 files
if( $fileext != "php3" )
continue;
/* no we have *only* php3 files. we will search
for the line
$title="something";
and split the content of the title, use it
in the link
*/
$linknm = "";
$fp=fopen($entry,"r");

38
while($buffer=fgets($fp, 4096)){
$buffer = trim($buffer);
// we know that all our files have the
title set at the top
// easy to search. will cause big
problems if you change
// the name of that variable...
if (ereg("title *= *\"", $buffer)){
/* we have that title
assignment. we take that
string, evaluate it. so it
executes as PHP code,
executing $title = "blah
blah" */
eval($buffer);
// and we copy title to linknm!
$linknm = $title;
break;
}
}
fclose($fp);
if ( $entry == basename($PHP_SELF) )
echo "$linknm";
else
echo "<A HREF=\"$entry\">$linknm</A>";
echo " | ";
}
$d->close();
echo " </P>\n";
?>

Photograph Collection Album


Here, we will use HTTP authentication, filesystem functions and file upload to maintain a
directory, where we keep our picture files.

We will also make a page that will return a list of all photos in that directory.

File Uploader

<?
include("include/common.inc");
39
// we do an authentication also here
if(!isset($PHP_AUTH_USER)) {
Header("WWW-Authenticate: Basic
realm=\"$MySiteName\"");
Header("HTTP/1.0 401 Unauthorized");
echo "Sorry, you are not authorized to upload files\
n";
exit;
} else {
if ( !($PHP_AUTH_USER==$MyName &&
$PHP_AUTH_PW==$MyPassword ) ){
// if wrong userid/password, force
re-authentication
Header("WWW-Authenticate: Basic
realm=\"My Realm\"");
Header("HTTP/1.0 401 Unauthorized");
echo "ERROR :
$PHP_AUTH_USER/$PHP_AUTH_PW is invalid.<P>";
exit;
}
}
if ( $cancelit ) {
// when user cancel's I want to go to the front page
header ( "Location: front_2.php3" );
exit;
}
function do_upload () {
global $userfile, $userfile_size,
$userfile_name, $userfile_type;
global $local_file, $error_msg;
global $HTTP_REFERER;
if ( $userfile == "none" ) {
$error_msg = "You did not specify a file for
uploading.";
return;
}
if ( $userfile_size > 2000000 ) {
$error_msg = "Sorry, your file is too
large.";
return;
}
// Wherever you have write permission below...
$upload_dir = "photos";
$local_file = "$upload_dir/$userfile_name";

40
if ( file_exists ( $local_file ) ) {
$error_msg = "Sorry, a file with that name
already exists";
return;
};
// you can also check the filename/type to
decide whether
// it is a gif, jpeg, mp3 etc...
rename($userfile, $local_file);
echo "The file is uploaded<BR>\n";
echo "<A HREF=\"$HTTP_REFERER\">Go
Back</A><BR>\n";
}
$title = "Upload File";
include("include/header.inc");
if (empty($userfile) || $userfile=="none") {
// print the form
?>
<FORM ACTION="<? echo "$PHP_SELF"; ?>"
ENCTYPE="multipart/form-data" METHOD=POST>
<INPUT TYPE="HIDDEN" NAME="MAX_FILE_SIZE"
VALUE="2000000">
<INPUT TYPE="FILE" NAME="userfile" SIZE="24"
MAXLENGTH="80">
<BR><BR>
<INPUT TYPE="SUBMIT" VALUE="Upload File!" NAME="sendit">
<INPUT TYPE="SUBMIT" VALUE="Cancel" NAME="cancelit"><BR>
</FORM>
<I><FONT SIZE="2">(You may notice a slight delay while
we upload your file.)</FONT></I>
<?
} else {
if ( $error_msg ) { echo
"<B>$error_msg</B><BR><BR>"; }
if ( $sendit ) {
do_upload ();
}
}
include("include/footer.inc");
?>

Gallery

41
<?
include("include/common.inc");
$title = "Gallery";
include("include/header.inc");
?>
<P>
Here are some of our family photos. This
PHP script can really
be made better, by splitting
into multiple pages.
</P>
<?
$d = dir("photos");
while($entry = $d->read()){
if
(is_file("photos/$entry"))echo "<IMG
SRC=\"photos/$entry\">\n";
}
$d->close();
?>
<?
include("include/footer.inc");
?>

Additionally, in the uploader, you can add a field to describe file's description. This can be
saved in a file, which is read by the gallery script to put comments for the pictures!

Next Previous Contents

Copyright© 2000 V.Satheesh Babu. All rights reserved.

42
Next Previous Contents

6. Resources
You can learn more about from PHP from lot of resources on the web. There are mailing
lists available for support. Some books are also available.

6.1 Websites
The exploding popularity of PHP has resulted in lot of www sites. Many of them have on-
line tutorials, sample code, tips and tricks etc.

• www.php.net - PHP Home


• www.devshed.com - Good tutorials
• px.sklar.com - Code Exchange
• www.phpbuilder.com - Tutorials, columns and mailing list archives
• www.weberdev.com - Articles and code
• www.phpwizard.net - Tips and tricks
• www.iometrics.com/php/phplist.php3/ - IOMetrics scripts' archive
• www.e-gineer.com/phpkb/ - PHP Knowledge Base

6.2 Mailing Lists


You can register to these lists from the Support section of the PHP site. Please note that
these are high volume lists, typically having 100 mails per day.

• php3@lists.php.net - Main list.


• php-dev@lists.php.net - For developers.

6.3 Books
So far, I know of two books, both of which are available from Amazon.com. I have not
read any of these books, and I think the on-line manual is more than sufficient. Still, if you
like reading books :

• Core PHP Programming by Leon Atkinsen


• Professional PHP by Castagnetto et al.
• PHP3 : Programming Browser-Based Applications by David Medinets.

6.4 Interesting Projects


Several full-fledged projects are already available in PHP. Some of the more interesting
ones are :

• phplib.netuse.de/ - PHPLib, a suite of library functions in PHP.


• www.phorum.org - Phorum is a full-fledged message-board system.
• www.phorum.org - Phorum is a full-fledged message-board system.
• www.fni.com/fcsql - FishCartSQL is an e-commerce solution.
• www.midgard-project.org - Midgard is a web-application development platform.

Next Previous Contents

Copyright© 2000 V.Satheesh Babu. All rights reserved.

44

You might also like