Page 1 of 1

PHP alter code for mobile detection

Posted: Mon May 03, 2010 11:30 am
by nexgraphics
Hi guys, new to this forum, and LOVE what you do!
I was needing a bit of help, as I am a web designer and not a coder in any way, so Im struggling a bit here for a lient.
I was given this code to use, to detect cell phones and redirect to a new page that fits cell phones.

<?php if (strpos($_SERVER['HTTP_USER_AGENT'], 'iPhone') !== FALSE)
{ header('Location: http://www.pc4me.com/mobile/index.php'); }
?>

So now I see that it only works on IPHONES, and it works well.
How do I alter the code please to allow blackberry, and maybe a few other of the more popular phones?

Thanks so much for any help!
Lee

Re: PHP alter code for mobile detection

Posted: Mon May 03, 2010 11:56 am
by AbraCadaver
Well you would need to know of something specific and unique to determine the phone type or something common with all mobile apps if you want all of them to redirect. This is just an example because I don't know what info is in the user agent for the phones you want, but here is the logic:

For all mobile devices, assuming that the word 'mobile' is in the user agent:

Code: Select all

<?php
if (strpos($_SERVER['HTTP_USER_AGENT'], 'mobile') !== FALSE)
   { header('Location: http://www.pc4me.com/mobile/index.php'); exit; }
?>
Or if you know specifics:

Code: Select all

<?php
$phones = array('iPhone', 'Blackberry', 'etc');

foreach($phones as $phone) {
   if (strpos($_SERVER['HTTP_USER_AGENT'], $phone) !== FALSE)
      { header('Location: http://www.pc4me.com/mobile/index.php'); exit; }
}
?>
Notice that you should use exit after the redirect.

Re: PHP alter code for mobile detection

Posted: Mon May 03, 2010 12:07 pm
by nexgraphics
i do know specifics so use only the 2nd code? because I dont see the url for the redirect or the exit you mentioned....can you give me the whole code please...
Thanks so much!

Re: PHP alter code for mobile detection

Posted: Mon May 03, 2010 12:08 pm
by AbraCadaver
nexgraphics wrote:i do know specifics so use only the 2nd code? because I dont see the url for the redirect or the exit you mentioned....can you give me the whole code please...
Thanks so much!
Use the scroll bar or click the expand link at the top of the code.

Re: PHP alter code for mobile detection

Posted: Mon May 03, 2010 4:03 pm
by jraede
I use AbraCadaver's method on my site and it's working for now. You can test what the agent is by trying access with different phones and echoing the HTTP_USER_AGENT, and then add that to the array. Of course, that requires you to have access to all different types of smart phones. I'm sure there's a place online that has a list as well.

Re: PHP alter code for mobile detection

Posted: Mon May 17, 2010 11:22 pm
by nexgraphics
Hi guys, tried this code and added the 'blackberry', but it didnt work :(
ANy idease please.....
Thanks!

Re: PHP alter code for mobile detection

Posted: Tue May 18, 2010 2:41 am
by Eran