With the evolution of web design, many websites have adopted responsive design. However, some sites still provide separate versions for mobile and desktop users. In such cases, a method is needed to display the version of the site that is best suited for the user’s device.
This article will introduce a simple implementation using PHP’s setcookie function to switch between mobile and desktop sites. By adopting this implementation, the selected display format (mobile or desktop) can be remembered for the next visit.
PHP Code for the Desktop Site
First, set up the PHP code on the desktop site. Implement it by following these steps:
- 1. Check if the `vmode` parameter is present.
- 2. If `vmode` exists, save its value in a cookie.
- 3. If `vmode` does not exist, retrieve the `vmode` value from an existing cookie.
- 4. Switch the display based on the value of `vmode` stored in the cookie and the user agent.
<?php
$vmode = "";
if(isset($_GET['vmode'])) { // When the parameter is received from the mobile site
$vmode = $_GET['vmode'];
setcookie("vmode", $vmode, null, "/"); // Set the parameter in the cookie
}else if(isset($_COOKIE['vmode'])){
$vmode = $_COOKIE['vmode'];
}
if($vmode != "pc" || $vmode == "") {
$str_ua = "(iPhone|iPod|Android.*Mobile|BlackBerry)";
if(preg_match($str_ua, $_SERVER['HTTP_USER_AGENT']) != 0) {
setcookie("vmode", "sp", null, "/");
header("Location: sp-site.php"); // Switch to the mobile page if accessed from a mobile device
}
}
?>
HTML Link on the Desktop Site
Next, set up a link for users to manually switch to the mobile site. Clicking this link will add the `vmode=sp` parameter to the URL.
<a href="index.php?vmode=sp">Switch to the mobile site</a>
HTML Code on the Mobile Site
Similarly, set up a link on the mobile site to switch to the desktop site.
<a href="index.php?vmode=pc">Switch to the desktop site</a>
Demo Pages for Switching Between Mobile and Desktop Sites Using PHP’s setcookie
Demo Page for the Desktop Site
Demo Page for Switching Between Mobile and Desktop Sites Using PHP’s setcookie (Desktop Site)
Demo Page for the Mobile Site
Demo Page for Switching Between Mobile and Desktop Sites Using PHP’s setcookie (Mobile Site)
By adopting this implementation, users can freely switch between the desktop and mobile sites. Additionally, since the selected display format is saved in a cookie, the site will be displayed in the same format on the next visit.
In Conclusion
When applying this implementation, it is necessary to appropriately set the cookie’s expiration, path, and domain, and to update the user agent check range as needed. This ensures accurate operation on various devices and browsers.
*Please use this implementation at your own risk.