0
0

PHPでiPhoneユーザーとAndroidユーザーを自動判別するサンプルコード

Posted at

PHPでiPhoneユーザーとAndroidユーザーを自動判別してリンク先を分けるシステムを作成することは可能です。以下にその実装方法を示します。

PHPコード
以下の例では、User-Agent ヘッダーを解析して、ユーザーがiPhoneまたはAndroidデバイスを使用しているかどうかを判別し、それに基づいてリダイレクトするコードを示します。

<?php
function detectDevice($userAgent) {
    if (strpos($userAgent, 'iPhone') !== false) {
        return 'iPhone';
    } elseif (strpos($userAgent, 'Android') !== false) {
        return 'Android';
    } else {
        return 'Unknown';
    }
}

$userAgent = $_SERVER['HTTP_USER_AGENT'];
$deviceType = detectDevice($userAgent);

if ($deviceType == 'iPhone') {
    header('Location: https://example.com/ios');
    exit();
} elseif ($deviceType == 'Android') {
    header('Location: https://example.com/android');
    exit();
} else {
    header('Location: https://example.com/unknown');
    exit();
}
?>

説明

User-Agentの取得: $_SERVER['HTTP_USER_AGENT'] を使ってユーザーの User-Agent ヘッダーを取得します。
デバイスの判別: detectDevice 関数で User-Agent を解析し、ユーザーがiPhone、Android、または不明なデバイスを使用しているかを判別します。
リダイレクト: デバイスの種類に応じて適切なURLにリダイレクトします。iPhoneユーザーは https://example.com/ios に、Androidユーザーは https://example.com/android に、不明なデバイスの場合は https://example.com/unknown にリダイレクトします。

使用方法

上記のPHPコードをファイル(例:index.php)に保存し、ウェブサーバー上に配置します。このスクリプトにアクセスすると、ユーザーのデバイスに応じて適切なページにリダイレクトされます。

0
0
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
0
0