Home  >  Article  >  Backend Development  >  A PHP code to determine whether the device is a mobile phone/tablet

A PHP code to determine whether the device is a mobile phone/tablet

WBOY
WBOYOriginal
2016-07-25 08:42:25909browse
When doing web development, you often need to use page matching for mobile devices. Of course, you can directly make the website responsive, but if you don’t want to do this, you can use PHP to determine the device type and then display the corresponding interface. and content. Today I will share a method of using PHP to determine whether the device is a mobile phone/tablet. The method comes from WordPress (wp-includes/vars.php:125) and is suitable for most types of mobile phones/tablets:
  1. /**
  2. * Test if the current browser runs on a mobile device (smart phone, tablet, etc.)
  3. *
  4. * @staticvar bool $is_mobile
  5. *
  6. * @return bool
  7. */
  8. function wp_is_mobile() {
  9. static $is_mobile = null;
  10. if ( isset( $is_mobile ) ) {
  11. return $is_mobile;
  12. }
  13. if ( empty($_SERVER['HTTP_USER_AGENT']) ) {
  14. $is_mobile = false;
  15. } elseif ( strpos($_SERVER['HTTP_USER_AGENT'], 'Mobile') !== false // many mobile devices (all iPhone, iPad, etc.)
  16. || strpos($ _SERVER['HTTP_USER_AGENT'], 'Android') !== false
  17. || strpos($_SERVER['HTTP_USER_AGENT'], 'Silk/') !== false
  18. || strpos($_SERVER['HTTP_USER_AGENT'], 'Kindle') !== false
  19. || strpos($_SERVER['HTTP_USER_AGENT'], 'BlackBerry') !== false
  20. || strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mini') !== false
  21. || strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mobi') !== false ) {
  22. $is_mobile = true;
  23. } else {
  24. $is_mobile = false;
  25. }
  26. return $is_mobile;
  27. }
Copy code

PHP


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn