Professional Documents
Culture Documents
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
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 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.
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.
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.
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.
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
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.
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!
Comments
PHP supports C, C++ and Unix style comments.
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.
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.
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."
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.
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 =.
• $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
• $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!
// or like in Python
if (expr1) :
...
...
elseif (expr2) :
13
...
else :
...
endif;
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.
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 show() {
echo "$this->empno, $this->empnm";
return;
}
function changenm($in_name){
$this->empnm = $in_name;
}
}
$sbabu->show();
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.
<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>
<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.
<?
// some sitewide defaults
$MyEmail = "phptalk@tnc.org";
$MyEmailLink = "<a
href=\"mailto:$MyEmail\">$MyEmail</a>";
$MyName = "PHP Talk";
$MySiteName = $MyName."'s Home Page";
?>
<?
// 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);
}
?>
<?
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");
?>
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.
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.
<?
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");
?>
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");
?>
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.
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";
<?
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);
?>
<? 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
}
?>
32
Next Previous Contents
5. Miscellaneous Stuff
<?
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!";
}
?>
<?
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.
( 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>
=======================================
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
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
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";
?>
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!
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.
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 :
44