关注前端开发
HTML5、CSS3、Javascript

php判断用户是否使用手机设备

搞移动页面调整的时候,需要用到这个东西,服务器端来判断用户的设备是不是手机。之前的d4在手机设备上浏览的时候,侧边栏是display:none的,这点很不人性化。手持设备注重的是速度和体验,没必要的东西最好不要上去,上去了又给隐藏掉,有点二。所以后来想想,如果在后端用php判断用户是否使用的是手机,那句比较轻松的防止加载没必要的东西了。之前是用css3来判断屏幕宽度,然后重定义css样式以获得最佳浏览体验。这个方法看似可行,其实病处不少,这个待后来慢慢讨论吧。回到本文的主题,php判断用户是否使用手机。

第一步:如果你和我一样使用的是wordpress,那就复制到主题的 function.php 文件

//判断是否属手机
function is_mobile() {
	$user_agent = $_SERVER['HTTP_USER_AGENT'];
	$mobile_agents = Array("240x320","acer","acoon","acs-","abacho","ahong","airness","alcatel","amoi","android","anywhereyougo.com","applewebkit/525","applewebkit/532","asus","audio","au-mic","avantogo","becker","benq","bilbo","bird","blackberry","blazer","bleu","cdm-","compal","coolpad","danger","dbtel","dopod","elaine","eric","etouch","fly ","fly_","fly-","go.web","goodaccess","gradiente","grundig","haier","hedy","hitachi","htc","huawei","hutchison","inno","ipad","ipaq","ipod","jbrowser","kddi","kgt","kwc","lenovo","lg ","lg2","lg3","lg4","lg5","lg7","lg8","lg9","lg-","lge-","lge9","longcos","maemo","mercator","meridian","micromax","midp","mini","mitsu","mmm","mmp","mobi","mot-","moto","nec-","netfront","newgen","nexian","nf-browser","nintendo","nitro","nokia","nook","novarra","obigo","palm","panasonic","pantech","philips","phone","pg-","playstation","pocket","pt-","qc-","qtek","rover","sagem","sama","samu","sanyo","samsung","sch-","scooter","sec-","sendo","sgh-","sharp","siemens","sie-","softbank","sony","spice","sprint","spv","symbian","tablet","talkabout","tcl-","teleca","telit","tianyu","tim-","toshiba","tsm","up.browser","utec","utstar","verykool","virgin","vk-","voda","voxtel","vx","wap","wellco","wig browser","wii","windows ce","wireless","xda","xde","zte");
	$is_mobile = false;
	foreach ($mobile_agents as $device) {
		if (stristr($user_agent, $device)) {
			$is_mobile = true;
			break;
		}
	}
	return $is_mobile;
}

第二步:if 语句

if( is_mobile() ){
Your Code
}
注意:是php

ok,看看d4主题使用的这种办法:

转载请注明出处大前端 » php判断用户是否使用手机设备

分享: