Saturday, April 6, 2013

Create Responsive HTML Theme in Minutes

Hello friends,

Today in Developer's Blog I will tell you the way to Create Responsive HTML Theme in Minutes.

Friends, most of us just focus on designing html only for web version and not for iPad, iPhone and other Mobile Phones.

Some of us don't know how to create responsive theme and some of us don't design it until our client asks us to do that.

But now a days, as we all know that we always like to keep our self online 24X7 just because we always want to be updated with everything. So we also visit the websites from our cell phones and in U.S., most of the persons uses iPhone and iPad to browse the website instead of Desktop PC. 

So we will have to design Responsive theme now and for that we will have to learn how to do that.

We will not have to do anything fancy to design responsive theme, we will just have to define min and max width of the screen in CSS and it will be applied in that particular device automatically.

So, we will start with the Small Phones with a resolution of 240 x 320.

@media screen and (min-width: 0px) and (max-width: 319px)
{
    // write your CSS here by having maximum width of 319px and it will work in Small Phones
}

Now we will write the CSS for iPhone with a resolution of 320 x 480.

@media screen and (min-width: 320px) and (max-width: 479px)
{
    // whatever CSS you defined for Small Phones will have to be defined here for iPhone.
}

Now we will write the CSS for Small Tablet with a resolution of 480 x 640.


@media screen and (min-width: 480px) and (max-width: 767px)
{
    // whatever CSS you defined above will have to be defined here for Small Tablet.
}


Now we will write the CSS for iPad (Portrait) with a resolution of 768 x 1024.


@media screen and (min-width: 768px) and (max-width: 979px)
{
    // whatever CSS you defined above will have to be defined here for iPad (Portrait).
}

Now we will write the CSS for iPad (Landscape) with a resolution of 1024 x 768.


@media screen and (min-width: 980px)
{
    // whatever CSS you defined above will have to be defined here for iPad (Landscape).
}

So by this you will be able to Create Responsive Theme which will work in all the Mobile Devices.

I hope this will help you and you will like it.

Don't forget to leave your comments.


Thank you
Ravinder


Friday, April 5, 2013

PHP Class to Detect Mobile Device

Hello friends,

Today in Developer's Blog I will tell you the way to Detect Mobile Device using PHP Class.

So this Class will help you to redirect to Mobile Website (If you develop that also along with web version) and will also help you redirect to Web version of the website if someone tries to open Mobile Version on the Desktop PC.

So below is the PHP Class to Detect Mobile Device.


<?php
class Mobile_Detect {

protected $accept;

protected $userAgent;
protected $isMobile     = false;
protected $isAndroid    = null;
protected $isBlackberry = null;
protected $isOpera      = null;
protected $isPalm       = null;
protected $isWindows    = null;
protected $isGeneric    = null;

protected $devices = array(
    "android"       => "android",
    "blackberry"    => "blackberry",
    "iphone"        => "(iphone|ipod)",
    "opera"         => "opera mini",
    "palm"          => "(avantgo|blazer|elaine|hiptop|palm|plucker|xiino)",
    "windows"       => "windows ce; (iemobile|ppc|smartphone)",
    "generic"       => "(kindle|mobile|mmp|midp|o2|pda|pocket|psp|symbian|smartphone|treo|up.browser|up.link|vodafone|wap)"
);


public function __construct() {
    $this->userAgent = $_SERVER['HTTP_USER_AGENT'];
    $this->accept    = $_SERVER['HTTP_ACCEPT'];

    if (isset($_SERVER['HTTP_X_WAP_PROFILE'])|| isset($_SERVER['HTTP_PROFILE'])) {
        $this->isMobile = true;
    } elseif (strpos($this->accept,'text/vnd.wap.wml') > 0 || strpos($this->accept,'application/vnd.wap.xhtml+xml') > 0) {
        $this->isMobile = true;
    } else {
        foreach ($this->devices as $device => $regexp) {
            if ($this->isDevice($device)) {
                $this->isMobile = true;
            }
        }
    }
}


/**
 * Overloads isAndroid() | isBlackberry() | isOpera() | isPalm() | isWindows() | isGeneric() through isDevice()
 *
 * @param string $name
 * @param array $arguments
 * @return bool
 */

public function __call($name, $arguments) {
    $device = substr($name, 2);
    if ($name == "is" . ucfirst($device)) {
        return $this->isDevice($device);
    } else {
        trigger_error("Method $name not defined", E_USER_ERROR);
    }
}


/**
 * Returns true if any type of mobile device detected, including special ones
 * @return bool
 */
public function isMobile() {
    return $this->isMobile;
}


protected function isDevice($device) {
    $var    = "is" . ucfirst($device);
    $return = $this->$var === null ? (bool) preg_match("/" . $this->devices[$device] . "/i", $this->userAgent) : $this->$var;

    if ($device != 'generic' && $return == true) {
        $this->isGeneric = false;
    }

    return $return;
}
}
?>

And then write below line of code on the Web version in the file which you are including on every page to redirect to mobile site from all pages.

<?php

include('Mobile_Detect.php');
$detect = new Mobile_Detect();
if ($detect->isMobile()) 
{
    // it is mobile platform
    header("Location:http://www.mobile.mywebsite.com");
}


?>

And if you want to redirect user who tries to access mobile version from Desktop PC then write below code in the file which you are including on every page to redirect to web version.

<?php



include('Mobile_Detect.php');
$detect = new Mobile_Detect();
if (!$detect->isMobile()) 
{
    // it is desktop pc
    header("Location:http://www.mywebsite.com");
}

?>

Download Source Files

So by this way, you have successfully Detected Mobile Device from a PHP Class.

I hope this will help you and you will like it.

Don't forget to leave your comments.


Thank you
Ravinder


Sunday, March 31, 2013

Create your own Error Handler in PHP.

Hello friends,

Yesterday, one of my friend told me that he doesn't like the notice and warning shown in PHP. So I read over Internet and here's what I came up with.

So today in Developer's Blog I will tell you the way to create our own Error handler in PHP. By doing this, we can get rid of default errors shown in PHP.

You can create your own Error handler in PHP like this :

function myErrorHandler($errno, $errstr, $errfile, $errline)
{
    if(!(error_reporting() & $errno)) {
            // This error code is not included in error_reporting
            return;
    }

    switch($errno) {
            case E_USER_ERROR:
            echo "<b>My ERROR</b> [$errno] $errstr<br />\n";
            echo "  Fatal error on line $errline in file $errfile";
            echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")<br />\n";
            echo "Aborting...<br />\n";
            exit(1);
            break;

            case E_USER_WARNING:
            echo "<b>My WARNING</b> [$errno] $errstr<br />\n";
            break;

            case E_USER_NOTICE:
            echo "<b>My NOTICE</b> [$errno] $errstr<br />\n";
            break;

            default:
            echo "Unknown error type: [$errno] $errstr<br />\n";
            break;
        }

        /* Don't execute PHP internal error handler */
        return true;
    }

    // function to test the error handling
    function scale_by_log($vect, $scale)
    {
        if(!is_numeric($scale) || $scale <= 0) {
            trigger_error("log(x) for x <= 0 is undefined, you used: scale = $scale", E_USER_ERROR);
        }

        if(!is_array($vect)) {
            trigger_error("Incorrect input vector, array of values expected", E_USER_WARNING);
            return null;
        }

        $temp = array();
        foreach($vect as $pos => $value) {
            if (!is_numeric($value)) {
                trigger_error("Value at position $pos is not a number, using 0 (zero)", E_USER_NOTICE);
                $value = 0;
            }
            $temp[$pos] = log($scale) * $value;
        }

        return $temp;
    }

    // set to the user defined error handler
    $old_error_handler = set_error_handler("myErrorHandler");

E.g.,

$a = array(2, 3, "foo", 5.5, 43.3, 21.11);
$b = scale_by_log($a, M_PI);

Output :

My NOTICE [1024] Value at position 2 is not a number, using 0 (zero)

So this was the way you can create your own error handler in PHP.

Download Source Files

I hope this will help you and you will like it.

Don't forget to leave your comments.


Thank you

Ravinder


INSERT, UPDATE, DELETE And SELECT Operations in a Magento Module

Hello friends,

Today in Developer's Blog I will tell you the way to perform INSERT, UPDATE, DELETE And SELECT Operations in a Magento Module.

Suppose, I have a module named mynews
Here follows the code to select, insert, update, and delete data from the news table.

INSERT DATA : 

$data contains array of data to be inserted. The key of the array should be the database table’s field name and the value should be the value to be inserted.

$data = array('title'=>'hello there','content'=>'how are you? i am fine over here.','status'=>1);

$model = Mage::getModel('mynews/mynews')->setData($data);

try{
    $insertId = $model->save()->getId();
    echo "Data successfully inserted. Insert ID: ".$insertId;
}catch (Exception $e){
    echo $e->getMessage();   
}

SELECT DATA :

$item->getData() prints array of data from news table.
$item->getTitle() prints the only the title field.

Similarly, to print content, we need to write $item->getContent().

$model = Mage::getModel('mynews/mynews');

$collection = $model->getCollection();

foreach($collection as $item){
    print_r($item->getData());
    print_r($item->getTitle());
}

UPDATE DATA :

$id is the database table row id to be updated.
$data contains array of data to be updated. The key of the array should be the database table’s field name and the value should be the value to be updated.

$id = $this->getRequest()->getParam('id');

$data = array('title'=>'hello test','content'=>'test how are you?','status'=>0);

$model = Mage::getModel('mynews/mynews')->load($id)
->addData($data);

try{
    $model->setId($id)->save();
    echo "Data updated successfully.";
}catch(Exception $e){
    echo $e->getMessage(); 
}

DELETE DATA :

$id is the database table row id to be deleted.

$id = $this->getRequest()->getParam('id');

$model = Mage::getModel('mynews/mynews');

try{
    $model->setId($id)->delete();
    echo "Data deleted successfully.";
}catch(Exception $e){
    echo $e->getMessage(); 
}

In this way you can perform select, insert, update and delete in your custom module and in custom code in Magento as well.

I hope this will help you and you will like it.

Don't forget to leave your comments.


Thank you

Ravinder

Saturday, March 30, 2013

PHP Function to calculate age from date of birth

Hello friends,

In almost every project in which we let the user register on our website, we definitely want date of birth (DOB) and age of the user. So I thought about creating a function which will calculate age from date of birth, so we won't have to take age from the user and it will save us some coding and time. 

So today in Developer's Blog we will learn that how to calculate age from date of birth.

function calculateAge($dob) 
{
    //calculate years of age (input string: YYYY-MM-DD)
    list($year, $month, $day) = explode("-", $dob);

    $year_diff  = date("Y") - $year;
    $month_diff = date("m") - $month;
    $day_diff   = date("d") - $day;

    if ($day_diff < 0 || $month_diff < 0)
        $year_diff--;

    return $year_diff;
}

I hope this will help you and you will like it.

Don't forget to leave your comments.

Thank you
Ravinder

Friday, March 29, 2013

PHP Function to addslashes to an array

Hello friends,

Few days before I posted the function which stripslashes from an array. Today I thought about creating a function which addslashes to an array. so I created this function and want to share it with you guys as well. So I am posting this code to addslashes to an array.

We all know that there is a function to addslashes to an string in PHP but the function which I am posting
 in Developer's Blog right now will addslashes to an array.


function addSlashesArray($array
{
    foreach ($array as $key => $val) 
    {
        if (is_array($val))
        {
            $array[$key] = addSlashesArray($val);
        }
        else
        {
            $array[$key] = addslashes($val);
        }
    }
    return $array;
}

I hope this will help you and you will like it.

Don't forget to leave your comments.

Thank you
Ravinder

Tuesday, March 26, 2013

PHP Function to stripslashes from an array

Hello friends,

Today I was working and was using stripslashes a lot from all the variables. So I thought about creating a function which can stripslashes from the whole array, so I created this function and want to share it with you guys as well. So I am posting this code to stripslashes from an array.

We all know that there is a function to stripslashes from an string in PHP but the function which I am posting in Developer's Blog right now will stripslashes from an array.

function stripSlashesArray($array)
{
    foreach($array as $key => $val)
    {
        if (is_array($val))
        {
             $array[$key] = stripSlashesArray($val);
        }
        else
        {
             $array[$key] = stripslashes($val);
        }
    }
    return $array;
}


I hope this will help you and you will like it.

Don't forget to leave your comments.

Thank you
Ravinder