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'.

6 comments:

  1. Thanks for this tip...it helped a lot. I ended up putting your function as part of the class in view.php then calling it in the view's __constructor eg:

    $this->validateUser();

    ...worked like a charm! :)

    ReplyDelete
  2. ...I should also note that it was the view class in JoomGallery that I updated

    ReplyDelete
  3. I need this as a module so I can redirect users to different registration pages depending on the article they want to access. I have loaded the sourcer plugin that allows me to plugin php script directly into custom HTML module. What would the code look like for that instance?

    ReplyDelete
  4. ok, but where should we place this function? in what file?

    ReplyDelete
    Replies
    1. You could do something similar to the first poster but avoid altering Joomla core files by sub-classing JView with a file in your own component. Make sure that your component's main controller class loads this new JView subclass, then derive all of your component's views from it instead of from JView.

      Delete