Monday 1 September 2014

Smarty: Request variables and other useful smarty functions


{$smarty} reserved variable The PHP reserved {$smarty} variable can be used to access several enviroment and request variables. The full list of them follows. Request variables {* display value of page from URL ($_GET) phplessonstips.blogspot.in/index.php?page=foo *} {$smarty.get.page} {* display the variable "page" from a form ($_POST['page']) *} {$smarty.post.page} {* display the value of the cookie "username" ($_COOKIE['username']) *} {$smarty.cookies.username} {* display the server variable "SERVER_NAME" ($_SERVER['SERVER_NAME'])*} {$smarty.server.SERVER_NAME} {* display the system environment variable "PATH" *} {$smarty.env.PATH} {* display the php session variable "id" ($_SESSION['id']) *} {$smarty.session.id} {* display the variable "username" from merged get/post/cookies/server/env *} {$smarty.request.username} {$smarty.now} The current timestamp can be accessed with {$smarty.now} {* use the date_format modifier to show current date and time *} {$smarty.now|date_format:'%Y-%m-%d %H:%M:%S'} {$smarty.version} Returns the version of Smarty the template was compiled with.

Thursday 28 August 2014

Add Drop Down to Yii Grid


Add  Drop Down to Yii Grid

$myColumns [] = array(
    'type' => 'raw',
    'header' => "Page Size",
'filter' => CHtml::dropDownList('pageSize', $pageSize, Yii::app()->params['defaultPageDdSize'], array('style' => 'font-size:11px; width: 50px; padding: 0px 0px 0px 0px; height: initial; ',)),
      'value' => '"<a href=\'javascript:void(0);\' onclick=\'renderView(".$data->id_games.")\' class=\'view\' data-toggle=\'tooltip\' title=\'\' data-original-title=\'View\'>
                  <i class=\'icon-eye-open\'></i></a> &nbsp;
      <a href=\'' . Yii::app()->controller->createUrl('update&id=$data->id_games') . '\' class=\'update\'  data-toggle=\'tooltip\' title=\'\' data-original-title=\'Update\'>
        <i class=\'icon-pencil\'></i></a> &nbsp;
<a class=\'delete\' onclick=\'renderDeleteForm(".$data->id_games.")\' data-toggle=\'tooltip\' title=\'\' data-original-title=\'Delete\'>
        <i class=\'icon-trash\'></i></a>
"',
    'htmlOptions' => array('class' => 'button-column','style' => 'width:62px')
);

Monday 18 August 2014

Get the count of records from a table in yii


Get the count of records from a table .
The best of way of retrieving the count of a query in yii.

For all record
$sql = "SELECT COUNT(*) FROM tablename;
$numRecordsFound = Yii::app()->db->createCommand($sql)->queryScalar();

For Criteria Based record.

$sql = "SELECT COUNT(*) FROM tablename where columnName=".$columnValue;
$numRecordsFound = Yii::app()->db->createCommand($sql)->queryScalar();

Monday 11 August 2014

Window.location.href () and Window.open () methods in JavaScript


window.location.href is not a method, it's a property that will tell you the current URL location of the browser. Setting the property to something different will redirect the page.

window.open() is a method that you can pass a URL to that you want to open in a new window. For
example:
window.location.href example:
window.location.href = 'phplessonstips.blogspot.in'; //Will take you to phplessonstips blog.
window.open() example:

window.open('phplessonstips.blogspot.in'); //This will open phplessonstips.blogspot.in in a new window.

Thursday 7 August 2014

How to get the day name from the date in php

If you solution for getting a day name from any past of future day, You are at right page of web.
Use below code.

<?php
$date  = '12-Jul-2014'; // Use any valid PHP date format
$timestamp = strtotime($date);
echo 'Short Name of Day => '. $day = date('D', $timestamp); //Short Name of Day => Sat
echo '<br> Full Name of Day => '. $day = date('l', $timestamp); //Full Name of Day => Saturday
?>


Wednesday 6 August 2014

Check page is home page or not in Joomla

This is the code which you have to write in files where you want to check for Joomla home page

$menu = & JSite::getMenu();
if ($menu->getActive()   == $menu->getDefault()) {
   echo "Home page";
} else {
   echo "Other page";
}

Joomla 2.5 Component Creation

If you want to create component in joomla 2.5 following steps are require I create just simple code for that

Steps
Remember that the folder name which you given com_student means student will you have to given in files In that .xml file is main file in which you have to give the files and folder path and component settings
  1. Create a folder for which you want to create component like For student : com_student
  2. Following are folder hierarchy
    student.xml
    site/student.php
    site/index.html
    admin/index.html
    admin/student.php
    admin/sql/index.html
    admin/sql/updates/index.html
    admin/sql/updates/mysql/index.html
    admin/sql/updates/mysql/0.0.1.sql
  3. Now just past the some code in relevant files Student.xml
     
     <?xml version="1.0" encoding="utf-8"?>
     <extension type="component" version="2.5.0" method="upgrade">
      <name>Student!>/name>
      <autthor>Amrish>/autthor>
      <copyright>Copyright Info>/copyright>
      <license>License Info>/license>
      
      
      <version>0.0.1</version>
      
      <update> 
       <schemas>
         <schemapath type="mysql">sql/updates/mysql</schemapath>
       </schemas>
      </update>
       
      <files folder="site">
       <filename>index.html</filename>
       <filename>student.php</filename>
       <filename>controller.php</filename>
       <folder>views</folder>
       <folder>models</folder>
      </files>
      
      <administration>
       
       <menu>Student!</menu>
       
       
       <files folder="admin">
        
        <filename>index.html</filename>
        <filename>student.php</filename>
        
        <folder>sql</folder>
       </files>
      </administration> 
     </extension>
     
    
    Index.html
    this file code is same for all index.html file
      <html><body bgcolor="#FFFFFF"></body></html>
     
    Site/student.php
    write any message which you want to print
    Like : Student Management System
    Admin/student.php
    write any message which you want to print
    Like : Student Management System Administrator
    admin/sql/updates/mysql/0.0.1.sql
    admin/sql/updates/mysql/0.0.1.sql is an empty file allowing to initialise schema version of the com_student component. Leave it blank
  4. you can also do the model and create view.
    For more information visit : Joomla 2.5 Component Creation

Tuesday 5 August 2014

How to Resize Image Dynamically in PHP

How to Resize Image Dynamically in PHP

There is an extremely useful PHP library called timthumb which comes very handy. It’s just a simple PHP script that you need to download and put in some folder under your website. And then simply call it with appropriate arguments.






  • Download timthumb.php and put under any folder.
  • Upload this script timthumb.php though FTP to your web hosting. Put it under a directory /script.
  • Just call timthumb.php with appropriate arguments, For example:
    <img src="/script/timthumb.php?src=/some/path/myimage.png&w=100&h=80"
        alt="resized image" />

    And that’s all!!


  • One thing worth noting here is that this library will create a folder cache in the directory where timthumb.php script resides. This folder will cache the resized image for better performance.

    You can refer following table for different parameters and its meaning.

    ParameterValuesMeaning
    srcsourceurl to imageTells TimThumb which image to resize
    wwidththe width to resize toRemove the width to scale proportionally (will then need the height)
    hheightthe height to resize toRemove the height to scale proportionally (will then need the width)
    qquality0 – 100Compression quality. The higher the number the nicer the image will look. I wouldn’t recommend going any higher than about 95 else the image will get too large
    aalignmentc, t, l, r, b, tl, tr, bl, brCrop alignment. c = center, t = top, b = bottom, r = right, l = left. The positions can be joined to create diagonal positions
    zczoom / crop0, 1, 2, 3Change the cropping and scaling settings
    ffilterstoo many to mentionLet’s you apply image filters to change the resized picture. For instance you can change brightness/ contrast or even blur the image
    ssharpenApply a sharpen filter to the image, makes scaled down images look a little crisper
    cccanvas colourhexadecimal colour value (#ffffff)Change background colour. Most used when changing the zoom and crop settings, which in turn can add borders to the image.
    ctcanvas transparencytrue (1)Use transparency and ignore background colour



    Hope this is useful for you :)

    Sunday 3 August 2014

    Redirecting www to non-www with .htaccess

    Redirecting www to non-www

    If you want to do the opposite, the code is very similar:

    RewriteEngine On
    RewriteCond %{HTTP_HOST} !^my-domain\.com$ [NC]
    RewriteRule ^(.*)$ http://my-domain.com/$1 [R=301,L]
    

    Redirect non-www url to www with .htaccess

    If you want to redirect all non-www requests to your site to the www version, all you need to do is add the following code to your .htaccess file:

    RewriteEngine On
    RewriteCond %{HTTP_HOST} !^www\.
    RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
    

    Friday 25 July 2014

    How to create Yii Web application and new info about Yii Framework

    About Yii
    Yii is a high-performance PHP framework best for developing Web 2.0 applications.
    Yii helps Web developers build complex applications and deliver them on-time.
    Yii is pronounced as Yee or [ji:], and is an acroynym for "Yes It Is!".
    Yii 1.1 is the latest stable version.
    The latest version of Yii 2 is 2.0.0 beta, released on April 13, 2014.
    Yii 2.0 is not ready for production use yet. It is currently under heavy development.

    How to set up yii web application in localhost.

    1. Down load the latest yii framework (yii version1.1) from below link
       http://www.yiiframework.com/download/

    2. Extract the code from zip or gaiz file,
    you will get following folders,
    demos
    framework,
    requirements
    and following four files
    CHNAGELOG
    LICENSE
    README
    UPGRADE

    3. Put all files to the root level in you localhost.
    for the xampp user they can place these files under the htdocs folder.

    4. run the below code for create the yii app (project)
    Create Yii Project In Local Host With Xampp Using Command Line
    Step 1 open command line
    Step 2 run below command it will create all the default structure for the project.
    Here "newyiiprojectname"  is the name of the folder(project) you want to create. you can change it as per your choice.
    C:\xampp\php>php C:/xampp/htdocs/framework/yiic.php webapp C:\xampp\htdocs\newyiiprojectname
    once you run above command it will ask you to create a web application under the defined path with yes/no option.
    here if you type yes and press enter it will create the new yii app(project) with the given folder name.

    Now your application is ready. You can access it by using following link
    http://localhost/newyiiprojectname/


    How to setup yii project in localhost

    Create Yii Project In Local Host With Xampp Using Command Line

    Step1 open command line

    Step 2 run below command it will create all the default structure for the project.

    here "newyiiprojectname"  is the name of the folder(project) you want to create. you can change it as per your choice.
    C:\xampp\php>php C:/xampp/htdocs/framework/yiic.php webapp C:\xampp\htdocs\newyiiprojectname

    Friday 18 July 2014

    How to hide index.php from url in yii

    URL rewriting in Yii to hide index.php

    To hide the index.php from url you have to make the changes in config/main.php  as shown below,
    ‘urlManager’=>array(
                                  ‘urlFormat’=>’path’,
                                  ‘showScriptName’=>false, //this option will be hide the index.php from url
                                  ‘rules’=>array(
                                                    ‘<controller:\w+>/<id:\d+>’=>’<controller>/view’,
                                                   ‘<controller:\w+>/<action:\w+>/<id:\d+>’=>’<controller>/<action>’,
                                                  ‘<controller:\w+>/<action:\w+>’=>’<controller>/<action>’,
                                                 ),
    ), 
    and create new .htaccess file in the same directory as my index.php file shown as below,
    RewriteEngine  On
    RewriteBase  /
    RewriteCond   %{REQUEST_FILENAME} !-f
    RewriteCond   %{REQUEST_FILENAME} !-d
    RewriteRule    ^(.*)\?*$ index.php/$1 [L,QSA]
    You can change the ”RewriteBase /’  as per project location like if project is located in ‘abc/′ of webroot.
    then it change like as    RewriteBase  /abc

    That will make sure your auto-generated links (CHtml::link or zii.widgets.CMenu) do not have index.php in them. This will not work without the .htaccess file. The reason is that the .htaccess file rewrites the url to point to index.php/$1 so that Yii actually gets the request properly. You will not see the index.php in the url at any time though.

    How to calculate the weeks between two dates

    How to calculate the weeks between two dates.

    //php code
    $today=date('Y-m-d h:i:s');
    $fromData="2014-01-01 00:00:00"
    $diff = strtotime($today, 0) - strtotime($fromData, 0);
    $weekNo = floor($diff / 604800);
    $weekNo = $weekNo+1;
    echo "This is the ".$weekNo." of the Year 2014";
    //end

    Friday 4 July 2014

    How to Get Customer billing and shipping information

    # Getting customer billing address information
    $quote = Mage::getSingleton(‘checkout/session’)->getQuote();
    $billingAddress = $quote->getBillingAddress();
    $country = $billingAddress->getCountryId();
    $city = $billingAddress->getCity();
    $zipcode = $billingAddress->getPostcode();

    # Get customer default billing information
    $customerAddressId = Mage::getSingleton(‘customer/session’)->getCustomer()->getDefaultBilling();
    if ($customerAddressId){
    $address = Mage::getModel(‘customer/address’)->load($customerAddressId);
    $address->getData();
    }

    # Get customer default shipping information

    $customerAddressId = Mage::getSingleton(‘customer/session’)->getCustomer()->getDefaultShipping();
    if ($customerAddressId){
    $address = Mage::getModel(‘customer/address’)->load($customerAddressId);
    $address->getData();
    }

    How to Create new Customer billing and shipping address

    $_custom_address = array (
        'firstname' => 'Sanjay',
        'lastname' => 'Rao',
        'street' => array (
            '0' => 'Line address part1',
            '1' => 'Line address part2',
        ),
        'city' => 'Ahemdabad',
        'region_id' => '',
        'region' => '',
        'postcode' => '380015',
        'country_id' => 'IN', /*India */
        'telephone' => '1234567890',
    );
    $customAddress = Mage::getModel('customer/address')
    $customAddress->setData($_custom_address)
                ->setCustomerId($customer->getId())
                ->setIsDefaultBilling('1')
                ->setIsDefaultShipping('1')
                ->setSaveInAddressBook('1');
    try {
        $customAddress->save();
    }
    catch (Exception $ex) {
        //Zend_Debug::dump($ex->getMessage());
    }

    How to Create new Customer in magento or update customer info in magento

    $customer = Mage::getModel('customer/customer');
    $password = '123456';
    $email = 'sanjay@rao.com';
    $customer->setWebsiteId(Mage::app()->getWebsite()->getId());
    $customer->loadByEmail($email);

    if(!$customer->getId()) {
        $customer->setEmail($email);
        $customer->setFirstname('Sanjay');
        $customer->setLastname('Rao');
        $customer->setPassword($password);
    }
    try {
        $customer->save();
        $customer->setConfirmation(null);
        $customer->save();
        //Make a "login" of new customer
        Mage::getSingleton('customer/session')->loginById($customer->getId());
    }
    catch (Exception $ex) {
        Zend_Debug::dump($ex->getMessage());
    }



    How to Get All State List In Magento for specific country

    //below code load all the State  of US
    $countryCode= ‘US’;
    $states = Mage::getModel('directory/country')->load($countryCode)->getRegions();
    $slist= array();
    foreach ($states as $state) {
    $sid = $state->getId();
                $sname = $state->getName();
                $slist[$sid]=$sname;                                                              
    }

    asort($slist);

    How to Get All Country List In Magento

    $clist= array();
    $collection = Mage::getModel('directory/country')->getCollection();
    foreach ($collection as $country){
    $cid = $country->getId();
                $cname = $country->getName();
                $clist[$cid]=$cname;
    }

    asort($clist); // sort country list 

    How to Get Customer Default Shipping Detail Using Customer Id in Magento

    If you know the customer id than direct use it other wise first you can get customer id than use that.

    $customerId =2; // already known

    Mage::getSingleton('customer/session')->loginById($customerId);
    $customerAddressId = Mage::getSingleton('customer/session')->getCustomer()->getDefaultShipping();
    $address = Mage::getModel('customer/address')->load($customerAddressId);
    $address_data = array (
                'prefix' => $address->getPrefix(),
                'firstname' => $address->getFirstname(),
                'lastname' => $address->getLastname(),
                'street' => $address->getStreet(),
    'city' => $address->getCity(),
                'region_id' => $address->getRegionId(),
                'region' => $address->getRegion(),
                'postcode' => $address->getPostcode(),
                'country_id' => $address->getCountryId(),
                'telephone' => $address->getTelephone(),
                'email' => $address->getEmail()

    );

    How to Get Customer Detail Using Email Id in Magento

    $customer = Mage::getModel("customer/customer");
    $customer->setWebsiteId(Mage::app()->getWebsite()->getId()); 
    $customer->loadByEmail($customer_email);
    //get customer id
    $customerId = $customer->getId();
    //get customer Email
    $customerEmail = $customer->getEmail ();
    //get customer First Name
    $fname = $customer->getFirstname();
    //get customer Last Name
    $lname = $customer->getLastname();
    //get customer Full Name
    $fullname = $customer->getName();

    Wednesday 16 April 2014

    PHP: How to Copy All Files and folders Within A Directory

    function recurse_copy($src,$dst) {
            $dir = opendir($src);
            @mkdir($dst, 0777);
            while(false !== ( $file = readdir($dir)) ) {
                    if (( $file != '.' ) && ( $file != '..' )) {
                            if ( is_dir($src . '/' . $file) ) {
                                    $this->recurse_copy($src . '/' . $file,$dst . '/' . $file);
                            }
                            else {
                                    copy($src . '/' . $file,$dst . '/' . $file);
                            }
                    }
            }
            closedir($dir);
        }

    Example : How to use above Function

    $src='www/abc'; // copy all the files and folder within abc directory
    $dst = 'www/newdir' //
    recurse_copy($src,$dst);

    above function first create the destination directory and than copy all the source directory content.
    Tips: to create directory and set its permission using following code in php
    mkdir($path, 0777, true)

    PHP: Unlink All Files Within A Directory, and then Deleting That Directory

    function recursiveRemoveDirectory($directory)
        {
            foreach(glob("{$directory}/*") as $file)
            {
                    if(is_dir($file)) {
                            $this->recursiveRemoveDirectory($file);
                    } else {
                            unlink($file);
                    }
            }
            rmdir($directory);
        }

    Example : How to use above function.
    $directory = 'www/abc';
    recursiveRemoveDirectory($directory)

    Friday 28 March 2014

    Use of in_array function in smarty

    use of  in_array function in smarty
    {if in_array($needle, $array)} {/if}

    Get Domain name from the URL using php function

    function get_domain($url)
    {
      $pieces = parse_url($url);
      $domain = isset($pieces['host']) ? $pieces['host'] : '';
      if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) {
        return $regs['domain'];
      }
      return false;
    }

    print get_domain("http://www.sanajyrao.com"); // outputs 'sanajyrao.com'
    print get_domain("http://www.demo.sanajyrao.com"); // outputs 'sanajyrao.com'
    print get_domain("http://demo.sanajyrao.com"); // outputs 'sanajyrao.com'
    print get_domain("http://sanajyrao.com"); // outputs 'sanajyrao.com'

    Sort Array values using specific(particuler) Key of array

    function sort_arr_of_obj($array, $sortby, $direction='asc') {
       
        $sortedArr = array();
        $tmp_Array = array();
       
        foreach($array as $k => $v) {
            $tmp_Array[] = strtolower($v[$sortby]);
        }
       
        if($direction=='asc'){
            asort($tmp_Array);
        }else{
            arsort($tmp_Array);
        }
       
        foreach($tmp_Array as $k=>$tmp){
            $sortedArr[] = $array[$k];
        }
       
        return $sortedArr;

    }

    $myArray=array(0=>array('size'=>5,'name'=>'Five'),1=>array('size'=>3,'name'=>'Three'),2=>array('size'=>9,'name'=>'Nine'));
    $myArray=sort_arr_of_obj($myArray,'size','asc');


    Tuesday 11 March 2014

    How to Check Url Access In YII for Role based Access

    Below function return true and false(1 or null) either yii user is able to access the url(authItemName) or not.

    Explample.
    Player list
    $url = http://localhost/YiiProject/index.php?r=player/playerList/index
    $allowedAccess = $this->checkUrlAccess($url );
    if($allowedAccess){
     echo "You are allowed to access Url";
    }else{
     echo 'Access denied';
    }
    function checkUrlAccess($authItemName)
      {
         #New Code ADDED            
                $allowedAccess='';
            if (strpos($authItemName, '?r=') != false)
            {
                       
                $urlQueryString=explode('?r=',$authItemName);          
                if (strpos($urlQueryString[1], '/') != false)
                {
                    $parts = explode('/', $urlQueryString[1]);
                    if ($this->upperCaseFirstLetter)
                    {
                      foreach ($parts as $i => $part)
                      {
                        $parts[$i] = ucfirst($part);
                      }
                    }
                    $moduleName=$controllerName=$actionName='';
                    $numOfParts = count($parts);
                    if ($numOfParts > 2)
                    {
                      $moduleName=$parts[$numOfParts - 3];
                    }
                                    $controllerName=$parts[$numOfParts - 2];
                    $actionName=$parts[$numOfParts - 1];
                                    $itemName = '';                   
                                     if(!empty($moduleName)){
                                             $itemName .= $moduleName . '.';
                                     }
                                     $itemName .= $controllerName;
                     $user = Yii::app()->getUser();
                     if ($user->isGuest){
                               if(empty($moduleName)){
                                   $allowedAccess =   Yii::app()->beforeControllerAction($controllerName,$actionName);
                                                 }
                     }else{
                          if ($user->checkAccess($itemName . '.*')){
                             $allowedAccess = 1;
                          }else{
                              $itemName .= '.' . $actionName;
                              if ($user->checkAccess($itemName, array())){
                                  $allowedAccess = 1;
                              }
                          }
                                                if(empty($moduleName) && empty($allowedAccess)){
                                                    $allowedAccess =   Yii::app()->beforeControllerAction($controllerName,$actionName);
                                                 }
                     }
              
                 }
            }
            #END
                    return $allowedAccess;
       
      }

    List OF BANK PAN Numbers

    List OF BANK PAN Numbers Bank/Home Loan Providers PAN Number Allahabad Bank AACCA8464F Andhra Bank AABCA7375C Axis Bank...