Magento get current url of a page

Posted by Damodar Bashyal on May 13, 2013

 

Magento core url helper allows you to get current url.

To get current url in magento you just need one line of code as below:

ref: public function getCurrentUrl()

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

You can also get current url as base64 encoded url as:

$magentoCurrentUrlBase64 = Mage::helper('core/url')->getCurrentBase64Url();
or,
$magentoCurrentUrlBase64 = Mage::helper('core/url')->getEncodedUrl($url);
// $url is optional

Same helper allows you to get home url which is base url:

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

Source: app\code\core\Mage\Core\Helper\Url.php

Functions used above as they appear on magento core url helper are as below:

    /**
     * Retrieve current url
     *
     * @return string
     */
    public function getCurrentUrl()
    {
        $request = Mage::app()->getRequest();
        $port = $request->getServer('SERVER_PORT');
        if ($port) {
            $defaultPorts = array(
                Mage_Core_Controller_Request_Http::DEFAULT_HTTP_PORT,
                Mage_Core_Controller_Request_Http::DEFAULT_HTTPS_PORT
            );
            $port = (in_array($port, $defaultPorts)) ? '' : ':' . $port;
        }
        $url = $request->getScheme() . '://' . $request->getHttpHost() . $port . $request->getServer('REQUEST_URI');
        return $url;
    }

    /**
     * Retrieve current url in base64 encoding
     *
     * @return string
     */
    public function getCurrentBase64Url()
    {
        return $this->urlEncode($this->getCurrentUrl());
    }

    public function getEncodedUrl($url=null)
    {
        if (!$url) {
            $url = $this->getCurrentUrl();
        }
        return $this->urlEncode($url);
    }

    /**
     * Retrieve homepage url
     *
     * @return string
     */
    public function getHomeUrl()
    {
        return Mage::getBaseUrl();
    }

MagePsycho posted on - Wednesday 14th of August 2013 10:24:15 PM

Just addtional note:
Correct way to find the current url:
if (!in_array(Mage::app()->getFrontController()->getAction()->getFullActionName(), array('cms_index_noRoute', 'cms_index_defaultNoRoute'))) {
    $currentUrl = Mage::helper('core/url')->getCurrentUrl();
}
Source: http://www.blog.magepsycho.com/how-to-find-current-url-in-magento/
 
not published on website


QR Code: Magento get current url of a page