8

Is there a reliable way in magento to redirect to the last page.

I have a small form that i want to redirect to the previous page if an error occurred.

The form sits on the product page and redirects to another page when completed successfully. However, I would like to redirect back to the product page if an error occurred.

My action url is /my/module/submit

Also when i say reliable, i mean that redirectReferer cant be relied on

1
  • 1
    RedirectReferer is reliable enough for Magento's Adminhtml to rely on pretty exclusively for back buttons?
    – philwinkle
    Commented Jun 24, 2013 at 14:54

1 Answer 1

23

Magento relies on the $_SERVER['HTTP_REFERER'] value for redirect logic without qualm; see Mage_Core_Controller_Varien_Action:

/**
 * Set referer url for redirect in responce
 *
 * @param   string $defaultUrl
 * @return  Mage_Core_Controller_Varien_Action
 */
protected function _redirectReferer($defaultUrl=null)
{

    $refererUrl = $this->_getRefererUrl();
    if (empty($refererUrl)) {
        $refererUrl = empty($defaultUrl) ? Mage::getBaseUrl() : $defaultUrl;
    }

    $this->getResponse()->setRedirect($refererUrl);
    return $this;
}

/**
 * Identify referer url via all accepted methods (HTTP_REFERER, regular or base64-encoded request param)
 *
 * @return string
 */
protected function _getRefererUrl()
{
    $refererUrl = $this->getRequest()->getServer('HTTP_REFERER');
    if ($url = $this->getRequest()->getParam(self::PARAM_NAME_REFERER_URL)) {
        $refererUrl = $url;
    }
    if ($url = $this->getRequest()->getParam(self::PARAM_NAME_BASE64_URL)) {
        $refererUrl = Mage::helper('core')->urlDecode($url);
    }
    if ($url = $this->getRequest()->getParam(self::PARAM_NAME_URL_ENCODED)) {
        $refererUrl = Mage::helper('core')->urlDecode($url);
    }

    if (!$this->_isUrlInternal($refererUrl)) {
        $refererUrl = Mage::app()->getStore()->getBaseUrl();
    }
    return $refererUrl;
}

If you aren't content to rely on the $_SERVER['HTTP_REFERER'], the only thing which you can do is store the most recently-visited URL in session and create a getter for this value which handles the case when someone navigates directly to the site.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.