• Function Reference
  • Other Basic Extensions
  • Misc. Functions

get_browser

(PHP 4, PHP 5, PHP 7, PHP 8)

get_browser — Tells what the user's browser is capable of

Description

Attempts to determine the capabilities of the user's browser, by looking up the browser's information in the browscap.ini file.

The User Agent to be analyzed. By default, the value of HTTP User-Agent header is used; however, you can alter this (i.e., look up another browser's info) by passing this parameter.

You can bypass this parameter with a null value.

If set to true , this function will return an array instead of an object .

Return Values

The information is returned in an object or an array which will contain various data elements representing, for instance, the browser's major and minor version numbers and ID string; true / false values for features such as frames, JavaScript, and cookies; and so forth.

The cookies value simply means that the browser itself is capable of accepting cookies and does not mean the user has enabled the browser to accept cookies or not. The only way to test if cookies are accepted is to set one with setcookie() , reload, and check for the value.

Returns false when no information can be retrieved, such as when the browscap configuration setting in php.ini has not been set.

Example #1 Listing all information about the users browser

The above example will output something similar to:

Note : In order for this to work, your browscap configuration setting in php.ini must point to the correct location of the browscap.ini file on your system. browscap.ini is not bundled with PHP, but you may find an up-to-date » php_browscap.ini file here. While browscap.ini contains information on many browsers, it relies on user updates to keep the database current. The format of the file is fairly self-explanatory.

Improve This Page

User contributed notes 17 notes.

To Top

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free

Browser detection using the user agent

Serving different Web pages or services to different browsers is usually a bad idea. The Web is meant to be accessible to everyone, regardless of which browser or device they're using. There are ways to develop your website to progressively enhance itself based on the availability of features rather than by targeting specific browsers.

But browsers and standards are not perfect, and there are still some edge cases where detecting the browser is needed. Using the user agent to detect the browser looks simple, but doing it well is, in fact, a very hard problem. This document will guide you in doing this as correctly as possible.

Note: It's worth re-iterating: it's very rarely a good idea to use user agent sniffing. You can almost always find a better, more broadly compatible way to solve your problem!

Considerations before using browser detection

When considering using the user agent string to detect which browser is being used, your first step is to try to avoid it if possible. Start by trying to identify why you want to do it.

Look, or ask, in specialized forums: you're unlikely to be the first to hit this problem. Also, experts, or people with another point of view, can give you ideas for working around the bug. If the problem seems uncommon, it's worth checking if this bug has been reported to the browser vendor via their bug tracking system ( Mozilla ; WebKit ; Blink ; Opera ). Browser makers do pay attention to bug reports, and the analysis may hint about other workarounds for the bug.

Your site needs to use a specific Web feature that some browsers don't yet support, and you want to send those users to an older website with fewer features but that you know will work. This is the worst reason to use user agent detection because odds are eventually all the other browsers will catch up. In addition, it is not practical to test every one of the less popular browsers and test for those Web features. You should never do user agent sniffing. There is always the alternative of doing feature detection instead.

This is usually a bad practice, but there are some cases in which this is necessary. In these cases, you should first analyze your situation to be sure it's really necessary. Can you prevent it by adding some non-semantic <div> or <span> elements? The difficulty of successfully using user agent detection is worth a few disruptions to the purity of your HTML. Also, rethink your design: can you use progressive enhancement or fluid layouts to help remove the need to do this?

Avoiding user agent detection

If you want to avoid using user agent detection, you have options!

Feature detection is where you don't try to figure out which browser is rendering your page, but instead, you check to see if the specific feature you need is available. If it's not, you use a fallback. In those rare cases where behavior differs between browsers, instead of checking the user agent string, you should instead implement a test to detect how the browser implements the API and determine how to use it from that. An example of feature detection is as follows. In 2017, Chrome unflagged experimental lookbehind support in regular expressions , but no other browser supported it. So, you might have thought to do this:

The above code would have made several incorrect assumptions: First, it assumed that all user agent strings that include the substring "Chrome" are Chrome. UA strings are notoriously misleading. Then, it assumed that the lookbehind feature would always be available if the browser was Chrome. The agent might be an older version of Chrome, from before support was added, or (because the feature was experimental at the time) it could be a later version of Chrome that removed it. Most importantly, it assumed no other browsers would support the feature. Support could have been added to other browsers at any time, but this code would have continued choosing the inferior path.

Problems like these can be avoided by testing for support of the feature itself instead:

As the above code demonstrates, there is always a way to test browser support without user agent sniffing. There is never any reason to check the user agent string for this.

Lastly, the above code snippets bring about a critical issue with cross-browser coding that must always be taken into account. Don't unintentionally use the API you are testing for in unsupported browsers. This may sound obvious and simple, but sometimes it is not. For example, in the above code snippets, using lookbehind in short-regexp notation (for example, /reg/igm) will cause a parser error in unsupported browsers. Thus, in the above example, you would use new RegExp("(?<=look_behind_stuff)"); instead of /(?<=look_behind_stuff)/ , even in the lookbehind supported section of your code.

This design technique involves developing your website in 'layers', using a bottom-up approach, starting with a simpler layer and improving the capabilities of the site in successive layers, each using more features.

This is a top-down approach in which you build the best possible site using all the features you want, then tweak it to make it work on older browsers. This can be harder to do, and less effective, than progressive enhancement, but may be useful in some cases.

Arguably the most common use and misuse of user agent sniffing is to detect if the device is a mobile device. However, people too often overlook what they are really after. People use user agent sniffing to detect if the users' device is touch-friendly and has a small screen so they can optimize their website accordingly. While user agent sniffing can sometimes detect these, not all devices are the same: some mobile devices have big screen sizes, some desktops have a small touchscreen, some people use smart TV's which are an entirely different ballgame altogether, and some people can dynamically change the width and height of their screen by flipping their tablet on its side! So, user agent sniffing is definitely not the way to go. Thankfully, there are much better alternatives. Use Navigator.maxTouchPoints to detect if the user's device has a touchscreen. Then, default back to checking the user agent screen only if (!("maxTouchPoints" in navigator)) { /*Code here*/} . Using this information of whether the device has a touchscreen, do not change the entire layout of the website just for touch devices: you will only create more work and maintenance for yourself. Rather, add in touch conveniences such as bigger, more easily clickable buttons (you can do this using CSS by increasing the font size). Here is an example of code that increases the padding of #exampleButton to 1em on mobile devices.

As for the screen size, use window.innerWidth and window.addEventListener("resize", () => { /*refresh screen size dependent things*/ }). What you want to do for screen size is not slash off information on smaller screens. That will only annoy people because it will force them to use the desktop version. Rather, try to have fewer columns of information in a longer page on smaller screens while having more columns with a shorter page on larger screen sizes. This effect can be easily achieved using CSS flexboxes , sometimes with floats as a partial fallback.

Also try to move less relevant/important information down to the bottom and group the page's content together meaningfully. Although it is off-topic, perhaps the following detailed example might give you insights and ideas that persuade you to forgo user agent sniffing. Let us imagine a page composed of boxes of information; each box is about a different feline breed or canine breed. Each box has an image, an overview, and a historical fun fact. The pictures are kept to a maximum reasonable size even on large screens. For the purposes of grouping the content meaningfully, all the cat boxes are separated from all the dog boxes such that the cat and dog boxes are not intermixed together. On a large screen, it saves space to have multiple columns to reduce the space wasted to the left and to the right of the pictures. The boxes can be separated into multiple columns via two equally fair method. From this point on, we shall assume that all the dog boxes are at the top of the source code, that all the cat boxes are at the bottom of the source code, and that all these boxes have the same parent element. There a single instance of a dog box immediately above a cat box, of course. The first method uses horizontal Flexboxes to group the content such that when the page is displayed to the end user, all the dogs boxes are at the top of the page and all the cat boxes are lower on the page. The second method uses a Column layout and resents all the dogs to the left and all the cats to the right. Only in this particular scenario, it is appropriate to provide no fallback for the flexboxes/multicolumns, resulting in a single column of very wide boxes on old browsers. Also consider the following. If more people visit the webpage to see the cats, then it might be a good idea to put all the cats higher in the source code than the dogs so that more people can find what they are looking for faster on smaller screens where the content collapses down to one column.

Next, always make your code dynamic. The user can flip their mobile device on its side, changing the width and height of the page. Or, there might be some weird flip-phone-like device thing in the future where flipping it out extends the screen. Do not be the developer having a headache over how to deal with the flip-phone-like device thing. Never be satisfied with your webpage until you can open up the dev tools side panel and resize the screen while the webpage looks smooth, fluid, and dynamically resized. The simplest way to do this is to separate all the code that moves content around based on screen size to a single function that is called when the page is loaded and at each resize event thereafter. If there is a lot calculated by this layout function before it determines the new layout of the page, then consider debouncing the event listener such that it is not called as often. Also note that there is a huge difference between the media queries (max-width: 25em) , not all and (min-width: 25em) , and (max-width: 24.99em) : (max-width: 25em) excludes (max-width: 25em) , whereas not all and (min-width: 25em) includes (max-width: 25em) . (max-width: 24.99em) is a poor man's version of not all and (min-width: 25em) : do not use (max-width: 24.99em) because the layout might break on very high font sizes on very high definition devices in the future. Always be very deliberate about choosing the right media query and choosing the right >=, <=, >, or < in any corresponding JavaScript because it is very easy to get these mixed up, resulting in the website looking wonky right at the screen size where the layout changes. Thus, thoroughly test the website at the exact widths/heights where layout changes occur to ensure that the layout changes occur properly.

Making the best of user agent sniffing

After reviewing all of the above better alternatives to user agent sniffing, there are still some potential cases where user agent sniffing is appropriate and justified.

One such case is using user agent sniffing as a fallback when detecting if the device has a touch screen. See the Mobile Device Detection section for more information.

Another such case is for fixing bugs in browsers that do not automatically update. Webkit (on iOS) is a perfect example. Apple forces all of the browsers on IOS to use Webkit internally, thus the user has no way to get a better more updated browser on older devices. Most bugs can be detected, but some bugs take more effort to detect than others. In such cases, it might be beneficial to use user agent sniffing to save on performance. For example, Webkit 6 has a bug whereby when the device orientation changes, the browser might not fire MediaQueryList listeners when it should. To overcome this bug, observe the code below.

Which part of the user agent contains the information you are looking for?

As there is no uniformity of the different part of the user agent string, this is the tricky part.

Browser Name and version

When people say they want "browser detection", often they actually want "rendering engine detection". Do you actually want to detect Firefox, as opposed to SeaMonkey, or Chrome as opposed to Chromium? Or do you actually want to see if the browser is using the Gecko or the WebKit rendering engine? If this is what you need, see further down the page.

Most browsers set the name and version in the format BrowserName/VersionNumber . But as the name is not the only information in a user agent string that is in that format, you can not discover the name of the browser, you can only check if the name you are looking for exists. But note that some browsers are lying: Chrome for example reports both as Chrome and Safari. So to detect Safari you have to check for the Safari string and the absence of the Chrome string, Chromium often reports itself as Chrome too or Seamonkey sometimes reports itself as Firefox.

Also, pay attention not to use a simple regular expression on the BrowserName, user agents also contain strings outside the Keyword/Value syntax. Safari & Chrome contain the string 'like Gecko', for instance.

[1] Safari gives two version numbers: one technical in the Safari/xyz token, and one user-friendly in a Version/xyz token.

Of course, there is absolutely no guarantee that another browser will not hijack some of these things (like Chrome hijacked the Safari string in the past). That's why browser detection using the user agent string is unreliable and should be done only with the check of the version number (hijacking of past versions is less likely).

Rendering engine

As seen earlier, in most cases, looking for the rendering engine is a better way to go. This will help to not exclude lesser known browsers. Browsers sharing a common rendering engine will display a page in the same way: it is often a fair assumption that what will work in one will work in the other.

There are three active major rendering engines: Blink, Gecko, and WebKit. As sniffing the rendering engines names is common, a lot of user agents added other rendering names to trigger detection. It is therefore important to pay attention not to trigger false-positives when detecting the rendering engine.

Rendering engine version

Most rendering engines put the version number in the RenderingEngine/VersionNumber token, with the notable exception of Gecko. Gecko puts the Gecko version number in the comment part of the User Agent after the rv: string. From Gecko 14 for the mobile version and Gecko 17 for the desktop version, it also puts this value in the Gecko/version token (previous version put there the build date, then a fixed date called the GeckoTrail).

The Operating System is given in most User Agent strings (although not web-focused platforms like Firefox OS), but the format varies a lot. It is a fixed string between two semicolons, in the comment part of the User Agent. These strings are specific for each browser. They indicate the OS, but also often its version and information on the relying hardware (32 or 64 bits, Intel/PPC for Mac, or x86/ARM CPU architecture for Windows PCs).

Like in all cases, these strings may change in the future, one should use them only in conjunction with the detection of already released browsers. A technological survey must be in place to adapt the script when new browser versions are coming out.

Mobile, Tablet or Desktop

The most common reason to perform user agent sniffing is to determine which type of device the browser runs on. The goal is to serve different HTML to different device types.

  • Never assume that a browser or a rendering engine only runs on one type of device. Especially don't make different defaults for different browsers or rendering engines.
  • Never use the OS token to define if a browser is on mobile, tablet or desktop. The OS may run on more than one type of device (for example, Android runs on tablets as well as phones).

The following table summarizes the way common browser vendors indicate that their browsers are running on a mobile device:

In summary, we recommend looking for the string Mobi anywhere in the User Agent to detect a mobile device.

Note: If the device is large enough that it's not marked with Mobi , you should serve your desktop site (which, as a best practice, should support touch input anyway, as more desktop machines are appearing with touchscreens).

Detecting Safari with PHP

Is the following enough for detecting Safari? Or is there any other things I should be aware of?

I would say that browser sniffing like this is not a good idea. Check out felgall’s post here , as to why.

What is the reason you need to detect Safari? Couldn’t you rely on feature detection, instead?

Whether it is a good idea or not, I need to check if the user is trying to view the page with Safari because one thing I have on that page doesn’t work on Safari and it is not about a feature. There is no way to make it work, therefore I will show a slightly different page to Safari users.

Just out of interest, what is it that doesn’t work? Is it something that Safari doesn’t support?

With your PHP code, are you hoping to catch desktop and mobile Safari, or just one or the other?

You can see my previous question to see what the issue is. I have made a lot of research after that and came into conclusion that it is a Safari thing that is not curable on my side.

I am hoping to catch desktop Safari because mobile user agent check is done on a previous step.

Oh, ok. That looks like quite a gnarly problem. I think you were in the JavaScript forum with it recently, no? Anyway, the code you posted looks fine to me:

Latest Safari UA:

Latest Chrome UA:

Bearing in mind the above-mentioned caveats, this should work as expected.

BTW, I don’t know if you already found it, but when doing this kind of thing, this site can be quite helpful.

The version of Safari I have uses any of the following useragents in addition to the ones that include Safari in the text:

Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0) Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0) Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0.1) Gecko/20100101 Firefox/4.0.1 Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1 Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; en) Presto/2.8.131 Version/11.11 Opera/9.80 (Windows NT 6.1; U; en) Presto/2.8.131 Version/11.11

or you can select Other… and set it to anything at all.

http://green-beast.com/experiments/php_browser_sniffer.php

Thanks for the link, I bookmarked it. It will definitely help me from now on.

Can you please tell me where you select those in Safari? Do you think changing the useragent is something a regular visitor would do? I am aware of what you are trying to say but this is not used on a publicly available website, and the target users are not technical type of people who would mess with changing useragents of browsers. This is an assumption but as I start to get feedback, I will see ways for improving my script.

Thanks for the link.

It is the second option down in the Develop menu - that menu iis not on by default so it has to be deliberately turned on to get it to work.

It is something that is likely for visitors to do as there are man scripts using browser sensing and only recognising specific browsers - perhaps only Internet Explorer - and so people using other browsers must change their useragent to allow themselves access to sites where the site author has stupidly implemented browser sensing. Usually any problems such a test is intended to fix are long in the past and the code simply hasn’t been updated to reflect that all browsers now will work with their site.

How do you turn it on? I don’t think changing user agents is something non-technical people does.

I get your points, I am also against sensing browser for things that could be cured on the webmaster side but my issue is not one of them and the page I am building is not a publicly available page, besides people who will view it will most probably have no idea what a user agent is.

In that case you should simply be able to dictate what browsers those who have access to the page can use to access it. There are lots of pages on the web that are restricted to specific groups of people that do not work in all the popular browsers (as well as some that try to tell you incorrectly that they don’t work with the browser you are using).

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications

Ultra fast PHP library to detect browser, OS, platform and device type by User-Agent parsing

foroco/php-browser-detection

Folders and files, repository files navigation, php browser detection.

A PHP library to detect browser, OS, platform and device type by User-Agent parsing. This library focused on high performance and low memory usage HTTP client parsing. Uses a simple and fast algorithm to accurately detect more than 200 browsers/apps and over 60 OS. For most commonly browsers parsing process took less than 0.0005 second even on low-level shared hosting. In the case of rare User-Agents recognized time is less than 0.0008 second for the same conditioned hosting environment. The library supports only really actual Browsers and OS without support for outdated environments that are actually not used now. Newest MacOS Monterey, MacOS Ventura and Windows 11 User-Agents detection included. Works by use only one library file and without any third-party libraries dependency.

Requirements

This library requires PHP 5.3 or higher.

Manual installation

  • Simply upload library file BrowserDetection.php (placed in the src directory) to your project;
  • Connect PHP library file by using require_once :

Installation by using Composer

Install this library using Composer:

composer require foroco/php-browser-detection

Update library package by running a command:

composer update foroco/php-browser-detection

The first step requires the Composer autoloader:

The library will try to get environment data from the HTTP_USER_AGENT header sent by the HTTP client. Library PHP Class BrowserDetection contains four public methods which return Array or JSON string of recognized data from HTTP_USER_AGENT :

  • getBrowser();
  • getDevice();

First argument should contain User-Agent string from the HTTP_USER_AGENT header or your custom User-Agent string. Second argument (optional) may contain 'JSON' if you want to get returned result as JSON format.

The library class BrowserDetection also contains special method setTouchSupport() (optional, available from version 1.1). This method is necessary to detect mobile browsers in Desktop Mode condition (Android and iOS). For Desktop Mode detection setTouchSupport() method should call if browser supports Touch events. Touch events detection is performed by client-side JavaScript code in the target browser. Example:

Description for returned variables

OS Type ( os_type ) Returns type of operating system (OS). All possible values:

OS Family ( os_family ) Returns operating system (OS) family or unknown in cases of unable OS family recognition. Example: windows , linux , unix etc.

OS Name ( os_name ) Returns operating system (OS) name or unknown in cases of unable OS name recognition. Example: Windows , Android , macOS , iOS etc.

OS Version ( os_version ) Returns operating system (OS) version or 0 in cases of unable OS version recognition. May contains numeric, string or mixed types OS versions. In case of numeric OS version (e.g. Android ) contains major and minor version parts values, e.g. 4.4 , 8.1 , 10 etc. In case of string OS version (e.g. macOS ) contains string version name values, e.g. Mavericks , Mojave , Catalina etc. For Windows may contains mixed version types values: 10 , Vista , XP etc.

OS Title ( os_title ) Returns operating system (OS) title which contains OS name and OS version together. Also returns unknown if OS name is not recognized.

Device Type ( device_type ) Returns device type based on some User-Agent data. All possible values:

  • mediaplayer

Browser Name ( browser_name ) Returns browser name or unknown in cases of unable browser name recognition. Example: Chrome , Firefox , UC Browser , Huawei Browser , Vivaldi etc.

Browser Version ( browser_version ) Returns browser version number or 0 in cases of unable browser version recognition. Always contains numeric values (integer or float numbers). Returns float number (e.g. 3.5 , 10.5 , 13.1 ) for some browsers which should contains both major and minor browser version parts ( Safari , Vivaldi , PaleMoon etc). Returns only major decimal browser version (e.g. 15 , 37 , 81 ) for other browsers which has a lot of major versions ( Chrome , Firefox , Opera etc).

Browser Title ( browser_title ) Returns browser title which contains browser name and browser version together. Also returns unknown if browser name is not recognized.

Browser Chrome Original ( browser_chrome_original ) Returns 1 number if browser recognized as original Google Chrome browser or returns 0 if it's not.

Browser Firefox Original ( browser_firefox_original ) Returns 1 number if browser recognized as original Mozilla Firefox browser or returns 0 if it's not.

Browser Safari Original ( browser_safari_original ) Returns 1 number if browser recognized as original Apple Safari browser or returns 0 if it's not.

Browser Chromium Version ( browser_chromium_version ) Returns Chromium major engine version number if browser based on Chromium engine or returns 0 if it's not.

Browser Gecko Version ( browser_gecko_version ) Returns Gecko major engine version number if browser based on Gecko engine or returns 0 if it's not.

Browser WebKit Version ( browser_webkit_version ) Returns WebKit version engine number if browser based on WebKit engine or returns 0 if it's not. Always float number value.

Browser Android Webview ( browser_android_webview ) Returns 1 number if Android Webview mode detected or returns 0 if it's not.

Browser iOS Webview ( browser_ios_webview ) Returns 1 number if iOS Webview mode detected or returns 0 if it's not.

Browser Desktop Mode ( browser_desktop_mode ) Returns 1 number if mobile browser works in Desktop Mode or returns 0 if it's not detected. setTouchSupport() method should call for Desktop Mode detection if browser supports Touch events.

64 Bits Mode ( 64bits_mode ) Returns 1 number if operating system (OS) and browser work together in 64-bit mode or returns 0 if 64-bit mode not detected. Available only for getAll(); and getOS(); methods.

Usage Examples

See follow examples to understand library usage use cases.

To detect all possible environment data use:

OS Detection

To parse only OS data use:

Browser Detection

To parse only browser data use:

Device Detection

To parse only device type data use:

Desktop Mode Detection

To detect if mobile browser works in Desktop Mode use:

Detect All (JSON)

To pasre all possible environment data and returns JSON format string:

Benchmarking Test

Benchmarking was performed on a low-level shared hosting. Test server configuration: RedHat Linux + LiteSpeed + PHP Extension. Test conditions based on collection of random ~446000 non repeated real life User-Agent strings.

User-Agent recognition performance in PHP 7.3 (requests per second):

The MIT License (MIT)

Copyright (c) 2020-2023 Artem Murugov

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

  • PHP General

How to detect safari (iphone) browser in php?

muriel.schmidt

Facebook

 @ muriel.schmidt 

You can detect the Safari browser on an iPhone using the user agent string in PHP.

Here is an example code snippet to detect Safari on an iPhone:

This code checks if the user agent contains the strings "Safari" and "iPhone". If both are found, it means that the request is coming from the Safari browser on an iPhone.

Related Threads:

get_browser

Detect the browser in PHP

php if safari browser

In this tutorial, we are going to see how to detect the browser of a user using PHP programming language. Here we are going to create our own custom PHP function which we can call later to get the browser.

We will use the $_SERVER global variable. The $_SERVER[‘HTTP_USER_AGENT’] can returns various information related to the browser.

Now below is our PHP function that we can use to display the browser:

In the above code, we are checking each possible browser that may be and return the browser name. Here we haven’t checked the Mozilla because of most of the browser using this as the user agent string.

Below is how to display the browser name on our web page:

We will able to see the browser.

Note that, this will always not going to give us the right information. Server-side browser detection may wrong. So, client-side browser detection is better than server-side detection. We can use JavaScript to detect browser from the client side.

3 responses to “Detect the browser in PHP”

It can not detect chrome in iphone. It says safari.

From what I understand, Chrome on iOS is simply a wrapper on Safari. Due to their corporate “fiscal growth or death” requirement, Apple does not easily relinquish control of consumers and the gathering of consumer data to third parties.

thanks too This is very usefull to me tommorrow i has exam so i searched this question AND REMORE THANKS

Leave a Reply Cancel reply

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

Please enable JavaScript to submit this form.

Related Posts

  • Check if the page called from HTTP or HTTPS in PHP
  • Get visitors country and city in PHP using ipstack API
  • How to get the complete URL query string in PHP?

Please enable JavaScript in your browser to enjoy a better experience.

How to Detect a Visitor’s Browser in WordPress

There are times when you may need to deliver specific content or adjustments based on the web browser your site visitors are using. Various methods can help you achieve this. For instance, you can use the JavaScript BrowserDetect.browser function or comment tags targeting Internet Explorer .

Modernizr is another useful tool for browser feature detection. Although CSS3 media queries aren’t designed to identify browser types, they can be helpful for optimizing website presentation on mobile devices.

60+ Most Wanted WordPress Tricks and Hacks (Updated)

Have you ever came across a WordPress blog, saw something you liked, and thought; how they did that,... Read more

Using PHP for Browser Detection

While the above methods modify the front-end, the actual HTML markup remains the same. For example, if you have two <div> elements—one for Internet Explorer and another for other browsers—both will exist in the HTML document, regardless of the browser used.

In cases where front-end methods aren’t sufficient, server-side languages like PHP offer a more robust solution. For WordPress users, the PHP Browser Detection plugin makes this task easier.

Conditional Functions in PHP

Upon activation, this plugin doesn’t show anything in the WordPress Dashboard. Instead, it offers conditional functions that you can use in your theme files like page.php or index.php. These functions can detect various desktop and mobile devices, including iPads and iPhones.

Basic Implementation

For example, if you want to display a notification only to Chrome users, you can add the following code in your header.php file, within the <body> tag:

In contrast, users of other browsers like Firefox, Opera and Safari will not see this notification.

Similarly, you can target mobile devices to optimize your WordPress site’s performance. For instance, you can serve lower-resolution images on mobile devices and higher-resolution images on desktop browsers by adding the following function to your index.php file:

For more details and examples, visit the WordPress.org plugin page .

PHP Tutorial

Php advanced, mysql database, php examples, php reference, php if statements.

Conditional statements are used to perform different actions based on different conditions.

PHP Conditional Statements

Very often when you write code, you want to perform different actions for different conditions. You can use conditional statements in your code to do this.

In PHP we have the following conditional statements:

  • if statement - executes some code if one condition is true
  • if...else statement - executes some code if a condition is true and another code if that condition is false
  • if...elseif...else statement - executes different codes for more than two conditions
  • switch statement - selects one of many blocks of code to be executed

PHP - The if Statement

The if statement executes some code if one condition is true.

Output "Have a good day!" if 5 is larger than 3:

We can also use variables in the if statement:

Output "Have a good day!" if $t is less than 20:

PHP Exercises

Test yourself with exercises.

Output "Hello World" if $a is greater than $b .

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

PHPGurukul

Don't be Afraid of Source Code

How to get Browser Information In PHP

by Anuj Kumar

  • Intenet Explorer
  • Google Chrome
  • Safari etc…

Tags: browser information in php how to php

' src=

Hi! I am Anuj Kumar, a professional web developer with 5+ years of experience in this sector. I found PHPGurukul in September 2015. My keen interest in technology and sharing knowledge with others became the main reason for starting PHPGurukul. My basic aim is to offer all web development tutorials like PHP, PDO, jQuery, PHP oops, MySQL, etc. Apart from the tutorials, we also offer you PHP Projects, and we have around 100+ PHP Projects for you.

  • Next story  How to install wordpress on your local Computer
  • Previous story  PHPGurukul turns 1 Year old

Recommended Tutorials for you

You may also like....

php if safari browser

Automatic Logout after 10 minutes of inactive Session in PHP

How to upload and validate an image in php

How to upload and validate a image in php

How to fetch data in excel or generate excel file in PHP

How to fetch data in excel or generate excel file in PHP

Latest tutorials.

SQL Aliases

SQL BETWEEN Operator

SQL IN Operator

SQL LIKE Operator

Student Record System Using Python Django and MySQL

Online Cloth Rental System using PHP and MySQL

SQL AVG() Function

Apartment Visitors System Using Python Django and MySQL

Emergency Ambulance Hiring Portal using PHP and MySQL

Doctor Appointments System Using Python Django and MySQL

Tutorials Categories

  • .htaccess (5)
  • Android (19)
  • ASP.net Projects (1)
  • Codeigniter (19)
  • Differences (7)
  • General (6)
  • Javascript (11)
  • jQuery – Ajax Tutorials (5)
  • Laravel (1)
  • MySQL Snippet (3)
  • PHP Interview Questions and Answers (9)
  • PHP OOPs Concepts (22)
  • PHP Programs (6)
  • PHP Projects (152)
  • PHP Snippet (15)
  • Python Projects (8)
  • Python Tutorials (13)
  • Web Development (39)
  • Websevices (3)
  • Wordpress (18)

SQL Tutorials

  • SQL Select Distinct
  • SQL Order by
  • SQL AND Operator
  • SQL OR Operator
  • SQL OR vs AND
  • SQL NOT Operator
  • SQL INSERT INTO
  • SQL NULL Values
  • SQL Select TOP
  • SQL MIN() and MAX()
  • SQL Count()
  • SQL BETWEEN
  • SQL Aliases

Welcome to PHPGurukul .

How can I help you?

🟢 Online | Privacy policy

  • DSA with JS - Self Paced
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Operator
  • JS Projects
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter

How to detect the user browser ( Safari, Chrome, IE, Firefox and Opera ) using JavaScript ?

  • How to detect the browser language preference using JavaScript ?
  • How to detect browser or tab closing in JavaScript ?
  • How to detect the device is an Android device using JavaScript ?
  • How to detect the Internet connection is offline or not using JavaScript?
  • How to check the current runtime environment is a browser in JavaScript ?
  • How to detect the version of a browser ?
  • Detect the Operating System of User using JavaScript
  • How to check the user is using Internet Explorer in JavaScript?
  • How to detect operating system on the client machine using JavaScript ?
  • How to detect the user's device using jQuery ?
  • How to create a PHP detection browser script ?
  • Detect a device is iOS or not using JavaScript
  • How to detect touch screen device using JavaScript?
  • How to detect flash is installed or not using JavaScript ?
  • How to return true if browser tab page is focused in JavaScript ?
  • How to detect whether the website is being opened in a mobile device or a desktop in JavaScript ?
  • How to uniquely identify computers visiting web site in JavaScript?
  • JavaScript Detecting a mobile browser
  • How to detect HTTP or HTTPS then force redirect to HTTPS in JavaScript ?
  • How to calculate the number of days between two dates in JavaScript ?
  • Convert a String to an Integer in JavaScript
  • How to append HTML code to a div using JavaScript ?
  • How to Open URL in New Tab using JavaScript ?
  • Difference between var and let in JavaScript
  • How do you run JavaScript script through the Terminal?
  • Remove elements from a JavaScript Array
  • How to read a local text file using JavaScript?
  • JavaScript console.log() Method
  • JavaScript Number toString() Method

The browser on which the current page is opening can be checked using JavaScript.

The userAgent property of the navigator object is used to return the user-agent header string sent by the browser. This user-agent string contains information about the browser by including certain keywords that may be tested for their presence.

The presence of a specific user-string can be detected using the indexOf() method. The indexOf() method is used to return the first occurrence of the specified string value in a string. If the value does not come up in the string, “-1” is returned.

The user-agent string of the browser is accessed using the navigator.userAgent property and then stored in a variable. The presence of the strings of a browser in this user-agent string is detected one by one.

As the indexOf() method would return a value that is greater than “-1” to denote a successful search, the “greater-than” operator is used to return a boolean value on whether the search was successful or not. This is done for all the following tests.

One additional check is required in the case of the Safari browser as the user-agent of the Chrome browser also includes the Safari browser’s user-agent. If both the user-agents of Chrome and Safari are in the user-agent, it means that the browser is Chrome, and hence the Safari browser value is discarded.

One additional check is also required in the case of this browser as the user-agent of the Opera browser also includes the Chrome browser’s user-agent. If both the user-agents of Chrome and Opera are in the user-agent, it means that the browser is Opera, and hence the Chrome browser value is discarded.

chrome-output

Please Login to comment...

Similar reads.

author

  • JavaScript-Questions
  • Web Technologies

advertisewithusBannerImg

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

  • a. Send us an email
  • b. Anonymous form
  • Buyer's Guide
  • Upcoming Products
  • Tips / Contact Us
  • Podcast Instagram Facebook Twitter Mastodon YouTube Notifications RSS Newsletter

Apple Releases Safari Technology Preview 193 With Bug Fixes and Performance Improvements

Apple today released a new update for Safari Technology Preview , the experimental browser Apple first introduced in March 2016. Apple designed the ‌Safari Technology Preview‌ to test features that may be introduced into future release versions of Safari.

Safari Technology Preview Feature

The current ‌Safari Technology Preview‌ release is compatible with machines running macOS Ventura and macOS Sonoma , the latest version of macOS that Apple released in September 2023.

The ‌Safari Technology Preview‌ update is available through the Software Update mechanism in System Preferences or System Settings to anyone who has downloaded the browser . Full release notes for the update are available on the Safari Technology Preview website .

Apple's aim with ‌Safari Technology Preview‌ is to gather feedback from developers and users on its browser development process. ‌Safari Technology Preview‌ can run side-by-side with the existing Safari browser and while designed for developers, it does not require a developer account to download.

Get weekly top MacRumors stories in your inbox.

Top Rated Comments

benface Avatar

I'm always curious about these Safari Tech Preview posts. Are they just a quick way to add another headline? I suspect so, as I don't see many people trusting these builds as their daily driver. I've tried that in the past, but it never stuck.

macmac30 Avatar

Popular Stories

iOS 18 Siri Integrated Feature

iOS 18 Rumored to Add These 10 New Features to Your iPhone

apple id account

Apple ID Accounts Logging Out Users and Requiring Password Reset

macos sonoma feature purple green

Apple's Regular Mac Base RAM Boosts Ended When Tim Cook Took Over

maxresdefault

The MacRumors Show: Apple's iPad Event Finally Announced!

ipad pro 2022

Apple Event Rumors: iPad Pro With M4 Chip and New Apple Pencil With Haptic Feedback

maxresdefault

Apple Announces 'Let Loose' Event on May 7 Amid Rumors of New iPads

Next article.

Whatsapp Feature

Our comprehensive guide highlighting every major new addition in iOS 17, plus how-tos that walk you through using the new features.

ios 17 4 sidebar square

App Store changes for the EU, new emoji, Podcasts transcripts, and more.

iphone 15 series

Get the most out your iPhone 15 with our complete guide to all the new features.

sonoma icon upcoming square

A deep dive into new features in macOS Sonoma, big and small.

ipad pro 2022 blue square

Revamped models with OLED displays, M3 chip, and redesigned Magic Keyboard accessory.

ipad air 12 9 square

Updated 10.9-inch model and new 12.9-inch model, M2 chip expected.

wwdc 2024 upcoming square

Apple's annual Worldwide Developers Conference will kick off with a keynote on June 10.

ios 18 upcoming square

Expected to see new AI-focused features and more. Preview coming at WWDC in June with public release in September.

Other Stories

Apple Event Let Loose Pastel Blellow

2 days ago by Tim Hardwick

iPad Air 12

3 days ago by Joe Rossignol

General Apps Reddit Feature

3 days ago by MacRumors Staff

iOS 18 Siri Integrated Feature

4 days ago by Joe Rossignol

ipads yellow sale imag

5 days ago by Tim Hardwick

Your Guide to Private Browsing in Safari

Private browsing is often misunderstood, but it can be a helpful feature if you know what’s what.

Quick Links

What private browsing does in safari, how to use safari private browsing on iphone and ipad, how to use safari private browsing on a mac, how to disable safari private browsing on iphone and ipad, how to disable safari private browsing on a mac, key takeaways.

  • Private Browsing in Safari hides browsing history, autofill details, downloads, and locks tabs after inactivity.
  • Safari on Mac groups private and non-private tabs, while on iPhone it shows all tabs regardless of mode.
  • To use Private Browsing in Safari, identify it by a dark address bar, "Private" indicator, or "Private" next to the site URL.

Most browsers offer a private browsing mode that aims to keep the websites you view off the record. But what exactly does it do in Safari and how do you get the best out of it?

First and foremost, Private Browsing keeps the website pages you visit out of your History . The aim is to prevent someone else from seeing which pages you have visited if they have access to your phone or computer.

In Safari, Private Browsing does a lot more than just hide URLs. It also:

  • Prevents recent searches from showing up in your history.
  • Stops remembering details you enter in forms for autofill.
  • Keeps downloaded items from appearing in your Downloads list.
  • Locks private tabs after a period of inactivity.
  • Adds tracking and fingerprinting protection.

However, it’s important to note that Private Browsing does not stop you from being tracked altogether. Websites you visit will still be able to use various methods to track you, and will still have access to all data that you send them.

On macOS, iOS, and iPadOS, Safari groups private tabs together, and separates them from non-private tabs. On Mac, each Safari window is either private or non-private, and can have as many tabs as you want.

On iPhone, you can switch between private and non-private modes, each of which shows all tabs belonging to that mode.

You can spot when you’re viewing a private tab with these signs:

  • The address bar has a dark background. This may be less noticeable if you’re using Dark Mode .
  • On Mac, you’ll see a prominent Private indicator in the title bar.
  • On iPhone, you’ll see Private alongside the site URL at the bottom of your screen.

The steps to enter Private Browsing mode are nearly identical on an iPhone and iPad. The only difference is that the tab icon is at the bottom of the screen on iOS and the top on iPadOS.

  • Long-press the tab icon (two overlapping pages) on the bottom-right (iPhone) or top-right (iPad) of your screen.
  • Tap the New Private Tab menu item.
  • If locked, enter your passcode to unlock Private Browsing.

You can enter Private Browsing mode on macOS using either a menu item or a keyboard shortcut:

  • Open the File menu and choose New Private Window .
  • Alternatively, use the keyboard shortcut Shift + Cmd + n .
  • Use the browser as you normally would. Any tabs you open from this window will open in the same window, in private mode.

You may want to prevent users of an iPhone or iPad from using Private Browsing mode at all. To do so:

  • Open the Settings app.
  • Tap on Screen Time .
  • Under RESTRICTIONS , click on Content & Privacy Restrictions .
  • If not already enabled, press the toggle next to Content & Privacy Restrictions to enable.
  • Tap Content Restrictions .
  • Change the Web Content setting to Limit Adult Websites .

The option to enter private mode will now be gone.

On macOS, the wording of certain options differs slightly, but the overall process is near-identical to iOS:

  • Open System Settings via the Apple menu.
  • Click on Screen Time in the left panel.
  • Under the Restrictions section, click on Content & Privacy .
  • Click Content Restrictions .
  • Change the Access to Web Content setting to Limit Adult Websites .

Private Browsing will now be unavailable in Safari, although any existing private windows will stay open.

Of course, anyone can re-enable Private Browsing using the same process, in reverse. However, you can use Screen Time’s Lock Screen Time Settings option to set a passcode and enforce the setting permanently.

IMAGES

  1. Easy Ways to Run a PHP File in a Browser: 11 Steps (with Pictures

    php if safari browser

  2. php tutorial

    php if safari browser

  3. if else Statement in PHP

    php if safari browser

  4. How to Use the Safari Web Browser on iOS Devices

    php if safari browser

  5. Safari 11: How to Customize the Way Websites Are Displayed

    php if safari browser

  6. How to Change the Default Search Engine in Safari Browser

    php if safari browser

VIDEO

  1. How to add safari browser to Home Screen

  2. iOS SAFARI BROWSER FOR ANY ANDROID ❗ #ios #ytshorts #safari

  3. Safari Shortcuts in Mac

  4. Using LISTEN TO PAGE

  5. SAFARI BROWSER IS DONE FOR! 👀🫣

  6. 3 Ways To Turn On Private Browsing Mode On Safari

COMMENTS

  1. Php : Finding Chrome and Safari Browsers

    But my chrome browser returning below useragent suddenly. Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25..1364.155 Safari/537.22 It contains the word safari and chrome.so both the browser names are printed.what is the solution for this.thanks.

  2. PHP/HTML/CSS

    With CSS there is no way you can achieve browser detection. However with PHP, ASP and other programming languages you can get browser detection within the page. I am not here to tell you the pro or cons about it - I take it you know about the bad and good about browser detection and web standards but here is the list. ... // Safari CSS and ...

  3. PHP: get_browser

    get_browser is a PHP function that returns information about the user's browser, such as its name, version, platform, and capabilities. It can be useful for customizing web pages or detecting browser compatibility issues. To use this function, you need to have the browscap.ini file in your system.

  4. How to Detect Browser with PHP

    Once you try printing $_SERVER['HTTP_USER_AGENT'], you will receive the information about the browser. But note that, depending on the browser, the output can be different. To overcome such kind of issues, a specific code should be written. So, for detecting the browser with PHP, you can use the getBrowser() function in the following way:

  5. Browser detection using the user agent

    It is a fixed string between two semicolons, in the comment part of the User Agent. These strings are specific for each browser. They indicate the OS, but also often its version and information on the relying hardware (32 or 64 bits, Intel/PPC for Mac, or x86/ARM CPU architecture for Windows PCs).

  6. reliable user browser detection with php

    reliable user browser detection with php. There are several ways to detect a user's browser using PHP. One common method is to use the $_SERVER ['HTTP_USER_AGENT'] variable, which contains information about the user's browser, such as its name and version. You can use regular expressions to match this string against known patterns for different ...

  7. Detecting Safari with PHP

    The version of Safari I have uses any of the following useragents in addition to the ones that include Safari in the text: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0;

  8. PHP Browser Detection

    The library will try to get environment data from the HTTP_USER_AGENT header sent by the HTTP client. Library PHP Class BrowserDetection contains four public methods which return Array or JSON string of recognized data from HTTP_USER_AGENT:. getAll(); getOS(); getBrowser(); getDevice(); First argument should contain User-Agent string from the HTTP_USER_AGENT header or your custom User-Agent ...

  9. How to detect safari (iphone) browser in php?

    This code checks if the user agent contains the strings "Safari" and "iPhone". If both are found, it means that the request is coming from the Safari browser on an iPhone. 0 | 0

  10. PHP function

    Supported Versions: PHP 4, PHP 5, PHP 7, PHP 8. Tells what the user's browser is capable of. get_browser ...

  11. Detecting browsers of iPhone, iPod, iPad, Android and ...

    To begin with, we need to understand that in the HTTP protocol, browser send its identity called user agent to the server to request the wanted webpage. Every browser has its only unique user agent…

  12. How to create a PHP detection browser script

    The output is shown as the result you can get from the function when you run the script. Output: get_browser (): The get_browser () function in PHP is an inbuilt function that is used to tell the user about the browser's capabilities. This function looks up the user's browscap.ini file and returns the capabilities of the user's browser.

  13. functions

    The audio player won't seek and the end time shows NaN:NaN. From Googling the issue, it seems this has been a problem since 2010 with Safari and serving audio through PHP. I figured if I could detect the Safari desktop browser I can include it in my "ismobile" shortcode so the real audio link gets sent to Safari desktop users. Make sense?

  14. Detect the browser in PHP

    In the above code, we are checking each possible browser that may be and return the browser name. Here we haven't checked the Mozilla because of most of the browser using this as the user agent string. Below is how to display the browser name on our web page: echo get_the_browser(); We will able to see the browser.

  15. How to Detect a Visitor's Browser in WordPress

    In cases where front-end methods aren't sufficient, server-side languages like PHP offer a more robust solution. For WordPress users, the PHP Browser Detection plugin makes this task easier. Conditional Functions in PHP. Upon activation, this plugin doesn't show anything in the WordPress Dashboard.

  16. PHP if Statements

    PHP Conditional Statements. Very often when you write code, you want to perform different actions for different conditions. You can use conditional statements in your code to do this. In PHP we have the following conditional statements: if statement - executes some code if one condition is true

  17. How to get Browser Information In PHP

    A browser is application software which displays content from the World Wide Web, which includes images, video etc. Today there are many browsers available in the market. Some browsers are as follows: Intenet Explorer; Firebox; Google Chrome; Safari etc… To Find Browser Name in PHP If you want to know a browser name through PHP then you can ...

  18. How to Fix 'Your browser is a bit unusual' Error Message on ...

    6. Try a Different Web Browser. If you've followed all the above steps but are still experiencing the same issue, consider trying GoDaddy on a different browser. This will help you determine if the problem is with your browser. There are many alternatives to use for GoDaddy. Please refer to this article to select the best one.

  19. How to detect the user browser ( Safari, Chrome, IE ...

    Detecting the Chrome browser: The user-agent of the Chrome browser is "Chrome". This value is passed to indexOf() method to detect this value in the user-agent string. As the indexOf() method would return a value that is greater than "-1" to denote a successful search, the "greater-than" operator is used to return a boolean value on whether the search was successful or not

  20. php if statments to get the browser

    Im trying to call a script if the browser is firefox and its working. But now i want to do the same if the browser is Safari and im not being able to figure it out im missing the way that php works in if statments , im new to php.

  21. Apple Releases Safari Technology Preview 193 With Bug Fixes and

    Apple today released a new update for Safari Technology Preview, the experimental browser Apple first introduced in March 2016. Apple designed the ‌Safari Technology Preview‌ to test features ...

  22. Your Guide to Private Browsing in Safari

    Private Browsing in Safari hides browsing history, autofill details, downloads, and locks tabs after inactivity. Safari on Mac groups private and non-private tabs, while on iPhone it shows all tabs regardless of mode. To use Private Browsing in Safari, identify it by a dark address bar, "Private" indicator, or "Private" next to the site URL.

  23. php

    The old way to identify iPhone in JavaScript: IS_IPHONE = navigator.userAgent.match(/iPhone/i) != null) || (navigator.userAgent.match(/iPod/i) != null); If you were to go with this approach for detecting iPhone, you would end up with IS_IPHONE being true if a user comes from Facebook on an iPad.