Jump to content

Recommended Posts

Posted

Hello,

maybe it's too late or I had too little coffee or something else is sitting on my brain but I can't figure this out. I want to build a hook that determines if the User Agent is a phone and set a session variable accordingly:

$this->addHookBefore('Page::render', $this, 'checkMobile');
function checkMobile(HookEvent $event) {
    $page = $event->object;
 $session = wire('session');
    $domain = preg_replace("/^(m\.)/",'',$_SERVER['HTTP_HOST']);

# this is to force one version or the other:

 if(wire('input')->get->v == 'desktop') {
	 $session->isMobile = 'no';
 }
 if(wire('input')->get->v == 'mobile') {
	 $session->isMobile = 'yes';
 }

# /force
# here comes mobile detection via Mobile_Detect

 if(!$session->isMobile) {
	 require(wire('config')->paths->root.'/Mobile_Detect.php');
	 $detect = new Mobile_Detect();
	 $session->isMobile = $detect->isMobile()?'yes':'no';
 }

# /mobile detection
# now for the redirects. This is cosmetics but I would like it to work:

 if ($session->isMobile == "yes" && !preg_match("/\bm./", wire('config')->httpHost)) {
         wire("session")->redirect("//m.".$domain.$page->url);
 }
 if ($session->isMobile == "no" && preg_match("/\bm./", wire('config')->httpHost)) {
         $session->redirect("//".$domain.$page->url);
 }
}

The idea is, that if someone visits bmxrider.de on a mobile, he gets redirected to m.bmxrider.de and $session->isMobile is set to yes so I can change the templates later on. I also like to be able to force each version by setting $input->get->v

Whenever I use the query string to "force" a state, my site ends up in endless redirects. I checked the logs and it looks like $session->isMobile toggles between yes and no and I have no idea, why this happens.

Can someone help me out?

Thanks,

thomas

Update: The eternal redirect happens, when the domain doesn't match the query string. Like m.bmxrider/?v=desktop or bmxrider/?v=mobile

Posted

Ah, now I understand: m.bmxrider and bmxrider are two different sessions! No wonder this acts so weird!

So the next question is: Is there a way to make sessions work across subdomains? In this case here, it's not that big of a problem, but I have another site that depends heavily on session variables and I'd like to use the same mobile detect mechanism there. Or can I pass session ids when going to another domain?

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...