Showing posts with label redirection. Show all posts
Showing posts with label redirection. Show all posts

Wednesday, August 8, 2012

Joomla 2.5 - Redirect to login page with return URL

If you have a private page that is supposed to be viewed only by registered users and if URL is accessed directly or is accessed on session expire you want to redirect user to login page and on successful login return him to the requested page then simply make a function named something like 'validateUser' and call it for all such views. Here is the brief and comprehensive function:


function validateUser()
{
        $user = JFactory::getUser();
        $userId = $user->get('id');
        if(!$userId)
        {
            $mainframe = &JFactory::getApplication();
            $return = JFactory::getURI()->toString();
            $url  = 'index.php?option=com_users&view=login';
            $url .= '&return='.base64_encode($return);
            $mainframe->redirect($url, JText::_('You must login first') );
            return false;
        }
        return true;
}

Note: If you are trying to do something similar for Joomla 1.5 note you would have to use 'option=com_user' instead of 'users'.