PHP

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.


Build Lightweight HTML Graphs

For simple bar graphs, you don’t need fancy images or flash movies, you can use this simple code to create bar graphs with HTML tables and PHP.

Code:

<html>
 <head>
 <title>HTML Graphs</title>
 </head>
 <?php
 $data = array(
 array('movies', 10),
 array('music', 20),
 array('games', 80),
 array('series', 40)
 );
 $max = 0;
 foreach($data as $dt)
 {
   $max += $dt[1];
 }
 ?>
 <body>
 <table width="400" cellspacing="0" cellpadding="2">
 <?php
 foreach($data as $dt)
 {
   $percent = ($dt[1]/$max)*100;
 ?>
 <tr>
 <td width="20%"><?=$dt[0]?></td>
 <td width="10%"><?=$dt[1]?>%</td>
 <td>
 <table width="<?=$percent?>%" bgcolor="#666666">
 <tr><td>&nbsp;</td></tr>
 </table>
 </td>
 </tr>
 <?php
 }
 ?>
 </table>
 </body>
 </html>

Photo:

Save the code as html_graphs.php

Colored bar graphs

If you want to add some color to the data use the next code.

Code:

<html>
 <head>
 <title>HTML Graphs</title>
 </head>
 <?php
 $data = array(
 array('movies', 10, '#ff0000'),
 array('music', 20, '#ff9900'),
 array('games', 80, '#006600'),
 array('series', 40, '#000000')
 );
 $max = 0;
 foreach($data as $dt)
 {
   $max += $dt[1];
 }
 ?>
 <body>
 <table width="400" cellspacing="0" cellpadding="2">
 <?php
 foreach($data as $dt)
 {
   $percent = ($dt[1]/$max)*100;
 ?>
 <tr>
 <td width="20%"><?=$dt[0]?></td>
 <td width="10%"><?=$dt[1]?>%</td>
 <td>
 <table width="<?=$percent?>%" bgcolor="<?=$dt[2]?>">
 <tr><td>&nbsp;</td></tr>
 </table>
 </td>
 </tr>
 <?php
 }
 ?>
 </table>
 </body>
 </html>

Photo:

Save the code as html_colored_graphs.php


Formatting Control with XSL

Amazon provides an interesting service to its corporate customers.The customer can skin an Amazon page by providing an XSL stylesheet that formats the XML data about the products,prices and related data.This means that if you are a corporate customer, you can add your own links and graphs and even customize the look of Amazon.com.

The scripts below do the same with PHP’s XSL engine.The processor takes two inputs, the input.xml file contains the data for the page, and the format.xsl file contains the formatting for the page.

Output from XML and XSL:

<?php
 $xml = new DOMDocument();
 $xml->Load("input.xml");
 $xsl = new DOMDocument();
 $xsl->Load("format.xsl");
 $xslproc = new XSLTProcessor();
 $xslproc->importStylesheet($xsl);
 print $xslproc->transformToXML($xml);
 ?>
Save the code as output.php.
XML file:
<?xml version="1.0" encoding="UTF-8"?>
 <books>
 <book name="book1" />
 <book name="book2" />
 <book name="book3" />
 </books>
Save the code as input.xml.
XSL  to handle formatting:
<?xml version="1.0" encoding="UTF-8"?>
 <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
 <xsl:output method="html" />
 <xsl:template match="/">
 <html>
 <body>
 <xsl:for-each select="/books/book">
 <xsl:value-of select="@name" />
 </xsl:for-each>
 </body>
 </html>
 </xsl:template>
 </xsl:stylesheet>

Save the code as format.xsl.

Execute output.php from the command line:

% php output.php


Add tabs to your interface

An easy way to break up a site is to display it using tabs, where the data is broken into subelements each correlating to a named tab.

Code:

<?php
 require_once('tabs.php');
 ?>
 <html>
 <head>
 <style type="text/css">
 .tab
 {
   border-bottom:1px solid black;
   text-align:center;
 }
 .tab-active
 {
   border-left:1px solid black;
   border-top:1px solid black;
   border-right:1px solid black;
   text-align:center;
   font-weight:bold;
 }
 .tab-content
 {
   padding:5px;
   border-left:1px solid black;
   border-bottom:1px solid black;
   border-right:1px solid black;
 }
 </style>
 <title>Tabs</title>
 </head>
 <body>
 <div style="width:600px;">
 <?php tabs_start(); ?>
 <?php tab('tab one'); ?>
 The first tab.
 <?php tab('tab two'); ?>
 The second tab.
 <?php tabs_end(); ?>
 </div>
 </body>
 </html>

Save the code as index.php.

Code:

<?php
 $tabs = array();
 function tabs_start()
 {
   ob_start();
 }
 function endtab()
 {
   global $tabs;
   $text = ob_get_clean();
   $tabs[count($tabs) - 1]['text'] = $text;
   ob_start();
 }
 function tab($title)
 {
   global $tabs;
   if(count($tabs) > 0)
   {
    endtab();
   }
   $tabs[] = array('title' => $title, 'text'=> '');
 }
 function tabs_end()
 {
   global $tabs;
   endtab();
   ob_end_clean();
   $index = 0;
   if($_GET['tabindex'])
   {
     $index = $_GET['tabindex'];
   }
?>
 <table width="100%" cellspacing="0" cellpadding="0">
 <tr>
 <?php
 $baseuri = $_SERVER['REQUEST_URI'];
 $baseuri = preg_replace("/\?.*$/", "", $baseuri);
 $curindex = 0;
 foreach($tabs as $tab)
 {
   $class = "tab";
   if($index == $curindex)
   {
     $class = "tab-active";
   }
?>
  <td class="<?=$class?>">
  <a href="<?php echo $baseuri."?tabindex=".$curindex; ?>">
  <?=$tab['title']?>
  </a>
  </td>
 <?php
  $curindex++;
 }
 ?>
 </tr>
 <tr><td class="tab-content" colspan="<?php echo(count($tabs) + 1); ?>">
 <?php echo $tabs[$index]['text']; ?>
 </td>
 </tr>
 </table>
 <?php
 }
 ?>

Save the code as tabs.php.


HTML Boxes

Sometimes it’s useful to put your page content into boxes to make it easier for users to navigate your site.

Code:

<?php
 function boxStyles()
 {
?>
 <style type="text/css">
 .box
 {
   font-family:arial, verdana, sans-serif;
   font-size:x-small;
   background:#ccc;
 }
 .box_title
 {
   font-size:small;
   font-weight:bold;
   color:#fff;
   background:#777;
   padding:5px;
   text-align:center;
 }
 .box-content
 {
   background:#fff;
   padding:5px;
 }
 </style>
<?php
 }
 function start_box($title)
 {
?>
   <table class="box">
   <tr>
   <td class="box-title"><?=$title?></td>
   </tr>
   <tr>
   <td class="box-content">
<?php
 }
 function end_box()
 {
?>
   </td>
   </tr>
   </table>
<?php
 }
?>
<html>
 <head>
 <title>Html Boxes</title>
 <?php boxStyles(); ?>
 </head>
 <body>
 <div style="width:300px;">
 <?php start_box("Greece"); ?>
 Greece was the first area in Europe where advanced early civilizations emerged,
 beginning with the Minoan civilization in Crete
 and then the Mycenean civilization on the mainland...
 <?php end_box(); ?>
 </div>
 </body>
 </html>

Note: if you want several different colors of boxes you can create different CSS classes for the colors.


Breadcrumbs

Breadcrumbs is a navigation aid used in user interfaces. It gives users a way to keep track of their location within programs or documents. A breadcrumb trail allows a user to navigate back up the heirarchy where he would find more revelant information.

Code:

<?php
 $id = $_GET['id'];
 if(strlen($id) < 1)
 $id = "profile";
 $pages = array(
                 'profile' => array(
                                    'id' => 'profile',
                                    'previous' => '',
                                    'title' => 'Profile',
                                    'url' => 'mypage.php?id=profile'
                                   ),
                 'bookmarks' => array(
                                      'id' => 'bookmarks',
                                      'previous' => 'profile',
                                      'title' => 'Bookmarks',
                                      'url' => 'mypage.php?id=bookmarks'
                                     ),
                 'comments' => array(
                                     'id' => 'comments',
                                     'previous' => 'comments',
                                     'title' => 'Comments',
                                     'url' => 'mypage.php?id=comments'
                                    )
              );
 //------------------------------------------------------------------------
 function breadcrumbs($id, $pages)
 {
   $n = array();
   while(strlen($id) > 0)
   {
     $n[] = $id;
     $id = $pages[$id]['previous'];
   }
   for($i=count($n)-1; $i>=0; $i--)
   {
     $page = $pages[$n[$i]];
     if($i > 0)
     {
       print "<a href=\"{$page['url']}\">";
     }
     print $page['title'];
     if($i > 0)
     {
       print "</a> | ";
     }
   }
 }
 ?>
 <html>
 <head>
 <title><?php print $id; ?></title>
 </head>
 <body>
 Location: <?php breadcrumbs($id, $pages); ?><br />
 Page: <?php print $id; ?>
 </body>
 </html>

Save this code as mypage.php in your php server.


Vote System version 1.0.0

Vote system 1.0.0 is a bar graph system giving percentage values, it produces bar columns for each vote option (see photos).

Language: PHP

The system creates a unique hash key for each different url this means that the url is the identifier.

Example:

http://www.mysite.com/movies.php?movie=themovie vote for the movie

http://www.mysite.com/movies.php?movie=themovie&actor=theactor vote for the actor

Features:

  • Add or remove vote options
  • Change options names
  • Change bar colors
  • Change the background color
  • Change text color

Also a manage system is included in this version.

Photos:



Download Vote System version 1.0.0


Skinnable Interface

Create a skinnable interface with CSS and allow the user to change the look of your web application.

Adding stylesheets or letting users upload their stylesheets you can create a completely custom enviroment for each individual user.

Code:

Save the code as index.php in your PHP server

<html>
 <head>
 <?php 
 $style = "default";
 if($_GET['style'])
 {
   $style = $_GET['style'];
 }
 $files = array();
 $dir = opendir('styles');
 while($file = @readdir($dir))
 {
   if(preg_match("#[.]css$#", $file))
   {
     $files[] = $file;
   }
 }
 ?>
 <style type="text/css">@import url('styles/<?php echo $style; ?>');</style>
 </head>
 <body>
 <table width="1000">
 <tr>
 <td width="300" class="links" valign="top">
 <div class="active"><a href="">Home</a></div>
 <div class="inactive"><a href="">Browse</a></div>
 <div class="inactive"><a href="">About</a></div>
 </td>
 <td width="700" valign="top">
 <table class="box">
 <tr>
 <td class="title">
 INFO
 </td>
 </tr>
 <tr>
 <td class="entry">
 Hello World!
 </td>
 </tr>
 </table>
 </td>
 </tr>
 </table>
 <form>
 Select Style:
 <select name="style">
 <?php
 foreach($files as $file)
 {
 ?>
   <option value="<?php print $file; ?>" <?php print($file == $style ? 'selected' : ''); ?>><?php print $file; ?></option>
 <?php
 }
 ?>
 </select>
 <input type="submit" value="Style" />
 </form>
 </body>
 </html>

Create a styles directory in the same directory with index.php script

Save the next code as styles/default.css

CSS Code:

 body
 {
   font-family:verdana;
   font-size:90%;
   margin:0;
 }
.box
 {
   background-color:#0066CC;
 }
 .title
 {
   color:#fff;
   font-weight:bold;
   text-align:center;
 }
 .entry
 {
   background-color:#fff;
   font-size:80%;
   padding:10px;
 }
 .links
 {
   margin:5px;
 }
 .active
 {
   padding:5px;
   background-color:#CC0000;
 }
 .active a
 {
   color:#fff;
   font-weight:bold;
   text-decoration:none;
 }
 .inactive
 {
   padding:5px;
   background-color:#ccc;
 }
 .inactive a
 {
   color:#000;
   text-decoration:none;
 }

Save the next code as styles/style1.css

CSS Code:

 body
 {
   font-family:verdana;
   font-size:90%;
   margin:0;
 }
 .box
 {
   background-color:#666;
 }
 .title
 {
   color:#fff;
   font-weight:bold;
   text-align:center;
 }
 .entry
 {
   background-color:#fff;
   font-size:80%;
   padding:10px;
 }
.links
 {
   margin:5px;
 }
.active
 {
   padding:5px;
   background-color:#CC0000;
 }
 .active a
 {
   color:#fff;
   font-weight:bold;
   text-decoration:none;
 }
 .inactive
 {
   padding:5px;
   background-color:#666;
 }
 .inactive a
 {
   color:#fff;
   text-decoration:none;
 }

Magic Pagination

The MagicPagination is a tool which help you to split large result sets over multiple pages.
The only thing that you must to do is to follow the next pattern:

<?php

$paginationObj = new pagination(total_limit);
$limit = $paginationObj->paginationGetLimit();

mysql query(variable $limit goes here)

$paginationObj->paginationCreatePages();

?>

Default values

total_limit:500
results per page:30
Number of pagination links:5

Note: works only with dynamic urls.(http://www.example.com/script.php?page=num or script.php?var=something&page=num etc)

Code:

<?php
 class pagination
 {

   //-----------------------------------------------------------------------------------------------------------------------
   private $max_rows = 30;//MAXIMUM NUMBER OF DISPLAYING ITEMS
   private $max_num = 5;//MAXIMUM NUMBER OF NUMERIC LINKS
   private $limit;
   private $maxId;//TOTAL NUMBER OF ITEMS
   private $lastpage;
   private $page;
   private $url;
   private $match = "page=";

 //------------------------------------------------------------------------------------------------------------------------
 public function __construct($maxId = null)
 {
   if(!$maxId)
   {
     $this->maxId = 500;
   }
   else
   {
     $this->maxId = $maxId;
   }
 }

 //-------------------------------------------------------GET CURRENT PAGE-------------------------------------------------------
 public function getPage()
 {
   return $this->page;
 }

 //--------------------------------------------------------PAGINATION UP DIVISION------------------------------------------------
 public function paginationGetLimit()
 {
   $this->page = isset($_GET['page']) ? strip_tags($_GET['page']) : 1;
   $this->lastpage = ceil($this->maxId / $this->max_rows);
   $this->page = (int)$this->page;
   if($this->page < 1)
   {
     $this->page = 1;
   }
   elseif($this->page > $this->lastpage)
   {
     $this->page = $this->lastpage;
   }
   return ($this->limit = 'LIMIT ' .($this->page - 1) * $this->max_rows .',' .$this->max_rows);
 }

 //-----------------------------------------------------PAGINATION DOWN DIVISION SIMPLE PAGES-------------------------------------
 public function paginationCreatePages()
 {
   //.........................................................
   $this->url = $_SERVER['REQUEST_URI'];//THE REQUESTED URL
   $pos = strpos($this->url, $this->match);
   //.........................................................
   echo "<div class='pagination'>";
   echo "<ul>";
   //NEXT ENTRIES
   if ($this->page == 1)
   {
     //do nothing
   }
   else
   {
     $prevpage = $this->page-1;
     if($pos != '')
     {
       $nextUrl = str_replace($this->match.$this->page, $this->match.$prevpage, $this->url);
       echo "<li>";
       echo "<a href='".$nextUrl."'>&laquo;</a>";
       echo "</li> ";
     }
     else
     {
       print "The document can not create pages";
       return;
     }
   }
   //MIDDLE PAGES
   if($this->lastpage != 1)
   {
     $max_links = $this->max_num + 1;
     $h = 1;
     if($this->page > $max_links)
     {
       $h = (($h + $this->page) - $max_links);
     }
     if($this->page >= 1)
     {
       $max_links = $max_links + ($this->page-1);
     }
     if($max_links > $this->lastpage)
     {
       $max_links = $this->lastpage + 1;
     }
     for($i=$h; $i<$max_links; $i++)
     {
       if ($i == $this->page)
       {
         echo "<li id='f'>";
         echo $i;
         echo "</li>";
       }
       else
       {
         if($pos == '')
         {
           if(strpos($this->url, '?') != '')
           {
             $specialChar = "&amp;";
           }
           else
           {
             $specialChar = "?";
           }
           $currentUrl = $this->url.$specialChar.$this->match.$i;
         }
         else
         {
           $currentUrl = str_replace($this->match.$this->page, $this->match.$i, $this->url);
         }
         echo "<li>";
         echo "<a href='".$currentUrl."'>$i</a>";
         echo "</li> ";
       }
     }
   }
   //PREVIOUS ENTRIES
   if ($this->page == $this->lastpage)
   {
     //do nothing
   }
   else
   {
     $nextpage = $this->page + 1;
     if($pos == '')
     {
       if(strpos($this->url, '?') != '')
       {
         $specialChar = "&amp;";
       }
       else
       {
         $specialChar = "?";
       }
       $prevUrl = $this->url.$specialChar.$this->match.$nextpage;
     }
     else
     {
       $prevUrl = str_replace($this->match.$this->page, $this->match.$nextpage, $this->url);
     }
     echo "<li>";
     echo "<a href='".$prevUrl."'>&raquo;</a>";
     echo "</li> ";
   }
   //-------------------------------------------------------------------------------
   echo "</ul>";
   echo "</div>";
 }

 //--------------------------------------------------------------------------------------------
}
?>

ccs code:

/* CSS Document */
 .pagination
 {
   width:100%;
   margin-top:20px;
   margin-left:10px;
   clear:left
 }
 .pagination ul
 {
   list-style-type: none;
   margin:0;
   padding:0;
 }
 .pagination ul li
 {
   color:#666666;
   float:left;
   font: Eras Bold ITC;
   font-size: 12px;
   letter-spacing: .01em;
 }
 .pagination ul li a
 {
   color: #47809E;
   display: block;
   margin: 0 0.1em;
   padding: 2px;
   padding-left: 4px;
   padding-right: 4px;
   text-decoration: none;
 }
 li#f
 {
   background-color:#fff;
   display: block;
   margin: 0 0.1em;
   padding: 2px;
   padding-left: 4px;
   padding-right: 4px;
   text-decoration: none;
   color:#666666;
 }
 .pagination ul li a:hover
 {
   text-decoration:underline;
 }