PHP – How to read a file from another server using FTP credentials?

I had a task to read file from another server. Obvious you would suggest file_get_contents or cURL for same. But those files was not accessible through URL. I have to read it using FTP server credentials, Initially I was trying with ftp_get and some other FTP functions. But it was download all files to my local server.

But finally I got the solution, here its….

    $filename = 'ftp://username:password@hostname/files/path/and/name.txt';
    $handle = fopen($filename, "r");
    $contents = fread($handle, filesize($filename));
    echo $contents;

I hope this would help you….

Magento – Category tree view listing in drop-down

It took bit time to complete this task. After a big fight with the code, finally I am done with the category drop-down with subcategories parent and child tree view.

dropdown post

Here is the code, You can just create bellow function under the block or helper with your module.

function getCategoriesTreeView() {
    // Get category collection
    $categories = Mage::getModel('catalog/category')
        ->addAttributeToSort('path', 'asc')
        ->addFieldToFilter('is_active', array('eq'=>'1'))

    // Arrange categories in required array
    $categoryList = array();
    foreach ($categories as $catId => $category) {
        if (isset($category['name'])) {
            $categoryList[] = array(
                'label' => $category['name'],
                'level'  =>$category['level'],
                'value' => $catId
    return $categoryList;

Now its time for design, bellow is the code which will give you the category drop down.

<select id="categorylist" name="categorylist">
<option value="">Select Category</option>
    $categoriesTreeView = getCategoriesTreeView();

    foreach($categoriesTreeView as $value)
        $catName    = $value['label'];
        $catId      = $value['value'];
        $catLevel    = $value['level'];

        $space = '&nbsp;';
        for($i=1; $i<$catLevel; $i++){
            $space = $space."&nbsp;";
        $catName = $space.$catName;

     <option value="<?php echo $catIdIs; ?>"><?php echo $catName ?></option>

With the same code you can create category switcher / category changer. Just you need to get the category’s URL with the category collection and redirect to that category with on change event of drop-down.

Magento – Onepage checkout not working after upgrade/update Magento 1.8

We have resolve the issue with top menu navigation after upgrade magento to least version. Just recently I get new issue with checkout page that, step 3 Shipping Method is not working after upgrade magento 1.8 with my custom theme. Checkout process is stuck on step 3 Shipping Method.

After exploring web and debugging the code I have found solution. In order to resolve this issue you just need to add new class to html tag fieldset as shown below,

Go to /app/design/frontend/base/default/template/checkout/onepage/payment.phtml

look for the code

<?php echo $this->getChildHtml('methods') ?>

change it to this

<fieldset id="checkout-payment-method-load">
<?php echo $this->getChildHtml('methods') ?>

I hope this would resolve your issue….

Topmenu not functioning after upgrade magento 1.8 fatal error addCacheTag()

As we seen with my previous blog upgrade community edition magento 1.7 to magento 1.8,  we know how to upgrade magento with latest version.

When I was doing the same with one my project, I come across the error something like,

Fatal error: Call to a member function addCacheTag() on a non-object in (Base Path)/app/code/core/Mage/Catalog/Model/Observer.php on line 215

For quick fix, initially I have comment out two lines from file app/code/core/Mage/Catalog/Model/Observer.php

Line # 241 ($menuBlock->addModelTags($categoryModel);) 
Line # 215 ($block->addCacheTag(Mage_Catalog_Model_Category::CACHE_TAG);)

But after spending some time, I come to know that I have used one of the menu extension which is exptending the “Mage_Page_Block_Html_Topmenu” and there is some problem with Mage::dispatchEvent.

With my extended code it was just something like

Mage::dispatchEvent('page_block_html_topmenu_gethtml_before', array(
          'menu' => $this->_menu

Updated code is,

Mage::dispatchEvent('page_block_html_topmenu_gethtml_before', array(
        'menu' => $this->_menu,
        'block' => $this         //add this line

Most probebly this would resolve your issue.

How to upgrade magento to 1.8

Magento 1.8 has been released with,

  • Major overhaul of tax calculation formulas, correction of rounding errors, and additional assistance with configuration.
  • Optimized cache adapters for single-server systems.
  • Upgraded Redis cache adapters for multi-server systems.
  • Eliminated many types of database deadlocks.
  • And many more updates and changes………..

Now, Magento developers get a new JOB to upgrade magento from older version to magento 1.8.

Magento recommends you upgrade your installation using the following guidelines in a development or test environment, separate from your existing production environment:

  1. Create a parallel development or testing system, identical to your current production system.
    • You’ll use this parallel system to implement and test the Magento upgrade.
  2. In your current production environment:
    • Back up your Magento database.
    • Archive the file system. This includes the media directory and subdirectories; all extensions and customizations; and all custom themes.
  3. In the development or test environment:
    • Create a new, empty database instance.
    • Import the production database tables into the development database instance.
    • Copy your production media directory, extensions, themes, and other customizations to the development system.
    • Copy local.xml to magento-install-dir/app/etc and edit it if necessary to reference the production database instance.
    • In a web browser, go to your development system base URL.
    • Wait for upgrade scripts to run.
    • Verify the development system is now identical to the production system.
    • If not, fix issues, retest, and upgrade again.
  4. Test the development system thoroughly, including:
    • Verify all extensions, themes, and customizations work.
    • Place orders using all webstores and all payment methods.

Magento query master

This post is collection of mysql query to perform particular task, this will make you life easy.

NOTE : Basically this is not good practis to work with database directlly for live project. Make sure that you have database back up before run query.

Update customer group of all subscriber customer using query – Magento

    customer_entity.`group_id` = 5
    customer_entity.`entity_id` = newsletter_subscriber.`customer_id`
    newsletter_subscriber.`subscriber_status` = 1;

Turn template hints on/off using query – Magento

   value = 0
   path = "dev/debug/template_hints"
   path = "dev/debug/template_hints_blocks";

Change admin user password using query – magento

UPDATE admin_user SET password=CONCAT(MD5('qXpassword'), ':qX') WHERE username='admin';

Delete particular order using query – Magento

SET @increment_id='43290';
SELECT @order_id:=entity_id FROM sales_order_entity WHERE increment_id=@increment_id;
DELETE FROM sales_order_entity WHERE entity_id=@order_id OR parent_id=@order_id;
DELETE FROM sales_order WHERE increment_id=@increment_id;

Mass Exclude/Unexclude Images using query – Magento

//Mass Unexclude
UPDATE`catalog_product_entity_media_gallery_value` SET `disabled` = '0' WHERE `disabled` = '1';
//Mass Exclude
UPDATE`catalog_product_entity_media_gallery_value` SET `disabled` = '1' WHERE `disabled` = '0';

Delete all products using query – Magento

TRUNCATE TABLE `catalog_product_bundle_option`;
TRUNCATE TABLE `catalog_product_bundle_option_value`;
TRUNCATE TABLE `catalog_product_bundle_selection`;
TRUNCATE TABLE `catalog_product_entity_datetime`;
TRUNCATE TABLE `catalog_product_entity_decimal`;
TRUNCATE TABLE `catalog_product_entity_gallery`;
TRUNCATE TABLE `catalog_product_entity_int`;
TRUNCATE TABLE `catalog_product_entity_media_gallery`;
TRUNCATE TABLE `catalog_product_entity_media_gallery_value`;
TRUNCATE TABLE `catalog_product_entity_text`;
TRUNCATE TABLE `catalog_product_entity_tier_price`;
TRUNCATE TABLE `catalog_product_entity_varchar`;
TRUNCATE TABLE `catalog_product_link`;
TRUNCATE TABLE `catalog_product_link_attribute_decimal`;
TRUNCATE TABLE `catalog_product_link_attribute_int`;
TRUNCATE TABLE `catalog_product_link_attribute_varchar`;
TRUNCATE TABLE `catalog_product_option`;
TRUNCATE TABLE `catalog_product_option_price`;
TRUNCATE TABLE `catalog_product_option_title`;
TRUNCATE TABLE `catalog_product_option_type_price`;
TRUNCATE TABLE `catalog_product_option_type_title`;
TRUNCATE TABLE `catalog_product_option_type_value`;
TRUNCATE TABLE `catalog_product_super_attribute`;
TRUNCATE TABLE `catalog_product_super_attribute_label`;
TRUNCATE TABLE `catalog_product_super_attribute_pricing`;
TRUNCATE TABLE `catalog_product_super_link`;
TRUNCATE TABLE `catalog_product_enabled_index`;
TRUNCATE TABLE `catalog_product_website`;
TRUNCATE TABLE `catalog_product_entity`;
TRUNCATE TABLE `cataloginventory_stock_item`;
TRUNCATE TABLE `cataloginventory_stock_status`;

Get class and methods of an object – PHP

Use get_class to get the name of an object’s class.

<?php $class_name = get_class($object); ?>

Now, Use get_class_methods to get a list of all the accessible methods on an object

$class_name = get_class($object);
$methods = get_class_methods($class_name);
foreach($methods as $method)
    echo "<br>";

Magento – Filter product collection by multiple categories

Magento providing verious type of filter that can be used directly from product collection. Including category filter,

$_category = Mage::getModel('catalog/category')->load($category_id);
$collection= Mage::getResourceModel('catalog/product')->getCollection()->addCategoryFilter($_category);

But the issue is with multiple categories to filter. You can use bellow code to overcome this problem,

$collection = Mage::getModel('catalog/product')->getCollection()
             ->joinField('category_id', 'catalog/category_product', 'category_id', 'product_id = entity_id', null, 'left')
             ->addAttributeToFilter('category_id', array(
                 array('finset' => '4'),
                 array('finset' => '8'))
             ->addAttributeToSort('created_at', 'desc');

How magento store password and validate password – Magento

Magento uses MD5 and salt algorithems to store password for customer as well admin user.

How magento create encrypted password

Magento create encrypted password with,


Here is the logic of decrypt($password) function,

 $password = "12345678";
 $salt = "at";
 $encyPasswod = md5($salt.$pass).":".$salt;

In above function, $salt is randomly generated string of two alphanumeric character.

How magento validate password

Bellow functiona will validate the user password,

Mage::getModel('customer/customer')->authenticate($email, $password);

Logic behind above function is,

 $email = "";
 $password = "123456";

 //Load a customer by email address
 $customer = Mage::getModel('customer/customer')

 // if loaded! get stored password from database
 $hash = $customer->getData("password_hash");

 // Get last two digits separate by :";
 $hashArr = explode(':', $hash);

 public function validateHash($password, $hash)
     $hashArr = explode(':', $hash);
     switch (count($hashArr)) {
         case 1:
             return $this->hash($password) === $hash;
         case 2:
             return $this->hash($hashArr[1] . $password) === $hashArr[0];
     Mage::throwException('Invalid hash.');

So, it simply means that even if you have not added salt key and only MD5 text as password, login will work.

Magento – Show Product Reviews on Product detail Page

Product review is one of the good feature of magento but with default magento theme product review listed on separate page. Usually  customer like to see all detail on same page instead redirect to another page. With this though we would like to show the product reviews  on product detail page only.

Bellow are steps which can help you to show product reviews on product detail page.

Call product review block on product detail page, you can add bellow code to local.xml

    <reference name="content">
        <block type="review/product_view_list" name="" as="reviews" template="review/product/view/review_summary.phtml" />
    </reference name="content">

Create new template file review_summary.phtml, under template/review/product/view/ folder

    $_items = $this->getReviewsCollection()->getItems();
    if( count( $_items ) )
        foreach( $_items as $_review ){
        // Get the Review Title
        echo $this->htmlEscape( $_review->getTitle() );
        // Get the Review Content
        echo $this->htmlEscape( $_review->getDetail() );
        // Get the Review Author
        echo $this->htmlEscape( $_review->getNickname() );

Call review block on view.phtml, where you need the block to be show based on your design.

<?php echo $this->getChildHtml('reviews') ?>