PHP

Dynamic Navigation Menus

Next code demonstrates how to build a simple menu function with the current page high-lighted.

Code:

<?php
require_once('menu.php');
$page = isset($_GET['page']) ? $_GET['page'] : 'home';
?>
<html>
<head>
<title>Page - <?=$page?>
<style type="text/css">
.inactive, .active
{
 padding:2px 2px 2px 20px;
}

.inactive
{
 background:#ddd;
} 

.active
{
 background:black;
 font-weight:bold;
}

.inactive a
{
 text-decoration:none;
}

.active a
{
 text-decoration:none;
 color:white;
}
</style>
</title>
</head>
<body>
<table>
<tr>
<td width="200" valign="top">
<?php page_menu($page); ?>
</td>
<td width="600" valign="top">
Page: <?=$page?>
</td>
</tr>
</table>
</body>
</html>

Save this code as index.php

<?php
function menu_item($id, $title, $current)
{
  $class = ($current == $id) ? "active" : "inactive";
?>
  <tr><td class=<?=$class?>>
  <a href="index.php?page=<?=$id?>"><?=$title?></a>
  </td></tr>
<?php
}

function page_menu($page)
{
?>
  <table width="100%">
  <?php menu_item('home', 'Home', $page); ?>
  <?php menu_item('about', 'About', $page); ?>
  <?php menu_item('browse', 'Browse', $page); ?>
  <?php menu_item('download', 'Download', $page); ?>
</table>
<?php
}    
?>

Save this code as menu.php


Drop-Down Stickies

Attaching a drop-down sticky to a word or phrase in your document is an easy way to add valuable information close to the word, without obscuring it.

Code:

<?php
function start_link($text, $nextid)
{
  $idtext = $nextid;
?>
  <a href="javascript:void drop('<?=$idtext?>');">
  <span id="a_<?=$idtext?>"><?=$text?></span>
  </a>
  <div id="<?=$idtext?>" class="drop" style="display:none">
  <table cellspacing="0" cellpadding="0" width="170">
  <tr>
  <td valign="top" width="20">
  <a href="javascript:void close(<?=$idtext?>)">
  <img src="close.gif" border="0" />
  </a>
  </td>
  <td valign="top" width="150">
<?php
}
//--------------------
function end_link()
{
?>
  </td>
  </tr>
  </table>
  </div>
<?php
}
//-----------------
function link_header()
{
?>
  <style type="text/css">
  .drop
  {
    padding:5px;
    font-size:small;
    background:#eeeeee;
    border:1px solid black;
    position:absolute;
  }
  </style>
  <script type="text/javascript">
  function drop(sid)
  {
    aobj = document.getElementById("a_" + sid);
    divobj = document.getElementById(sid);
    divobj.style.top = (aobj.offsetBottom + 10) + "px";
    divobj.style.left = (aobj.offsetLeft + 10) + "px";
    divobj.style.display = "block";
  }
  function close(sid)
  {
    divobj = document.getElementById(sid);
    divobj.style.display = "none";
  }
  </script>
<?php
}
?>
<html>
<head>
<?php link_header(); ?>
</head>
<body>
Hello <?php start_link("my friend", 1); ?>
Jimmy <?php end_link(); ?> .How are you?
</body>
</html>

Save this code as drop-down.php


Section Content with Spinners

This code shows how to create sections on your page with spinners that open and show section of the content interactively.

Code:

<?php
function start_section($id, $title)
{
?>
<table cellspacing="0" cellpadding="0">
<tr>
<td width="30" valign="top">
<a href="javascript:void twist('<?=$id?>');">
<img src="up.gif" border="0" id="img-<?=$id?>" />
</a>
</td>
<td width="90%">
<h1><?=$title?></h1>
<div style="display:none;position:absolute" id="<?=$id?>" class="content">
<?php
}
function end_section()
{
?>
</div>
</td>
</tr>
</table>
<?php
}
?>
<html>
<head>
<style type="text/css">
body{font-family:Verdana;}
h1{font-size:medium;border-bottom:1px solid black;}
.content{font-size:small; margin-left:10px; padding:10px;}
</style>
<script type="text/javascript">
function twist(sid)
{
  imgobj = document.getElementById("img-" + sid);
  divobj = document.getElementById(sid);
  if(imgobj.src.match("up.gif"))
  {
    imgobj.src = "down.gif";
    divobj.style.position = "relative";
    divobj.style.display = "block";
  }
  else
  {
    imgobj.src = "up.gif";
    divobj.style.display = "none";
    divobj.style.position = "absolute";
  }
}
</script>
</head>
<body>
<?php start_section("first", "section one"); ?>
first part  first part first part first part first part.
first part first part first part first part first part.
<?php end_section(); ?>
<?php start_section("sec", "section two"); ?>
section two section two section two  section two section two.
section two section two section two section two section two.
<?php end_section(); ?>
</body>
</html>

Save the as spinners.php


Caching Output

High-traffic sites can often benefit from caching of pages, to save processing of the same data over and over again.

Put the first function cache_start in the beginning of php script and the second cache_end in the end of script.

Code:

function cache_start($_time, $dir)
{
  $cachefile = $dir.'/'.sha1($_SERVER['REQUEST_URI']).'.html';
  $cachetime = $_time;
  ob_start();

  if(file_exists($cachefile) && (time( )-$cachetime < filemtime($cachefile)))
  {
    include($cachefile);
    ob_end_flush();
    exit;
  }
}

//——————————————–

function cache_end($dir)
{
  $cachefile = $dir.'/'.sha1($_SERVER['REQUEST_URI']).'.html';
  $fp = fopen($cachefile, 'w');
  fwrite($fp, ob_get_contents());
  fclose($fp);
  ob_end_flush();
}

//————————————–
$_time : cache time

$dir : directory to cache files


Catching Keywords from Search Engines

With this class we try to catch some keywords from google, yahoo and bing search engines.

Code:

<?php
class keywords
{
 private $referer;
 private $_e;
 public $keywords;

 public function __construct()
 {
   if($_SERVER['HTTP_REFERER'])
   {
     if(preg_match("#\.google|search\.yahoo|\.bing#", $_SERVER['HTTP_REFERER']))
     {
       $this->referer = urldecode($_SERVER['HTTP_REFERER']);
     }
     else
     {
       return;
     }    
   }
   else
   {
     return;
   }    
 }

 private function getSeparators()
 {
   $this->_e = (preg_match("#\?q=|\?p=#", $this->referer)) ? "\?" : "&";
 }

 public function getKeywords()
 {
   if(!empty($this->referer))
   {
     $this->getSeparators();
     //google
     if(preg_match("#\.google#", $this->referer))
     {
       $m_ = preg_match("#{$this->_e}q=(.+?)&#si", $this->referer, $this->keywords);

       if($m_ == 0)
       {
         return false;
       }
     }
     //yahoo
     elseif(preg_match("#search\.yahoo#", $this->referer))
     {
       $m_ = preg_match("#{$this->_e}p=(.+?)\&#si", $this->referer, $this->keywords);

       if($m_ == 0)
       {
         return false;
       }
     }
     //bing
     elseif(preg_match("#\.bing#", $this->referer))
     {
       $m_ = preg_match("#{$this->_e}q=(.+?)\&#si", $this->referer, $this->keywords);

       if($m_ == 0)
       {
         return false;
       }
     }
     else
     {
       return false;
     }

     return $this->keywords[1];
   }
   else
   {
     return false;
   }
  }
}
?>

Save this script as keywords_class.php

Now let’s try to print these keywords.

Code:

<?php
require_once('keywords_class.php');
$keywordsObj = new keywords();
$keys = $keywordsObj->getKeywords();

if($keys)
{
 print $keys;
}
else
{
 print "ooops";
}
?>

Save this code as index.php


Drag - Drop Lists

This code uses an open source drag - drop library from Tool-Man to create drag-drop lists. Download and unpack the drag-drop libraries onto your server.

Code:

<html>
 <head>
 <title>Drag - Drop Lists</title>

 <style>
 #cities li {margin:0px;}
 ul.box li {margin:3px;}
 ul.sortable li {position:relative;}
 ul.box
 {
  list-style-type:none;
  padding:0px;
  margin:2px;
  width:20em;
  font-size:13px;
  font-family:"Times New Roman", Times, serif;
 }
 ul.box li
 {
  cursor:move;
  padding:2px 2px;
  border:1px solid #cccccc;
  background:#eee;
 }
 .clickable a
 {
  display:block;
  text-decoration:none;
  cursor:pointer;
  cursor:hand;
 }
 clickable li:hover
 {
  background:#f6f6f6;
 }
 </style>

 <script type="text/javascript" src="source/org/tool-man/core.js"></script>
 <script type="text/javascript" src="source/org/tool-man/events.js"></script>
 <script type="text/javascript" src="source/org/tool-man/css.js"></script>
 <script type="text/javascript" src="source/org/tool-man/drag.js"></script>
 <script type="text/javascript" src="source/org/tool-man/coordinates.js"></script>
 <script type="text/javascript" src="source/org/tool-man/dragsort.js"></script>
 <script type="text/javascript" src="source/org/tool-man/cookies.js"></script> 

 <script type="text/javascript">
 <!--
 var dragsort = ToolMan.dragsort();
 var junkdrawer = ToolMan.junkdrawer();

 window.onLoad = function()
 {
   dragsort.makeListSortable(document.getElementById("cities"), verticalOnly, saveOrder);
 }

 function verticalOnly(item)
 {
   item.toolManDragGroup.verticalOnly();
 }

 function saveOrder(item) { }

 function prepFields()
 {
   document.getElementById("cities_txt").value = junkdrawer.
   serializeList(document.getElementById("cities"));
   return true;
 }
 //-->
 </script>
 </head>
 <body>
 <ul id="cities" class="box">
 <li>Paris</li>
 <li>Rome</li>
 <li>Athens</li>
 </ul>

 <form method="post" action="display.php">
 <input type="hidden" name="cities" value="" id="cities_txt" />
 <input type="submit" onclick="prepFields();" />
 </form>
 </body>
</html>

Save the code as dragdrop.html

The simple code below used to print out values from the list.

Code:

<html>
<body>
You chose: <?=$_POST['states']?>
</body>
</html>

Save the code as display.php.


Magnet Link

This PHP function return the urn (Uniform Resource Name) formed from the content hash of a particular torrent file. The urn refering to the Base32 encoded hash of the file.

Code:

function base32_encode ($hash)
{
$outString = '';
$compBits = '';
$BASE32_TABLE = array(
                         '00000' => 0x61,
                         '00001' => 0x62,
                         '00010' => 0x63,
                         '00011' => 0x64,
                         '00100' => 0x65,
                         '00101' => 0x66,
                         '00110' => 0x67,
                         '00111' => 0x68,
                         '01000' => 0x69,
                         '01001' => 0x6a,
                         '01010' => 0x6b,
                         '01011' => 0x6c,
                         '01100' => 0x6d,
                         '01101' => 0x6e,
                         '01110' => 0x6f,
                         '01111' => 0x70,
                         '10000' => 0x71,
                         '10001' => 0x72,
                         '10010' => 0x73,
                         '10011' => 0x74,
                         '10100' => 0x75,
                         '10101' => 0x76,
                         '10110' => 0x77,
                         '10111' => 0x78,
                         '11000' => 0x79,
                         '11001' => 0x7a,
                         '11010' => 0x32,
                         '11011' => 0x33,
                         '11100' => 0x34,
                         '11101' => 0x35,
                         '11110' => 0x36,
                         '11111' => 0x37,
                         );

   /* Turn the compressed string into a string that represents the bits as 0 and 1. */
   for ($i = 0; $i < strlen($hash); $i++) {
       $compBits .= str_pad(decbin(ord(substr($hash,$i,1))), 8, '0', STR_PAD_LEFT);
   }

   /* Pad the value with enough 0's to make it a multiple of 5 */
   if((strlen($compBits) % 5) != 0) {
       $compBits = str_pad($compBits, strlen($compBits)+(5-(strlen($compBits)%5)), '0', STR_PAD_RIGHT);
   }

   /* Create an array by chunking it every 5 chars */
   $fiveBitsArray = split("\n",rtrim(chunk_split($compBits, 5, "\n")));

   /* Look-up each chunk and add it to $outstring */
   foreach($fiveBitsArray as $fiveBitsString) {
       $outString .= chr($BASE32_TABLE[$fiveBitsString]);
   }
   return $outString;
}

Parametres:

dn - Filename

xl - Size in bytes

xt - urn containing file hash

as - Web link to the file online

xs - P2P link

kt - Key words for search

mt - link to the metafile that contains a list of magneto

xt is the most important part of  magnet links.

Sites that use this kind of magnet links: btscene.com , mininova.org


Pop-Up Hints

Download the overLIB javascript library.

Code:

<?php
function popup($txt, $popup)
{
?>
  <a href="javascript:void(0);"
  onmouseover="return overlib('<?=$popup?>');"
  onmouseout="return nd();">
  <?=$txt?>
  </a>
<?php
}
?>
<html>
<head>
<title>Popup hints</title>
<script type="text/javascript" src="overlib.js"></script>
</head>
<body>
<div id="over"
style="position:absolute;visibility:hidden;z-index:1000;">
</div>
Greece is a small
<?php
popup(
      'country ',
      'Small but very beautiful<br /> with many islands'
     );
?>
in southeast Europe.
</body>
</html>

Save the code as index.php

Unpack the overLIB library into your web server’s documents directory, add in the index.php file and surf to it on your browser. This popup can be used with images, tables, fonts, styles and whatever you want.


HTML Email

This code describes how to send email using a multipart construction, where one part contains a plain-text version of the email and the other part is HTML. If you customers have HTML email turned off they will still get a nice email even if they don’t get all of the HTML markup.

Code:

 <?php
 $to_nickname = "Jimmy";
 $to = "jimmy@email.com";
 $from_nickname = "Jack";
 $from = "jack@email.com";
 $subject = "HTML Email";
 $random_hash = "2343qwe";
 ob_start();
 ?>
 To: <?=$to_nickname?> < <?=$to?> >
 From: <?=$from_nickname?> < <?=$from?> >
 MIME-Version: 1.0
 Content-Type: multipart/alternative;boundary="==Multipart_Boundary_<?=$random_hash?>"
 <?php
 $headers = ob_get_clean();
 ob_start();
 ?>
This is a multi-part message in MIME format.
--==Multipart_boundary_<?php print "$random_hash\n"; ?>
 Content-Type: text/plain; charset="iso-8859-1"
 Content-Transfer-Encoding: 7bit
This is the text of the message in a simple tetx format.
--==Multipart_boundary_<?=$random_hash?>
 Content-Type: text/html; charset="iso-8859-1"
 Content-Transfer-Encoding: 7bit
<html>
 <body>
 <p>Here is something with HTML formatting. That can include all of the usual:</p>
 <ul>
 <li>Bulleted lists</li>
 <li>Tables</li>
 <li>Images (if you include them as attachments or external links)</li>
 <li>Character formatting</li>
 <li>etc</li>
 </ul>
 </body>
 </html>
--==Multipart_boundary_<?=$random_hash?>
 <?php
 $message = ob_get_clean();
 $mail = @mail($to, $subject, $message, $headers);
 $ok = $mail ? "Mail sent\n" : "Mail failed\n";
 print $ok;
 ?>

The only hitch comes from the images or other file-based resources. You have two alternatives with images. The first is to reference an image on a remote server. There are  a couple of problems with this approach. First it doesn’t work for offline mail reading. Second spammers use this mechanism to see whether you have opened their email.

The second approach is to embed the image as an attachment in another part of the multipart message. This will work, but the email message themselves will be larger because of the base-64-encoded images.


Size Image Tags

All of the modern browsers start showing web pages as quickly as possible. This means browsers will start showing a page well before any images or other accompanying resources are downloaded. Because the browser hasn’t downloaded the image before rendering the page, it doesn’t know how big the image should be, unless you specify height and width attributes on the img tag.
If you don’t specify the width and height of images ,though, the page will jerk around as it’s being downloaded. The browser will guess at the size of the image but then find out after the image is downloaded that the actual size is much larger. Thus the browser will need to lay out the page again to adjust for the new size.

Code:

<html>
 <head>
 <title>Image Size</title>
 <?php
 function getImageSize($image)
 {
   list($width, $height) = getimagesize($image);
   print "<img src=\"$image\" width=\"$width\" height=\"$height\" />";
 }
 ?>
 </head>
 <body>
 <?php getImageSize("your_image.png"); ?>
 </body>
 </html>

You can use this function anywhere you would have put an img tag previously, don’t use this function in static headers or footers where the size of the images will never change.