Retrieving the Previous URL in Magento as a String
As an experienced e-commerce developer, I often find myself needing to retrieve the previous page’s URL in my Magento projects. This can be particularly useful for redirecting users back to the product category after they’ve placed an order or for implementing pagination that respects the current sort and filter settings.
However, as you’ve discovered, trying to extract the URL from the response object directly can lead to confusing results. Let me guide you through a more robust approach to achieve this.
Understanding Mage Core Objects in Magento
Before we dive into the code, it’s crucial to have a basic understanding of how Magento handles requests and responses. In Magento 1.x, the core controller response is an instance of Mage_Core_Controller_Response_Http.
This object encapsulates the HTTP response data, including headers, status codes, and content. To interact with this object effectively, you need to understand its methods and properties.
Retrieving the Previous URL
To retrieve the previous URL in Magento, we will leverage the HTTP_REFERER environment variable provided by PHP. This variable contains the URL of the page (if any) that referred the user agent to the current page.
Let’s start by creating a simple helper function:
function getPreviousUrl()
{
return isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null;
}
This function checks if the HTTP_REFERER variable is set and returns it. If it’s not set, it defaults to null.
Handling Empty or Invalid URLs
In some cases, the HTTP_REFERER might be empty or contain an invalid URL. For example, when a user enters your site directly (without clicking any links), the referrer will be blank.
To handle this gracefully, we can add some additional checks:
function getPreviousUrl()
{
$referrer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null;
if (!$referrer) {
return null;
}
// Check if the URL is valid and contains 'http://'
if (parse_url($referrer, PHP_URL_SCHEME) != 'http') {
return null;
}
return $referrer;
}
In this updated version of the function, we first check if the referrer is empty. If it is, we immediately return null. Then, using the parse_url function, we extract the scheme (protocol) from the URL and compare it to ‘http’. If the scheme is not ‘http’, we consider the URL invalid and return null.
Redirecting to the Previous Page
Now that you have a reliable way to retrieve the previous URL, you can use it to redirect users back to where they came from. For instance, in your controller’s postAction method:
public function postAction()
{
try {
// Process and save the form data
$this->_processFormData();
Mage::getSingleton('core/session')->addSuccess($this->__('Your changes have been saved.'));
} catch (Exception $e) {
Mage::getSingleton('core/session')->addError($this->__('An error occurred while saving your data.'));
}
// Redirect to the previous page
if ($previousUrl = $this->_getPreviousUrl()) {
Mage::app()->getResponse()->setRedirect($previousUrl);
} else {
$this->_redirect('/');
}
}
In this example, we first process and save the form data. After a successful operation or an exception occurs, we retrieve the previous URL using our getPreviousUrl function.
If the previous URL exists, we set it as a redirect for the current response using the setRedirect method of the Mage::app()->getResponse() object. If no previous URL is found, we simply direct the user to the homepage.
Conclusion
Retrieving the previous URL in Magento requires a solid understanding of how the core objects handle HTTP responses and request data. By leveraging the HTTP_REFERER environment variable and implementing proper checks, you can obtain a consistent and reliable way to redirect users back to their previous pages.
Remember that the HTTP_REFERER is not always set or may contain invalid URLs, so it’s crucial to handle these edge cases gracefully in your applications.