Friday, June 7, 2013

Adding a little PHP redirect logic to my moodle site...

I have been building some web site content the past couple weeks.  We are retiring a server that houses the *portal pages of our moodle site.  These pages are mainly a course listing, some information about registration and a few other things.  I have been *rebuilding that same portal functionality, plus a bit more (naturally - I have been enjoying doing some HTML - CSS - PHP - Javascript development) on our moodle site.  I created a /portal directory where I am housing the code for the pages.  They are located here.

One of the pages contains links to different logins required for our different services.  I am sending one of the links directly to the moodle login page for the site, which is fine, except that after validating the login, moodle re-directs back to the sender page.  I started initially creating logic on the portal login page that checked to see if the user had logged in using the native moodle function isloggedin(), where I would then display a different link back to the home page of moodle, but that is not what we want there.  Instead, we want to go directly to the home page upon a valid login.

I next started looking at the native moodle login page /login/index.php, trying to see how plausible it would be to put some conditional code somewhere that would sniff out where it came from and not redirect, but go to the home page.  After a little while, I realized that was a bad idea too, since I was modifying core code, and a very busy core page at that!  Instead, I ended up putting the conditional code into the portal page that send the request in the first place (this is the page that moodle would re-direct back to upon authenticating the login).  This seems like the best solution for now....

Next, I had to figure out how to conditionally trap the request URL value using PHP.  I dumped the PHP $_SERVER object and found the 'HTTP_REFERER' item.

var_dump($_REQUEST);

Code to handle redirect from moodle login page

At the top of my portal wide settings page (siteWideVars.php) , I added this conditional code

    if( isset($_SERVER['HTTP_REFERER']) AND $_SERVER['HTTP_REFERER'] == 'http://studentmoodle.accelerateu.org/student/login/index.php' )
{
        //send back to moodle home page
        header( 'Location: http://studentmoodle.accelerateu.org/student' ) ;
   }

2 comments:

  1. Hi James

    An alternative is to use the redirect function

    if(condition == needtoredirect) {
    redirect($CFG->wwwroot.'urlyouwant') ;
    }

    for example:

    if( isset($_SERVER['HTTP_REFERER']) AND $_SERVER['HTTP_REFERER'] == 'http://studentmoodle.accelerateu.org/student/login/index.php' )
    {
    redirect($CFG->wwwroot.'student') ;
    }

    ReplyDelete
    Replies
    1. How and where do i set the condition in the first place?

      Delete