Thursday, March 29, 2007

Tuesday, March 27, 2007

How to add keyboard shortcuts to your website

By Justin Silverton

The following javascript code will allow you to add keyboard shortcuts to any webpage.

The code

(put this on any page where you want keyboard shortcuts)

I can't put the HTML code please refer:- Html Code

(put this in a file called shortcut.js and upload to the same directory as the webpage with the above code). This example will display an alert message when the escape key is pressed.

function keyShortcut() {
var e = window.event;
var code = e.keyCode;
if (code == 112) { //checks for the escape key
alert('escape key pressed');
}
}

The following are some more keyboard codes that can be used within the above script (in the if code == X, where X is one of the codes below).

key Code
tab 9
enter 13
leftwindow key 91
right window key 92
f1 112
f2 113
f3 114
f4 115
f5 116
f6 117
f7 118
f8 119
f9 120
f10 121
f11 122
f12 123

Saturday, March 17, 2007

PHP Optimization Tricks

There are a number of tricks that you can use to squeeze the last bit of performance from your scripts. These tricks won't make your applications much faster, but can give you that little edge in performance you may be looking for.

1.When incrementing or decrementing the value of the variable $i++ happens to be a tad slower then ++$i. This is something PHP specific and does not apply to other languages, so don't go modifying your C or Java code thinking it'll suddenly become faster, it won't.

2.When working with strings and you need to check that the string is either of a certain length you'd understandably would want to use the strlen() function. But Calling isset() happens to be faster then strlen() because unlike strlen(), isset() is a language construct and not a function meaning that it's execution does not require function lookups and lowercase. This means you have virtually no overhead on top of the actual code that determines the string's length.

Ex.
if (strlen($foo) <> 1, "oranges" => 1, "mangoes" => 1, "tomatoes" => 1, "pickles" => 1);
if (isset($keys['mangoes'])) { ... }

The bottom search mechanism is roughly 3 times faster.

9.file including and requiring.

First, you should only use require if you KNOW you will need that file on that page. If you MIGHT use it, use
include instead because PHP opens up all files that are required, whether the script gets there or not. To help out the programmer,
I suggest using "include_once" and "require_once".

Second, get your source file sizes as small as possible and only include/require files you absolutley must have.
If you only need one function in a file, consider breaking that function into its own file. I found on my system
that for every KB of source code that was included/required, I lost one transaction per second (tps). This may
not lead to perfectly organized code, but if speed is a concern, it is definitley worth it.

10.true is faster than TRUE
How come true is faster than TRUE?
This is because when looking for constants PHP does a hash lookup for name as is. And since names are always stored lowercased, by using them you avoid 2 hash lookups.

11.Perl-regexps are faster than POSIX-regexps
http://www.oreilly.com/catalog/regex/ This books explains regex and why a posix regex is slower.

12.FOR vs. WHILE vs. DO-WHILE
just out of curiosity I wanted to see which one of these structures are faster. I believed that "for" will be the fastest but the tests proved I was wrong.

for: 2.078712940216064
while: 1.981828927993774
do: 1.936743974685669

For 2,000,000 iterations the do-while structure is almost 0.15 seconds faster than the for structure. This won't mean very much for small sites but in complex application where you'll have to handle many hits it will make a difference.

13.Here are two tips for loops. If the number of iterations in a loop is low, you might get some performance gain from replacing the loop with a number of statements. For example, consider a for loop that sets 10 values in an array. You can replace the loop with 10 statements, which is a duplication of code, but may execute slightly faster.

Also, don't recompute values inside a loop ex:- count(arrname) .The price for coding in this style was a slight hit in performance, as the loop calls the count function repeatedly.

If you know or have any additional optimization tricks let me know.

References:-
http://ilia.ws/archives/12-PHP-Optimization-Tricks.html
//Zend

How to use MySQL REPLACE function

Here’s a MySQL query fuction that’s easy to forget about: REPLACE. Let’s say I have a bunch of records in a field with http://www and want to quickly change all to http://. Here’s the syntax to update:

UPDATE tdurl_1 SET URL = REPLACE(URL, ‘http://www.tdurl.com/’,'http://tdurl.com/’);

Tuesday, February 20, 2007

Make images fly with JavaScript

From ibzi's blog

JavaScript can be quite fun, especially when you can use it on websites you don’t even own. Let me explain — If you visit a website and then clear the address bar and enter something like javascript:alert('javascript rocks'); you will see that the JavaScript actually executes. Try some of these examples (Just enter it into the address bar and Enter.):

javascript:alert(document.location.href);
javascript:document.bgColor='#FF00FF';void(0);

Keeping this in mind, you can go to great lengths. In fact, have a look at what code I came across. When you enter this code into your browser, the images start to fly in a solar-system like way. Try it out.

Flying images on Amazon.com

Here is the JavaScript for it, just copy it into your address bar and enter. Take note that this effect doesn’t work for all sites, so don’t start restarting your browsers/computer if one site doesn’t work.


javascript:R=0; x1=.1; y1=.05; x2=.25; y2=.24; x3=1.6; y3=.24; x4=300; y4=200; x5=300; y5=200; DI=document.images; DIL=DI.length; function A(){for(i=0; i-DIL; i++){DIS=DI[ i ].style; DIS.position='absolute'; DIS.left=Math.sin(R*x1+i*x2+x3)*x4+x5; DIS.top=Math.cos(R*y1+i*y2+y3)*y4+y5}R++}setInterval('A()',5); void(0);

Tuesday, January 23, 2007

Mysql Tip

If you insert a row, and needs it the generated id for subsequent inserts into other tables.. i hope every body would have faced this: Here is the cool and simple example..

CREATE TABLE customers
(custid INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name CHAR(40) UNIQUE);
CREATE TABLE sales
(salesid INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
custid INT UNSIGNED NOT NULL,
prodid INT UNSIGNED NOT NULL);
INSERT INTO customers VALUES (NULL,'Some Company');
SET @custid = LAST_INSERT_ID();
INSERT INTO sales VALUES (NULL,@custid,1234);
...

The value returned by LAST_INSERT_ID() is unique for this connection.

Friday, January 12, 2007

Which way to get the PHP self script name is the fastest?

From the WebDevLogs.com blog today, there's some benchmarking results from Mgcci's look at PHP's methods for grabbing some common data the script's own name. This includes the magic call to __FILE__: The result shows that __FILE__ is the fastest, so use that when you don't have to use any other method to find the script's self. __FILE__ is a built in constant show the location of the running script.

__FILE__;0.000740
$_SERVER["PHP_SELF"];0.001425
$_SERVER["SCRIPT_NAME"];0.001496
$_SERVER["REQUEST_URI"];0.001509
getenv("REQUEST_URI");0.003845
getenv("SCRIPT_NAME");0.003519
getenv("SCRIPT_URL");0.003480

Friday, December 29, 2006

Zip Code To Location Validation

Jason Palmer has a function which make sure the zip code entered by user matches the city and state upon verification function return true, otherwise false. Here goes the post from him..

Recently, a client was interested in verifying that any inputted zip code was matched correctly with the city and state the user provided. This can be a very valuable and important thing to verify, especially if you are shipping items.

Using the CodeBump GeoPlaces Web Service I constructed a function which takes three parameters (zip, city, state) and does a case-insensitive comparison to make sure that the given zip code matches the city and state. Upon verification the function will return true. Otherwise, it returns false.

The GeoPlaces Web Service requires a paid membership. Once you receive a subscription, CodeBump will send you a valid subscriptionID and that is the only thing you will have to provide for this function to work correctly.

<?PHP
//Written by Jason Palmer, 2006.
//Use as you please just please reference back to:
//http://www.jason-palmer.com/

//Returns true on success, and false on failure.
function zip_2_loc($zip, $city, $state)
{
//Provide your subscriptionID
$subscriptionID = ‘;

//Construct the URL
$url = "http://codebump.com/services/placelookup.asmx/
GetPlacesInside
";
$url .= "?AuthenticationHeader=" . $subscriptionID;
$url .= "&place=" . $zip . "&state=";

//Open the URL and read contents
$contents = fopen($url, "r");
$data = fread($contents, 8192);

//Convert XML data to array
$xml = new SimpleXMLElement($data);

foreach($xml->GeoPlaceDistance as $key => $value)
{
//Match case insensitive
if(strtolower($city) == strtolower($value->ToPlace)
&& strtolower($state) == strtolower($value->ToState))
{
//Match
return true;
}
}
return false;
}
?>

Saturday, December 16, 2006

A better RegEx pattern for matching e-mail addresses

Posted in Tiffany B Brown Blog.

Below is a more refined version.

^[-+.\w]{1,64}@[-.\w]{1,64}\.[-.\w]{2,6}$

Just as with the previous pattern, this one will match most valid e-mail addresses including:

  • Addresses with periods and plus signs (e.g. ‘tiffany.brown’ or ‘hotc0derch1ck+todolist’)
  • Top-level British and Australian domain names such as ‘.co.uk’ and ‘.com.au’
  • New top-level domains such as ‘.museum’ and ‘.travel’

This pattern takes advantage of the \w character type. It’s a simpler way of waying “a - z (both upper and lower case), 0 - 9 and the underscore character” (though for many languages, \w means any alphanumeric character).

It also checks to see whether a user or domain name contains at least one, but no more than 64 alphanumeric characters. Sixty-four is the maximum character length for user and domain names under SMTP.

This pattern should work with most regular expression engines.

Compressing files in PHP

by Justin Silverton

Zlib compression has been built into php since version 3 and it can be used to compress the output of your php applications (which can significantly decrease the amount of bandwidth of a page), but what you can also do is compress any file accessible from your webserver.

The code

The following are two functions: compress and uncompress, which can compress and uncompress a specified file.

function uncompress($srcName, $dstName) {
$string = implode(”", gzfile($srcName));
$fp = fopen($dstName, “w”);
fwrite($fp, $string, strlen($string));
fclose($fp);
}

function compress($srcName, $dstName)
{
$fp = fopen($srcName, “r”);
$data = fread ($fp, filesize($srcName));
fclose($fp);

$zp = gzopen($dstName, “w9″);
gzwrite($zp, $data);
gzclose($zp);
}

compress(”test.php”,”test.gz”);
uncompress(”test.gz”,”test2.php”);

Source code can be downloaded here

Description of related zlib functions

gzclose — Close an open gz-file pointer
gzcompress — Compress a string
gzencode — Create a gzip compressed string
gzeof — Test for end-of-file on a gz-file pointer
gzfile — Read entire gz-file into an array
gzgetc — Get character from gz-file pointer
gzgets — Get line from file pointer
gzgetss — Get line from gz-file pointer and strip HTML tags
gzinflate — Inflate a deflated string
gzopen — Open gz-file
gzpassthru — Output all remaining data on a gz-file pointer