jump to content

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>


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>

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 !


<?
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, 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" 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


<?
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.


<?
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))
                    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 :

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