2016年12月14日
【PHP】ユーザエージェント(デバイス)判定をして処理を行う方法
PC・スマートフォン・タブレット等のユーザーエージェント(デバイス)を判定して、処理を行う方法をメモメモ。
▼ユーザーエージェント(デバイス)判定
<?php class UserAgent{ private $ua; private $device; public function set(){ $this->ua = mb_strtolower($_SERVER['HTTP_USER_AGENT']); if(strpos($this->ua,'iphone') !== false){ $this->device = 'mobile'; }elseif(strpos($this->ua,'ipod') !== false){ $this->device = 'mobile'; }elseif((strpos($this->ua,'android') !== false) && (strpos($this->ua, 'mobile') !== false)){ $this->device = 'mobile'; }elseif((strpos($this->ua,'windows') !== false) && (strpos($this->ua, 'phone') !== false)){ $this->device = 'mobile'; }elseif((strpos($this->ua,'firefox') !== false) && (strpos($this->ua, 'mobile') !== false)){ $this->device = 'mobile'; }elseif(strpos($this->ua,'blackberry') !== false){ $this->device = 'mobile'; }elseif(strpos($this->ua,'ipad') !== false){ $this->device = 'tablet'; }elseif((strpos($this->ua,'windows') !== false) && (strpos($this->ua, 'touch') !== false && (strpos($this->ua, 'tablet pc') == false))){ $this->device = 'tablet'; }elseif((strpos($this->ua,'android') !== false) && (strpos($this->ua, 'mobile') === false)){ $this->device = 'tablet'; }elseif((strpos($this->ua,'firefox') !== false) && (strpos($this->ua, 'tablet') !== false)){ $this->device = 'tablet'; }elseif((strpos($this->ua,'kindle') !== false) || (strpos($this->ua, 'silk') !== false)){ $this->device = 'tablet'; }elseif((strpos($this->ua,'playbook') !== false)){ $this->device = 'tablet'; }else{ $this->device = 'others'; } return $this->device; } } ?>
▼使用方法
<?php $ua = new UserAgent(); if($ua->set() === "mobile") { //この中のコードはスマホにのみ適用 } elseif ($ua->set() === "tablet"){ //この中のコードはタブレットにのみ適用 }else{ //この中のコードはスマホとタブレット以外に適用 } ?>
関連記事
-
【PHP】現在のURLやホスト名等を表示する方法
【PHP】現在のURLやホスト名等を表示する方法
現在アクセスしているURL等を取得するサーバー環境変数「$_SERVER」。 非常に便利ですが、変数が多く覚えられないの・・・ -
【PHP】if文を1行で短くシンプルに記載する方法
【PHP】if文を1行で短くシンプルに記載する方法
ちょっとした分岐なのに、複数行にわたってしまうif文。 そのif文を1行でシンプルに書きたい場合などあるかと思います。そ・・・ -
【PHP】フルパス(絶対パス)を取得する方法
【PHP】フルパス(絶対パス)を取得する方法
頻繁ではないんですが、フルパス(絶対パス)を知りたいという時、たまにあります。 そんなときに使えるのでメモメモ。 [ph・・・ -
【PHP】指定した時間によって表示を変える方法
【PHP】指定した時間によって表示を変える方法
PHPが動作する環境やWordPressで指定した時間によって、表示する、しない方法をメモメモ ▼時間が経過することで内・・・ -
【PHP】実行時に発生したエラーを画面に表示する方法
【PHP】実行時に発生したエラーを画面に表示する方法
PHP実行時のエラーをブラウザ上に表示する方法をメモメモ [php] ini_set("display_err・・・