Monday, September 5

How to change Admin URL Path in Magento

Here is a quick guide on how to change admin url path in Magento. This need to be done for security reason to be safe from hacking/cracking issue. Basically, this is done not to let any general user to access the admin page.

Generally, we do have ‘admin‘ as the administrator path for Magento. So, the admin URL will be http://www.example.com/admin/

This article will show you, how you can change the admin url. Let’s say from ‘admin‘ to ‘backend‘. So, the new admin URL will be http://www.example.com/backend/

Here is how we do it:-

- Open app/etc/local.xml
- Find the following:-

<admin>
    <routers>
            <adminhtml>
                <args>
                    <frontName><![CDATA[admin]]></frontName>
                </args>
            </adminhtml>
        </routers>
</admin>

- Change

<frontName><![CDATA[admin]]></frontName>

to your desired name. Like below:-

<frontName><![CDATA[backend]]></frontName>

- Save the file
- Refresh the Cache from Magento Admin (System -> Cache Management)

Now, you should be able to access admin panel from http://www.example.com/backend/ instead of http://www.example.com/admin/
Important Note

If you just need to change the admin base URL then the proper way I find is by doing the change in local.xml like explained above, instead of editing configuration setting from admin like said below.

I tried to change the Admin Base URL from Magento admin panel. But, I ran into problem and could not access the admin after that. Here is what I did:-

- System -> Configuration -> ADVANCED -> Admin -> Admin Base URL
- Changed Use Custom Admin URL = Yes
- Changed Custom Admin URL (Once I tried with ‘backend/’ and then with ‘http://www.example.com/backend/’)

To solve the problem, I had to make some change in database. If you had similar problem then here is a workaround:-

- Open your database
- Browse table ‘core_config_data‘
- Search in path field for ‘admin/url/use_custom‘ and set its value to ’0′
- Search in path field for ‘admin/url/custom‘ and set its value to empty

- Search in path field for ‘web/secure/base_url‘
- You will find two row result. One with scope = default and another with scope = stores.
- Edit the value of row with scope = stores with the value of the row with scope = default

- Similarly, repeating the process for ‘web/unsecure/base_url‘:-

- Search in path field for ‘web/unsecure/base_url‘
- You will find two row result. One with scope = default and another with scope = stores.
- Edit the value of row with scope = stores with the value of the row with scope = default

- Now, you will be able to login to Magento admin with your old admin base URL.

Ref : http://blog.chapagain.com.np/magento-how-to-change-admin-url-path/

How to Sort latest product by ‘created date’ and ‘new from date’ in Magento

Here is a quick tip to sort/order latest product by both created date and new from date.

Created At date is automatically added when you add a new product. However, you have to set New from Date manually while adding or editing product.

You may have product with same new from date. And, then you need created at date to sort the latest product.

Here is the code to sort/order product by both created date and new from date:-

$todayDate  = Mage::app()->getLocale()->date()->toString(Varien_Date::DATETIME_INTERNAL_FORMAT);
 
$collection = Mage::getModel('catalog/product')
                    ->getCollection()
                    ->addAttributeToFilter('news_from_date', array('date' => true, 'to' => $todayDate))
                    ->addAttributeToFilter('news_to_date', array('or'=> array(
                        0 => array('date' => true, 'from' => $todayDate),
                        1 => array('is' => new Zend_Db_Expr('null')))
                    ), 'left')
                    ->addAttributeToSort('news_from_date', 'desc')
                    ->addAttributeToSort('created_at', 'desc');

Thanks to Mukesh Chapagain's Blog
Reference : http://blog.chapagain.com.np/magento-sort-latest-product-by-created-date-and-new-from-date

How to disable / remove Secret Key from Admin URL in Magento

A new secret key is created every time you login to Magento Admin. So, there will be a unique key (32 chars long) for each session of your Magento admin login. This key is appended to the admin URL as http://your-admin-url/key/743c37b1…adf6588/

This is basically added for security reason. In their release note, Magento say that they added secret key to URL for CSRF (Cross-site request forgery) Attack Prevention.

Cross-site request forgery, also known as a one-click attack or session riding and abbreviated as CSRF or XSRF, is a type of malicious exploit of a website whereby unauthorized commands are transmitted from a user that the website trusts. Unlike cross-site scripting (XSS), which exploits the trust a user has for a particular site, CSRF exploits the trust that a site has in a user’s browser.

You can learn more about CSRF here:- http://en.wikipedia.org/wiki/Cross-site_request_forgery

Sometime you may want to access admin URL without the secret key. For this, you can disable the secret key from admin URL.

Here is how you do it:-

- Login to admin
- Go to System -> Configuration -> ADVANCED -> Admin -> Security -> Add Secret Key to URLs
- Select No
- Save Config

You are done. You will not see the secret key in admin URL nowonwards.

Thanks to Mukesh Chapagain's Blog
Reference : http://blog.chapagain.com.np/magento-how-to-disable-remove-secret-key-from-admin-url

Can’t send header. Header is already sent” in Magento - Tips to solve the problem

In this article I will show you quick tip that will help you solve common problems in Magento: “Can’t send header. Header already sent” in Magento.

I got this error when I have managed to bring back the client store. Basically, this error happens when there is an extra space or character outside the the php tag . Thanks to the help of excellent Magento users, I have been able to solve it. I think it will be useful if I explained steps by steps what I personally have done so that you can reference it later. When this error happens, you should try the following things.

Open the file that has the problem. In my case, this file is index.php in the site root of Magento.

Open the file with some text editors that supports the encoding. I prefer Notepad++ because its great support in multi languages as well as encoding.

If you open it by Notepad++, click on the menu Encoding, click on UTF-8 without BOM. Save it and then re-upload it to the server.

We just save the error file in the UTF-8 encoding to make sure that everything extra space, line is wiped out. Encoding without BOM ensures you will not have any extra, unwanted characters in the file that prevent it from being executed properly.

Hope it Helps... Thanks..

Friday, August 19

How to get all store details in Magento

Here is the script to get all store details in Magento

<?php
$allStores = Mage::app()->getStores();
foreach ($allStores as $_eachStoreId => $val)
{
$_storeCode = Mage::app()->getStore($_eachStoreId)->getCode();
$_storeName = Mage::app()->getStore($_eachStoreId)->getName();
$_storeId = Mage::app()->getStore($_eachStoreId)->getId();
echo $_storeId;
echo $_storeCode;
echo $_storeName;
}
?> 

Hope it helps... Thanks....

Wednesday, August 10

Frequently Used Methods in Magento

1. Check if customer is logged in:
if(!Mage::getSingleton('customer/session')->isLoggedIn())
{
 $this->_redirect('customer/account/login/');
}

2. Get current site url:
<?php Mage::getUrl(); ?>

3. Get Category URL:
$categoryUrl = Mage::getModel('catalog/category')->load($categoryId)->getUrl(); 

4. Get product URL:
$productId = 1;
$product = Mage::getModel('catalog/product')->load($productId);
$path = Mage::getUrl().$product->getUrlPath();

5. Get Product image path:
$productId = 1;
$product = Mage::getModel('catalog/product')->load($productId);
$path = Mage::helper('catalog/image')->init($product, 'image')->resize(75, 75);

6. Format a number as price:
<?php $this->formatPrice(10);?>

7. Call a .phtml explicitly:
echo $this->getLayout()->createBlock('sales/order_recent')->setTemplate('sales/order/recent.phtml')->toHtml();


8. Get Currency Code:
Mage::app()->getStore()->getCurrentCurrencyCode();

9. Get Currency Symbol:
Mage::app()->getLocale()->currency(Mage::app()->getStore()->getCurrentCurrencyCode())->getSymbol();

10. Get Customer Shipping/Billing Address:
$customerAddressId = Mage::getSingleton('customer/session')->getCustomer()->getDefaultShipping();
if ($customerAddressId){
       $address = Mage::getModel('customer/address')->load($customerAddressId);
}

11. Get products details in the cart:
$mageFilename = 'app/Mage.php';
require_once $mageFilename;
umask(0);
Mage::app();
 
// Secret Sauce - Initializes the Session for the FRONTEND
// Magento uses different sessions for 'frontend' and 'adminhtml'
Mage::getSingleton('core/session', array('name'=>'frontend'));
 
$session = Mage::getSingleton('checkout/session');
foreach ($session->getQuote()->getAllItems() as $item) 
{
 $productid      = $item->getProductId();
 $name       = $item->getName();
 $qty       = $item->getQty();
  
 echo "Product Id-".$productid.', Name-'.$name. ', Quantity-'.$qty;
}

12. Find which class is loaded in current template:
<?php
    print_r(get_class_methods(get_class($this)));
?>
or
<?php
    print_r($this->debug());
?>
or
<?php
    echo Zend_Debug::dump($this);
?>

13. Get Current theme folder:
<?php echo $this->getSkinUrl('') ?>

14. Get total price of items in the cart:
<?php echo $this->helper('checkout')->formatPrice(Mage::getSingleton('checkout/cart')->getQuote()->getGrandTotal()); ?>

15. Get the current category:
<?php
    $currentCategory = Mage::registry('current_category');
?>
16. Add product to cart through querystring:
http://www.mydomain.com/checkout/cart/add?product=[id]&qty=[qty]
 
http://www.mydomain.com/checkout/cart/add?product=[id]&qty=[qty]&options[id]=[value]

These are the some of the frequently used functions in Magento

Hope it Helps... Thanks..

Tuesday, July 19

How to get Customer Group Id in Magento

Here is the script to get customer group id in Magento

<?php
$login = Mage::getSingleton( 'customer/session' )->isLoggedIn(); //Check if User is Logged In
if($login)
{
$groupId = Mage::getSingleton('customer/session')->getCustomerGroupId(); //Get Customers Group ID
if($groupId == 2) //My wholesale customer id was 2 So I checked for 2. You can check according to your requirement
{
echo 'You are a wholesale Customer';
}
}
?> 

Hope it helps .. Thanks...

Saturday, July 16

How to Add Customer Group field while Create Account in magento

Here is the step by step procedure to add customer group in account registration form


Step 1: go to app/code/core/Mage/customer/etc/config.xml and add the following code

<fieldsets><customer_account>
<group_id><create>1</create><update>1</update></group_id>
</customer_account></fieldsets>

Step : 2 Now go to register.phtml which resides app/design/frontend/your_interface/Your_theme/template/customer/form/Register.phtml and write the following code under the section where you wan't to put.

<li>
<label for="customer_groups" class="required"><em>*</em><?php echo $this->__('Customer Groups') ?></label>
<select name="customer_groups" id="customer_groups" title="<?php echo $this->__('Customer Groups') ?>" class="validate-group required-entry input-text">
<?php $cu_groups = Mage::helper('customer')->getGroups()->toOptionArray(); ?>
<?php foreach($cu_groups as $cuGroups){ ?>
<option value="<?php echo $cuGroups['value'] ?>"><?php echo $cuGroups['label'] ?></option>
<?php } ?>
</select>
</li>

Step 3: open accountcontroller.php in app/code/core/mage/customer/controllers/accountcontroller.php and add the following code in the "initialize customer group id" part

<?php
$customer->setGroupId($this->getRequest()->getPost('customer_groups'));
?>

now you can get the customer group field while registering account.

Hope it Helps.. Thanks....

Tuesday, July 12

How to set Different Prices for each store in Magento

Follow these steps to change the price for product for each store in magento

Step 1.  In the Admin panel, goto System, Configuration, Catolog, then Price.

Step 2. Change Price from Global to Website.

Step 3. You should see “Website” on the price page for the product now, instead of “Global”.

Step 4. For each product you want to set different prices on – select the product, then in the upper left corner you will see the option to chose your store view.  Select the first store

Step 5. Set the price for the first store and click “Save and Continue Editing”

Step 6. Select the store view for your second store and set the price for that store

Step 7. Repeat step 6 until all of your store have the prices you want.

Hope it helps .. Thanks...

Wednesday, July 6

How to get All Store Details in Magento

Here is the script to get all store Ids and Name in Magento

<?php
$allStores = Mage::app()->getStores();
foreach ($allStores as $_eachStoreId => $val)
{
$_storeCode = Mage::app()->getStore($_eachStoreId)->getCode();
$_storeName = Mage::app()->getStore($_eachStoreId)->getName();
$_storeId = Mage::app()->getStore($_eachStoreId)->getId();
echo $_storeId;
echo $_storeCode;
echo $_storeName;
}
?>

Hope it Helps.. Thanks...