How to show product’s rating any where in Magento

Reviews are another one of numerous excellent features in Magento. Usage of reviews can increase visitors’ trust in your brand, which, in return boosts your sales by a significant amount. Sometimes there is a need for showing star ratings outside the products’ review page. That’s what I’ll be addressing with this article.

The following code snippet works just about anywhere you have a product loaded (or if you know it’s ID) – cart being one of the examples.

How to add custom tabs into Magento Product Page

How to add custom tabs into Magento Product Page The product page is one of the most important parts of your store. That’s why so much attention is paid to make this page look perfect. Tabs is a good way to display a lot of data inside a compact block. It helps to avoid huge scroll bars and also looks much nicer on portable devices. You can find tons of Magento templates with tabs on the product view page and we are going to tell you the easiest way to add them there. All examples are applicable to the default Magento theme, but with practice you can use following methods to customize your own theme. First, go to your store theme folder and find there the following file app/design/frontend/default/yourtheme/layout/catalog.xml. If the file does not exist, you can always copy it from app/design/frontend/base/default/layout/. Note that your own theme can be located within a different path. In the file catalog.xml, find the section:

 

    
       
            product.tierprices
            
            product.info.addtocart
            product.info.addto
         
		

How to add new tab on product view page

After Magento 1.9 has been released people started asking how to handle the product page tabs since the previous method caused different troubles. The reason is in the modern RWD theme, which goes out of the box with Magento 1.9. It uses slightly different method for adding tabs than in the previous versions. So, let's review how you can easily add own tabs on the product page for RWD-based themes in Magento CE 1.9. First of all, let's make our implementations as clean as possible. To avoid copying of unnecessary pieces of code we will make our changes in the layout file that is being used for custom theme's modifications. You can find this file here: app/design/frontend/[theme_package]/[theme]/layout/local.xml There [theme_package] - it's your package's name and [theme] - it's your theme's name. If there's no such file – just create a clean one. Then, paste the following content in the newly created file:
<?xml version="1.0"?> version="1.0"?>

    
        
            
                detailed_info
                The New Tab
            
        
    

In case if this file already exists – just add the content between (including them) inside of node. As you can see, we have added a block with the class 'core/template' (Mage_Core_Block_Template) inside of the group called 'detailed_info'. That group is a built-in templates group for the product page tabs. You can use any name for your tab, just ensure that it's unique ('the_new_tab' in our example). Then, we have assigned the template file for our tab where the tab's content is placed – 'atwix/newtab.phtml'. Finally, we have set the name for our tab using the standard method 'setTitle()', so the name is 'The New Tab'. On the last step, we need to check if our product view template contains the tabs output logic. Open the following file: app/design/frontend/[theme_package]/[theme]/template/catalog/product/view.phtml

Login as a customer from Magento admin

Often there are situations where customer has some issues while placing orders or making operations from the “My Account” section. At that point, an ability for admin to login as a customer and see what is wrong becomes very useful. Sure, you can make a universal password logic, but that method has heavy security risks. Not so long ago, we’ve noticed that Magento has ability to load and use customer’s sessions different way. We will tell you how to create a simple extension for logging in as a customer from Magento admin. Step 1 For example, let’s call our module Arun_Ulogin. As always we must start by creating a module descriptor in app/etc/modules folder. So put the Arun_Ulogin.xml file into this directory. The file will be with the following content:
<&#63xml version="1.0"?>

    
         
            true
            community
          
    

Overriding Magento observers

As you may know, we need to override the Magento observers when we deal with the extension’s conflicts or want to disable (or modify) a part of some extension’s functionality. Usually, there is no difference between the observer’s overriding and overriding of any other regular model. But sometimes we can face with the issues working with the simple override. How should we act then to keep it conventionally? Let’s check the following step by step instruction for Magento observers overriding. First of all, we should pay attention to the naming. Let’s assume that we have some 3rd party extension. It is named Some_Extension, and this extension has the following observer:
<&#63php
/**
 * file path:
 * magento_root/app/code/local/Some/Extension/Model/Observer.php
 */
 
class Some_Extension_Model_Observer
{
   public function someMethod( $observer )
   {
      /** 
       *Do some stuff here 
       */
         
      return $observer;
   }
}
&#63>

How to rewrite url in Magento

Follow these instruction to rewrite url. Step 1:- Make a new category named with "laptop" and save it. Step 2:- Go to Catalog->Url rewrite management.And find your newly created category and click on it. more instruction see in below pic.


Some useful and important code in magento

Some useful and important code in magento :-
<&#63php  
Magento Home URL 
- Mage::getBaseUrl();
 
Magento Home Directory 
- Mage::getBaseDir();
 
URL of a file in the skin directory
- $this->getSkinUrl('images/myfile.png'); // in a template or Block
- Mage::getDesign()->getSkinUrl('images/myfile.png'); // from anywhere
 
Format a price value
- Mage::helper('core')->formatPrice($amount);
 

How to insert,update,delete and show data in Magento

Suppose, I have a module named mynews. Here follows the code to select, insert, update, and delete data from the news table
1. INSERT DATA
$data contains array of data to be inserted. The key of the array should be the database table’s field name and the value should be the value to be inserted.
<&#63php
$data = array('title'=>'hello there','content'=>'how are you? i am fine over here.','status'=>1);
$model = Mage::getModel('mynews/mynews')->setData($data);
try {
    $insertId = $model->save()->getId();
    echo "Data successfully inserted. Insert ID: ".$insertId;
} catch (Exception $e){
 echo $e->getMessage();   
}
&#63>

How to insert your block into any place in Magento

Hello guys, it’s time to tell you how to insert block into any place you want in Magento. As you know, very often we need to set some block into selected weird place without editing template, so we’ll try to describe the way how to do this using layouts and observers.In our case, for such experiments will be used category page. Let’s say, you need to place your block inside the other one and this block is instance of the Mage_Core_Block_Text_List class. That means, the block renders his children automatically, what’s easy. Then, you just need to follow the steps which are below:

    

This block will be displayed after all content of the “left“ block. But, what if we need it to be displayed before all content – just add the “before” directive. See below such example:

Important operatinol functions of Magento

1.How to get the category url in magento
<?php echo Mage::getModel('catalog/category')->load($catId)->getUrl() ?>
2.How to remove .html at the end of the url in magento
System => Configuration => Catalog => Search Engine Optimization and empty the fields "Product URL Suffix" and "Category URL Suffix"
3.How to get category’s Thumbnail image in magento
<?php $thumbnail=Mage::getModel('catalog/category')->load($categoryId)->getThumbnail();  //$category_Id -category id ,$thumbnail – image name
if($thumbnail !=''){
$imgPath = Mage::getBaseUrl('media').'catalog/category/'  // Get category image path
echo '';
?>
4.How to get Customer Details By Session
<?php  $customer = Mage::getSingleton('customer/session')->getCustomer();
    print_r($customer);?>
4.1How to get Customer Details By E-Mail
<?php   $customer = Mage::getModel('customer/customer')->loadByEmail(example@mail.com);
    print_r($customer); ?>
5.How to delete product by sku :-
<?php  $product = Mage::getModel('catalog/product');
   $productId = intval($product2->getIdBySku('putSkuHere');
   $product->load($productId)->delete(); ?>
6.How to get module table :-
<?php  
$resource = Mage::getSingleton('core/resource');
$tableName = $resource->getTableName('mymodule/mymodel') 
?>

how to upload any file in magento

Step 1 :- cretae html form for upload file
Step 2 :- Write Script for upload file
<?php

if(isset($_FILES['myfilename']['name']) && $_FILES['myfilename']['name'] != '')
{  
try
    {      
        $path = Mage::getBaseDir('media') . DS . 'csvfile' . DS;  //desitnation directory    
        $fname = $_FILES['myfilename']['name']; //file name
  $filpath = $path.$fname;
        $uploader = new Varien_File_Uploader('myfilename'); //load class
        $uploader->setAllowedExtensions(array('xls','xlsx','csv')); //Allowed extension for file
        $uploader->setAllowCreateFolders(true); //for creating the directory if not exists
        $uploader->setAllowRenameFiles(false); //if true, uploaded file's name will be changed, if file with the same name already exists directory.
        $uploader->setFilesDispersion(false);
        $uploader->save($path,$fname); //save the file on the specified path
    }
    catch (Exception $e)
    {
        echo 'Error Message: '.$e->getMessage();
    }
}
?>

How to create category from csv file

How to create bulk parent and sub category from csv file
Instruction:- Copy and save this code file in root folder of Magento and run it. exp :- http://yoursite/cat.php
<?php
error_reporting(E_ALL | E_STRICT);
$mageFilename = 'app/Mage.php';
require_once $mageFilename;
$app = Mage::app('admin'); 
Mage::setIsDeveloperMode(true);
ini_set('display_errors', 1);
ini_set('max_execution_time', 1800);
umask(0);
/************ Get CSV file **************/
  $path = Mage::getBaseDir('media') . DS . 'catcsvfile'; //file path of csv
  $files = glob($path.'/*'); // get all file names
  if($files){
   foreach($files as $file){ // iterate files   
     $csv  =  new Varien_File_Csv();
     $data =  $csv->getData($file); //path to csv
        }  
 array_shift($data);
 foreach($data as $_data){
/*****************  Prent category creation *****************/
   /*****************  Prent category creation *****************/
   $Pcat =  utf8_encode($_data[0]); // column to create parent category
   $getcategory = Mage::getResourceModel('catalog/category_collection')->addFieldToFilter('name',$Pcat);
   $catData = $getcategory->getData();
   $catcount  = count($catData);
    if($catcount==0 && !empty($Pcat))
   {  $category = Mage::getModel('catalog/category');
     $category->setName($Pcat);
     $category->setUrlKey($Pcat);
     $category->setMetaTitle($Pcat);
     $category->setIsActive(1);
     $category->setDisplayMode('PRODUCTS');
     $category->setIsAnchor(1); //for active achor
     $category->setStoreId(Mage::app()->getStore()->getId());
     $parentCategory = Mage::getModel('catalog/category')->load(2);
     $category->setPath($parentCategory->getPath());
     $category->save();
  }
/*    Child category creation             **********************/
   global $childcat;
    $childcat = utf8_encode($_data[1]); // column to create sub category
   $pgetcategory = Mage::getResourceModel('catalog/category_collection')->addFieldToFilter('name',$childcat);
   $pcatData = $pgetcategory->getData();
   if(!$pcatData) {
    $getcategory2 = Mage::getResourceModel('catalog/category_collection')->addFieldToFilter('name',$Pcat);
    $catData2 = array();
   $catData2 = $getcategory2->getData();
   if(!empty($catData2)){
   $ParentCategoryId2 = $catData2[0]['entity_id'];   
     $category = Mage::getModel('catalog/category');
     $category->setName($childcat);
     $category->setUrlKey($childcat);
     $category->setMetaTitle($childcat);
     $category->setIsActive(1);
     $category->setDisplayMode('PRODUCTS');
     $category->setIsAnchor(1); //for active achor
     $category->setStoreId(Mage::app()->getStore()->getId());
     $parentCategory = Mage::getModel('catalog/category')->load($ParentCategoryId2);
     $category->setPath($parentCategory->getPath());
     $category->save();
   }  
   }
 }
}
else
{
echo 'file not found';
}
?>

How to get category id by category name in magento

<?php
$category = Mage::getResourceModel('catalog/category_collection')->addFieldToFilter('name','cateNameHere'));
    $catData = $category->getData();      
 $categoryId = $catData[0][entity_id];
 echo $categoryId;
 ?>

How to delete all category in magento

Instruction :- Copy and save this code file in root folder of Magento and run it; exp :- http://yoursite/deletecat.php
<?php 
error_reporting(E_ALL | E_STRICT);
$mageFilename = 'app/Mage.php';
require_once $mageFilename;
Mage::setIsDeveloperMode(true);
ini_set('display_errors', 1);
ini_set('max_execution_time', 1800);
umask(0);
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
foreach(Mage::getModel('catalog/category')
->getCollection()
->addFieldToFilter('entity_id', array('gt' => 2)) as $cat) {
$cat->delete();
}
?>

How to write secure code in Php -1

PHP is a very easy language to learn, and many people without any sort of background in programming learn it as a way to add interactivity to their web sites. Unfortunately, that often means PHP programmers, especially those newer to web development, are unaware of the potential security risks their web applications can contain. Here are a few of the more common security problems and how to avoid them.

Rule Number One: Never, Ever, Trust Your Users
It can never be said enough times, you should never, ever, ever trust your users to send you the data you expect. I have heard many people respond to that with something like "Oh, nobody malicious would be interested in my site". Leaving aside that that could not be more wrong, it is not always a malicious user who can exploit a security hole - problems can just as easily arise because of a user unintentionally doing something wrong.

How to write secure code in Php -2

Learn how to improve your security a little further with the second part of this PHP tutorial.
In Writing Secure PHP, I covered a few of the most common security holes in websites. It's time to move on, though, to a few more advanced techniques for securing a website. As techniques for 'breaking into' a site or crashing a site become more advanced, so must the methods used to stop those attacks.


File Systems
Most hosting environments are very similar, and rather predictable. Many web developers are also very predictable. It doesn't take a genius to guess that a site's includes (and most dynamic sites use an includes directory for common files) is an www.website.com/includes/. If the site owner has allowed directory listing on the server, anyone can navigate to that folder and browse files.

How to write secure code in Php -3

The third part of the Writing Secure PHP series, covering weak passwords, clients and more advanced topics.
In How to write secure code in Php-1, 2  and 3 I covered many of the basic mistakes PHP developers make, and how to avoid common security problems. It is time to get a little deeper into security though, and begin to tackle some more advanced issues.
Context
Before I start, it is worth mentioning at this point in this series that much of what is to come is highly dependant on context. If you are running a small personal site and are regularly backing it up, the chances are that there is no real benefit to you spending weeks on advanced security issues. If an attacker can gain nothing (and cause no harm) by compromising your site, and it would only take you ten minutes to restore it, should something go wrong, then it would be a waste to spend too long on security concerns. At the other end of the scale, if you are managing an ecommerce site that processes thousands of credit cards a day, then it is negligent not to spend a lot of time researching and improving your site's security.

How to wright secure code in Php-4


Cross-Site Scripting (XSS)
Cross-site scripting (often abbreviated to XSS) is a form of injection, where an attacker finds a way to have the target site display code they control. In its most basic form, this can be as simple as a site that allows HTML characters in usernames, where someone can specify a username like:
DaveChild<script type="text/javascript" src="http://www.example.com/my_script.js"></script>
Now, whenever someone sees my username on the target site, the script I've added to my username will run. I could potentially use this to grab the person's login information, log their keystrokes - any number of nefarious activities.

How to make a xml file in php

Here is the PHP code you can customize it according to your requirements.

<&#63php
$xml = new SimpleXMLElement('<root/>');

$track = $xml->addChild('track');

$track->addChild('fieldName1','fieldValue');

$track->addChild('fieldName2','fieldValue');

$track->addChild('fieldName3','fieldValue');

$track->addChild('fieldName4','fieldValue');

Header('Content-type: text/xml');

print($xml->asXML());

&#63>
Enjoy Coding ..!!