LoginSignup
7
13

More than 5 years have passed since last update.

PHPでユーザエージェントや引数からデバイスを判定

Last updated at Posted at 2017-03-07

メモ。

Device.class.php
/**
 * デバイス
 *
 * @method is_smartphone
 * @method is_fb_crawler
 * @method pc_or_android_or_ios
 * @method check_strict
 */
class Device
{
    /**
     * スマホか判定
     * @param  string $ua ユーザエージェント
     * @return boolean スマートフォンからのアクセスか否か
     */
    static public function is_smartphone($ua = null)
    {
        if ( is_null($ua) ) {
            $ua = $_SERVER['HTTP_USER_AGENT'];
        }

        if ( preg_match('/iPhone|iPod|iPad|Android/ui', $ua) ) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * Facebookのクローラか判定
     * @return boolean Facebookのクローラか否か
     */
    static public function is_fb_crawler()
    {
        if ( isset($_SERVER['HTTP_USER_AGENT']) && preg_match('/^facebookexternalhit/u', $_SERVER['HTTP_USER_AGENT']) ) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * デバイス判定
     * @param  string $ua ユーザエージェント
     * @return string pc|android|ios
     */
    static public function pc_or_android_or_ios($ua = null)
    {
        if ( is_null($ua) ) {
            $ua = $_SERVER['HTTP_USER_AGENT'];
        }

        if ( preg_match('/iPhone|iPod|iPad/ui', $ua) ) {
            return 'ios';
        } else if ( preg_match('/Android/ui', $ua) ) {
            return 'android';
        } else {
            return 'pc';
        }
    }


    /**
     * 厳密にデバイスを判定
     * @param  string $ua ユーザエージェント
     * @return string|boolean デバイス。Windows|Macintosh|iPhone|iPad|iPod|Android|AndroidTablet|WindowsPhone|false(一致なし)
     */
    static public function check_strict($ua = null)
    {
        if ( is_null($ua) ) {
            $ua = $_SERVER['HTTP_USER_AGENT'];
        }

        if ( preg_match('/Windows Phone/ui', $ua) ) { //UAにAndroidも含まれるので注意
            return 'WindowsPhone';
        } else if ( preg_match('/Windows/', $ua) ) {
            return 'Windows';
        } else if ( preg_match('/Macintosh/', $ua) ) {
            return 'Macintosh';
        } else if ( preg_match('/iPhone/', $ua) ) {
            return 'iPhone';
        } else if ( preg_match('/iPad/', $ua) ) {
            return 'iPad';
        } else if ( preg_match('/iPod/', $ua) ) {
            return 'iPod';
        } else if ( preg_match('/Android/', $ua) ) {
            if ( preg_match('/Mobile/', $ua) ) {
                return 'Android';
            } else {
                return 'AndroidTablet';
            }
        } else {
            return false;
        }
    }
}
7
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
13