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….

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

I hope this would help you….

Advertisements

Magento – What is the difference between getAllVisibleItems() and getAllItems()?

Before we start with answer of the question, I would like to explain what are these functions. These bothe functionas are used to get all order items,

// load form order ID
$order_id = 1234;
$order = Mage::getModel("sales/order")->load($order_id);
OR
// Get current order ID
$order_id = Mage::getSingleton('checkout/session')->getLastRealOrderId();
$order = Mage::getModel('sales/order')->loadByIncrementId($order_id);
//$order->getSubtotal() ; $order->getGrandTotal() ;
$items = $order->getAllItems(); OR $order->getAllVisibleItems();
$itemcount=count($items);
foreach ($items as $itemId => $item)
{
    $item->getName();
    $item->getPrice();
    $item->getSku();
    $item->getProductId();
    $item->getQtyOrdered(); //$item->getQtyToInvoice();
}

Above code will give all the information of order and ordered items.

Now lets get back to the main question. Let’s look at the code of both methods first,

public function getAllItems()
{
    $items = array();
    foreach ($this->getItemsCollection() as $item) {
       if (!$item->isDeleted()) {
          $items[] = $item;
       }
    }
    return $items;
}
public function getAllVisibleItems()
{
    $items = array();
    foreach ($this->getItemsCollection() as $item) {
       if (!$item->isDeleted() && !$item->getParentItemId()) {
          $items[] = $item;
      }
    }
    return $items;
}

From the code we can see, The only difference is getAllVisibleItems() has an additional check for each item that is,

!$item->getParentItemId()

Which will allow parent item only, It means if you have Configurable Product in your order, getAllVisibleItems will show you only the parent item while getAllItem will show both products.

$order->getAllItems() refers to the all items parent and it’s child (ref: configurable product and it’s child items)
getallitems

$order->getAllVisibleItems() refers to the Parent items only (Ref: configurable product only)
getallvisibleitems

Conclusion, If you need to show order product or do some kind calculation on total ordered items getAllVisibleItems is more preferable.

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')
        ->getCollection()
        ->addAttributeToSelect('name')
        ->addAttributeToSort('path', 'asc')
        ->addFieldToFilter('is_active', array('eq'=>'1'))
        ->load()
        ->toArray();

    // 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>
<?php
    $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>
 <?php
    }
?>
</select>

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

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

change it to this

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

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.

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

UPDATE
    customer_entity,
    newsletter_subscriber
SET
    customer_entity.`group_id` = 5
WHERE
    customer_entity.`entity_id` = newsletter_subscriber.`customer_id`
AND
    newsletter_subscriber.`subscriber_status` = 1;

Turn template hints on/off using query – Magento

UPDATE
   core_config_data
SET
   value = 0
WHERE
   path = "dev/debug/template_hints"
OR
   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

<?php
$class_name = get_class($object);
$methods = get_class_methods($class_name);
foreach($methods as $method)
{
    var_dump($method);
    echo "<br>";
}
?>

Magento: get current CMS page identifier

Below function will returns page identifier, if the current page is CMS page.

public function getCurrentCmsPage() {
    $dataCurrentPage = $this->getHelper('cms/page')->getPage()->getData();
    if ($dataCurrentPage) {
        $identifierCurrentPage = $dataCurrentPage['identifier'];
        return $identifierCurrentPage;  
    } 
    return;     
}

Magento – Insert Static Block in Magento Templates

There are basically three ways to insert static blocks into magento templates

1.Inserting into template-file.phtml

<?php
     echo  $this->getLayout()->createBlock('cms/block')->setBlockId('CMS-block-id')->toHtml() ;
?>

2. Inserting into CMS

{{block type="cms/block" block_id="CMS-block-id" template="cms/example-template.phtml"}}

3. Inserting into layout.xml

<layout>
    <example>
    <reference name="content">
     <block type="cms/block" name="cms_store_check">
     <action method="setBlockId"><block_id>CMS-block-id</block_id></action>
     </block>
     </reference>
     </example>
</layout>

Magento remove index.php from URL

Normally we find index.php in URL, and mostly we don’t like it to be there. This post will allow you to change your URL from

http://www.yourdomain.com/index.php/about

to

http://www.yourdomain.com/about

For that,

go to Admin > System > Configuration > Web > Search Engine Optimization,
change the value of Web Server Rewrites to Yes.

Make sure, your web server rewrite module is enabled and Check the file permission of .htaccess, it should be present in Magento root directory and readable by server.