Sanjoy Roy

[MCM, MCP, SCJP] – Senior PHP Programmer

Monthly Archives: January 2011

Easy CMS/Block – Frontend Features

  • Extension key: magento-community/AsiaConnect_FreeCMS


    Easy CMS allow to put any HTML content to any position on Magento site. You can put text, banner, advertisement, images, flash, music, video, product… After a short time with more than 4000+ download, EasyCMS Frontend Features is available to install via Magento Connect now. Get the extension and have a happy time with your site now. Read more of this post

Magento Fontis ANZ eGate

Provides integration with the ANZ eGate gateway interface. Only payments and refunds are allowed; void or pre-authorisation are not currently included in the extension. For more information, including screenshots, version history and instructions on configuration and usage, please see the Fontis ANZ eGate Magento extension page. To stay up-to-date with the latest releases, follow us on Twitter and subscribe to our blog. If you’d like to link to this extension, please use our extension page rather than this Connect listing. To see the other extensions we have available, visit our Magento extension page for a complete list. The development of this extension is commercially supported by Fontis. We welcome any feedback and suggestions from the community on the ongoing development of the extension. We can also provide customisation and development services upon request.

Magento how to remove minimum quantity allowed for purchase validation error

Just comment the line below: (Lines from #499 to #505)

if ($this->getMinSaleQty() && ($qty) getMinSaleQty()) {
                ->setMessage(Mage::helper('cataloginventory')->__('The minimum quantity allowed for purchase is %s.', $this->getMinSaleQty() * 1))
                ->setQuoteMessage(Mage::helper('cataloginventory')->__('Some of the products cannot be ordered in requested quantity.'))
            return $result;

Magento how to change default quantity add to cart?

<input name="qty" type="text" class="input-text qty” id="qty" maxlength="12" value="<?php echo $this->getMinimalQty($_product)== null?1:$this->getMinimalQty($_product) ?>"/>

put this code on \app\design\frontend\default\modern\template\catalog\product\view\type/sipmle.html
and check the there will appear the 1 on text box

Where is Magento’s advanced search link?

Magento where is database configuration file?

Find the local.xml in local \\\magento\app\etc\local.xml
<pre class="brush:xml">



Magento storing in session

$storage = array('a'=>'b');

// store data so we can fetch it in subtotal methods

// get data
$rbanhShipping = Mage::getSingleton('core/session')->getRbanhShipping(); 
$rbanhShipping = unserialize($rbanhShipping);

Magento how to get shipping quote per item in cart

foreach ($session->getQuote()->getAllItems() as $item) 
    $output .= "

"; $output .= $item->getWeight(); $output .= "
"; $output .= $item->getName() . "
"; $output .= "QTY:" . $item->getQty() . " | $" . number_format($item->getPrice(), 2); $output .= "

"; $temp_product = Mage::getModel('catalog/product') ->setCurrentStore(1) ->load($item->getProduct()->getId()); $quote2 = Mage::getModel('sales/quote'); //$quote2->setDestPostcode($session->getQuote()->getShippingAddress() ->getPostcode()); //$quote2->getShippingAddress()->setCountryId('US'); $quote2->setShippingAddress($session->getQuote() ->getShippingAddress()); $temp_product->getStockItem()->setUseConfigManageStock(false); $temp_product->getStockItem()->setManageStock(false); $quote2->addProduct($temp_product); $quote2->setPackageWeight($item->getWeight()); $quote2->getShippingAddress()->setCollectShippingRates(true); $quote2->getShippingAddress()->collectTotals(); $rates = $quote2->getShippingAddress()->getShippingRatesCollection(); //$rates = $quote2->getShippingAddress()->getAllShippingRates(); //var_export($rates); foreach ($rates as $rate) { $output .= " rbanh = ".$rate->getPrice()." " . $rate->getCode() . " END
"; } }

Magento auto add product custom options

// *Special note: make sure you check your sql table name, 
//  and change the option title from what i have below.

// rbanh special methods
private function rbanh_get_custom_option_id($product_id)
    $sql = "
            catalog_product_option o
        inner join
            catalog_product_option_title t on t.option_id = o.option_id
            t.title = 'Shipping Description'
            and o.product_id = '".$product_id."'
        limit 1
    $data = Mage::getSingleton('core/resource') ->getConnection('core_read')->fetchAll($sql);
    if (count($data) > 0)
        return current($data[0]);
    return false;

// rbanh special methods
private function rbanh_add_custom_option($product_id)
    // make the option active
    //$write = Mage::getSingleton('core/resource')->getConnection('core_write');
    //$write->query("update catalog_product_entity set has_options = 1 where entity_id='$product_id'"); 
    $write = Mage::getSingleton('core/resource')->getConnection('core_write');
    $sql  = "update catalog_product_entity set has_options = 1 where entity_id=?";
    $write->query($sql, $product_id); 
    $product = Mage::getModel('catalog/product');
    $opt = Mage::getModel('catalog/product_option');
    $option = array(
        'is_delete' => 0,
        'is_require' => false,
        'previous_group' => 'text',
        'title' => 'Shipping Description',
        'type' => 'field',
        'price_type' => 'fixed',
        'price' => '0.0000'
    return $this->rbanh_get_custom_option_id($product_id);

Magento How to add new products

require_once 'app/Mage.php';
// instatiate Product
$product = Mage::getModel('catalog/product');
$product->setSku('rand-sku-' . rand());
$product->setType('Simple Product');
$product->setName('Product Name'.rand(1,200000));
$product->setDescription('The Product Description');
$product->setShortDescription('Brief Description');
// "Stock Item" still required regardless of whether inventory
// control is used, or stock item error given at checkout!
$stockItem = Mage::getModel('cataloginventory/stock_item');
$stockItem->setData('is_in_stock', 1);
header("Location: /checkout/cart/add/product/".$product->getId()."/); 

Magento observer sales order

 * Register an event trigger after the order has been saved
 * Is triggered by sales_order_save_after event 
public function hookSalesOrderSaveAfter ($observer)
    $order = $observer->getEvent()->getOrder(); // returns the Mage_Sales_Model_Order Object
    Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID); // Magento can only save attributes in admin mode
    $order->getResource()->saveAttribute($order, "vendor");
    $order->getResource()->saveAttribute($order, "call_to_action");
    $order->getResource()->saveAttribute($order, "keycode");
    return $this;

Magento displaying store id

Display Magento sub categories

    $currentCat = Mage::registry('current_category');

    if ( $currentCat->getParentId() == Mage::app()->getStore()->getRootCategoryId() )
        // current category is a toplevel category
        $loadCategory = $currentCat;
        // current category is a sub-(or subsub-, etc...)category of a toplevel category
        // load the parent category of the current category
        $loadCategory = Mage::getModel('catalog/category')->load($currentCat->getParentId());
    $subCategories = explode(',', $loadCategory->getChildren());

    foreach ( $subCategories as $subCategoryId )
        $cat = Mage::getModel('catalog/category')->load($subCategoryId);


            echo 'getURL().'">'.$cat->getName().'
'; echo $cat->getDescription(); echo 'getImage().'">'; } }

Magento cart total + items

getSummaryQty(); ?>
There are  items  in your cart
					getQuote()->getAllItems() as $item) {
    $output .= "

"; $output .= $item->getName() . "
"; $output .= "QTY:" . $item->getQty() . " | $" . number_format($item->getPrice(), 2); $output .= "
"; } print $output;?>

Magento shopping cart total

Magento – How to load static block?

Modify Magento TAX Calculation

Change the following file: magento\app\code\core\Mage\Tax\Model\Calculation.php

     * Calculate rated tax abount based on price and tax rate.
     * If you are using price including tax $priceIncludeTax should be true.
     * @param   float $price
     * @param   float $taxRate
     * @param   boolean $priceIncludeTax
     * @return  float
    public function calcTaxAmount($price, $taxRate, $priceIncludeTax=false, $round=true)
        $taxRate = 10;
		$taxRate = $taxRate/100;
		$this->insertInLog('taxRate', $taxRate);
		$this->insertInLog('price', $price);
        if ($priceIncludeTax) {
            $amount = $price*(1-1/(1+$taxRate));
        } else {
            $amount = $price*$taxRate;
		$this->insertInLog('Amount', $amount);
        if ($round) {
            return $this->round($amount);
        } else {
            return $amount;

     * Insert in to Log Table. It helps to trace and stores in table
     * @param   varchar $title
     * @param   varchar $desc

	function insertInLog($title, $desc){		
		$sql = "insert into log_tbl values('".$title."', '".$desc."', '".date("Y-m-d h:i:s")."')";

Edit PHTML Files in Dreamweaver

By default, Dreamweaver cannot read PHTML files. You can add the file type to the “Open in Code View” section of the preferences if you wish to have fast access, however you cannot view the file in design view if you do that. So if you use Dreamweaver (versions 4, MX, MX2004, 8, or 9, aka CS3,CS4) to design your sites, and you wish to open Magento’s Template files (they have .phtml extensions) in Dreamweaver, you can follow these steps to add support for .phtml and make Dreamweaver render PHP code (with coloring, hinting, et al) as well as allow you to see the design in code view if desired. Below are three steps to follow.*

IMPORTANT NOTES: This guide is for Dreamweaver on Windows (XP or Vista) or Mac OS X. Note: I have excluded version numbers from the file locations shown, and if you are using a version older than Dreamweaver 9 (CS3) replace “Adobe” with “Macromedia” in the file locations shown. Some spaces have also been removed to keep the references on one line.

* Dreamweaver 4 users: if you are using the archaic Dreamweaver 4, you only need to follow step one. However, it’s highly recommended that you just upgrade to version 8, CS3 or newer for superb CSS and Web Standards support.

* Vista may need to edit files by running notepad as Administrator, however this requirement is not common and if encountered, may be avoidable by following these steps after a fresh restart. However, if unavoidable, simply go to Start > All Programs > Accessories, and then right click on Notepad and select “Run as Administrator”. Once notepad is open, use File > Open to browse to the applicable file before making the necessary changes.

Step One: Add .phtml to extension.txt in your Application Data

Open the following extension configuration file in a notepad and change the lines as specified below:

XP: Documents and Settings > [user] > Application Data > Adobe Dreamweaver > Configuration > extensions.txt

NOTE: If you cannot see the Application Data Folder, go to Tools → Folder Options → View and make sure that Show Hidden Files and Folders is checked.

Vista: Users > [user] > AppData > Roaming > Adobe > Dreamweaver 9 > Configuration > Extensions.txt Read more of this post

How to retrieve customer name/firstname in Magento

require_once 'app/Mage.php';
$session = Mage::getSingleton('customer/session');
if($session->isLoggedIn()) {
   $customer = $session->getCustomer();
   echo $customer->getName();
   echo $customer->getFirstname();

Magento isRecurring

     * Whether there are recurring items
     * @return bool
    public function hasRecurringItems()
        foreach ($this->getAllVisibleItems() as $item) {
            if ($item->getProduct() && $item->getProduct()->isRecurring()) {
                return true;
        return false;

Top PHP 5 Projects

icon.png Kumbia PHP Framework php Framawork spanish, mvc, full support, forms generation, AJAX and Web 2,0 focused
latus_logo.gif LATUS LATUS is the Site Management System developed by MoveNext from Leiden, the Netherlands
live_agent_logo.gif Live Agent Chat LiveAgent live chat software is THE live chat solution for your website. This PHP / MySQL / AJAX script is completely web based.
LoveCMS LoveCMS is a simple content managment system for producing websites without learning curve.
logo_s.jpg Magike Magike is a powerful blog software based on PHP5.

Read more of this post

How to create a Password Protected Directory using linux command prompt?

Create a .htaccess file in the folder you want to set.
#root@adu [/home/hostsite/public_html/admin]# vi .htaccess
copy and paste the following lines:
AuthName “Secure Area”
AuthType Basic
AuthUserFile /home/hostsite/public_html/admin/.htpasswd
require valid-user
Now set a password:
#htpasswd -c .htpasswd admin
New password: admin321
confirm password: admin321

You are done. test it: and enter user name as admin and password as admin321

Magento Indexing Problem and solution

Stock Status Index process is working now. Please try run this process later.

I have resolved the indexing problem. Problem was with the permission and ownership  to /public_html/var/locks directory.
#chown -R owner_name:group_name directory
e.g [/home/spsimpo/public_html/var]# chown -R spsimpo:spsimpo locks
Also need to chmod 777 to all files under /public_html/var/locks
[/home/spsimpo/public_html/var]# chmod -R 777 locks

All the files under /public_html/var/locks has to be like below:

-rwxrwxrwx 1 spsimpo spsimpo   31 Jan 24 11:05 index_process_1.lock*
-rwxrwxrwx 1 spsimpo spsimpo   31 Jan 24 11:05 index_process_2.lock*
-rwxrwxrwx 1 spsimpo spsimpo   31 Jan 24 11:05 index_process_3.lock*
-rwxrwxrwx 1 spsimpo spsimpo   31 Jan 24 11:17 index_process_4.lock*
-rwxrwxrwx 1 spsimpo spsimpo   31 Jan 24 11:09 index_process_5.lock*
-rwxrwxrwx 1 spsimpo spsimpo   31 Jan 24 11:07 index_process_7.lock*
-rwxrwxrwx 1 spsimpo spsimpo   31 Jan 24 11:05 index_process_9.lock*


Cpanel Webalizer statistics without cpanel login

CPanel offers you the ability to check your website statistics with a program called webalizer. The problem with this system is that you are required to login via cpanel, and click through 2 diferent subsections in order to access them. This tutorial will guide you on the steps needed to make your webalizer statistics available via .

Login to your hosting account via ssh. If you do not have ssh, ask your host to enable it. if they won’t enable it, ask them to read this tutorial, and run through these directions yourself.

Navigate to your public_html directory by running the following command

cd public_html

Once there, type the following:

vi .htaccess

once that loads, hit your i key, and type the following:

Options +FollowSymLinks

Once that is done, hit your Esc (escape) key, and type the following:


This will write to the .htaccess file, and quit.

Next, run the following command

ln -s ~/tmp/webalizer stats

you can replace the “stats” part of that command with name you want to use in order to access your website statistics.

After that, run the following commands

chmod 755 ~/tmp
chmod 755 ~/tmp/webalizer

now you can access to access your webalizer statistics.


Extjs Themes

Ext JS comes with a handful of themes that make your rich web app look polished without lifting a finger. With three included themes to choose from, you can be sure your app looks fantastic in all major browsers.

Extjs Themes Download

To install swap css and images in your Extjs resources folder. It’s made to work with version 3.1.
Extjs forum topic

More Themes are here.

Change password shell script

#!/usr/local/bin/expect -f
# Password change shell script, tested on Linux and FreeBSD
# ----------------------------------
# It need expect tool. If you are using Linux use following command
# to install expect
# apt-get install expect
# FreeBSD user can use ports or following command:
# pkg_add -r -v expect
# ----------------------------------
# If you are using linux change first line
# From:
#!/usr/local/bin/expect -f
# To:
#!/usr/bin/expect -f
# -----------------------------------------------
# Copyright (c) 2006 nixCraft project
# This script is licensed under GNU GPL version 2.0 or above
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit for more information.
# -------------------------------------------------------------------------
# display usage
if {$argc!=2} {
   send_user "usage: $argv0 username password \n"
# script must be run by root user
set whoami [exec id -u]
if {$whoami!=0} {
   send_user "You must be a root user to run this script\n"
set timeout -1
match_max 100000
# stopre password
set password [lindex $argv 1]
# username
set user [lindex $argv 0]
# opem shell
spawn $env(SHELL)
# send passwd command
send -- "passwd $user\r"
expect "assword:"
send "$password\r"
expect  "assword:"
send "$password\r"
send "\r"
expect eof

Magento is slow?


1. Sign in to Backend (index.php/admin)
2. From the menu choose System->Cache Management
3. Click on Select All link
4. Choose Enable from Actions drop down list
5. Press Submit button.
6. To enable additional cache management press both the “Flush Catalog Images Cache” and “Flush JavaScript/CSS Cache” buttons.

(~public_html/.htaccess file changes)

<IfModule mod_deflate.c>
DeflateBufferSize 32768
DeflateCompressionLevel 5

<Location />
SetOutputFilter DEFLATE
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png|tiff)$ no-gzip dont-vary
Header append Vary User-Agent env=!dont-vary


zlib.output_compression = on

%d bloggers like this: