Simple redirection to mobile site on log in

I build many variations of custom Content Management Systems areas for clients and my personal projects. Recently I have started building mobile versions of their CMS, that runs along side the desktop version, usually with simplified functionality that is easier to use on a mobile screen.

Using jQuery and php, we are going to build a simple website log in form that will detect mobile phones and log them into a mobile version of the website. With the redirection being done at the log in level, you can easily give visitor the ability to switch between the desktop site or the mobile site with ease.

The Theory:
We are going to add a hidden field “isMobile”, to the log in form that has its default value set to “false”, then with jQuery we will check the screen width and if the screen size is less than our limit “isMobile” is then set to “true”.

Then in your log in script, we then check the value of “isMobile” and redirect to the appropriate website.

The Code:
Lets begin with building the log in form, in this example we will use fields for “username”, “password”, “isMobile” and a submit button.

<form action="login.php" method="post" name="loginform">
    <label for="username">Username:</label>
    <input type="text" name="username" value="" />
    <label for="password">Password:</label>
    <input type="password" name="password" />
    <input type="hidden" name="isMobile" value="false" />
    <input type="submit" value="Log In" />
</form>

And then we are going to add some jQuery that will check the screen resolution and change the value of “isMobile” to “true”.

<script type="text/javascript">
$(document).ready(function(){
	if (window.screen.width < 750) {
		$("input[name='isMobile']").val("true");
	}
});
</script>

On your log in checking form we then check the value of “isMobile” to redirect the site to the desktop or mobile version of the CMS. There is a lot more to the log in process that you will work out or already have built but for this example we are going to do a simple redirect based on the “isMobile” value.

if($_POST['mobile']=="true"){ 
    $siteversion = "http://m.mydomain.com/mobile-admin/"; 
} else { 
    $siteversion = "http://www.mydomain.com/admin/"; 
}
header('Location: '.$siteversion);
exit();