Thursday 4 October 2012

Image Resize and Cropping Using Php

 # ====================================================================#
 IMAGE RESIZE CLASS AS BELOW
 # ====================================================================#
class resize
        {
            // *** Class variables
            private $image;
            private $width;
            private $height;
            private $imageResized;

            function __construct($fileName)
            {
                // *** Open up the file
                $this->image = $this->openImage($fileName);

                // *** Get width and height
                $this->width  = imagesx($this->image);
                $this->height = imagesy($this->image);
            }

            ## --------------------------------------------------------

            private function openImage($file)
            {
                // *** Get extension
                $extension = strtolower(strrchr($file, '.'));

                switch($extension)
                {
                    case '.jpg':
                    case '.jpeg':
                        $img = @imagecreatefromjpeg($file);
                        break;
                    case '.gif':
                        $img = @imagecreatefromgif($file);
                        break;
                    case '.png':
                        $img = @imagecreatefrompng($file);
                        break;
                    default:
                        $img = false;
                        break;
                }
                return $img;
            }

            ## --------------------------------------------------------

            public function resizeImage($newWidth, $newHeight, $option="auto")
            {
                // *** Get optimal width and height - based on $option
                $optionArray = $this->getDimensions($newWidth, $newHeight, $option);

                $optimalWidth  = $optionArray['optimalWidth'];
                $optimalHeight = $optionArray['optimalHeight'];


                // *** Resample - create image canvas of x, y size
                $this->imageResized = imagecreatetruecolor($optimalWidth, $optimalHeight);
                imagecopyresampled($this->imageResized, $this->image, 0, 0, 0, 0, $optimalWidth, $optimalHeight, $this->width, $this->height);


                // *** if option is 'crop', then crop too
                if ($option == 'crop') {
                    $this->crop($optimalWidth, $optimalHeight, $newWidth, $newHeight);
                }
            }

            ## --------------------------------------------------------
           
            private function getDimensions($newWidth, $newHeight, $option)
            {

               switch ($option)
                {
                    case 'exact':
                        $optimalWidth = $newWidth;
                        $optimalHeight= $newHeight;
                        break;
                    case 'portrait':
                        $optimalWidth = $this->getSizeByFixedHeight($newHeight);
                        $optimalHeight= $newHeight;
                        break;
                    case 'landscape':
                        $optimalWidth = $newWidth;
                        $optimalHeight= $this->getSizeByFixedWidth($newWidth);
                        break;
                    case 'auto':
                        $optionArray = $this->getSizeByAuto($newWidth, $newHeight);
                        $optimalWidth = $optionArray['optimalWidth'];
                        $optimalHeight = $optionArray['optimalHeight'];
                        break;
                    case 'crop':
                        $optionArray = $this->getOptimalCrop($newWidth, $newHeight);
                        $optimalWidth = $optionArray['optimalWidth'];
                        $optimalHeight = $optionArray['optimalHeight'];
                        break;
                }
                return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
            }

            ## --------------------------------------------------------

            private function getSizeByFixedHeight($newHeight)
            {
                $ratio = $this->width / $this->height;
                $newWidth = $newHeight * $ratio;
                return $newWidth;
            }

            private function getSizeByFixedWidth($newWidth)
            {
                $ratio = $this->height / $this->width;
                $newHeight = $newWidth * $ratio;
                return $newHeight;
            }

            private function getSizeByAuto($newWidth, $newHeight)
            {
                if ($this->height < $this->width)
                // *** Image to be resized is wider (landscape)
                {
                    $optimalWidth = $newWidth;
                    $optimalHeight= $this->getSizeByFixedWidth($newWidth);
                }
                elseif ($this->height > $this->width)
                // *** Image to be resized is taller (portrait)
                {
                    $optimalWidth = $this->getSizeByFixedHeight($newHeight);
                    $optimalHeight= $newHeight;
                }
                else
                // *** Image to be resizerd is a square
                {
                    if ($newHeight < $newWidth) {
                        $optimalWidth = $newWidth;
                        $optimalHeight= $this->getSizeByFixedWidth($newWidth);
                    } else if ($newHeight > $newWidth) {
                        $optimalWidth = $this->getSizeByFixedHeight($newHeight);
                        $optimalHeight= $newHeight;
                    } else {
                        // *** Sqaure being resized to a square
                        $optimalWidth = $newWidth;
                        $optimalHeight= $newHeight;
                    }
                }

                return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
            }

            ## --------------------------------------------------------

            private function getOptimalCrop($newWidth, $newHeight)
            {

                $heightRatio = $this->height / $newHeight;
                $widthRatio  = $this->width /  $newWidth;

                if ($heightRatio < $widthRatio) {
                    $optimalRatio = $heightRatio;
                } else {
                    $optimalRatio = $widthRatio;
                }

                $optimalHeight = $this->height / $optimalRatio;
                $optimalWidth  = $this->width  / $optimalRatio;

                return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
            }

            ## --------------------------------------------------------

            private function crop($optimalWidth, $optimalHeight, $newWidth, $newHeight)
            {
                // *** Find center - this will be used for the crop
                $cropStartX = ( $optimalWidth / 2) - ( $newWidth /2 );
                $cropStartY = ( $optimalHeight/ 2) - ( $newHeight/2 );

                $crop = $this->imageResized;
                //imagedestroy($this->imageResized);

                // *** Now crop from center to exact requested size
                $this->imageResized = imagecreatetruecolor($newWidth , $newHeight);
                imagecopyresampled($this->imageResized, $crop , 0, 0, $cropStartX, $cropStartY, $newWidth, $newHeight , $newWidth, $newHeight);
            }

            ## --------------------------------------------------------

            public function saveImage($savePath, $imageQuality="100")
            {
                // *** Get extension
                $extension = strrchr($savePath, '.');
                   $extension = strtolower($extension);

                switch($extension)
                {
                    case '.jpg':
                    case '.jpeg':
                        if (imagetypes() & IMG_JPG) {
                            imagejpeg($this->imageResized, $savePath, $imageQuality);
                        }
                        break;

                    case '.gif':
                        if (imagetypes() & IMG_GIF) {
                            imagegif($this->imageResized, $savePath);
                        }
                        break;

                    case '.png':
                        // *** Scale quality from 0-100 to 0-9
                        $scaleQuality = round(($imageQuality/100) * 9);

                        // *** Invert quality setting as 0 is best, not 9
                        $invertScaleQuality = 9 - $scaleQuality;

                        if (imagetypes() & IMG_PNG) {
                             imagepng($this->imageResized, $savePath, $invertScaleQuality);
                        }
                        break;

                    // ... etc

                    default:
                        // *** No extension - No save.
                        break;
                }

                imagedestroy($this->imageResized);
            }


            ## --------------------------------------------------------

        }

 # ====================================================================#
 INCLUDE THIS CLASS AS FOLLOWS
 # ====================================================================#

# Include Image Resize Class #
include("../includes/resize-class.php");

// *** 1) Initialise / load image
$resize = new resize('Image Path Put Here')

// *** 2) Resize image (options: exact, portrait, landscape, auto, crop)
 $resize -> resizeImage('Image Width Put Here','Image Height Put Here','exact');
          
 // *** 3) Save image
 $resize-> saveImage('Image Path Put Here');

Saturday 29 September 2012

SImple Ajax Pagination

<?php
/*
 ********************************************************************
THIS IS PAGINATION CLASS FILE
 ********************************************************************
*/
 class Paginate {

    /**
     * Which method of pagination are we using? AJAX is the only one for right now.
     * @var string
     */
    public $method = 'ajax';

    /**
     * How many records do we want per page
     * @var integer
     */
    public $rows_per_page = 20;

    /**
     * This variable holds the number of pages we will have
     * @var integer
     */
    public $pages = 0;

    /**
     * Holds the current page number. Default is page 1.
     * @var integer
     */
    public $current_page_number = 1;

    /**
     * How many records to display in SQL.
     * @var integer
     */
    public $sql_offset = 0;

    /**
     * This will be appended to the SQL query that is run to retrieve records
     * @var string
     */
    public $sql_append = '';

    /**
     * Holds total records received from query
     * @var integer
     */
    public $query_total_records = 0;

    /**
     * Holds the output for the generated pagination links
     * @var string
     */
    public $links = '';

    /**
     * How many links to display before and after the current page
     * @var integer
     */
    public $link_spread = 4;

    /**
     * Given the total records returned by a query we can set up how many
     * pages are needed.
     * @param   int $query_total_records is the total record count of the
     *          returned query
     */
    public function set_pages($query_total_records) {
        $this->query_total_records = $query_total_records;
        $this->pages = ceil($this->query_total_records / $this->rows_per_page);
    }

    /**
     * This method will set sql_append with the correct offset to append
     * to our queries so that page navigation works.
     */
    public function set_query_offset_append() {
        if ($this->current_page_number > $this->pages)
            $this->current_page_number = $this->pages;
        if ($this->current_page_number < 1)
            $this->current_page_number = 1;
        // calculate offset bases on rows per page
        $this->sql_offset = ($this->current_page_number - 1) * $this->rows_per_page;
        // if we have more records than rows per page append offset
        if ($this->query_total_records > $this->rows_per_page)
            $this->sql_append = " LIMIT {$this->sql_offset}, {$this->rows_per_page}";
    }

    /**
     * This method will build pagination links and set the
     * pagination_links with the proper HTML
     * @param   array $params used to give extra options
     *          class = span class
     *          class_current = span class of the current page number
     *          function = name of the function that will do the AJAX magic whatever(pageNum)
     */
    public function build_pagination_links($params = array()) {
        if ($this->current_page_number > 1) {
            $this->links = '<span ';
            $this->links .= (!empty($params['class']))      ? 'class="'.$params['class'].'"' : '';
            $this->links .= '><a href="#" ';
            $this->links .= (!empty($params['function']))   ? 'onclick="'.$params['function'].'(1);"' : '';
            $this->links .= '><< First</a></span> <span ';
            $this->links .= (!empty($params['class']))      ? 'class="'.$params['class'].'"' : '';
            $this->links .= '><a href="#" ';
            $prev_page = $this->current_page_number - 1;
            $this->links .= (!empty($params['function']))   ? 'onclick="'.$params['function'].'(' . $prev_page . ');"' : '';
            $this->links .= '>< Prev</a></span> ';
        }

        // loop over the rest of the links
        for ($i=($this->current_page_number-$this->link_spread);$i<(($this->current_page_number+$this->link_spread)+1);$i++) {
            if (($i > 0) && ($i <= $this->pages)) {
                if ($i == $this->current_page_number) {
                    // current page link
                    $this->links .= '<span ';
                    $this->links .= (!empty($params['class_current'])) ? 'class="'.$params['class_current'].'"' : '';
                    $this->links .= '><b>'.$i.'</b></span> ';
                } else {
                    // not current link
                    $this->links .= '<span ';
                    $this->links .= (!empty($params['class']))      ? 'class="'.$params['class'].'"' : '';
                    $this->links .= '><a href="#" ';
                    $this->links .= (!empty($params['function']))   ? 'onclick="'.$params['function'].'(' . $i . ');"' : '';
                    $this->links .= '>' . $i . '</a></span> ';
                }

            }
        }

        if ($this->current_page_number != $this->pages) {
            // not on last page        
            $this->links .= '<span ';
            $this->links .= (!empty($params['class']))      ? 'class="'.$params['class'].'"' : '';
            $this->links .= '><a href="#" ';
            $next_page = $this->current_page_number + 1;
            $this->links .= (!empty($params['function']))   ? 'onclick="'.$params['function'].'(' . $next_page . ');"' : '';
            $this->links .= '>Next ></a></span> ';
            $this->links .= '<span ';
            $this->links .= (!empty($params['class']))      ? 'class="'.$params['class'].'"' : '';
            $this->links .= '><a href="#" ';
            $this->links .= (!empty($params['function']))   ? 'onclick="'.$params['function'].'(' . $this->pages . ');"' : '';
            $this->links .= '>Last >></a></span> ';
        }
    }

 }

 ?>

INCLUDE PAGINATION CLASS INTO YOUR PHP CODE

<?php
include('path/to/class/paginate.php');

// query the database for our registration
$db = new Database('host', 'user', 'pass', 'dbname');
$query = "SELECT * FROM REGISTRATION";
$result = $db->query($query);

// get a count of returned  our query
$numCount = $db->num_rows($result);

$pagination = new Paginate();
$pagination->set_pages($numCount);

// now we need to check if we got a page number from POST or GET
if (isset($_POST['page']) && !empty($_POST['page']))
    $pagination->current_page_number = $_POST['page'];

// we need to take care of the offset to append to our sql queries
$pagination->set_query_offset_append();

// now we want to attach the offset to our original query
$query = $query . $pagination->sql_append;
$strQuery = mysql_fetch_asssc($query);

// start output
echo "<div id='pagination'>"

// Now we want to generate our PHP pagination links.
// Notice the last set of key value pair, function is js_paginate, which is the name of JavaScript function
// we will use. js_paginate(page)
$params = array('class'=>'pagination', 'class_current'=>'pagination-current', 'function'=>'js_paginate');
$pagination->build_pagination_links($params);
echo $pagination->links;
echo '<table>';

foreach ($$strQueryas $num => $sqlResult) {
    echo '<tr><td>' . $sqlResult->name . '</td></tr>';
}
?>





USE BELOW JAVASCRIPT FUNCTION HEAD TAG IN SAME PAGE
function js_paginate(page) {
    $('#pagination').load( // this is the id of the div holding our list
        'pagename.php', // the script that handles our listing from above
        {'page':page}
    );
}

//SOME CODE SETTING IN CLASS
$pagination = new Paginate();
// set how many rows to show per page
$pagination->rows_per_page = 10;

// set the link spread 1 2 3 4 (5) 6 7 8 9 of how many links to the left and right of the current page
$pagination->link_spread = 5;

Wednesday 5 September 2012

jQuery Ajax Sending Request

Send data to the server, save some data to the server, and notify the user once it's complete. If the request fails, alert messge will display to user.

var request=$.ajax({
                url:'ajax_filter_search.php',
                data:'action=filterSearch&filterId='+filterId+'&restId='+restId,
                });
           
            // IF REQUEST IS DONE   
            request.done(function(result){
                setTimeout( function() {
                        $('#middlecontent').html(result);
                    }, 800 );   
                });
           
            // IF REQUEST IS FAIL   
            request.fail(function(jqXHR,textStatus) {
              alert( "Request failed: " + textStatus );
            });    

Tuesday 4 September 2012

Simple Php Classes

<?php
class Database {

    private $host;
    private $user;
    private $pass;
    private $name;
    private $link;
    private $error;
    private $errno;
    private $query;

    function __construct($host, $user, $pass, $name = "", $conn = 1) {
        $this -> host = $host;
        $this -> user = $user;
        $this -> pass = $pass;
        if (!empty($name)) $this -> name = $name;      
        if ($conn == 1) $this -> connect();
    }

    function __destruct() {
        @mysql_close($this->link);
    }

    public function connect() {
        if ($this -> link = mysql_connect($this -> host, $this -> user, $this -> pass)) {
            if (!empty($this -> name)) {
                if (!mysql_select_db($this -> name)) $this -> exception("Could not connect to the database!");
            }
        } else {
            $this -> exception("Could not create database connection!");
        }
    }

    public function close() {
        @mysql_close($this->link);
    }

    public function query($sql) {
        if ($this->query = @mysql_query($sql)) {
            return $this->query;
        } else {
            $this->exception("Could not query database!");
            return false;
        }
    }

    public function num_rows($qid) {
        if (empty($qid)) {         
            $this->exception("Could not get number of rows because no query id was supplied!");
            return false;
        } else {
            return mysql_numrows($qid);
        }
    }

    public function fetch_array($qid) {
        if (empty($qid)) {
            $this->exception("Could not fetch array because no query id was supplied!");
            return false;
        } else {
            $data = mysql_fetch_array($qid);
        }
        return $data;
    }

    public function fetch_array_assoc($qid) {
        if (empty($qid)) {
            $this->exception("Could not fetch array assoc because no query id was supplied!");
            return false;
        } else {
            $data = mysql_fetch_array($qid, MYSQL_ASSOC);
        }
        return $data;
    }

    public function fetch_all_array($sql, $assoc = true) {
        $data = array();
        if ($qid = $this->query($sql)) {
            if ($assoc) {
                while ($row = $this->fetch_array_assoc($qid)) {
                    $data[] = $row;
                }
            } else {
                while ($row = $this->fetch_array($qid)) {
                    $data[] = $row;
                }
            }
        } else {
            return false;
        }
        return $data;
    }

    public function last_id() {
        if ($id = mysql_insert_id()) {
            return $id;
        } else {
            return false;
        }
    }

    private function exception($message) {
        if ($this->link) {
            $this->error = mysql_error($this->link);
            $this->errno = mysql_errno($this->link);
        } else {
            $this->error = mysql_error();
            $this->errno = mysql_errno();
        }
        if (PHP_SAPI !== 'cli') {
        ?>

            <div class="alert-bad">
                <div>
                    Database Error
                </div>
                <div>
                    Message: <?php echo $message; ?>
                </div>
                <?php if (strlen($this->error) > 0): ?>
                    <div>
                        <?php echo $this->error; ?>
                    </div>
                <?php endif; ?>
                <div>
                    Script: <?php echo @$_SERVER['REQUEST_URI']; ?>
                </div>
                <?php if (strlen(@$_SERVER['HTTP_REFERER']) > 0): ?>
                    <div>
                        <?php echo @$_SERVER['HTTP_REFERER']; ?>
                    </div>
                <?php endif; ?>
            </div>
        <?php
        } else {
            echo "+-------+ +-------+\n";
            echo "| +---+ | |       |\n";
            echo "| |   | | |  +----+\n";
            echo "| |   | | |  |     \n";
            echo "| |   | | |  +----+\n";
            echo "| |   | | |       |\n";
            echo "| +---+ | |  +----+\n";
            echo "|  ___  | |  |     \n";
            echo "| (   ) | |  +----+\n";
            echo "|  ---  | |       |\n";
            echo "+-------+ +-------+\n";
            echo "MYSQL ERROR: " . ((isset($this->error) && !empty($this->error)) ? $this->error:'') . "\n";
        };
    }

}
?>

To use this PHP MySQL class an example below:
$db = Database('localhost', 'username', 'password', 'database_name');
// query database
$q = "SELECT * FROM articles ORDER BY id DESC";
$r = $db->query($q);
// if we have a result loop over the result
if ($db->num_rows($r) > 0) {
  while ($a = $db->fetch_array_assoc($r)) {
    echo "{$a['author']} wrote {$a['title']}\n";
  }
}

// fetch array of articles with less code
$q = "SELECT * FROM articles ORDER BY id DESC";
$a = $db->fetch_all_array($q);
if (!empty($a)) {
  foreach ($a as $k => $v) {
    echo "{$v['author']} wrote {$v['title']}\n";
  }
}

Thursday 23 August 2012

Copy Table Row Using DOM Object

// Call this function onClick event in javascript for copying TR
function addRow(tableID)
{
    dml=document.forms['add_products'];// Form Name
               
    // get the number of elements from the document
    len = dml.elements.length;
     for( i=0 ; i<len ; i++)
     {
        //check the textbox with the elements name
            if (dml.elements[i].name=='rest_prod_price[]')
            {
              // if exists do the validation and set the focus to the textbox
                if (dml.elements[i].value=="")
                {
                    alert("Invalid empty data");
                    dml.elements[i].focus();
                    return false;           
                }
            }
     }
   
     var table = document.getElementById(tableID);
    var rowCount = table.rows.length;
    var row = table.insertRow(rowCount);
    var colCount = table.rows[0].cells.length;
   
    for(var i=0; i<colCount; i++)
    {
        var newcell = row.insertCell(i);
        newcell.innerHTML = table.rows[0].cells[i].innerHTML;
    }
}

 // Call this function onClick event in javascript for delete TR
function deleteRow(tableID)
{   
     var table = document.getElementById(tableID);
    var rowCount = table.rows.length;
    if(rowCount > 1)
    {table.deleteRow(rowCount - 1);}
    else
    {alert('No More Control To Delete.');}
   
}

Wednesday 15 August 2012

Secure Login with Ajax and Jquery

NOTE:-testLogin.php page is where you write login code 
 
function CheckLogin(){
var LoginObj = new Object();
LoginObj.UserName = $("#txtUserName").val();
LoginObj.Password = $("#txtPassword").val();
//Define DTO i.e. Data Transfer Object as follows
var DTO = { 'userLogin': LoginObj };
$.ajax({
type: "POST",
url: "testLogin.php/CheckLogin",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(DTO),
success: function(msg) {
if (msg.d)
$(".alertmsg").html("Valid Login");
else
$(".alertmsg").html("Invalid Login");
},
error: function(xhr, status, error) {
alert("An error has occurred during
processing: " + error);
}
});
}

Wednesday 8 August 2012

Html div over Flash or Content over a embed object

 
<object id="player" classid="3540000" name="player" width="300" height="200">
              <param name="movie" value="player-viral.swf" />
              <param name="wmode" value="transparent" />
              <param name="allowfullscreen" value="true" />
              <param name="allowscriptaccess" value="always" />
              <param name="flashvars" value="URL" />
              <embed type="application/x-shockwave-flash"
                id="player2"
              name="player2"
               src="player-viral.swf"
             width="300"
            height="200"
                    wmode="transparent"
 allowscriptaccess="always"
   allowfullscreen="true"
   flashvars="file=URL"
       />
</object>

Tuesday 7 August 2012

PHP History & Information

With an increasing community; PHP is considered today as one of the most famous scripting languages. It is widely used today as a general purpose scripting language, particularly useful for web developments and like other scripting languages; it can also be embedded directly into the HTML code. Within a short span of time, PHP has gained remarkable popularity and its community is increasing rapidly. There are various reasons for that, for instance:
  • PHP, as you may know, is a free software and anyone can download it; use it and it supports various operating systems
  • The syntax of PHP is quite similar to C which makes it more appealing for computer programmers.
  • Whatever you have done with Perl in the past, you can do it with PHP.
  • PHP is web specific and is more powerful than Perl.
  • PHP works equally well and can be deployed on many web servers like Apache, IIS etc
  • PHP scripts can be used for various standard network protocols as well.
PHP, as mentioned earlier, stands for PHP Hypertext Processor. It is an open source software so you can easily download it from its site; www.php.net. PHP is a mixture of various languages like Java, C and Perl. It was designed with the intention of producing dynamic and interactive web pages. It is capable of producing standalone graphical web applications. Another important fact about PHP is that it can be used as a procedural language in order to create complex objects.
PHP was originally a personal project called as Personal Home Page Tools developed by Rasmus Lerdorf in the year 1994. That was the original version of PHP which consisted of some basic web tools, a parser and some macros. After a while, in the year 1997, the parser was again rewritten and this parser became the basis of PHP3 that gained remarkable popularity. After that, PHP continued to grow and version 4 included a new parser with added features. Today, all the PHP implementations are produced by the PHP group.
Now, as you have learnt some basics of PHP, we shall try building a simple PHP application that will demonstrate you and will help you in learning PHP. Carefully go through the following steps:
  • First of all, you must be aware of the fact that you should have some knowledge of HTML because PHP code is directly embedded into HTML code.
  • Remember that all PHP files have an extension of .phtml or .php.
  • If you haven’t downloaded PHP engine and the Web server then download it immediately before you can use your code. For downloading PHP, visit www.php.net/downloads.php and for downloading Apache server, visit http://httpd.apache.org/download.cgi. Carefully follow the instructions given in the manual in order to install PHP and the Web Server.
  • After you have successfully downloaded PHP and the Web Server, you are ready to create your first PHP web page.
  • Open a notepad file and start writing PHP code.
  • PHP syntax is very simple; every scripting block of PHP starts with <?php and ends with ?>. You can place this scripting block anywhere in the document.
  • Enter the following code of the most famous Hello World example in order to learn the basic syntax of PHP
<html>
<body>
<?php
echo “Hello World”;
?>
</body>
</html>
Echo is used to write output to the browser screen. The most important point here to remember is that, like C, every line of code in PHP ends up with a semi colon. Echo can be replaced with print to get the same functionality. If anyone of you has ever worked on C programming language, you would have noticed the similarity between C and PHP. Save the above file with .php extension and open it, you should be able to see Hello World on the browser screen.