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

Marty Wallace
  • 5,631
  • 13
  • 65
  • 90
  • 1
    RedirectReferer is reliable enough for Magento's Adminhtml to rely on pretty exclusively for back buttons? – philwinkle Jun 24 '13 at 14:54

1 Answers1

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.

benmarks
  • 16,675
  • 4
  • 41
  • 108