views:

44

answers:

1

Hi
I'm trying to figure the best way to execute a PHP script inside Joomla!
I want to redirect users if they are not from X country (already have a database and the script)
I found this extension but I want to make my own stuff http://bit.ly/daenzU

1) How could I execute the script once for each visitor? Working with Cookies?
2) As I'll put the script inside Joomla! template, I'll modify templates/XXX/index.php
3) Based on 2), Joomla! loads templates/XXX/index.php each time a page loads, so I have to avoid redirection script to be executed twice for an user

Thanks in advance for your ideas and suggestions

A: 

DO NOT modify the template, this will do the trick but is not the right place.

I advise you to create a plug-in, see Joomla docs on plug-ins. Here is event execution order of events.

Create a system plugin and implement onAfterInitialise method. In that method add all of your code.

To prevent the execution of script twice for each user set the user state, see Joomla documentation for states. You can also use session $session = JFactory::getSession(), see documentation.

Here is code... for your plug-in.

// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport( 'joomla.plugin.plugin' );

class plgMyPlugin extends JPlugin {

    //
    public function __construct(){
        //  your code here
    }

    //
    public function onAfterInitialise(){
        $app = JFactory::getApplication();

        //
        $state = $app->getUserStateFromRequest( "plgMyPlugin.is_processed", 'is_processed', null );
        if (!$state){
            //  your code here
            //  ....

            //  Set the Steate to prevent from execution
            $app->setUserState( "plgMyPlugin.is_processed", 1 );
        }


    }
}
Alex
Hi Alex... do you know why functions like header("Location...") are ignored inside system plugins code? Any workaround?
Enrique
`header()` is never ignored. Only reason that is does not work it because header was already sent. Use Joomla's method to redirect to different page `JFactory::getApplication()->redirect('index.php')`
Alex