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.

Access URL restricted with .htpasswd in PHP with cURL

We are used to accessing external web application or web services using cURL in PHP for information exchange. bellow is the code for that,

<?php
$url = "xyz.com";
// initiate curl resource 
$ch = curl_init();
// set url to be read
curl_setopt($ch, CURLOPT_URL, $url);
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
//$output contains the output in string 
$output = curl_exec($ch); 
//close curl resource to free up system resources
curl_close($ch);
?>

Some time (mostly on development / staging server) we need to access URLs or files which are protected by .htpasswd. Just with the above code We can not access such URLs.

To access such file or URL which is protected by .htpasswd, we need to pass its user name and password with bellow code,

$username = "testuser";
$password = "testpass";
$url = "xyz.com";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, “$username:$password”);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
$output = curl_exec($ch); 
curl_close($ch);

Git – File Rename

We have seen the basic commands in Git – Setup repository and basic operation

Let add something more in to that, how to rename file with git svn. Here is the command for that,

git mv oldname newname

i.e.

git mv -f event.php Event.php

here -f stand for force, Force renaming file even if the target exists.

Basically above command line will just do,

git add newname
git rm oldname

git mv command is also use to move file from one to another location. As bellow,

git mv <source> <destination>

Magento : How to get all active payment methods and shipping methods

Bellow chunk of code will get you all active payment methodes,

$payments = Mage::getSingleton('payment/config')->getActiveMethods();
$payMethods = array();
foreach ($payments as $paymentCode=>$paymentModel) 
{
    $paymentTitle = Mage::getStoreConfig('payment/'.$paymentCode.'/title');
    $payMethods[$paymentCode] = $paymentTitle;
}
return $payMethods;

This code will returns all active shipping methods,

$methods = Mage::getSingleton('shipping/config')->getActiveCarriers();
$shipMethods = array();
foreach ($methods as $shippigCode=>$shippingModel) 
{
    $shippingTitle = Mage::getStoreConfig('carriers/'.$shippigCode.'/title');
    $shipMethods[$shippigCode] = $shippingTitle;
}
return $shipMethods;

what are magic methods in PHP?

This post will give you very simple and basic understanding of magic methods in PHP. That is, “The function name which start with double underscore “__” are called magic functions.”  Those are Always  defined inside classes, they could not be stand alone functions.

The reasons behind the name “magic functions” is,

  • The programmer has to define the definition of magic functions. PHP does not provide the definitions of the magic functions.
  • Magic functions will never directly called by the programmer. Actually, PHP will call the magic function ‘automatically based on requirement’.

So many magic functions available in PHP : __construct(), __destruct(), __call(), __autoload(), __get(), __set(), __isset(), __unset(), __wakeup(), __toString(), __invoke(), etc. some more magic functions are also available. Magic functions are like a widgets for programer, which can be utilize for powerful programing.

Lets just take one simple example of “__construct()” to make it more simple. This most commonly used magic function, This function is introduce with PHP5. Programmer will give the definition of the __construct function, but that will called automatically while the object of class is define.

Here is an example,

class Area
{
   public $height;      // height
   public $weight;     // weight

   public function __construct($height, $weight) 
   {
     $this->height = $height;  //set the height
     $this->weight = $weight;  //set the weight
   }
}

In above code, we have a simply define __construct function, which will set height and weight of area object. In bellow line we have just create object of area calls.

$area = new Area(10, 50);

So finally what happen here, we have just define the construct function, which is to set height and width of and object. Now when we will create an object it will automatically called __construct function and set the values of variables. This is the magic of magic functions.

Magento – get directory paths, get Base URLs, get URLs in static block, get secure URL

This post help you to get url, directory path, to get module URL. This is very basic post, that will help to beginners.

Get Base URL

 Mage::getBaseUrl() => Get base url path e.g. http://yourwebsite.com/
 Mage::getBaseUrl('media') => Get MEDIA folder path e.g. http://yourwebsite.com/media/
 Mage::getBaseUrl('js') => Get JS folder path e.g. http://yourwebsite.com/js/
 Mage::getBaseUrl('skin') => Get SKIN folder path e.g. http://yourwebsite.com/skin/

Get Current URL

Mage::helper('core/url')->getCurrentUrl();

Get Home URL

Mage::helper('core/url')->getHomeUrl();

Create module your

Mage::getUrl('module/controller/action');

Get secure URL
To get secure URL you just need to add one more parameter as bellow,

Mage::getUrl('',array('_secure'=>true))
Mage::getUrl('module/controller/action',array('_secure'=>true))

Get Directory paths

Mage::getBaseDir()
 //output : /var/www/html/magento
Mage::getBaseDir('app')
 //output : /var/www/html/magento/app
Mage::getBaseDir('media')
 //output : /var/www/html/magento/media

Same way you can get more directory path,
Mage::getBaseDir(‘design’) => Get design directory path
Mage::getBaseDir(‘code’) => Gives code directory file path
Mage::getBaseDir(‘lib’) => Gives lib directory file path
Mage::getBaseDir(‘skin’) => Gives skin directory file path
Mage::getBaseDir(‘var’) => Gives var directory file path
Mage::getBaseDir(‘cache’) => Gives cache directory file path
Mage::getBaseDir(‘log’) => Gives log directory file path

Get URL path in Static Block
Get Base URL

{{base url=''}}

Get Skin URL

{{skin url='images/skinimage.jpg'}}

Get Media URL

{{media url='/mediaimage.jpg'}}

Get Store URL

{{store url=''}}

Get country code from country name in Magento

Its very simple to get the country name by given country code with following code,

$country_name=Mage::app()->getLocale()->getCountryTranslation("in");
or
$countryName = Mage::getModel("directory/country")->load("in")->getName();

But in one of the application I come across the situation where I need get country code from country name. I have used bellow logic to fulfill my need,

$countryList = Mage::getResourceModel('directory/country_collection')
                    ->loadData()
                    ->toOptionArray(false);
$needle = "India";
foreach ($countryList as $key => $val) 
{
   if (strtolower($val['label']) === strtolower($needle)) {
       echo $val['value'];
       break;
   }
}

You will get the array of all country list with in $countryList variable. From that array I am searching for my required country code.

I am sure there must be some alternate way to get the same. If you know some alternate way, which is more convenient you are most welcome to post your ideas or suggestions.

Uploads file to FTP server programmatically using PHP script

PHP it self provide us the FTP functions library which allow to implement client access to files servers (FTP). This library providing a wide range of control to executing script including read or write file to FTP server. This post will particularly post show you how to Send Files to send file using php script. Here is the  script which allow you to upload file to FTP server,

<?php
    // Connect to server
    $conn = ftp_connect("ftp.yourserver.com") or die("Could not connect");

    ftp_login($conn,"username","password") or die("invelid username or password");

    // move to path where you need to upload file
    ftp_chdir($conn, "/upload/") or die("could not find dir");

    // upload file to particular path
    $upload = ftp_put($conn,"allproduct.xml","allproduct.xml",FTP_BINARY);

    if (!$upload) { echo 'FTP upload failed!'; }

    ftp_close($conn);
?>

Some time you need to create dir dynamically on server, in that case you can use bellow code instead of change dir,

if(!ftp_chdir($conn, $folder_path))
{
    $create_folder = ftp_mkdir($conn, $folder_path);
    ftp_chmod($conn, 0777, $folder_path);
    ftp_chdir($conn, $folder_path);
}

Above part of script will check for particular dir. If it could not find, it will create that dir and moved to particular dir path. Then you can continue to upload part.