How to Detect If a Website Is Being Browsed Through a Mobile Device with PHP


As technology is changing, and a great percentage of the total Internet users browse the web through their mobile devices, it’s become essential for a web developer, to add support for these devices. This can be achieved in various ways, but today, I’ll show you how to do it with PHP.

Difficulty level: Easy

1. Open up the header.php file of your website or the index.php file; if you just want to test it, simply create a new PHP file.

2. At the top, add the following:

if(strstr($_SERVER['HTTP_USER_AGENT'],'iPhone') || strstr($_SERVER['HTTP_USER_AGENT'],'iPod') || strstr($_SERVER['HTTP_USER_AGENT'],'iPad')  || strstr($_SERVER['HTTP_USER_AGENT'],'BlackBerry')) {

What we did here, was to detect the device’s user agent. We have added support for iPhone, iPod, iPad, and BlackBerry. Next, if it finds that we are using a mobile device, we are going to be redirected to whichever website we want to. In this example, we would be redirected to, which must be changed to match your needs.

Guess what? You’ve finished! Test it by saving it and uploading it to your server, and browsing it through your mobile device. If you would like to make the redirection to a subdomain: “m”, and don’t know how to, please read this article written by Arian Jahansouz.

Any comments, problems, suggestions, please let me know and I’d be more than glad to assist you.

Best Regards,



Looking for quality Linux Web Hosting? Try out Arvixe web hosting and you won’t be disappointed.
Tags: , , , , , , , , , , , , , , | Posted under Domain Names, Internet, Mobile | RSS 2.0

Author Spotlight

Richi González

I started programming when I was 12. I'm a Developer and have been working with the Clip-Bucket script since it came out. I'm the Liaison between Arvixe and Clip-Bucket, so anything you need regarding Clip-Bucket or any particular computer-related subject you need, let me know so I can assist you.

4 Comments on How to Detect If a Website Is Being Browsed Through a Mobile Device with PHP

  1. Matt says:

    And if it’s an android device? A windows mobile device?
    User agent sniffing is considered bad!
    Use something like

  2. Andrew Ivanov says:

    I agree with Matt – it’s not very elegant solution…

    • Hello,

      When I used wurfl, it was not a what we now considered “elegant solution”. I see it has advanced in many ways, thanks for letting me know wurlf is now better, I will definitely write an article about it.


  3. babanature says:

    hello guys,
    you know many people from where i am from are still using opera mini and the code above wont redirect when using opera mini or ucbrowser.

Leave a Reply

Your email address will not be published. Required fields are marked *