Tuesday, July 29, 2008

PHP Email Address Validation

<?Php
function check_email_address($email) {
// First, we check that there's one @ symbol, and that the lengths are right
if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) {
// Email invalid because wrong number of characters in one section, or wrong number of @ symbols.
return false;
}
// Split it into sections to make life easier
$email_array = explode("@", $email);
$local_array = explode(".", $email_array[0]);
for ($i = 0; $i < sizeof($local_array); $i++) {
if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i])) {
return false;
}
}
if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) { // Check if domain is IP. If not, it should be valid domain name
$domain_array = explode(".", $email_array[1]);
if (sizeof($domain_array) < 2) {
return false; // Not enough parts to domain
}
for ($i = 0; $i < sizeof($domain_array); $i++) {
if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i])) {
return false;
}
}
}
return true;
}
?>


Using the function above is relatively simple, as you can see:

<?Php
if (check_email_address($email)) {
    echo $email . ' is a valid email address.';
} else {
    echo $email . ' is not a valid email address.';
}
?>

PHP MySQL Database Class

A class for very basic MySQL database connectivity. Written to reduce redundant code in my own projects aswell as aid in debugging and error reporting during the developement phase. Currently connects to a database, execute external files containing SQL commands, insert and update from an array of key => value pairs, insert and update with sql command, query (one result), query (multiple rows), and dump a select query to a table. The zip file contains the class aswell as a demonstration script.

Download Version 1.0.4: db-1.0.4.zip

Returning an array of variables from PHP function

From a function we can get back a set of variables by using an array. A function returns any variable to the main script by using return statement. Here we will try to return a set of variables by using an array. Our main script will receive the array and we will use while each statement to display all elements of an array.

We will change a script a bit and try to pass ( as input ) a string to the function. This string we will break by using split command and create an array. This array we will return to main script for displaying.

<?Php

function test($my_string){
// creating an array by split command
$my_array=split(" ",$my_string);
return $my_array; // returning the array
}

// sending a string to function as input //
$collect_array=test("Hello welcome to plus2net");

// displaying the elements of the collected array
while (list ($key, $val) = each ($collect_array)) {
echo "$key -> $val <br>";
}

?>

Monday, July 28, 2008

Turnkey PHP shopping cart software

  • Complete ready-to-run PHP shopping cart software

  • No programming required

  • Cost-effective

  • All major ecommerce features

  • Easy design integration in any HTML editor

  • A set of ready-to-use skin templates included

  • Search Engine friendly

  • Online credit card processing

  • Integrated with Google Checkout and PayPal Pro

  • Real-time shipping quotes

  • Order notifications by email and SMS

  • Easy localization

  • Free installation service

  • Free 24/7 customer support

  • WEBSITE: http://www.shop-script.com/

    Thursday, July 24, 2008

    Joomla - Cutting Edge Content Management

    [caption id="attachment_11" align="alignleft" width="165" caption="Joomla"]Joomla[/caption]

    Joomla! is one of the most powerful Open Source Content Management Systems on the planet. It is used all over the world for everything from simple websites to complex corporate applications. Joomla! is easy to install, simple to manage, and reliable.

    Joomla! is different from the normal models for content management software. For a start, it's not complicated. Joomla! has been developed for everybody, and anybody can develop it further. It is designed to work (primarily) with other Open Source, free, software such as PHP, MySQL, and Apache.

    It is easy to install and administer, and is reliable.

    Joomla! doesn't even require the user or administrator of the system to know HTML to operate it once it's up and running.

    To get the perfect Web site with all the functionality that you require for your particular application may take additional time and effort, but with the Joomla! Community support that is available and the many Third Party Developers actively creating and releasing new Extensions for the 1.5 platform on an almost daily basis, there is likely to be something out there to meet your needs. Or you could develop your own Extensions and make these available to the rest of the community.

    Wednesday, July 23, 2008

    Easy PHP Calendar

    The Easy PHP Calendar is a powerful PHP calendar script that is easily integrated into web sites and is simple to customize. This attractive, full-featured calendar is suitable for display on a calendar of events page, home page, or any other page that needs a calendar.
    * The Easy PHP Calendar was formerly known as the Easily Simple Calendar.

    Key Features:



    • mySQL database support

    • Flat-file database support - No mySQL server required!

    • Single events, recurring events and floating events plus multiple categories

    • Complete and easy event and setup administration

    • Mouse-over and pop-up event details

    • Customizable categories and multiple event administrators

    • Rich event descriptions including font sizes/colors and images

    • and much more...


    With the Easy PHP Calendar, you can easily customize colors, font sizes, table sizes and more by adjusting a single CSS file. It's simple to take complete control over the PHP calendar's looks and how it interacts with users! With support for multiple date, time and language formats, the Easy PHP Calendar can be used for anywhere in the world!

    The Easy PHP Calendar is well-supported through the user forums. Take your time to view the online demonstration, download a free trial version, and you'll see that the Easy PHP Calendar is the PHP calendar script for you!
     
    DOWNLOAD

    Monday, July 7, 2008

    Selecting random record from MySQL database table



    The simplest way of selecting random rows from the MySQL database is to use "ORDER BY RAND()" clause in the query.

    Solution 1 [SQL]
    SELECT * FROM `table` ORDER BY RAND() LIMIT 0,1;
    The problem with this method is that it is very slow. The reason for it being so slow is that MySQL creates a temporary table with all the result rows and assigns each one of them a random sorting index. The results are then sorted and returned.

    There are several workarounds to speed things up.

    The basic idea is to get a random number and then select a specific row using this number.

    In the case that all the rows have unique ids we will just have to pick a random number between the smallest and the biggest id and then select the row with id that equals that number. To make this method work when ids are not evenly distributed we will have to use ">=" operator instead of "=" in the last query.

    To get the minimum and maximum id values in the entire table we will use MAX() and MIN() aggregate functions. These functions will return minimum and maximum value in the specified group. The group in our case is all the values of `id` column in our table.

    Solution 2 [PHP]
    $range_result = mysql_query( " SELECT MAX(`id`) AS max_id , MIN(`id`) AS min_id FROM `table` ");
    $range_row = mysql_fetch_object( $range_result );
    $random = mt_rand( $range_row->min_id , $range_row->max_id );
    $result = mysql_query( " SELECT * FROM `table` WHERE `id` >= $random LIMIT 0,1 ");
    As we mentioned this method is limited to tables with unique id for each row. What to do if it's not the case?

    The solution is to use the MySQL LIMIT clause. LIMIT accepts two arguments. The first argument specifies the offset of the first row to return, and the second specifies the maximum number of rows to return. The offset of the initial row is 0 (not 1).

    To calculate the offset to the first row we will generate a random number between 0 and 1 using MySQL's RAND() function. Then we will multiply this number by number of records in the table, which we will get using COUNT() function. Since LIMIT arguments must be integers and not float values we will round the resulting number using FLOOR() function. FLOOR() is an arithmetic function that calculates the largest integer value that is smaller than or equal to the expression. The resulting code will look like this:

    Solution 3 [PHP]
    $offset_result = mysql_query( " SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM `table` ");
    $offset_row = mysql_fetch_object( $offset_result );
    $offset = $offset_row->offset;
    $result = mysql_query( " SELECT * FROM `table` LIMIT $offset, 1 " );
    In MySQL 4.1 and later we can combine two previous methods using subquery like so:

    Solution 4 [SQL]
    SELECT * FROM `table` WHERE id >= (SELECT FLOOR( MAX(id) * RAND()) FROM `table` ) ORDER BY id LIMIT 1;
    This solution has the same weakness as the solution 2 e.g. it only works for tables with unique ids.

    Remember the reason we started looked for alternative ways of selecting random rows? Speed! So how do these methods compare in terms of execution times. I am not going to go into specifics of hardware and software configuration or give precise numbers. The approximate results are:

    • The slowest method is solution 1. Let's say that it took 100% of time to execute.

    • Solution 2 took 79%.

    • Solution 3 - 13%.

    • Solution 4 - 16%.


    The winner is solution 3.

    Friday, July 4, 2008

    Drag N Drop File Upload With Progress Bar

    Make your site more user friendly. With Rad Upload's drag and drop functionality, your visitors can transfer files to your server just as easily as copying from one folder to another.


    The lite edition is available for free download. It does not expire and contains most of the features of the standard edition. Rad Upload Plus has many advanced features such as client side filtering and on the fly GZip compression.

    PHP Captcha Security Images for Anti Spamming

    <?php
    session_start();

    /*
    * File: CaptchaSecurityImages.php
    * Author: Simon Jarvis
    * Copyright: 2006 Simon Jarvis
    * Date: 03/08/06
    * Updated: 07/02/07
    * Requirements: PHP 4/5 with GD and FreeType libraries
    * Link:
    http://www.white-hat-web-design.co.uk/articles/php-captcha.php
    *
    * This program is free software; you can redistribute it and/or
    * modify it under the terms of the GNU General Public License
    * as published by the Free Software Foundation; either version 2
    * of the License, or (at your option) any later version.
    *
    * This program is distributed in the hope that it will be useful,
    * but WITHOUT ANY WARRANTY; without even the implied warranty of
    * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    * GNU General Public License for more details:
    *
    http://www.gnu.org/licenses/gpl.html
    *
    */


    class CaptchaSecurityImages {

    var $font = 'monofont.ttf';

    function generateCode($characters) {
    /* list all possible characters, similar looking characters and vowels have been removed */
    $possible = '23456789bcdfghjkmnpqrstvwxyz';
    $code = '';
    $i = 0;
    while ($i < $characters) {
    $code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
    $i++;
    }
    return $code;
    }

    function CaptchaSecurityImages($width='120',$height='40',$characters='6') {
    $code = $this->generateCode($characters);
    /* font size will be 75% of the image height */
    $font_size = $height * 0.75;
    $image = imagecreate($width, $height) or die('Cannot initialize new GD image stream');
    /* set the colours */
    $background_color = imagecolorallocate($image, 255, 255, 255);
    $text_color = imagecolorallocate($image, 20, 40, 100);
    $noise_color = imagecolorallocate($image, 100, 120, 180);
    /* generate random dots in background */
    for( $i=0; $i<($width*$height)/3; $i++ ) {
    imagefilledellipse($image, mt_rand(0,$width), mt_rand(0,$height), 1, 1, $noise_color);
    }
    /* generate random lines in background */
    for( $i=0; $i<($width*$height)/150; $i++ ) {
    imageline($image, mt_rand(0,$width), mt_rand(0,$height), mt_rand(0,$width), mt_rand(0,$height), $noise_color);
    }
    /* create textbox and add text */
    $textbox = imagettfbbox($font_size, 0, $this->font, $code) or die('Error in imagettfbbox function');
    $x = ($width - $textbox[4])/2;
    $y = ($height - $textbox[5])/2;
    imagettftext($image, $font_size, 0, $x, $y, $text_color, $this->font , $code) or die('Error in imagettftext function');
    /* output captcha image to browser */
    header('Content-Type: image/jpeg');
    imagejpeg($image);
    imagedestroy($image);
    $_SESSION['security_code'] = $code;
    }

    }

    $width = isset($_GET['width']) && $_GET['height'] < 600 ? $_GET['width'] : '120';
    $height = isset($_GET['height']) && $_GET['height'] < 200 ? $_GET['height'] : '40';
    $characters = isset($_GET['characters']) && $_GET['characters'] > 2 ? $_GET['characters'] : '6';

    $captcha = new CaptchaSecurityImages($width,$height,$characters);

    ?>
    Download Link