jump to content

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;
        } 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" ) {
   $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

Here we will briefly see some very commonly needed functions.

Arrays

Date & Time

Directory, FileSystem

Regular Expressions

String

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"); 
        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");
// 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";
        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


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