WXforum.net
May 24, 2013, 10:09:19 AM *
Welcome, Guest. Please login or register.

Login with username, password and session length
Members: 6620  •  Posts: 178766  •  Topics: 18137
Please welcome moranbahweather, our newest member.
Welcome to the the new hosting for WXforum.net.
 
   Home   Help Search Login Register  
Pages: [1]   Go Down
  Print  
Author Topic: Detection and pages for mobile devices & phones  (Read 3476 times)
0 Members and 1 Guest are viewing this topic.
up10ad
Forecaster
*****
Offline Offline

Posts: 556



WWW
« on: November 29, 2009, 11:34:20 AM »

Well,  I just spent a few days setting up a special page for mobile devices, and creating an auto-detection feature to send mobile visitors there automatically, with an option to return and use the full desktop site.  

I borrowed a lot of ideas from the web and other members and I'll try and give credit where I can.

The basis of the mobile page was taken from a template mentioned in a topic in the Weather Display forum. Although it calls it an iPhone template, it works great on most smartphones and I renamed it to mobile.php.   It gives credit to Anchorage, KY Weather Center for the original concept and modifications by Snoqualmie, WA Weather.  There are versions that work with WVS and WD outut.  Creating the mobile.php page will require you to edit the code to add references to your specific tags (vws or wd) and to link to your cam and radar, etc.  This is probably the hardest part, locating the proper links to your specific point forecast, etc.  In the next message I will include a full copy of the mobile.php file I use with highlights showing the items that I changed.

The code to perform the checking is done in php and was found on the net at http://detectmobilebrowsers.mobi/  This site offers code at no cost for non-commercial use. NOTE:  You must download device_mobile_detect.php and put the file on your web site root.

Additional code to create and test for cookies was then added to check to see if the mobile visitor had already been to the site and requested to use the desktop version rather than the mobile version.  

So, how do you do it?

1.  First, create your mobile.php file using the template from the WD forum links (or use any mobile page you want!).  Once you have the mobile page working to your satisfaction you can move on to the next step.

2.  Next, add the code from detectmobilebrowsers.mobi to your main entry web page, or better yet, to the top of every page (very easy if you have a template that every page uses).  Here is how every page on my site begins:

Code:
<?php
include('mobile_device_detect.php');
if (isset(
$_COOKIE["DWCmobile"]))
  echo 
"";
else
mobile_device_detect(true,true,true,true,true,true,'http://deltaweathercam.com/mobile.php',false);
?>

Note that the code for which devices are selected as mobile can be changed by altering the 'true' values.  See the .mobi site for details, its easy.  Mine is set to route all mobiles to the mobile page.

Also note that the mobile detection only gets invoked in the absence of a cookie which is set when a visitor hits the mobile page.  This results in all mobile visitors going to the mobile page first, but then allows them to ask for the desktop version from there if desired.  The cookie allows them to bypass the mobile check but it expires in an hour which means the next visit they start again at the mobile page.  For the purists, the echo "" is a leftover from some testing, and is there in the event you want to send a blurb to mobile users.

3.  The mobile page also needs some code to create the cookie.  This is at the top of my mobile.php page:

Code:
<?php
setcookie
("DWCmobile""Been There"time()+3600);
?>

The cookie name DWCmobile should be changed to something relevant to your site, but also remember to change the cookie reference in the code at the top of each page in previous code callout!  The text Been There is not significant, it is just what the cookie contains.  You can also change the expiration time which is currently set to the current time plus 3600 seconds (1 hour).

4.  Finally, I added a small link at the very top left corner of my desktop page that links to the mobile page, and a link on the mobile page that goes to the desktop.  You can see these links at http://deltaweathercam.com/index.php and http://deltaweathercam.com/mobile.php.  Don't be fooled by the width of the mobile page, it is elastic and will shrink in width as needed.

The most common problem encountered after implementing this type of check for the user agent is a message similar to:

Code:
Warning: Cannot modify header information - headers already sent by (output started at /path/to/yourfilename.php:#) in /path/to/mobile_device_detect.php on line x

This is because your page is sending 'something' before calling the file.  There are several solutions but one of the easiest is to configure your php to enable output buffering.  Normally, session, cookie or HTTP header data in a PHP script must be sent before any output is generated by the script. If this is not possible in your application, you can enable what PHP calls output buffering, with the output_buffering variable.  With output buffering on, PHP stores the output of your script in a special memory buffer and sends it only when explicitly told to do so. This allows you to send special HTTP headers and cookie data even in the middle or at the end of your script.  Use of output buffering can slightly degrade performance but only on a very busy site.  The setting in php.ini is:  output_buffering = Off

That's about all there is to it.  I'd love to see of the experts here make some changes and improvements.  Perhaps add an option for a mobile visitor to set a permanent cookie so they never go to the mobile page, or even a configurable one.  
« Last Edit: May 13, 2011, 03:34:05 PM by up10ad » Logged

Rick
Have you joined USAWeatherFinder.com yet?

up10ad
Forecaster
*****
Offline Offline

Posts: 556



WWW
« Reply #1 on: November 29, 2009, 11:54:58 AM »

OK,  here is my mobile.php with the highlighted lines I had to change:

==============================
<?php
setcookie("DWCmobile", "Been There", time()+3600);
?>


<!--   /////////////////     START CALL PHP DATA FOR CURRENT CONDITIONS       /////////////    -->

<?php
include("./wd/testtags.php");
?>


<!--   /////////////////     END CALL PHP DATA FOR CURRENT CONDITIONS       /////////////    -->
      

<!--   /////////////////     START 7 DAY FORECAST SCRIPT       /////////////    -->

<?php
/*------------------------------------------------
//import NOAA Forecast info
//data ends up in three different arrays:
//$forecasticons
  •   x = 0 thru 9   This is the icon and text around it
//$forecasttitles
  •   x = 0 thru 12   This is the title word for the time period
//$forecasttext
  •   x = 0 thru 12  This is the detail text for the forecast
//
//And one more variable - $lastupdate  This is the time of last update
//
//Also, in order for this to work correctly, you need the NOAA icons (or make your own...
//there are over 200!). These need to be placed in the path \ifps\text\images\ to work
//properly (so make a folder in your web HTML root called "ifps", then make a folder in it
//called "text", then make a folder in it called "images" and place the icons in this folder)
//
//http://members.cox.net/carterlakeweather/forecasticons.zip (380K)
//
//URL below --MUST BE-- the Printable Point Forecast from the NOAA website
//
//Not every area of the US has a printable point forecast
//
//This script will ONLY WORK with a printable point forecast!
//
//To find yours in your area:
//
//Go to www.noaa.gov
//Click on the Storm Watch map (middle lower left of page)
//Click on your state
//Click on  your area of the state
//Scroll down to the "Additional Forecasts & Info"
//Click on Printable Forecast
//The title of the page should say "Point Forecast (Printable)"
//------------------------------------------------*/

$html = implode('', file('http://forecast.weather.gov/MapClick.php?CityName=Delta&state=CO&site=GJT&textField1=38.7448&textField2=-108.074&e=0&TextType=2'));

      // Just get the top of the NWS page for editing

      preg_match('|<tr valign ="top" align="center">(.*)<table width="670"|s', $html, $betweenspan);
      $forecastop  = $betweenspan[1];

      // Chop up each icon html and place in array
      preg_match_all("/<td.*>(.*)<\/td>/Uis", $forecastop, $headers);
      $forecasticons = $headers[1];

      // Now get just the bottom of the NWS page for editing
      preg_match('|</table>(.*)<hr>|s', $html, $betweenspan);
      $forecast  = $betweenspan[1];

      // Chop up each title text and place in array
      preg_match_all('|<b>(.*): </b>|Ui', $forecast, $headers);
      $forecasttitles = $headers[1];

      // Chop up each forecast text and place in array
      preg_match_all('|</b>(.*)<br>|Ui', $forecast, $headers);
      $forecasttext = $headers[1];

      // Grab the Last Update date and time.
      preg_match('|Last Update: (.*)|', $html, $betweenspan);
      $lastupdate  = $betweenspan[1];

?>

<!--   /////////////////     END 7 DAY FORECAST SCRIPT       /////////////    -->

<!--   /////////////////     START DATE/TIME ZONE SET FOR GRAPH CALL       /////////////    -->

<?php
date_default_timezone_set('America/Denver');
$d = date('j');
$m = date('n');
$y = date('Y');
?>


<!--   /////////////////     END DATE/TIME ZONE SET FOR GRAPH CALL       /////////////    -->





<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
   <head>
      <title>DeltaWeatherCam for Mobile Devices</title>
      <meta name="description" content="Delta, CO Weather Center for iPhone" />
      <meta name="keywords" content="Delta, CO, weather, forecast, current conditions, radar, warnings, apple, iphone" />

      <meta name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"/>
      <link rel="stylesheet" type="text/css"  href="iphone_iui.css" />
      <link rel="stylesheet" type="text/css" href="iphone_base.css" />
   </head>
   <body>
      <div class="panel" selected="true">
      <a name="top"></a>
      <fieldset>
      <table cellspacing="0" width=295 cellpadding="2" class="center" id="searchTable">
<tr>
<td>
<center>
  DeltaWeatherCam.com for Mobile Devices
  <br /><font size="-1">
  (<a href="index.php">switch to our desktop site</a>)</font>
</center>

</td>
</tr>
      </table>
      </fieldset>
      <script language="javascript">
   function ShowCustomDateSelect()
   {
      document.getElementById("custom_date_select").style.visibility="visible";
      document.getElementById("normal_date_select").style.visibility="hidden";
   }
</script>
<a name="current"></a>
<h2>Current Conditions</h2>
<fieldset>
   <div class="barMenu">
      <span class="button">Current</span>
      <a href="#webcam" class="button">Webcam</a>
      <a href="#severe" class="button">Severe</a>
      <a href="#radar" class="button">Radar</a>
   </div>
   <p class="taC b"></p>
   <div id="pwsSelect"></div>
      
   <table cellspacing="0" width=320 cellpadding="5" class="full taL">



<tr>
<td align=left>


At <?php echo $time ?><BR>
Temperature&nbsp;<?php echo $tempnodp  ?>&deg;&nbsp;F<BR>
Humidity&nbsp; <?php echo $humidity ?>% <BR>
Dew Point&nbsp; <?php echo $tempnodpf?>&deg;&nbsp;F<BR>
Barometer&nbsp; <?php echo $baroinusa2dp ?>&nbsp;in./Hg<BR>
&nbsp; and&nbsp; <?php echo $trend ?><BR>
Wind&nbsp; <?php echo $dirlabel ?> &nbsp;at&nbsp; <?php echo $avgspd ?> m.p.h.<BR>
Rain Rate&nbsp; <?php echo $hourrn ?> in./hr.<BR>
Daily Rain&nbsp; <?php echo $dayrnusa ?> in.<BR>
Storm Total&nbsp; <?php echo $vpstormrain ?> in.<BR>
Monthly Rain&nbsp; <?php echo $monthrn ?> in.<BR>
Heat Index&nbsp; <?php echo $heati ?>&deg;&nbsp;F<BR>
Wind Chill&nbsp;  <?php echo $windch ?>&deg;&nbsp;F<BR>
Sunrise&nbsp;  <?php echo $sunrise ?><BR>
Sunset&nbsp;  <?php echo $sunset ?><BR><BR>


</td>
</tr>

<tr valign ="top">
<td>
<?echo $forecasticons[0]?><BR><BR>
</td>
</tr>




<tr valign ="top">
<td align=left>
<?echo $forecasttitles[0]?>: </b><?echo $forecasttext[0]?>
</td>
</tr>
</table>
   </fieldset>
<a name="graph"></a>
<h2>Graphs</h2>
<fieldset>
   
   <div class="taC tm10 bm10"><img src="http://i.wund.com/cgi-bin/wxStationGraphAll?ID=KCODELTA2&type=3&showtemp=1&showpressure=1&showwind=1&showwinddir=1&showrain=1&showtitle=0&day=<?php echo $d; ?>&year=<?php echo $y; ?>&month=<?php echo $m; ?>&width=280" alt="KCODELTA2 Weather Graph"></div>
</fieldset>
   <a name="webcam"></a>
   <h2>Webcam</h2>
   <fieldset>
      <div class="barMenu">
      <a href="#current" class="button">Current</a>
      <span class="button">Webcam</span>
      <a href="#severe" class="button">Severe</a>
      <a href="#radar" class="button">Radar</a>
      </div>
      <div class="taC bm10"><img src="http://deltaweathercam.com/toshibafixed/toshibathumb.jpg" name="camImage" id="camImage" /></div><br />

        <!-- Note I added a second cam, you can delete this if you have only 1 -->
<div class="taC bm10"><img src="http://deltaweathercam.com/toshibafixed/c50thumb.jpg" id="camImage" /></div>

   </fieldset>

<a name="severe"></a>
<h2>Severe</h2>
<fieldset>
   <div class="barMenu">
      <a href="#current" class="button">Current</a>
      <a href="#webcam" class="button">Webcam</a>
      <span class="button">Severe</span>
      <a href="#radar" class="button">Radar</a>
   </div>
   <table cellspacing="0" cellpadding="5">
      <tr>
      <td>
      
<?php

// Force Defaults for Zone and County
if ( ! isset($_REQUEST['warnzone']) )
        $_REQUEST['warnzone']="COZ011";
if ( ! isset($_REQUEST['warncounty']) )
        $_REQUEST['warncounty']="COC029";
if ( ! isset($_REQUEST['warnlocal']) )
        $_REQUEST['warnlocal']="Delta+CO";

//You can pass data to this script with:
// http://www.carterlake.org/testadvisory.php?warnzone=KYZ030&warncounty=KYC111&warnlocal=Anchorage+KY
//Where the zone is your zone and the county is your county and location is your location
//using pluses in place of spaces

$warnzone = $_REQUEST['warnzone'];
$warncounty = $_REQUEST['warncounty'];
$warnlocal = $_REQUEST['warnlocal'];

//import NOAA Advisory info
//data can be altered by changing the zone and county numbers
//Target data ends up in $targetwarn and $targettext[0]

$html = implode('', file("http://www.crh.noaa.gov/showsigwx.php?warnzone=${warnzone}&warncounty=${warncounty}"));

//Get the advisory headers and put them in an array

      preg_match_all('|<h3>(.*)</h3>|', $html, $headers);
      $warnheaders = $headers[1];

//Get the advisory text and put them into an array as well

      preg_match_all('|<pre>(.*)</pre>|Uis', $html, $headers);
      $warntext = $headers[1];

//If there is more than one advisory, we need to set its priority

if (count($warnheaders) >= 1) {

$i = 0;
$flag = 0;

//First, around here tornados are the biggest danger. A warning is critical information.
//Display this one first no matter what!

   while ($i < count($warnheaders)):
      if (preg_match("/Tornado Warning/i", $warnheaders[$i])) { 
         $targetwarn = $warnheaders[$i];
         $targettext = $warntext[$i];
         $targettext = explode("$$",$targettext);
         $flag = 1;
         break;
      }
      $i++;
   endwhile;

//Next if there are none of the above found. Display the first warning message.

   if ($flag == 0) {
      $i = 0;
      while ($i < count($warnheaders)):
         if (preg_match("/Warning/i", $warnheaders[$i])) { 
         $targetwarn = $warnheaders[$i];
         $targettext = $warntext[$i];
         $targettext = explode("$$",$targettext);
            $flag = 1;
            break;
         }
         $i++;
      endwhile;
   }

//Next if there are none of the above found. Display the first watch message.

   if ($flag == 0) {
      $i = 0;
      while ($i < count($warnheaders)):
         if (preg_match("/Watch/i", $warnheaders[$i])) { 
         $targetwarn = $warnheaders[$i];
         $targettext = $warntext[$i];
         $targettext = explode("$$",$targettext);
            $flag = 1;
            break;
         }
         $i++;
      endwhile;
   }

//Next if there are none of the above found. Display the first advisory message.

   if ($flag == 0) {
      $i = 0;
      while ($i < count($warnheaders)):
         if (preg_match("/Advisory/i", $warnheaders[$i])) { 
         $targetwarn = $warnheaders[$i];
         $targettext = $warntext[$i];
         $targettext = explode("$$",$targettext);
            $flag = 1;
            break;
         }
         $i++;
      endwhile;
   }

//Next if there are none of the above found. Display the first statement message.

   if ($flag == 0) {
      $i = 0;
      while ($i < count($warnheaders)):
         if (preg_match("/Statement/i", $warnheaders[$i])) { 
         $targetwarn = $warnheaders[$i];
         $targettext = $warntext[$i];
         $targettext = explode("$$",$targettext);
            $flag = 1;
            break;
         }
         $i++;
      endwhile;
   }

//Next if there are none of the above found. Set the advisory to default message.

   if ($targetwarn == "Hazardous Weather Outlook") {
      $targetwarn = "NO CURRENT DELTA ADVISORIES";
      $targettext[0] = "THERE ARE NO ACTIVE WATCHES, WARNINGS OR ADVISORIES FOR DELTA";
   } else if ($targetwarn == "No Active Hazardous Weather Conditions Found") {
      $targetwarn = "NO CURRENT DELTA ADVISORIES";
      $targettext[0] = "THERE ARE NO ACTIVE WATCHES, WARNINGS OR ADVISORIES FOR DELTA";
   } else if (empty($targetwarn)) {
      $targetwarn = "NO CURRENT DELTA ADVISORIES";
      $targettext[0] = "THERE ARE NO ACTIVE WATCHES, WARNINGS OR ADVISORIES FOR DELTA";
   } else if ($targetwarn == "Short Term Forecast") {
      $targetwarn = "NO CURRENT DELTA ADVISORIES";
      $targettext[0] = "THERE ARE NO ACTIVE WATCHES, WARNINGS OR ADVISORIES FOR DELTA";
   }

   if ($targetwarn <> "NO CURRENT DELTA ADVISORIES") {

   $warnlist = 'ALL CURRENT ADVISORIES:';

      for ($i = 0; $i <= count($warnheaders); $i++) {
             $warnheaderplus = preg_replace( '| |', '+', $warnheaders[$i] );
             $warnlist = $warnlist . '<br><a href="http://www.crh.noaa.gov/showsigwx.php?warnzone=' . $warnzone. '&warncounty=' . $warncounty . '&local_place1=' . $warnlocal . '&product1=' . $warnheaderplus . '" target="_new">' . $warnheaders[$i] . '</a>';
      }
   }

}

echo "<br>";
echo "<center>";
echo "<b>";
echo $targetwarn;
echo "</b>";
echo "</center>";
echo "<br><br>";
echo "<center>";
echo $warnlist;
echo "</center>";
?>
      </FONT></td>
      </tr>
   </table>
   </fieldset>            


   <script type="text/javascript">
   var animated = false;
   var severe = false;
   var radius = 80;
   function wui_setOpacity_severe(image,opacity){
  if(opacity<0){opacity=0;}  if(opacity>=100){opacity=100;}
  var c=opacity/100;
  if(typeof(image.style.filter)!='undefined'){image.style.filter='alpha(opacity:'+opacity+')';}
  if(typeof(image.style.KHTMLOpacity)=='string'){image.style.KHTMLOpacity=c;}
  if(typeof(image.style.MozOpacity)=='string'){image.style.MozOpacity=c;}
  if(typeof(image.style.opacity)=='string'){image.style.opacity=c;}
   }
   function toggleRadar(element) {
      element.setAttribute("toggled", element.getAttribute("toggled") != "true");
      if(animated==true) {
      animated = false;
      }
      else {
      animated = true;
      }
      changeRadarSource(animated, radius);
   }
   function toggleSevere(element) {
      var severe_overlay = document.getElementById('severe_overlay');
      element.setAttribute("toggled", element.getAttribute("toggled") != "true");
      if(severe==true) {
      wui_setOpacity_severe( severe_overlay,0);
      severe = false;
      }
      else {
      wui_setOpacity_severe( severe_overlay,60);
      severe = true;
      }
   }
   function changeSevereSource(radius)
   {
      var myradius = radius*1.852;
      var severe_overlay="http://wumaps.wunderground.com/cgi-bin/mapgen?theme=severe&stdout=1&size=278x278&lat=38.740&lon=-108.091&format=gif&alpha=1&radius="+myradius+"&r="+new Date().getTime();
      document.getElementById('severe_overlay').src = severe_overlay;
      return;
   }
   function changeRadarSource(animated, radius)
   {
      var num = 1;
      if (animated == true)
      num = 6;
      document.getElementById('radarImage').src = "http://radblast.wunderground.com/cgi-bin/radar/WUNIDS_composite?centerlat=38.740&centerlon=-108.091&radius="+radius+"&type=N0R&frame=0&num="+num+"&delay=15&width=278&height=278&newmaps=1&r=1225814451&smooth=1&rainsnow=1&lat=38.740&lon=-108.091&label=You+Are+Here";
      return;
   }
   function DimButtons(target)
   {
      document.getElementById('radar_region').className = "whiteButton";
      document.getElementById('radar_default').className = "whiteButton";
      document.getElementById('radar_local').className = "whiteButton";
      target.className = "whiteButtonDim";
      return;
   }
</script>
<a name="radar"></a>
<h2>Current Radar</h2>
<fieldset>

<div class="barMenu">
      <a href="#current" class="button">Current</a>
      <a href="#webcam" class="button">Webcam</a>
      <a href="#severe" class="button">Severe</a>
      <span class="button">Radar</span>
   </div>

      <div class="taC" style="height: 288px;">
      <img src="javascript: changeRadarSource(animated,radius);" alt="" id="radarImage" /><br />
      <img src="" width="278" height="278" id="severe_overlay" style="position: relative; top: -278px;" />
   </div>
   <script language="javascript">
      changeRadarSource(animated,radius);
      severe=false; changeSevereSource(radius); wui_setOpacity_severe( document.getElementById('severe_overlay'),0);
   </script>
   <table cellspacing="0" cellpadding="0" class="zoomMenu">
      <tr>
      <td><a id="radar_region" href="#radar" class="whiteButton" onclick="radius=120; changeRadarSource(animated, radius); changeSevereSource(radius); DimButtons(this); return false;">Region</a></td>
      <td><a id="radar_default" href="#radar" class="whiteButtonDim" onclick="radius=80; changeRadarSource(animated, radius); changeSevereSource(radius); DimButtons(this); return false;">Default</a></td>
      <td><a id="radar_local" href="#radar" class="whiteButton" onclick="radius=15; changeRadarSource(animated, radius); changeSevereSource(radius); DimButtons(this); return false;">Local</a></td>
      </tr>
   </table>
   <div class="row">
      <label class="nobr">Animated Radar:</label>
      <div class="toggle" onclick="toggleRadar(this)" toggled="true">
      <span class="thumb"></span>
      <span class="toggleOn">No</span>
      <span class="toggleOff">Yes</span>
      </div>
   </div>
   <div class="row">
      <label class="nobr">Severe Overlay:</label>
      <div class="toggle" onclick="toggleSevere(this)" toggled="true">
      <span class="thumb"></span>
      <span class="toggleOn">No</span>
      <span class="toggleOff">Yes</span>
      </div>
   </div>
</fieldset>



<a name="about"></a>
<h2>About</h2>
<fieldset>
      <table cellspacing="0" width=320 cellpadding="5" class="full taL">
      <tr>
      <td class="full">
      <div><span class="b">Elevation:</span> 5,060 ft</div>
      <div><span class="b">Hardware:</span>Davis Vantage Pro 2 </div>
      <div><span class="b">Software:</span>Virtual Weather Station & Weather Display<br /><a href="http://usaweatherfinder.com/">
<img src="http://usaweatherfinder.com/button.php?u=up10ad" alt="USA Weather Finder" border="0" />
</a>
</div>
      </td>
      </tr>
   </table>
               

<p class="taC">
Logged

Rick
Have you joined USAWeatherFinder.com yet?

up10ad
Forecaster
*****
Offline Offline

Posts: 556



WWW
« Reply #2 on: April 17, 2010, 10:30:27 AM »

I feel like I'm the only one reading this and using mobile device detection  Brick wall  but I'll add some more info anyway.   Shocked

I had to make some adjustments to my web site because the iPad is detected and treated as an iPhone/iPod by many site detection checkers, including this one. Seems that although it specifically says iPad, it still contains the word 'mobile'.

Quote
Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.10

The solution isn't especially hard to code, but I suspect it will be overlooked by many sites for a while. My feeling is that is should NOT be treated as a mobile device since most sites render better in full mode. I have made additions to my checking algorithm to specifically use the standard mode unless mobile/iPhone rendering is manually requested.

I added the an additional 'case' code as the first check in mobile_device_detect.php:

...
function mobile_device_detect($iphone=true,$android=true,$opera=true,$blackberry=true,$palm=true,$windows=true,$mobileredirect=false,$desktopredirect=false){

  $mobile_browser   = false; // set mobile browser as false till we can prove otherwise
  $user_agent       = $_SERVER['HTTP_USER_AGENT']; // get the user agent value - this should be cleaned to ensure no nefarious input gets executed
  $accept           = $_SERVER['HTTP_ACCEPT']; // get the content accept value - this should be cleaned to ensure no nefarious input gets executed

  switch(true){ // using a switch against the following statements which could return true is more efficient than the previous method of using if statements

   case (eregi('ipad',$user_agent)); // we find the words ipad in the user agent
      $mobile_browser = false; // set mobile browser to false
    break; // break out and skip the rest if we've had a match on the ipad


   case (eregi('ipod',$user_agent)||eregi('iphone',$user_agent)); // we find the words iphone or ipod in the user agent
      $mobile_browser = $iphone; // mobile browser is either true or false depending on the setting of iphone when calling the function
      if(substr($iphone,0,4)=='http'){ // does the value of iphone resemble a url
        $mobileredirect = $iphone; // set the mobile redirect url to the url value stored in the iphone value
      } // ends the if for iphone being a url
    break; // break out and skip the rest if we've had a match on the iphone or ipod
...


After using the iPad for a few weeks now I am convinced that there is no reason to treat it as a mobile browser, despite the fact that it contains the word mobile in its user agent string.
Logged

Rick
Have you joined USAWeatherFinder.com yet?

DaculaWeather
It's a Jeep thing... you wouldn't understand.
Forecaster
*****
Offline Offline

Posts: 2746


SCCA EM #156


WWW
« Reply #3 on: April 17, 2010, 12:26:24 PM »

I just saw this, I can't wait to try it! I already have a mobile page but it gives the user a nice option. My mobile page is very small and only has one page. So yes, they will (hopefully) have the option now to go to the mobile or regular pages.

I'll let you know how it goes although it might be tomorrow before I can get to it.
Thanks Rick!
Logged

Steve
Davis Vue, VWS, WDisplay, VVP, StartWatch CWOP 

wxflint
Flint, Michigan Weather
Senior Contributor
****
Offline Offline

Posts: 263


When The Weather Gets Tough.. Get With The Weather



« Reply #4 on: April 17, 2010, 12:30:03 PM »

Nice article Razz Have this already implemented in to my site as well as the blog  Applause
Logged
CNYWeather
Forecaster
*****
Offline Offline

Posts: 1386



WWW
« Reply #5 on: April 17, 2010, 12:42:22 PM »

Cool. Thanks for writing that. I've got a mobile pages up. Gonna put some code up
to detect phones on my site now.  Thanks!!
Logged

up10ad
Forecaster
*****
Offline Offline

Posts: 556



WWW
« Reply #6 on: April 17, 2010, 11:53:48 PM »

I'm really glad to see some interest in this.  The use of mobile devices has increased exponentially and having auto-detection is important IMHO.  I'll try and answer any questions but I'm not an expert by any means. 
Logged

Rick
Have you joined USAWeatherFinder.com yet?

dhrandy
Senior Member
**
Offline Offline

Posts: 50



WWW
« Reply #7 on: April 18, 2010, 01:47:10 PM »

I just wrote a simple script for my site that re-directs if the screen width resolution is less than 700 for my html site.  Be sure to put it between the <head></head> tags.  I chose 700 because your netbooks are typically 800 wide.

Code:
<script type="text/javascript">
if (screen.width<700)
{
window.location="your mobile site link goes here"
}
</script>

If you want to test it out just go to www.gwhizpc.com/weather from your mobile device.  I still left a link on the main site just in case it doesn't work for all mobile browsers.
« Last Edit: April 18, 2010, 04:01:32 PM by dhrandy » Logged

La Crosse  WS-2315  l  Cumulus 1.89 l  Gentry Weather
K3JAE
Senior Member
**
Offline Offline

Posts: 79


Davis VP2 Wireless


WWW
« Reply #8 on: May 12, 2011, 01:18:14 AM »

I just implemented the above items... all appear to be working but cannot check if the iPod coding is working as I do not have one. Both my Android and iPhone work flawlessly.

My question is let us assume not everyone wants to go directly to the mobile side of the site when on a mobile device. On my iPhone I want to see my entire site at times and not necessarily just the mobile side mainly to make sure all is working OK. Is there something that can be added, done etc. to ask a mobile user if they want the Main Site or the mobile side before forcing a redirect?

Also I have a link on my mobile side for the main site but it keeps kicking me back to the mobile side... of course my index page has the mobile detection code in it so I understand why, but how do I get around it?

Using the above code and setting cookies does not allow my mobile devices within the hour, to go to the main site nor is there any request to choose which side to go to or be allowed even when using the link to go to the main site. I created my own mobile side, not using a "template" so cookie cutting code may not work.

http://www.k3jae.com or http://www.k3jae.com/index.php will redirect to http://www.k3jae.com/wxindex.php I tried putting the mobile detect script on the index.php page but that bombed badly. The mobile page is: http://www.k3jae.com/cell.php?skip=1

Anyone want to tackle this so I can get around to the main site from the mobile device please?
« Last Edit: May 12, 2011, 01:55:00 AM by K3JAE » Logged



73's de K3JAE

John
K3JAE Weather Station
up10ad
Forecaster
*****
Offline Offline

Posts: 556



WWW
« Reply #9 on: May 12, 2011, 11:05:39 AM »

My question is let us assume not everyone wants to go directly to the mobile side of the site when on a mobile device. On my iPhone I want to see my entire site at times and not necessarily just the mobile side mainly to make sure all is working OK. Is there something that can be added, done etc. to ask a mobile user if they want the Main Site or the mobile side before forcing a redirect?

Your mobile detection does work.  However, at the bottom of your mobile page your link to the desktop version just gets redirected to the mobile site again, suggesting that your mobile site is not setting a cookie, or your desktop site is not checking for the cookie.

Also I have a link on my mobile side for the main site but it keeps kicking me back to the mobile side... of course my index page has the mobile detection code in it so I understand why, but how do I get around it?

Does your mobile page have the cookie set code in it?

==============================
<?php
setcookie("DWCmobile", "Been There", time()+3600);
?>


And does your desktop site have the ckeck for cookie code in it?

<?php
include('mobile_device_detect.php');
if (isset($_COOKIE["DWCmobile"]))
  echo "";
else
mobile_device_detect(true,true,true,true,true,true,'http://deltaweathercam.com/mobile.php',false);
?>

And does the cookie name match in both?

Logged

Rick
Have you joined USAWeatherFinder.com yet?

AF6GL
Member
*
Offline Offline

Posts: 33


WWW
« Reply #10 on: May 12, 2011, 04:30:43 PM »

I just saw this and am hugely interested. The sad part is I am leaving for vacation (Dayton Hamvention) on Sunday and won't have time to play with it for a couple of weeks.
Logged
K3JAE
Senior Member
**
Offline Offline

Posts: 79


Davis VP2 Wireless


WWW
« Reply #11 on: May 13, 2011, 12:08:59 AM »

Quote
Does your mobile page have the cookie set code in it?

==============================
<?php
setcookie("DWCmobile", "Been There", time()+3600);
?>


And does your desktop site have the ckeck for cookie code in it?

<?php
include('mobile_device_detect.php');
if (isset($_COOKIE["DWCmobile"]))
  echo "";
else
mobile_device_detect(true,true,true,true,true,true,'http://deltaweathercam.com/mobile.php',false);
?>

And does the cookie name match in both?

I have set up as follows:

On my wxindex.php page:
Code:
<?php
require_once('mobile_device_detect.php'); 
if (isset(
$_COOKIE["K3JAEmobile"]))
  echo 
"";
else
mobile_device_detect(true,false,true,true,true,true,true,'http://www.k3jae.com/cell.php?skip=1',false);
?>

On my cell.php page:
Code:
<?php
setcookie
("K3JAEmobile""Been There"time()+3600);
?>


Again, if a person comes in under http://www.k3jae.com or http://www.k3jae.com/index.php it will auto redirect to http://www.k3jae.com/wxindex.php.

Once this happens, of course and if it is a mobile device then it gets redirected to the mobile page.

If I use:
Code:
<?php
include('mobile_device_detect.php');
if (isset(
$_COOKIE["K3JAEmobile"]))
  echo 
"";
else
mobile_device_detect(true,true,true,true,true,true,'http://www.k3jae.com/cell.php?skip=1',false);
?>
The redirect does not work.... basically everything after the "else" statement.

How do I determine if the website is setting the cookie?
« Last Edit: May 13, 2011, 01:21:09 AM by K3JAE » Logged



73's de K3JAE

John
K3JAE Weather Station
up10ad
Forecaster
*****
Offline Offline

Posts: 556



WWW
« Reply #12 on: May 13, 2011, 09:50:16 AM »

If I use:
Code:
<?php
include('mobile_device_detect.php');
if (isset(
$_COOKIE["K3JAEmobile"]))
  echo 
"";
else
mobile_device_detect(true,true,true,true,true,true,'http://www.k3jae.com/cell.php?skip=1',false);
?>
The redirect does not work.... basically everything after the "else" statement.

It looks like the only difference is the first uses:
(true,false,true,true,true,true,true,...
and the second uses
(true,true,true,true,true,true,...

The sequence and count of true/false items corresponds to the sequence of CASE tests in mobile_device_detect.php, but only those that have the $mobileredirect set to a variable phone name like:
Code:
$mobileredirect = $ipad; // set the mobile redirect url to the url value stored in the ipad value

Some are always set to redirect like:
Code:
$mobile_browser = true; // set mobile browser to true

Mine currently has 11 CASE choices, but only the first 7 need a true/false in my main page as follows:

Quote
 switch(true){ // using a switch against the following statements which could return true is more efficient than the previous method of using if statements

    case (preg_match('/ipad/i',$user_agent)); // we find the word ipad in the user agent
      $mobile_browser = $ipad; // mobile browser is either true or false depending on the setting of ipad when calling the function
      $status = 'Apple iPad';
      if(substr($ipad,0,4)=='http'){ // does the value of ipad resemble a url
        $mobileredirect = $ipad; // set the mobile redirect url to the url value stored in the ipad value
      } // ends the if for ipad being a url
    break; // break out and skip the rest if we've had a match on the ipad // this goes before the iphone to catch it else it would return on the iphone instead

    case (preg_match('/ipod/i',$user_agent)||preg_match('/iphone/i',$user_agent)); // we find the words iphone or ipod in the user agent
      $mobile_browser = $iphone; // mobile browser is either true or false depending on the setting of iphone when calling the function
      $status = 'Apple';
      if(substr($iphone,0,4)=='http'){ // does the value of iphone resemble a url
        $mobileredirect = $iphone; // set the mobile redirect url to the url value stored in the iphone value
      } // ends the if for iphone being a url
    break; // break out and skip the rest if we've had a match on the iphone or ipod

    case (preg_match('/android/i',$user_agent));  // we find android in the user agent
      $mobile_browser = $android; // mobile browser is either true or false depending on the setting of android when calling the function
      $status = 'Android';
      if(substr($android,0,4)=='http'){ // does the value of android resemble a url
        $mobileredirect = $android; // set the mobile redirect url to the url value stored in the android value
      } // ends the if for android being a url
    break; // break out and skip the rest if we've had a match on android

    case (preg_match('/opera mini/i',$user_agent)); // we find opera mini in the user agent
      $mobile_browser = $opera; // mobile browser is either true or false depending on the setting of opera when calling the function
      $status = 'Opera';
      if(substr($opera,0,4)=='http'){ // does the value of opera resemble a rul
        $mobileredirect = $opera; // set the mobile redirect url to the url value stored in the opera value
      } // ends the if for opera being a url
    break; // break out and skip the rest if we've had a match on opera

    case (preg_match('/blackberry/i',$user_agent)); // we find blackberry in the user agent
      $mobile_browser = $blackberry; // mobile browser is either true or false depending on the setting of blackberry when calling the function
      $status = 'Blackberry';
      if(substr($blackberry,0,4)=='http'){ // does the value of blackberry resemble a rul
        $mobileredirect = $blackberry; // set the mobile redirect url to the url value stored in the blackberry value
      } // ends the if for blackberry being a url
    break; // break out and skip the rest if we've had a match on blackberry

    case (preg_match('/(pre\/|palm os|palm|hiptop|avantgo|plucker|xiino|blazer|elaine)/i',$user_agent)); // we find palm os in the user agent - the i at the end makes it case insensitive
      $mobile_browser = $palm; // mobile browser is either true or false depending on the setting of palm when calling the function
      $status = 'Palm';
      if(substr($palm,0,4)=='http'){ // does the value of palm resemble a rul
        $mobileredirect = $palm; // set the mobile redirect url to the url value stored in the palm value
      } // ends the if for palm being a url
    break; // break out and skip the rest if we've had a match on palm os

    case (preg_match('/(iris|3g_t|windows ce|opera mobi|windows ce; smartphone;|windows ce; iemobile)/i',$user_agent)); // we find windows mobile in the user agent - the i at the end makes it case insensitive
      $mobile_browser = $windows; // mobile browser is either true or false depending on the setting of windows when calling the function
      $status = 'Windows Smartphone';
      if(substr($windows,0,4)=='http'){ // does the value of windows resemble a rul
        $mobileredirect = $windows; // set the mobile redirect url to the url value stored in the windows value
      } // ends the if for windows being a url
    break; // break out and skip the rest if we've had a match on windows

    case (preg_match('/(mini 9.5|vx1000|lge |m800|e860|u940|ux840|compal|wireless| mobi|ahong|lg380|lgku|lgu900|lg210|lg47|lg920|lg840|lg370|sam-r|mg50|s55|g83|t66|vx400|mk99|d615|d763|el370|sl900|mp500|samu3|samu4|vx10|xda_|samu5|samu6|samu7|samu9|a615|b832|m881|s920|n210|s700|c-810|_h797|mob-x|sk16d|848b|mowser|s580|r800|471x|v120|rim8|c500foma:|160x|x160|480x|x640|t503|w839|i250|sprint|w398samr810|m5252|c7100|mt126|x225|s5330|s820|htil-g1|fly v71|s302|-x113|novarra|k610i|-three|8325rc|8352rc|sanyo|vx54|c888|nx250|n120|mtk |c5588|s710|t880|c5005|i;458x|p404i|s210|c5100|teleca|s940|c500|s590|foma|samsu|vx8|vx9|a1000|_mms|myx|a700|gu1100|bc831|e300|ems100|me701|me702m-three|sd588|s800|8325rc|ac831|mw200|brew |d88|htc\/|htc_touch|355x|m50|km100|d736|p-9521|telco|sl74|ktouch|m4u\/|me702|8325rc|kddi|phone|lg |sonyericsson|samsung|240x|x320|vx10|nokia|sony cmd|motorola|up.browser|up.link|mmp|symbian|smartphone|midp|wap|vodafone|o2|pocket|kindle|mobile|psp|treo)/i',$user_agent)); // check if any of the values listed create a match on the user agent - these are some of the most common terms used in agents to identify them as being mobile devices - the i at the end makes it case insensitive
     $mobile_browser = true; // set mobile browser to true
      $status = 'Mobile matched on piped preg_match';
    break; // break out and skip the rest if we've preg_match on the user agent returned true

    case ((strpos($accept,'text/vnd.wap.wml')>0)||(strpos($accept,'application/vnd.wap.xhtml+xml')>0)); // is the device showing signs of support for text/vnd.wap.wml or application/vnd.wap.xhtml+xml
      $mobile_browser = true; // set mobile browser to true
      $status = 'Mobile matched on content accept header';
    break; // break out and skip the rest if we've had a match on the content accept headers

    case (isset($_SERVER['HTTP_X_WAP_PROFILE'])||isset($_SERVER['HTTP_PROFILE'])); // is the device giving us a HTTP_X_WAP_PROFILE or HTTP_PROFILE header - only mobile devices would do this
      $mobile_browser = true; // set mobile browser to true
      $status = 'Mobile matched on profile headers being set';
    break; // break out and skip the final step if we've had a return true on the mobile specfic headers

    case (in_array(strtolower(substr($user_agent,0,4)),array('1207'=>'1207','3gso'=>'3gso','4thp'=>'4thp','501i'=>'501i','502i'=>'502i','503i'=>'503i','504i'=>'504i','505i'=>'505i','506i'=>'506i','6310'=>'6310','6590'=>'6590','770s'=>'770s','802s'=>'802s','a wa'=>'a wa','acer'=>'acer','acs-'=>'acs-','airn'=>'airn', REMOVED A BUNCH OF ITEMS TO SHORTEN DISPLAY        'alav'=>'alav','asus'=>'asus','attw'=>'attw','au-m'=>'au-','wapa'=>'wapa','wapi'=>'wapi','wapp'=>'wapp','wapr'=>'wapr','webc'=>'webc','whit'=>'whit','winw'=>'winw','wmlb'=>'wmlb','xda-'=>'xda-',))); // check against a list of trimmed user agents to see if we find a match
      $mobile_browser = true; // set mobile browser to true
      $status = 'Mobile matched on in_array';
    break; // break even though it's the last statement in the switch so there's nothing to break away from but it seems better to include it than exclude it

    default;
      $mobile_browser = false; // set mobile browser to false
      $status = 'Desktop / full capability browser';
    break; // break even though it's the last statement in the switch so there's nothing to break away from but it seems better to include it than exclude it

  } // ends the switch
Make sure the number and order of true or false statements equals the order of your CASE$mobile_browser values that are NOT set to true.  

How do I determine if the website is setting the cookie?

It's really fairly easy. depending on what browser you have. Google 'how to check cookies in [browser name]'.  In IE9 just press F12 to bring up the developer toolbar and click on Cache|View Cookie Information.  If I have visited my mobile page in the last hour mine shows:

Quote
NAME  DWCmobile
VALUE  Been+There
DOMAIN  deltaweathercam.com
PATH  /
EXPIRES  5/13/2011 8:47:32 AM


Hope this helps.  Maybe if you posted your mobile_device_detect.php page it would help.
« Last Edit: May 13, 2011, 09:53:55 AM by up10ad » Logged

Rick
Have you joined USAWeatherFinder.com yet?

Bushman
Forecaster
*****
Offline Offline

Posts: 3492


WWW
« Reply #13 on: May 13, 2011, 11:40:00 AM »

Same sort of thing incl. other languages. http://www.hand-interactive.com/resources/detect-mobile-php.htm
Logged
K3JAE
Senior Member
**
Offline Offline

Posts: 79


Davis VP2 Wireless


WWW
« Reply #14 on: May 13, 2011, 03:27:47 PM »

Per your request, the mobile-device-detect.php (less all the commented out lines):

Code:
<?php
function mobile_device_detect($iphone=true,$ipad=true,$android=true,$opera=true,$blackberry=true,$palm=true,$windows=true,$mobileredirect=false,$desktopredirect=false){

  
$mobile_browser   false// set mobile browser as false till we can prove otherwise
  
$user_agent       $_SERVER['HTTP_USER_AGENT']; // get the user agent value - this should be cleaned to ensure no nefarious input gets executed
  
$accept           $_SERVER['HTTP_ACCEPT']; // get the content accept value - this should be cleaned to ensure no nefarious input gets executed

  
switch(true){ // using a switch against the following statements which could return true is more efficient than the previous method of using if statements

    
case (preg_match('/ipad/i',$user_agent)); // we find the word ipad in the user agent
      
$mobile_browser $ipad// mobile browser is either true or false depending on the setting of ipad when calling the function
      
$status 'Apple iPad';
      if(
substr($ipad,0,4)=='http'){ // does the value of ipad resemble a url
        
$mobileredirect $ipad// set the mobile redirect url to the url value stored in the ipad value
      
// ends the if for ipad being a url
    
break; // break out and skip the rest if we've had a match on the ipad // this goes before the iphone to catch it else it would return on the iphone instead

    
case (preg_match('/ipod/i',$user_agent)||preg_match('/iphone/i',$user_agent)); // we find the words iphone or ipod in the user agent
      
$mobile_browser $iphone// mobile browser is either true or false depending on the setting of iphone when calling the function
      
$status 'Apple';
      if(
substr($iphone,0,4)=='http'){ // does the value of iphone resemble a url
        
$mobileredirect $iphone// set the mobile redirect url to the url value stored in the iphone value
      
// ends the if for iphone being a url
    
break; // break out and skip the rest if we've had a match on the iphone or ipod

    
case (preg_match('/android/i',$user_agent));  // we find android in the user agent
      
$mobile_browser $android// mobile browser is either true or false depending on the setting of android when calling the function
      
$status 'Android';
      if(
substr($android,0,4)=='http'){ // does the value of android resemble a url
        
$mobileredirect $android// set the mobile redirect url to the url value stored in the android value
      
// ends the if for android being a url
    
break; // break out and skip the rest if we've had a match on android

    
case (preg_match('/opera mini/i',$user_agent)); // we find opera mini in the user agent
      
$mobile_browser $opera// mobile browser is either true or false depending on the setting of opera when calling the function
      
$status 'Opera';
      if(
substr($opera,0,4)=='http'){ // does the value of opera resemble a rul
        
$mobileredirect $opera// set the mobile redirect url to the url value stored in the opera value
      
// ends the if for opera being a url 
    
break; // break out and skip the rest if we've had a match on opera

    
case (preg_match('/blackberry/i',$user_agent)); // we find blackberry in the user agent
      
$mobile_browser $blackberry// mobile browser is either true or false depending on the setting of blackberry when calling the function
      
$status 'Blackberry';
      if(
substr($blackberry,0,4)=='http'){ // does the value of blackberry resemble a rul
        
$mobileredirect $blackberry// set the mobile redirect url to the url value stored in the blackberry value
      
// ends the if for blackberry being a url 
    
break; // break out and skip the rest if we've had a match on blackberry

    
case (preg_match('/(pre\/|palm os|palm|hiptop|avantgo|plucker|xiino|blazer|elaine)/i',$user_agent)); // we find palm os in the user agent - the i at the end makes it case insensitive
      
$mobile_browser $palm// mobile browser is either true or false depending on the setting of palm when calling the function
      
$status 'Palm';
      if(
substr($palm,0,4)=='http'){ // does the value of palm resemble a rul
        
$mobileredirect $palm// set the mobile redirect url to the url value stored in the palm value
      
// ends the if for palm being a url 
    
break; // break out and skip the rest if we've had a match on palm os

    
case (preg_match('/(iris|3g_t|windows ce|opera mobi|windows ce; smartphone;|windows ce; iemobile)/i',$user_agent)); // we find windows mobile in the user agent - the i at the end makes it case insensitive
      
$mobile_browser $windows// mobile browser is either true or false depending on the setting of windows when calling the function
      
$status 'Windows Smartphone';
      if(
substr($windows,0,4)=='http'){ // does the value of windows resemble a rul
        
$mobileredirect $windows// set the mobile redirect url to the url value stored in the windows value
      
// ends the if for windows being a url 
    
break; // break out and skip the rest if we've had a match on windows

    
case (preg_match('/(mini 9.5|vx1000|lge |m800|e860|u940|ux840|compal|wireless| mobi|ahong|lg380|lgku|lgu900|lg210|lg47|lg920|lg840|lg370|sam-r|mg50|s55|g83|t66|vx400|mk99|d615|d763|el370|sl900|mp500|samu3|samu4|vx10|xda_|samu5|samu6|samu7|samu9|a615|b832|m881|s920|n210|s700|c-810|_h797|mob-x|sk16d|848b|mowser|s580|r800|471x|v120|rim8|c500foma:|160x|x160|480x|x640|t503|w839|i250|sprint|w398samr810|m5252|c7100|mt126|x225|s5330|s820|htil-g1|fly v71|s302|-x113|novarra|k610i|-three|8325rc|8352rc|sanyo|vx54|c888|nx250|n120|mtk |c5588|s710|t880|c5005|i;458x|p404i|s210|c5100|teleca|s940|c500|s590|foma|samsu|vx8|vx9|a1000|_mms|myx|a700|gu1100|bc831|e300|ems100|me701|me702m-three|sd588|s800|8325rc|ac831|mw200|brew |d88|htc\/|htc_touch|355x|m50|km100|d736|p-9521|telco|sl74|ktouch|m4u\/|me702|8325rc|kddi|phone|lg |sonyericsson|samsung|240x|x320|vx10|nokia|sony cmd|motorola|up.browser|up.link|mmp|symbian|smartphone|midp|wap|vodafone|o2|pocket|kindle|mobile|psp|treo)/i',$user_agent)); // check if any of the values listed create a match on the user agent - these are some of the most common terms used in agents to identify them as being mobile devices - the i at the end makes it case insensitive
      
$mobile_browser true// set mobile browser to true
      
$status 'Mobile matched on piped preg_match';
    break; 
// break out and skip the rest if we've preg_match on the user agent returned true 

    
case ((strpos($accept,'text/vnd.wap.wml')>0)||(strpos($accept,'application/vnd.wap.xhtml+xml')>0)); // is the device showing signs of support for text/vnd.wap.wml or application/vnd.wap.xhtml+xml
      
$mobile_browser true// set mobile browser to true
      
$status 'Mobile matched on content accept header';
    break; 
// break out and skip the rest if we've had a match on the content accept headers

    
case (isset($_SERVER['HTTP_X_WAP_PROFILE'])||isset($_SERVER['HTTP_PROFILE'])); // is the device giving us a HTTP_X_WAP_PROFILE or HTTP_PROFILE header - only mobile devices would do this
      
$mobile_browser true// set mobile browser to true
      
$status 'Mobile matched on profile headers being set';
    break; 
// break out and skip the final step if we've had a return true on the mobile specfic headers

    
case (in_array(strtolower(substr($user_agent,0,4)),array('1207'=>'1207','3gso'=>'3gso','4thp'=>'4thp','501i'=>'501i','502i'=>'502i','503i'=>'503i','504i'=>'504i','505i'=>'505i','506i'=>'506i','6310'=>'6310','6590'=>'6590','770s'=>'770s','802s'=>'802s','a wa'=>'a wa','acer'=>'acer','acs-'=>'acs-','airn'=>'airn','alav'=>'alav','asus'=>'asus','attw'=>'attw','au-m'=>'au-m','aur '=>'aur ','aus '=>'aus ','abac'=>'abac','acoo'=>'acoo','aiko'=>'aiko','alco'=>'alco','alca'=>'alca','amoi'=>'amoi','anex'=>'anex','anny'=>'anny','anyw'=>'anyw','aptu'=>'aptu','arch'=>'arch','argo'=>'argo','bell'=>'bell','bird'=>'bird','bw-n'=>'bw-n','bw-u'=>'bw-u','beck'=>'beck','benq'=>'benq','bilb'=>'bilb','blac'=>'blac','c55/'=>'c55/','cdm-'=>'cdm-','chtm'=>'chtm','capi'=>'capi','cond'=>'cond','craw'=>'craw','dall'=>'dall','dbte'=>'dbte','dc-s'=>'dc-s','dica'=>'dica','ds-d'=>'ds-d','ds12'=>'ds12','dait'=>'dait','devi'=>'devi','dmob'=>'dmob','doco'=>'doco','dopo'=>'dopo','el49'=>'el49','erk0'=>'erk0','esl8'=>'esl8','ez40'=>'ez40','ez60'=>'ez60','ez70'=>'ez70','ezos'=>'ezos','ezze'=>'ezze','elai'=>'elai','emul'=>'emul','eric'=>'eric','ezwa'=>'ezwa','fake'=>'fake','fly-'=>'fly-','fly_'=>'fly_','g-mo'=>'g-mo','g1 u'=>'g1 u','g560'=>'g560','gf-5'=>'gf-5','grun'=>'grun','gene'=>'gene','go.w'=>'go.w','good'=>'good','grad'=>'grad','hcit'=>'hcit','hd-m'=>'hd-m','hd-p'=>'hd-p','hd-t'=>'hd-t','hei-'=>'hei-','hp i'=>'hp i','hpip'=>'hpip','hs-c'=>'hs-c','htc '=>'htc ','htc-'=>'htc-','htca'=>'htca','htcg'=>'htcg','htcp'=>'htcp','htcs'=>'htcs','htct'=>'htct','htc_'=>'htc_','haie'=>'haie','hita'=>'hita','huaw'=>'huaw','hutc'=>'hutc','i-20'=>'i-20','i-go'=>'i-go','i-ma'=>'i-ma','i230'=>'i230','iac'=>'iac','iac-'=>'iac-','iac/'=>'iac/','ig01'=>'ig01','im1k'=>'im1k','inno'=>'inno','iris'=>'iris','jata'=>'jata','java'=>'java','kddi'=>'kddi','kgt'=>'kgt','kgt/'=>'kgt/','kpt '=>'kpt ','kwc-'=>'kwc-','klon'=>'klon','lexi'=>'lexi','lg g'=>'lg g','lg-a'=>'lg-a','lg-b'=>'lg-b','lg-c'=>'lg-c','lg-d'=>'lg-d','lg-f'=>'lg-f','lg-g'=>'lg-g','lg-k'=>'lg-k','lg-l'=>'lg-l','lg-m'=>'lg-m','lg-o'=>'lg-o','lg-p'=>'lg-p','lg-s'=>'lg-s','lg-t'=>'lg-t','lg-u'=>'lg-u','lg-w'=>'lg-w','lg/k'=>'lg/k','lg/l'=>'lg/l','lg/u'=>'lg/u','lg50'=>'lg50','lg54'=>'lg54','lge-'=>'lge-','lge/'=>'lge/','lynx'=>'lynx','leno'=>'leno','m1-w'=>'m1-w','m3ga'=>'m3ga','m50/'=>'m50/','maui'=>'maui','mc01'=>'mc01','mc21'=>'mc21','mcca'=>'mcca','medi'=>'medi','meri'=>'meri','mio8'=>'mio8','mioa'=>'mioa','mo01'=>'mo01','mo02'=>'mo02','mode'=>'mode','modo'=>'modo','mot '=>'mot ','mot-'=>'mot-','mt50'=>'mt50','mtp1'=>'mtp1','mtv '=>'mtv ','mate'=>'mate','maxo'=>'maxo','merc'=>'merc','mits'=>'mits','mobi'=>'mobi','motv'=>'motv','mozz'=>'mozz','n100'=>'n100','n101'=>'n101','n102'=>'n102','n202'=>'n202','n203'=>'n203','n300'=>'n300','n302'=>'n302','n500'=>'n500','n502'=>'n502','n505'=>'n505','n700'=>'n700','n701'=>'n701','n710'=>'n710','nec-'=>'nec-','nem-'=>'nem-','newg'=>'newg','neon'=>'neon','netf'=>'netf','noki'=>'noki','nzph'=>'nzph','o2 x'=>'o2 x','o2-x'=>'o2-x','opwv'=>'opwv','owg1'=>'owg1','opti'=>'opti','oran'=>'oran','p800'=>'p800','pand'=>'pand','pg-1'=>'pg-1','pg-2'=>'pg-2','pg-3'=>'pg-3','pg-6'=>'pg-6','pg-8'=>'pg-8','pg-c'=>'pg-c','pg13'=>'pg13','phil'=>'phil','pn-2'=>'pn-2','pt-g'=>'pt-g','palm'=>'palm','pana'=>'pana','pire'=>'pire','pock'=>'pock','pose'=>'pose','psio'=>'psio','qa-a'=>'qa-a','qc-2'=>'qc-2','qc-3'=>'qc-3','qc-5'=>'qc-5','qc-7'=>'qc-7','qc07'=>'qc07','qc12'=>'qc12','qc21'=>'qc21','qc32'=>'qc32','qc60'=>'qc60','qci-'=>'qci-','qwap'=>'qwap','qtek'=>'qtek','r380'=>'r380','r600'=>'r600','raks'=>'raks','rim9'=>'rim9','rove'=>'rove','s55/'=>'s55/','sage'=>'sage','sams'=>'sams','sc01'=>'sc01','sch-'=>'sch-','scp-'=>'scp-','sdk/'=>'sdk/','se47'=>'se47','sec-'=>'sec-','sec0'=>'sec0','sec1'=>'sec1','semc'=>'semc','sgh-'=>'sgh-','shar'=>'shar','sie-'=>'sie-','sk-0'=>'sk-0','sl45'=>'sl45','slid'=>'slid','smb3'=>'smb3','smt5'=>'smt5','sp01'=>'sp01','sph-'=>'sph-','spv '=>'spv ','spv-'=>'spv-','sy01'=>'sy01','samm'=>'samm','sany'=>'sany','sava'=>'sava','scoo'=>'scoo','send'=>'send','siem'=>'siem','smar'=>'smar','smit'=>'smit','soft'=>'soft','sony'=>'sony','t-mo'=>'t-mo','t218'=>'t218','t250'=>'t250','t600'=>'t600','t610'=>'t610','t618'=>'t618','tcl-'=>'tcl-','tdg-'=>'tdg-','telm'=>'telm','tim-'=>'tim-','ts70'=>'ts70','tsm-'=>'tsm-','tsm3'=>'tsm3','tsm5'=>'tsm5','tx-9'=>'tx-9','tagt'=>'tagt','talk'=>'talk','teli'=>'teli','topl'=>'topl','hiba'=>'hiba','up.b'=>'up.b','upg1'=>'upg1','utst'=>'utst','v400'=>'v400','v750'=>'v750','veri'=>'veri','vk-v'=>'vk-v','vk40'=>'vk40','vk50'=>'vk50','vk52'=>'vk52','vk53'=>'vk53','vm40'=>'vm40','vx98'=>'vx98','virg'=>'virg','vite'=>'vite','voda'=>'voda','vulc'=>'vulc','w3c '=>'w3c ','w3c-'=>'w3c-','wapj'=>'wapj','wapp'=>'wapp','wapu'=>'wapu','wapm'=>'wapm','wig '=>'wig ','wapi'=>'wapi','wapr'=>'wapr','wapv'=>'wapv','wapy'=>'wapy','wapa'=>'wapa','waps'=>'waps','wapt'=>'wapt','winc'=>'winc','winw'=>'winw','wonu'=>'wonu','x700'=>'x700','xda2'=>'xda2','xdag'=>'xdag','yas-'=>'yas-','your'=>'your','zte-'=>'zte-','zeto'=>'zeto','acs-'=>'acs-','alav'=>'alav','alca'=>'alca','amoi'=>'amoi','aste'=>'aste','audi'=>'audi','avan'=>'avan','benq'=>'benq','bird'=>'bird','blac'=>'blac','blaz'=>'blaz','brew'=>'brew','brvw'=>'brvw','bumb'=>'bumb','ccwa'=>'ccwa','cell'=>'cell','cldc'=>'cldc','cmd-'=>'cmd-','dang'=>'dang','doco'=>'doco','eml2'=>'eml2','eric'=>'eric','fetc'=>'fetc','hipt'=>'hipt','http'=>'http','ibro'=>'ibro','idea'=>'idea','ikom'=>'ikom','inno'=>'inno','ipaq'=>'ipaq','jbro'=>'jbro','jemu'=>'jemu','java'=>'java','jigs'=>'jigs','kddi'=>'kddi','keji'=>'keji','kyoc'=>'kyoc','kyok'=>'kyok','leno'=>'leno','lg-c'=>'lg-c','lg-d'=>'lg-d','lg-g'=>'lg-g','lge-'=>'lge-','libw'=>'libw','m-cr'=>'m-cr','maui'=>'maui','maxo'=>'maxo','midp'=>'midp','mits'=>'mits','mmef'=>'mmef','mobi'=>'mobi','mot-'=>'mot-','moto'=>'moto','mwbp'=>'mwbp','mywa'=>'mywa','nec-'=>'nec-','newt'=>'newt','nok6'=>'nok6','noki'=>'noki','o2im'=>'o2im','opwv'=>'opwv','palm'=>'palm','pana'=>'pana','pant'=>'pant','pdxg'=>'pdxg','phil'=>'phil','play'=>'play','pluc'=>'pluc','port'=>'port','prox'=>'prox','qtek'=>'qtek','qwap'=>'qwap','rozo'=>'rozo','sage'=>'sage','sama'=>'sama','sams'=>'sams','sany'=>'sany','sch-'=>'sch-','sec-'=>'sec-','send'=>'send','seri'=>'seri','sgh-'=>'sgh-','shar'=>'shar','sie-'=>'sie-','siem'=>'siem','smal'=>'smal','smar'=>'smar','sony'=>'sony','sph-'=>'sph-','symb'=>'symb','t-mo'=>'t-mo','teli'=>'teli','tim-'=>'tim-','tosh'=>'tosh','treo'=>'treo','tsm-'=>'tsm-','upg1'=>'upg1','upsi'=>'upsi','vk-v'=>'vk-v','voda'=>'voda','vx52'=>'vx52','vx53'=>'vx53','vx60'=>'vx60','vx61'=>'vx61','vx70'=>'vx70','vx80'=>'vx80','vx81'=>'vx81','vx83'=>'vx83','vx85'=>'vx85','wap-'=>'wap-','wapa'=>'wapa','wapi'=>'wapi','wapp'=>'wapp','wapr'=>'wapr','webc'=>'webc','whit'=>'whit','winw'=>'winw','wmlb'=>'wmlb','xda-'=>'xda-',))); // check against a list of trimmed user agents to see if we find a match
      
$mobile_browser true// set mobile browser to true
      
$status 'Mobile matched on in_array';
    break; 
// break even though it's the last statement in the switch so there's nothing to break away from but it seems better to include it than exclude it

    
default;
      
$mobile_browser false// set mobile browser to false
      
$status 'Desktop / full capability browser';
    break; 
// break even though it's the last statement in the switch so there's nothing to break away from but it seems better to include it than exclude it

  
// ends the switch 

  // tell adaptation services (transcoders and proxies) to not alter the content based on user agent as it's already being managed by this script, some of them suck though and will disregard this....
// header('Cache-Control: no-transform'); // http://mobiforge.com/developing/story/setting-http-headers-advise-transcoding-proxies
// header('Vary: User-Agent, Accept'); // http://mobiforge.com/developing/story/setting-http-headers-advise-transcoding-proxies

  // if redirect (either the value of the mobile or desktop redirect depending on the value of $mobile_browser) is true redirect else we return the status of $mobile_browser
  
if($redirect = ($mobile_browser==true) ? $mobileredirect $desktopredirect){
    
header('Location: '.$redirect); // redirect to the right url for this device
    
exit;
  }else{ 
// a couple of folkas have asked about the status - that's there to help you debug and understand what the script is doing
if($mobile_browser==''){
return $mobile_browser// will return either true or false 
}else{
return array($mobile_browser,$status); // is a mobile so we are returning an array ['0'] is true ['1'] is the $status value
}
}

// ends function mobile_device_detect

?>

As I count it, I see the need for 7 "True/False" elements. Correct?

Regardless, I am going to snatch your switch statement as you have above and try it, if that is OK with you.

Also I exclusively use Firefox... so will look up how to detect cookies.
Logged



73's de K3JAE

John
K3JAE Weather Station
K3JAE
Senior Member
**
Offline Offline

Posts: 79


Davis VP2 Wireless


WWW
« Reply #15 on: May 13, 2011, 05:37:05 PM »

I think me has me problem resolved. I counted, then reset my TRUE/FALSE elements and now all appears to be working OK using my original mobile-device-detect.php file as originally posted.

Even my second hit on the page flips me to the actual main site.
Logged



73's de K3JAE

John
K3JAE Weather Station
Bushman
Forecaster
*****
Offline Offline

Posts: 3492


WWW
« Reply #16 on: May 13, 2011, 05:45:49 PM »

OK - this is weird.  There is NO TEXT in any message in this thread, and this thread only on the forum.  The thread displays but does not show the message text.  Is it due to some weird code inline or maybe my Opera browser?
Logged
up10ad
Forecaster
*****
Offline Offline

Posts: 556



WWW
« Reply #17 on: May 13, 2011, 06:13:11 PM »

Good news John.  I think you have the correct 7 elements now. 
Logged

Rick
Have you joined USAWeatherFinder.com yet?

K3JAE
Senior Member
**
Offline Offline

Posts: 79


Davis VP2 Wireless


WWW
« Reply #18 on: May 13, 2011, 09:02:07 PM »

Good news John.  I think you have the correct 7 elements now. 

Thanks for the guidance. It was an interesting learning experience! Always something new to learn!
Logged



73's de K3JAE

John
K3JAE Weather Station
Pages: [1]   Go Up
  Print  
 
Jump to:  

Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines Valid XHTML 1.0! Valid CSS!
Page created in 0.178 seconds with 19 queries.