Webmaster

Rozrywka

Zwierz?ta

Motoryzacja

Transport, ci???arowe

O ci???ar??wkach i transporcie

Sport

Koszyk??wka

Basketball - newsy

Fotografia

Komputery

O serwisie

Serwis ten jest agregatorem RSS, który magazynuje zebrane informacje tak, aby można było do nich swobodnie później wrócić. Wszystkie treści pochodzą z kanałów RSS i są własnością twórców serwisów, które je udostępniają.
Tytuł każdego artykułu jest odnośnikiem do strony, z której dana treść pochodzi.
Baza zawiera 167733 akrtykułów.

Polecamy

Bielizna
Rachunki bankowe dla firmy
Fotografia Sklep
Ebooki PDF
Trojan PodSzefka
Dzwonki na telefon
Czytnik RSS
Wygaszacze na telefon komórkowy


Use HTML and CSS to create a tabbed interface for your web application.

Sometimes there is just too much data to put onto one web page. An easy way to break up a site (or even a content-heavy page) is to display it using tabs, where the data is broken up into subelements, each correlating to a named tab. Lucky for us, tabs are a piece of cake with PHP.

The Code

Save the code in Example 1 as index.php.

Example 1. Using the tabs library to show a tabbed interface

<?php

require_once("tabs.php");

?>

<html>

<head>

<?php tabs_header(); ?>

</head>

<body>

<div>

<?php tabs_start(); ?>

<?php tab( "Tab one" ); ?>

This is the first tab.

<?php tab( "Tab two" ); ?>

This is the second tab.

<?php tabs_end(); ?>

</div>

</body>

</html>


Next, code up a nice PHP and CSS library. Save the code in Example 2 as tabs.php.

Example 2. Using PHP and some CSS to create user-friendly tabs

<?php

$tabs = array();


function tabs_header()

{

?>

<style type="text/css">

.tab {

border-bottom: 1px solid black;

text-align: center;

font-family: arial, verdana;

}

.tab-active {

border-left: 1px solid black;

border-top: 1px solid black;

border-right: 1px solid black;

text-align: center;

font-family: arial, verdana;

font-weight: bold;

}

.tab-content {

padding: 5px;

border-left: 1px solid black;

border-right: 1px solid black;

border-bottom: 1px solid black;

}

</style>

<?php

}


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"<?php echo($class); ?>">

<a href="<?php echo( $baseuri."?tabindex=".$curindex ); ?>">

<?php echo( $tab['title'] ); ?>

</a>

</td>

<?php

$curindex += 1;

}

?>

</tr>

<tr><td colspan="<?php echo( count( $tabs ) + 1 ); ?>">

<?php echo( $tabs[$index ]['text'] ); ?>

</td></tr>

</table>

<?php

}

?>


I designed the API on this tabs system to make it easy to create tabs in your document. It starts with invoking tabs_header in the header section of the document. This will set up the CSS for the tabs. Then, within the body, the call to tabs_start sets up the tab system. Each new tab starts with a call to tab with the name of the tab. The call to tabs_end then ends the construction of the tabs.

Internally, the tabs system uses output buffering to hold onto the contents of each tab, and to display whichever tab is selected "on top."

Running


Upload the files to your PHP server and point your browser at index.php. You should see something close to Figure 2.

Figure 2. The first tab

Click on the second tab (labeled "Tab two"), and you will see the second tab selected and the contents of the second tab (as shown in Figure 3).

Figure 3. The second tab

[3081]

Use HTML to create simple graphs for your data.

It seems as though every site you go to these days requires QuickTime or Flash so that you can see fancy images and graphs. For simple bar graphs, though, you don't need fancy image rendering or Flash movies. You can use this hack to create bar graphs with just a few HTML tables and some PHP. The result looks just as cool as those other Flash-heavy sites but doesn't require any extra plug-ins or downloads.

The Code

Save the code in Example 1 as htmlgraph.php.

Example 1. Drawing some simple bar graphs

<html>

<?

$data = array(

array( "movies", 20 ),

array( "food", 30 ),

array( "workout", 10 ),

array( "work", 40 )

);

$max = 0;

foreach ( $data as $d ) { $max += $d[1]; }

?>

<body>

<table width="400" cellspacing="0" cellpadding="2">

<? foreach( $data as $d ) {

$percent = ( $d[1] / $max ) * 100;

?>

<tr>

<td width="20%"><? echo( $d[0] ) ?></td>

<td width="10%"><? echo( $d[1] ) ?>%</td>

<td>

<table width="<? echo($percent) ?>%" bgcolor="#aaa">

<tr><td> </td></tr>

</table>

</td>

</tr>

<? } ?>

</table>

</body>

</html>


You can use several techniques to create HTML graphs. I chose to use two tables; the first contains the textual data, and the second contains a set of nested tables, each with a width value based on the graph value in that row.

I calculate the width by first finding the maximum value of the combined data, and storing that in $max. I then derive the percentage by dividing $max by the current value, and multiplying the result by 100 (to set the scale between 0 and 100). That number is stored in $percent, which is then used in the width attribute of the table.

Running

Use your browser to surf to the htmlgraph.php page. You should see something similar to Figure 1

Figure 1. The simple HTML graph as seen in Safari

Start Running

I admit that gray is not the prettiest color for a graph, so Example 2 is a slightly altered version of the script, which adds a little color to the data.

Example 2. Adding a splash of color

<html>

<?

$data = array(

array( "movies", 20, "red" ),

array( "food", 30, "green" ),

array( "workout", 10, "blue" ),

array( "work", 40, "black" )

);

$max = 0;

foreach ( $data as $d ) { $max += $d[1]; }

?>

<body>

<table width="400" cellspacing="0" cellpadding="2">

<? foreach( $data as $d ) {

$percent = ( $d[1] / $max ) * 100;

?>

<tr>

<td width="20%"><? echo( $d[0] ) ?></td>

<td width="10%"><? echo( $d[1] ) ?>%</td>

<td>

<table width="<? echo($percent) ?>%" bgcolor="<? echo($d[2]) ?>">

<tr><td> </td></tr>

</table>

</td>

</tr>

<? } ?>

</table>

</body>

</html>


The new third value is used to set the background color of the bar graph table. This gives the output a rainbow look that is a little nicer on the eyes than the gray version.

[3080]

Use the ActiveWidgets spreadsheet library to put an interactive JavaScript data control on your page.

Let's face it: some dataparticularly financial and statistical datajust looks better when it's presented as a spreadsheet. Unfortunately, HTML does a poor job of giving you an interactive spreadsheet-style feel, especially when it comes to scrolling around, sorting, or any of the truly interactive user experience elements of a spreadsheet.

This hack uses the ActiveWidgets (http://activewidgets.com/) grid control to create a spreadsheet-style interface on a web page.

The Code

Save the code in Example 1 as index.php.

Example 1. A script that provides state-specific data in a spreadsheet format

<?php $states = array(

array( "Alabama",4447100,1963711,

52419.02,1675.01,50744,87.6,38.7 ),

array( "Alaska",626932,260978,

663267.26,91316,571951.26,1.1,0.5 ),

array( "Arizona",5130632,2189189,

113998.3,363.73,113634.57,45.2,19.3 ),

array( "Arkansas",2673400,1173043,

53178.62,1110.45,52068.17,51.3,22.5 ),

array( "California",33871648,12214549,

163695.57,7736.23,155959.34,217.2,78.3 ),


array( "Colorado",4301261,1808037,104093.57,

376.04,103717.53,41.5,17.4 ),

array( "South Dakota",754844,323208,77116.49,

1231.85,75884.64,9.9,4.3 ),

??

array( "Tennessee",5689283,2439443,42143.27,

926.15,41217.12,138,59.2 ),

array( "Texas",20851820,8157575,268580.82,

6783.7,261797.12,79.6,31.2 ),

array( "Utah",2233169,768594,84898.83,

2755.18,82143.65,27.2,9.4 ),

array( "Vermont",608827,294382,9614.26,

364.7,9249.56,65.8,31.8 ),

array( "Virginia",7078515,2904192,42774.2,

3180.13,39594.07,178.8,73.3 ),

array( "Washington",5894121,2451075,71299.64,

4755.58,66544.06,88.6,36.8 ),

array( "West Virginia",1808344,844623,24229.76,

152.03,24077.73,75.1,35.1 ),

array( "Wisconsin",5363675,2321144,65497.82,

11187.72,54310.1,98.8,42.7 ),

array( "Wyoming",493782,223854,97813.56,713.16,

97100.4,5.1,2.3 ),

array( "Puerto Rico",3808610,1418476,5324.5,1899.94,

3424.56,1112.1,414.2 )

);

?>

<html>

<head>

<link href="runtime/styles/xp/grid.css" rel="stylesheet" type="text/css" ></link>

<script src="runtime/lib/grid.js"></script>

</head>

<body>

<div>

<script>

var data = [

<?php $first = true; foreach( $states as $state )

{ if ( !$first ) echo( "," );

?>

[ "<?php echo($state[0]); ?>", <?php echo($state[1]); ?>,

<?php echo($state[2]); ?>, <?php echo($state[3]); ?>,

<?php echo($state[4]); ?>, <?php echo($state[5]); ?>,

<?php echo($state[6]); ?>, <?php echo($state[7]); ?> ]

<?php $first = false; } ?>

];


var columns = [ "State", "Population", "Housing Units", "Total Area",

"Total Water", "Total Land", "Population Density", "Housing Density" ];


function dataLookup( row, col )

{

return data[row][col];

}


function headerLookup( col )

{

return columns[ col ];

}


var grid = new Active.Controls.Grid;

grid.setRowCount( data.length );

grid.setColumnCount( columns.length );

grid.setDataText( dataLookup );


grid.setColumnText( headerLookup );

document.write( grid );

</script>

</div>

</body>

</html>


Running

Download the ActiveWidgets grid library and unpack it. Move that directory to your server and place the index.php file in the same directory as the ActiveWidgets files. Then point your browser to index.php; you should see something like Figure 1

Figure 1. An ActiveWidgets grid control with U.S. census data

This simple page does a JavaScript source include on the ActiveWidgets grid control library. Then it loads the data into a JavaScript array and creates the grid control. The script then sets the data lookup to a local function called dataLookup(), which just returns the data at that row and column. The column headers work the same way.




[3079]

Use the overLIB library to pop up hints for words on your web page using JavaScript and PHP.

With the overLIB JavaScript library (http://www.bosrup.com/web/overlib/), you can have handy pop-up labels that appear above text on your page. This hack makes it a little easier to create these links by providing a PHP wrapper function to invoke the library.

The Code

Save the code shown in Example 1 as index.php.

Example 1. A wrapper function that simplifies overLIB use, courtesy of PHP

<?php

function popup( $text, $popup )

{

?>

<a href="javascript:void(0);""return overlib('<?php echo($popup); ?>

');"><?php echo($text); ?></a>

<?php

}

?>

<html>

<head>

<script type="text/javascript" src="overlib.js"><!-- overLIB (c) Erik Bosrup -->

</script>

</head>

<body>

<div>

</div>

So this is just a test of popups. Not something interesting about <?php popup(

'rabbits', 'Small furry woodland creatures.<br/>Rabbits also make good pets.'

); ?>. Because that would just be silly.

</body>

</html>


You could also put the wrapper function into a PHP library, include that library in your PHP pages, and turn this into a nice, reusable utility function.

Running

Download and unpack the overLIB library into your web server's documents directory. Then add in the index.php file and surf to it on your browser. You should see something similar to Figure 1.

Figure 1. The page with the pop-up link

Next, move the mouse over the word rabbits, and you will see the pop up appear, which gives you a little more information about rabbits (as seen in Figure 2).

This pop up can be as elaborate as you like, with images, tables, different fonts, styles, and whatever else you please.

[3078]

Use JavaScript, DHTML, and PHP to create and use drag-and-drop lists.

Creating an interface that allows the user to prioritize a list has always been a problem when working with HTML. With PHP, though, this is no longer the case. This hack uses an open source drag-and-drop library from ToolMan (http://tool-man.org/) to create drag-and-drop lists.

The Code

Enter the code shown in Example 1 and save it as index.html.

Example 1. Building a drag-and-drop list with HTML and CSS
<html>
<head>
 
<style>
#states li { margin: 0px; }
        
ul.boxy li { margin: 3px; }
 
ul.sortable li {
               position: relative;
}
 
ul.boxy {
               list-style-type: none;
               padding: 0px;
               margin: 2px;
               width: 20em;
               font-size: 13px;
               font-family: Arial, sans-serif;
}
ul.boxy li {
               cursor:move;
               padding: 2px 2px;
               border: 1px solid #ccc;
               background-color: #eee;
}
.clickable a {
                display: block;
                text-decoration: none;
                cursor: pointer;
                cursor: hand;
}
.clickable li:hover {
               background-color: #f6f6f6;
}
 
</style>
 
<script language="JavaScript" type="text/javascript"
         src="source/org/tool-man/core.js"></script>
<script language="JavaScript" type="text/javascript"
         src="source/org/tool-man/events.js"></script>
<script language="JavaScript" type="text/javascript"
         src="source/org/tool-man/css.js"></script>
<script language="JavaScript" type="text/javascript"
         src="source/org/tool-man/coordinates.js"></script>
<script language="JavaScript" type="text/javascript"
         src="source/org/tool-man/drag.js"></script>
<script language="JavaScript" type="text/javascript"
         src="source/org/tool-man/dragsort.js"></script>
<script language="JavaScript" type="text/javascript"
         src="source/org/tool-man/cookies.js"></script>
 
<script language="JavaScript" type="text/javascript">
<!--
var dragsort = ToolMan.dragsort( )
var junkdrawer = ToolMan.junkdrawer( )
 
window.onload = function( )
{
dragsort.makeListSortable(document.getElementById("states"),
verticalOnly, saveOrder)
}
 
function verticalOnly(item)
{ item.toolManDragGroup.verticalOnly( ) }
 
function saveOrder(item) { }
 
function prepFields( )
{
document.getElementById( "states_text" ).value = junkdrawer.
serializeList( document.getElementById( "states" ) );
               return true;
}
//-->
</script>
</head>
<body>
 
<ul>
<li>California</li>
<li>Texas</li>
<li>Alaska</li>
</ul>
 
<form method="post" action="tellme.php">
<input type="hidden" name="states" value="" />
<input type="submit">
</form>
 
</body>
 
</html>

The simple code in Example 2 saved as tellme.phpprints out values in an array.

Example 2. PHP used to print out some values from the list
<body>
<html>
You chose: <?php echo( $_POST['states'] ); ?>
</html>
</body>

Running

Download and unpack the drag-and-drop libraries onto your web server. Then upload the files and navigate to the index.html page. You should see something that looks like Figure 1.

Figure 1. The drag-and-drop list

Now drag and drop the lines to rearrange the items however you like; then click the Submit button. At that point, the contents of the list will be transferred into a hidden form variable called states, and uploaded to the server. The tellme.php script then prints the values from that variable in the order you specified (as shown in Figure 2).

Figure 2. After clicking on the Submit button

Dynamic, little interface widgets such as this one can differentiate between your web application and others in terms of ease of use. And sometimes it's good having one just for a little perk during demos! With the results of a drag stored in a form variable, your PHP can easily retrieve the data and do anything you want it to do.


[3077]

Using DHTML, you can build graphs that change without requiring even a page refresh. The result? Your users can play with data in real time.

Something is fundamentally unsatisfying about the way the Web works. You click on a link, the page disappears, and that lovely spinning ball or ticking clock grinds by as a new page appears section by section, (hopefully) with the information you want. This certainly is not the interactivity we're all used to from our client-side applications.

But, thank goodness, you can make an application that works without a page refresh. This hack shows you how to make an interactive scatter plot using a few graphics, some PHP, and a whole slew of JavaScript.

The Code

The index file, index.php, is shown in Example 1.

Example 1. JavaScript, the real workhorse in this hack
<?php $states = array(
array("Alabama",4447100,1963711,52419.02,
1675.01,50744,87.6,38.7),
array("Alaska",626932,260978,663267.26,91316,
571951.26,1.1,0.5),
array("Arizona",5130632,2189189,113998.3,363.73,
113634.57,45.2,19.3),
array("Arkansas",2673400,1173043,53178.62,
1110.45,52068.17,51.3,22.5),
array("California",33871648,12214549,163695.57,
7736.23,155959.34,217.2,78.3),
array( "Colorado",4301261,1808037,104093.57,
376.04,103717.53,41.5,17.4 ),
??
array( "Washington",5894121,2451075,71299.64,
4755.58,66544.06,88.6,36.8 ),
array( "West Virginia",1808344,844623,24229.76,
152.03,24077.73,75.1,35.1 ),
array( "Wisconsin",5363675,2321144,65497.82,
11187.72,54310.1,98.8,42.7 ),
array( "Wyoming",493782,223854,97813.56,713.16,
97100.4,5.1,2.3 ),
array( "Puerto Rico",3808610,1418476,5324.5,
1899.94,3424.56,1112.1,414.2 )
);
?>
<html>
<head>
<script language="Javascript">
var width = 300;
var height = 300;
 
var axes = [
"population", "housing_units", "total_area",
"total_water", "total_
land", "people_density", "housing_density" ];
 
var data = [
<?php $first = true; foreach( $states as $state )
{ if ( !$first ) echo( "," );
?>
{ state: "<?php echo($state[0]); ?>",
population: <?php echo($state[1]); ?>,
housing_units: <?php echo($state[2]); ?>,
total_area: <?php echo($state[3]); ?>,
total_water: <?php echo($state[4]); ?>,
total_land: <?php echo($state[5]); ?>,
people_density: <?php echo($state[6]); ?>,
housing_density: <?php
echo($state[7]); ?> }
<?php $first = false; } ?>
];
 
var axmin = {};
var axmax = {};
 
for( axind in axes )
{
        axmin[ axes[axind] ] = 100000000;
        axmax[ axes[axind] ] = -100000000;
}
for( ind in data )
{
        row = data[ind];
        for( axind in axes )
        {
          axis = axes[axind];
          if ( row[axis] < axmin[axis] )
            axmin[axis] = row[axis];
 
          if ( row[axis] > axmax[axis] )
            axmax[axis] = row[axis];
        }
}
 
function cleargraph( )
{
        graph = document.getElementById( "graph" );
        graph.innerHTML = "";
}
 
function adddot( value, size, x, y, text )
{
      var left = x - ( size / 2 );
      var top = width - ( y + ( size / 2 ) );
 
      var cleft = "auto";
      var ctop = "auto";
      var cright = "auto";
      var cbottom = "auto";
 
      if ( left < 0 ) { cright = ( left * -1 ) + "px"; }
      if ( left + size > width ) { cleft = ( width - left ) + "px"; }
      if ( top < 0 ) { ctop = ( top * -1 ) + "px"; }
      if ( top + size > height ) { cbottom = ( height - top ) + "px"; }
 
      if ( value <= 0.25 )
             img = "ltgray.gif";
      else if ( value <= 0.50 )
             img = "gray.gif";
      else if ( value <= 0.75 )
             img = "dkgray.gif";
      else
             img = "black.gif";
 
    html = "<img src=\""+img+"\" width=\""+size+"\" height=\""+size+"\" ";
    html += "style=\"position:absolute;left:"+left+"px;top:"+top+"px;";
    html += "clip:rect( "+ctop+" "+cleft+" "+cbottom+" "+cright+" );";
    html += "\"\"alert(\'"+text+"\')\"/>";
 
    graph = document.getElementById( "graph" );
    graph.innerHTML += html;
}
 
function calculate_value( row, field, min, max )
{
      var val = row[ field ] - axmin[ field ];
      var scale = ( max - min ) / ( axmax[ field ] - axmin[ field ] );
      return min + ( scale * val );
}
 
function drawgraph( )
{
      cleargraph( );
 
      var xvar = document.getElementById( "bottom" ).value;
      var yvar = document.getElementById( "side" ).value;
      var sizevar = document.getElementById( "size" ).value;
      var valuevar = document.getElementById( "color" ).value;
 
      for( rowind in data )
      {
             var row = data[rowind];
             var x = calculate_value( row, xvar, 5, width - 5 );
             var y = calculate_value( row, yvar, 5, height - 5 );
             var size = calculate_value( row, sizevar, 5, 30 );
             var value = calculate_value( row, valuevar, 0, 1 );
             adddot( value, size, x, y, row.state );
        }
}
 
function buildselect( axis, current )
{
        var html = "<select\""+axis+"\" onchange=\"drawgraph( )\">";
        for( axind in axes )
        {
        var selected = "";
        if ( axes[axind] == current )
          selected = " selected=\"true\"";
        html += "<option value=\""+axes[axind]+"\""+selected+">"+axes[axind]+"
          </option>";
      }
      html += "</select>";
      document.write( html );
}
</script>
</head>
<body onload="drawgraph( );">
Side: <script language="Javascript">
buildselect( "side", "population" );</script>
Bottom: <script language="Javascript">
buildselect( "bottom", "housing_units" );</
script>
Size: <script language="Javascript">
buildselect( "size", "total_area" );</script>
Color: <script language="Javascript">
buildselect( "color", "total_water" );</
script>
<divcolor: rgb(153, 0, 0);">300px); width:300px; height:300px;">
</div>
</body>
</html>

The script starts by creating the data array, first in PHP and then in JavaScript. The data needs to be available to JavaScript so that the graph can be dynamically built on the fly using DHTML. Once the data is loaded into the page, the rest is left up to the browser.

The first thing the browser does is create the drop downs using the buildselect( ) function. Then, the onload() event fires on the body tag, which calls the drawgraph() function. This function in turn creates a new HTML string that's made up of lots of img tags, one for each state. The size of the image, as well as the position of the image on the graph, depends on which data attributes are assigned to what graph attributes via the drop down. Once the graph is created, the drawgraph() function sets the inner HTML of the graph <div> tag to the new HTML, rendering all of the images.

If the user selects a different attribute with one of the drop downs, the drawgraph( ) function is called again, and the graph is updated.

Running

Upload the PHP page and the images to the server, and then navigate to the page in your web browser. You should see something along the lines of Figure 1. Now use the combo boxes to assign different variables to the different portions of the graph. The Side drop down changes the Y axis. The Bottom drop down changes the X axis. The Size drop down sets which of the attributes will alter the size of the ball, and the Color drop down assigns a data attribute to the color of the ball.

The Y axis represents housing units, and land area increases along the X axis. While most of the plot appears closely packed, there are a few outliers. Click on one of these to see which data point is represented; for instance, clicking on the black ball in the lower righthand corner results in the pop up shown in Figure 2.

This tells me that, not surprisingly, Alaska has the largest total size but has very few housing units. The size of the ball tells me that Alaska has a large amount of land mass as well. I'm not surprised by the size of the land mass, but the very low housing units number is somewhat interesting. There are also two other outliers: the medium gray ball in the middle of the graph (Texas), and the ball at the very top of the graph (California).

Figure 1. The scatter plot after some experimentation

Figure 2. After clicking on the ball in the lower-right corner


[3076]

Use spinners to divide your page content into sections, each of which you can show or hide individually.

The Code

The code for index.php is shown in Example 1.

Example 1. PHP allowing for user selection of a specific spinner
<?php
function start_section( $id, $title )
{
?>
<table cellspacing="0" cellpadding="0">
<tr>
<td width="30" valign="top">
<a href="javascript: void twist('<?php echo($id); ?>');">
<img src="up.gif" border="0""img_<?php echo($id); ?>"/>
</a>
</td>
<td width="90%">
<h1><?php echo( $title ); ?></h1>
<div
  id="<?php echo($id); ?>">
<?php
}
function end_section( )
{
?>
</div>
</td>
</tr>
</table>
<?php
}
function spinner_header( )
{
?>
<style type="text/css">
 
body { font-family: arial, verdana; }
h1 { font-size: medium; border-bottom: 1px solid black; }
.spin-content{font-size:small;margin-left:10px;padding:10px;}
</style>
<script language="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.visibility = "visible";
  }
  else
  {
        imgobj.src = "up.gif";
        divobj.style.visibility = "hidden";
        divobj.style.position = "absolute";
  }
}
</script>
<?php
}
?>
<html>
<head>
<?php spinner_header( ) ?>
</head>
<body>
<?php start_section( "one", "Report part one" ) ?>
This report will tell you a lot of stuff you didn't
know before.
And that's good.
Because that's what a report should do.
But it will tell you so much that it needs to be
rolled up into sections
so that you don't have to gasp as you see it all at once.
<?php end_section( ) ?>
<?php start_section( "two", "Report part two" ) ?>
This is a table of numbers and such:<br/>
<table>
<tr><th>State</th><th>Total</th></tr>
<tr><td>CA</td><td>$35M</td></tr>
<tr><td>PA</td><td>$22M</td></tr>
<tr><td>NC</td><td>$5M</td></tr>
<tr><td>FL</td><td>$15M</td></tr>
</table>
<?php end_section( ) ?>
</body>
</html>

The script starts by defining the start_section and end_section functions, which bracket the blocks of content on the page that will be shown (or hidden) interactively. The top section also defines a spinner_header function that will define the CSS and JavaScript used by the DHTML portion of the system.

The start_section function creates a table where the first column has the spinner graphic, and the second has the title of the section and a div element that will hold the content. The div element is initially set to be invisible, and its position attribute is set initially to "absolute" (a div element that is positioned as "relative" will still be accounted for in the layout). To make the div element and its content disappear, the position attribute's value is set to "absolute"; it can then be set back to "relative" for a reappearance.

Running

Upload the code and images to the server, and point your browser at index.php. You should see something that looks like Figure 1

Figure 1. The sections closed up

Click on the arrow next to the first part of the report, and watch it spin to expose the report section (as shown in Figure 2).

Figure 2. The first section opened up

When writing code that does dynamic repositioning, as with this hack, it's very important to test it on every browser you intend to support. Positioning visible and invisible elements is one of those "gotcha" areas in DHTML.

[3075]

Use DHTML to position sticky drop-down windows relative to keywords in your HTML.

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. That way, the user can click on the word and get more contextual information, all without scrolling or lots of mouse movement.

The Code

Save the code in Example 1 as index.php.

Example 1. PHP and JavaScript cooperate to make drop-down stickies work
<?php
$nextid = 1;
function start_link( $text )
{
  global $nextid;
  $idtext = "a"+$nextid;
 
?>
<a href="javascript: void drop( '<?php echo($idtext); ?>' );">
<span"a_<?php echo($idtext); ?>"><?php echo($text); ?>
</span></a>
<div"<?php echo($idtext); ?>"
class="drop">
<table cellspacing="0" cellpadding="0" width="170"><tr>
<td valign="top" width="20">
<a href="javascript: void close(<?php echo($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">
body { font-family: arial, verdana; }
.drop {
  padding: 5px;
  font-size: small;
  background: #eee;
  border: 1px solid black;
  position: absolute;
}
</style>
<script language="Javascript">
function drop( sid )
{
  aobj = document.getElementById( "a_"+sid );
  divobj = document.getElementById( sid );
  divobj.style.top = aobj.offsetBottom+10;
  divobj.style.left = aobj.offsetLeft+10;
  divobj.style.visibility = "visible";
}
function close( sid )
{
  divobj = document.getElementById( sid );
  divobj.style.visibility = "hidden";
}
</script>
<?php
}
?>
 
<html>
<head>
<?php link_header( ); ?>
</head>
<body>
Hey <?php start_link( "this is interesting" ); ?>
That really<br/>
Is interesting <?php end_link( ); ?>. How about that.

The popup will go over text and all that.<br/>
And it will stay up until it's dismissed with the close
button.
</body>
</html>

The script defines three functions at the top of the file: start_link, end_link, and link_header. The call to start_link takes the text of the link as an argument. The contents of the drop-down box are then supplied, and the end_link call is made.

Running

Copy the code and the images to the server. Point your browser to the index.php script and you will see something similar to Figure 1.

Figure 1. A clickable keyword in the document

Now click on the link and you will get the drop-down box with a close icon, as shown in Figure 2.

Figure 2. The drop down positioned under the link


[3074]

Use PHP to build a navigation menu widget that works consistently across your site.

Writing the navigation menu for your site can be a pain. You don't want to write the same code over and over on every page. Ideally, you would have a PHP menu function that would render the menu with the current page highlighted. This hack gives you that simple menu function (for the low cost of this book, no less!).

The Code

Save the code in Example 1, which demonstrates the use of menu.php as index.php.

Example 1. Using the menu library
<?php
require_once( "menu.php" );
 
$page = "home";
if ( $_GET['page'] )
               $page = $_GET['page'];
?>
<html>
<head>
<title>Page - <?php echo($page); ?></title>
<?php echo menu_css( ); ?>
</head>
<body>
<table cellspaceing="0" cellpadding="5">
<tr>
<td width="200" valign="top">
<?php page_menu( $page ); ?>
</td>
<td width="600" valign="top">
Page: <?php echo( $page ); ?>
 
</td>
</tr>
</table>
</body>
</html>

Example 2 shows the library, which is surprisingly simple.

Example 2. Making everything work with the PHP library, menu.php
<?php
function menu_css( ) {
?>
<style type="text/css">
.menu-inactive, .menu-active {
               padding: 2px;
               padding-left: 20px;
               font-family: arial, verdana;
}
.menu-inactive { background: #ddd; }
.menu-active { background: #000; font-weight: bold; }
.menu-inactive a { text-decoration: none; }
.menu-active a { color: white; text-decoration: none; }
</style>
<?php
}
 
function menu_item( $id, $title, $current ) {
$class = "menu-inactive";
if ( $current == $id )
               $class = "menu-active";
?>
<tr><td"<?php echo($class); ?>">
<a href="index.php?page=<?php echo( $id ); ?>">
<?php echo( $title ); ?>
</a>
</td></tr>
<?php
}
 
function page_menu( $page ) {
?>
<table width="100%">
<?php menu_item( 'home', 'Home', $page ); ?>
<?php menu_item( 'faq', 'FAQ', $page ); ?>
<?php menu_item( 'download', 'Download', $page ); ?>
<?php menu_item( 'links', 'Links', $page ); ?>
<?php menu_item( 'credits', 'Credits', $page ); ?>
</table>
<?php
}
?>

index.php creates the menu by calling the page_menu function and specifying the page ID. The ID of the page is used to decide which menu item is selected. The index.php script also calls the menu_css function to set up the CSS styles for the menu.

You can change the makeup of the menu by altering the bottom portion of the menu.php file to add or remove menu items. You can also change the look and feel of the menu by altering the CSS class definitions in the menu_css function.

Running

Upload the code to the server and point your browser at index.php. Your display should look like Figure 1.

Figure 1. The home page

Now click on the FAQ link; you should see something like Figure 2.

Figure 2. The FAQ page


[3073]
If you remember writing CGI applications in C in your early days of web application development, you know how tedious form processing can be. With PHP's register_globals directive enabled, the complexity of parsing raw form data is taken care of for you, and global variables are created from numerous remote sources. This makes writing PHP applications very easy and convenient, but it also poses a security risk.

In truth, register_globals is unfairly maligned. Alone, it does not create a security vulnerabilitya developer must make a mistake. However, two primary reasons you should develop and deploy applications with register_globals disabled are that it:

  • Can increase the magnitude of a security vulnerability

  • Hides the origin of data, conflicting with a developer's responsibility to keep track of data at all times

All examples in this book assume register_globals to be disabled. Instead, I use superglobal arrays such as $_GET and $_POST. Using these arrays is nearly as convenient as relying on register_globals, and the slight lack of convenience is well worth the increase in security.

[3072]
Strony: [01] [02] [03]