User agent iphone php

How Can I Detect the iPhone & iPad’s User Agent?

So you’ve decided to create a mobile website for iPhone and iPad users, rather than creating a web applications. Where do you start? This tutorial will show you how to detect the popular mobile devices using JavaScript, PHP and your site’s .htaccess file!

Detecting the iPhone and iPad

Obviously, if you’ve created a page specifically for iPhone and iPad users, the first thing you’ll need to do is to find out when a user is visiting your site via an iPhone or iPad. Apple provides the iPad’s user agent string, which appears as follows:

The iPhone’s user agent string appears as follows:

Provided with this information, it’s fairly straight forward to use JavaScript to detect the user agent, and send the user to a specific page:

Using the same information, you can do the dirty work on the server side using PHP instead:

Finally, you could always use your site’s .htaccess file to do the same thing on the server side of things:

Now, assuming you want to purchase a ready-made package that detects all mobile devices, you can visit the Detect Mobile Browsers website for their $50 PHP-based mobile device detection script. It is free for non-profit or personal use, however commercial websites need to purchase it. Not only will it detect iPhones and iPads, it will also detect Android, Opera Mini, Blackberry, Palm and Windows devices. You can even use their function generator to create the specific action you wish to, once the user agent is detected. Actions include treating the user agent as a mobile device, directing the user to a specific page for the device, or displaying the page normally as it would for any other browser.

Next week we’ll get into the creation of iPhone and iPad specific websites, show you how to detect and set the iPhone and iPad’s viewport orientation using JavaScript and more!

Источник

PHP — получите точную версию iOS от User-Agent

Я хотел бы получить точную версию iOS в PHP от User-Agent. Я хорошо осведомлен о возможностях фальсификации пользовательских агентов, но в моем случае это не проблема.

Обычная строка User-Agent iPhone выглядит следующим образом:

Как мне извлечь версию ОС из этого? В данном случае это «11_2_1». Я должен быть в состоянии извлечь это из пользовательских агентов iPhone, iPad и iPod. Это также может быть X_X вместо X_X_X.

Читайте также:  Apple to apples how to play

Пока я получил это:

Однако, посещение этого с iPhone показывает пустую страницу. Может кто-то мне помочь, пожалуйста?

4 ответа

Есть несколько регулярных выражений, которые вы можете выполнить, чтобы получить версию ОС. Ниже приведено регулярное выражение:

Примечание . Все эти регулярные выражения используют флаг i .

Также могут быть использованы другие варианты, такие как:

Использование

Примечание . Чтобы отделить каждую часть версии в результате, вы можете использовать следующую строку , как показано здесь :

Использование — с кодом ОП

Полученные результаты

Выход

Вывод совпадения с помощью explode() в _ ( в примечании под первым разделом Использование ):

Объяснение

  • ip Сопоставьте это буквально
  • (?:hone|[ao]d) Соответствует любому из следующих
  • hone Сопоставьте это буквально (делает iphone )
  • [ao]d Соответствует либо a , либо o , за которыми следует d (делает ipad или ipod )
  • Соответствует буквальному пробелу
  • os Сопоставьте это буквально
  • Match a literal space character. I noticed the OP also had OS\_ , что наводит меня на мысль, что здесь может быть символ подчеркивания. В этом случае это можно изменить вместо [ _] .
  • \K Сбрасывает начальную точку матча. Все ранее использованные персонажи исключаются из финального матча
  • [\d_]+ Совпадение с одним или несколькими цифрами или символами подчеркивания
  • Вы можете использовать парсер User-Agent или даже создать свой собственный. Здесь у вас есть пример. Также я нашел этот проект php PhpUserAgent, который должен быть очень простым в использовании:

    Затем вы можете извлечь version из этого объекта.

    Этот user-agent-parser для javascript также работает очень хорошо.

    Попробуйте использовать это: «/(i(?:phone|pad|pod)) OS (\d+_\d+_\d+)/i» .

    Источник

    Библиотека для определения типа и модели устройства на PHP

    Mobile Detect это легковесный PHP класс для определения типа мобильного устройства, (включая и планшеты). Для определения устройства происходит анализ опции User-Agent и HTTP заголовков.

    Общие возможности

    isMobile() — определяет является ли устройство мобильным

    isTablet() — определяет является ли устройство планшетом

    Возможности библиотеки

    Для проверки мы можем заюзать следующие методы:

    Определение телефона

    Определение планшета

    • isBlackBerryTablet()
    • isiPad()
    • isKindle()
    • isSamsungTablet()
    • isHTCtablet()
    • isMotorolaTablet()
    • isAsusTablet()
    • isNookTablet()
    • isAcerTablet()
    • isYarvikTablet()
    • isGenericTablet()

    Определение операционной системы

    • isAndroidOS()
    • isBlackBerryOS()
    • isPalmOS()
    • isSymbianOS()
    • isWindowsMobileOS()
    • isiOS()
    • isFlashLiteOS()
    • isJavaOS()
    • isNokiaOS()
    • iswebOS()
    • isbadaOS()
    • isBREWOS()

    Определение мобильного браузера

    Примеры

    Данный урок подготовлен для вас командой сайта ruseller.com
    Источник урока: http://mobiledetect.net/
    Перевел: Станислав Протасевич
    Урок создан: 15 Января 2014
    Просмотров: 55018
    Правила перепечатки

    5 последних уроков рубрики «PHP»

    Фильтрация данных с помощью zend-filter

    Когда речь идёт о безопасности веб-сайта, то фраза «фильтруйте всё, экранируйте всё» всегда будет актуальна. Сегодня поговорим о фильтрации данных.

    Контекстное экранирование с помощью zend-escaper

    Обеспечение безопасности веб-сайта — это не только защита от SQL инъекций, но и протекция от межсайтового скриптинга (XSS), межсайтовой подделки запросов (CSRF) и от других видов атак. В частности, вам нужно очень осторожно подходить к формированию HTML, CSS и JavaScript кода.

    Подключение Zend модулей к Expressive

    Expressive 2 поддерживает возможность подключения других ZF компонент по специальной схеме. Не всем нравится данное решение. В этой статье мы расскажем как улучшили процесс подключение нескольких модулей.

    Совет: отправка информации в Google Analytics через API

    Предположим, что вам необходимо отправить какую-то информацию в Google Analytics из серверного скрипта. Как это сделать. Ответ в этой заметке.

    Подборка PHP песочниц

    Подборка из нескольких видов PHP песочниц. На некоторых вы в режиме online сможете потестить свой код, но есть так же решения, которые можно внедрить на свой сайт.

    Источник

    Creating a proxy to spoof iPhone user-agent in PHP?

    I’m writing a web based iPhone simulator and I’m looking for a way to spoof iPhone’s Safari browser so that web pages loaded within the simulator (iframe) to use the mobile versions. From my understanding I need to modify the user-agent.

    How do I go about creating a PHP proxy script to spoof the iPhone’s user-agent?

    3 Answers 3

    You could use a PHP class, such as Ben Alman’s Simple PHP Proxy / Github.

    It let’s you redirect cross-domain URL’s in a variety of ways, including the following method to «change up» your User Agent.

    I use it to insert an iFrame — with the iPhone version of google voice — into any page, for example.

    Some of the many other ways you can alter the request by using this script are.

    You could use a library like cURL to request the page with the iPhone user agent, and return that page to your site (be sure to expand relative URLs to absolute, with DOMDocument).

    However, you may run into edge cases where CSS/JavaScript/images are served differently via the user agent. This is probably not worth requesting each of these assets on the off chance. You could limit the work by requesting once with your user agent, and then the iPhone user agent, doing md5_file() and seeing if they are different. I wouldn’t bother though 😛

    You could also try this JavaScript.

    Also remember you may want to give a warning if your users aren’t using Safari, which will be the closest to simulate Mobile Safari.

    Источник

    iPhone user agent

    The iPhone launched with this user agent:

    Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3

    Here’s a tip to find out the user agent for any browser or device that you’re on (e.g. a kiosk at a mall, a different cell phone, or something else that you tinker with):

    – Go to Google
    – Search for the word phpinfo. If you visit a webserver running the phpinfo() command, the resulting web page will tell you info about the web server, but it will also tell you about your browser’s user agent.
    – Look for a page that actually runs phpinfo() instead of documentation about phpinfo(). Usually there’s a few such pages in the top 10. If you’re having trouble finding a phpinfo() page, you can do a more specific search for the words phpinfo http_user_agent.
    – Click on the phpinfo() page and near the bottom of the page look for a string called HTTP_USER_AGENT. You’ll see something like this:

    Sorry that the picture runs in the right-hand column; I didn’t want to clip or resize the image. I took this picture running Firefox on my Ubuntu Desktop, so that’s the user agent you see. But this tip works with iPhones and almost any other browser that can search on Google.

    54 Responses to iPhone user agent (Leave a comment)

    It actually has several agents, this is a sampling from several hundred or more phones..

    +——————————————————————————————————————————+
    | k |
    +——————————————————————————————————————————+
    | Mozilla/5.0 (iPhone; U; XXXXX like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/241 Safari/419.3 |
    | Mozilla/5.0 (iPhone; U; XXXXX like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A477c Safari/419.3 |
    | Mozilla/5.0 (iPhone; U; XXXXX like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A477d Safari/419.3 |
    | Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A498b Safari/419.3 |
    | Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A535b Safari/419.3 |
    | Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A538b Safari/419.3 |
    | Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3 |
    | Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Kevin) Version/3.0 Mobile/1A543a Safari/419.3 |
    | Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A566a Safari/419.3 |
    | Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1C9 Safari/419.3 |
    | Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1C10 Safari/419.3 |
    | Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A522a Safari/419.3 |
    | Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1C6 Safari/419.3 |
    | Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A537a Safari/419.3 |
    +——————————————————————————————————————————+

    What I usually do in this case is just resize my browser so the table shrinks to the right size before taking the screenshot =)

    neat tip. Didn’t think of it. I had forgotten that phpinfo included that, and actually wrote a small 1 liner to spit out just that information for me when I was writing some mobile apps last nite.

    It might be helpful to include tips for your readers about how to check the headers in code and redirect appropriately. I know I’ve been asked several questions about it myself since blogging about writing for the iPhone.

    I said it before, but I really think the iPhone browser is going to steer developers toward thinking about the mobile web and mobile devices. We should see a lot of cool things come out in that area in the next few months.

    Got my iPhone too, way too much fun!

    I built an app a few days before the iPhone was released and have been watching stats with Google Analytics. I recently posted about how to tell if you have iPhone visitors because Google doesn’t discriminate in browser or OS between the iPhone and Mac visitors, except in screen resolution:

    Yep, we noticed our first iPhone user agent string on my fireworks website on July 3rd.

    Источник

    Читайте также:  Обои для айфона руны
    Оцените статью