PHP Limit users browser type - php

I need to limit what browsers can user use to view on my page. I want to allow only Chrome, FireFox 4+ and all WebKit based browsers. If user use i.e. explorer, PHP will produce output i.e.: "You have not supported browser, use Chrome, Firefox 4+ or WebKit based browser!"
How can I do it?

PHP sniffer is a library that handles extracting information about the user and user-agent (browser).
It uses the same data that get_browser() or $_SEREVER['HTTP_USER_AGENT'] can give you but it formats it into a nicely structured object that you can use in your code.

Use $_SERVER\['HTTP_USER_AGENT'\] or get_browser().
But you should really ask yourself why this is necessary. If your site doesn't work with all feature, than it's ok to show a message saying:
Please upgrade your browser in order to use all features.
You can also detect whether specific JS functions/objects exists so you won't run into Undefined identifier errors (credits to epascarello).

$_SERVER['HTTP_USER_AGENT'] will give you browser details, and from that you can work your way up to verification good luck
This may be so lame, since I am PHP newbie but, I would check if someone is using Mozilla (firefox)
by doing this:
$browser = $_SERVER['HTTP_USER_AGENT'];
if (strpos($browser,'Mozilla') !== false) {
echo 'You are using Mozilla';
} else {
echo 'You are not using Mozilla';
}

You can check server variable:
<?php
echo $_SERVER['HTTP_USER_AGENT'];
?>

Related

Browser Detection with Javascript

Reasoning for this Question
I am aware that browser detection can never be 100% reliable as the User Agent header can always be forged, however, I am not bothered by this.
Although there are many questions on this topic, they all seem to be quite old, so to get an up to date answer I felt I should ask this question again.
I am currently detecting the browser name and version server side using the PHP browscap, and then returning the name and version into javascript variables (not a very good method). The reason why I need to do this is simply to display a message to visitors if they are not using a supported browser.
Current method (something similar):
<script type="text/javascript">
var browser = new Array();
browser['browser'] = '<?php echo $browser_name; ?>';
browser['version'] = '<?php echo $browser_version; ?>';
browser['error'] = '<?php echo $browser_error; ?>';
</script>
It would be much better to do this client side as the browscap can be quite slow, and it would prevent me having to pass values into javascript variables from PHP. If you think using PHP is a better method then please state in your answer, this is just my opinion.
Question
Therefore, my question quite simply, is the following link a reliable method for determining the browser name and version?
Javascript Detect
I am aware that new browsers will need to be added to this, this does not bother me. I am more concerned about whether the algorithm used is reliable.
Thanks in advance
UPDATE 1
To see what I mean, take a look at https://www.icloud.com/ in Internet Explorer 7 or less. You will receive a message saying that the browser is not supported. This is easy to do for IE as you can simply use the <!--[if gt IE..., however, I need to test all browsers.
This does not look right, you can fetch browser information from Javascript. No need to mix JS and PHP code to do that.
You can do something like this to fetch, and detect user browser with just JavaScript:
var userAgent = navigator.userAgent.toLowerCase();
var old = false;
// Internet Explorer 7
if (userAgent.indexOf('msie 7.0b') !== -1) { old = true; }
else if (userAgent.indexOf('msie 7.0') !== -1) { old = true; }
// Internet Explorer 6
else if (userAgent.indexOf('msie 6.1') !== -1) { old = true; }
else if (userAgent.indexOf('msie 6.01') !== -1) { old = true; }
else if (userAgent.indexOf('msie 6.0b') !== -1) { old = true; }
else if (userAgent.indexOf('msie 6.0') !== -1) { old = true; }
...
// Detect any other browser versions you consider old
if(old = true) {
// Show notification and alert users that they are using old browser
}
This is how you can do it using JS, but you can also use HTML to achieve this:
<!--[if lte IE 6]>
// include your .css style or do whatever you want to alert users their browser is old
<![endif]-->
Short answer to your question is YES, its wrong to detect user browser the way you do it, since you can do it with plain JavaScript, or even with HTML. No need to mix PHP and JS code here, and at the end, both PHP and JS will get the same UserAgent info.
Explanation
After extensive research and discussing amongst other developers, it is clear that there is no reliable method for retrieving the browser name and version from the User Agent. This is down to several reasons:
The format of a browsers User Agent can change at any time if the developers of the browser so wish to do so. This could immediately prevent some scripts from working correctly.
Users can forge their User Agents to mimic other browsers, and therefore would appear to be using a browser they are not.
Possible Solutions
Whilst I hugely discourage the use of these scripts as they could stop working at the release of an update to any browser anytime, if you do wish to detect the browser name and version in Javascript then I would advise using this script:
Javascript Detect
However, the most reliable method for retrieving the details of the browser is without a doubt the browscap supplied by Gary Keith. The browscap project offers extensive information about each browser and OS gathered from the User Agent. It is very easy to implement and even easier to use. To read more, take a look at:
Gary Keith - Browscap
If you choose to use the browscap by Gary Keith, you will need to ensure it is updated weekly at the very least.
Answer
Whilst I am contradicting myself with this answer, it is clear that detecting the browser information with any sort of script is not advised. The only reliable method of browser detection is that of the Internet Explorer HTML conditions, and as stated, these only cover Internet Explorer.
Try to avoid browser specific functions and notices, and make use of the built in features such as:
media="only screen and (device-width: 768px)"
and
<!--[if IE 8]>I am IE 8<![endif]-->
This question needs an updated answer. I think the best option these days for client-side detection is WURFL.
Its an updated library of devices based on Useragents - think Browscap for the client side.
Load the JS and it returns JSON based on the device that requested the js. Perfect!
<script type="text/javascript" src="//wurfl.io/wurfl.js"></script>
Because it does the parsing on the WURFL server side, you need to load the js remotely and not save it in your dir tree.
A super easy
WURFL.is_mobile
is all it takes to determine mobile for example.
Good luck.
You could try having a look at navigator.appName and navigator.userAgent.
The yepnopejs IE detection (!ie prefixes) works by utilizing the MS conditional comments.
A short snippet for detecting versions of IE prior to IE10 in JavaScript without resorting to user-agent sniffing.
while (
div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->'
);
// …
https://github.com/SlexAxton/yepnope.js/blob/master/prefixes/yepnope.ie-prefix.js
yepnope usage example:
yepnope({
load: ['normal.js', 'ie6!ie7!ie-patch.js'] // patch for ie6 or ie7 only
});
You can use a perfect plugin for this information written in jQuery (like javascript)
look at this link:
https://github.com/jquery/plugins.jquery.com
Be sure to do feature detection instead of browser detection when you want to determine if a certain feature is available in a browser, apply bugfixes, etc.

How to see what browser (and version) a user is using?

Due to the CSS3 and HTML5, I would like to check what browser (and version) the visitor is using. What is the best way of doing that? I know that most ways screw up certain checks, for example phones or tablets, as well as some uncommon browsers, but there ought to be a way to get that information properly?
I recommend you take a look at Modernizr. It's a js library that does what you need
No need to have JS libraries or other included files!
$browser = get_browser(null, true);
echo $browser['browser'];
This will return something like "Firefox," "Opera," "Safari," etc.
You can use PHP for this
<?php
echo $_SERVER['HTTP_USER_AGENT'] . "\n\n";
?>
$browser = $_SERVER['HTTP_USER_AGENT'];
OR you can use google analytic to view live data of your visitor

How to get, in php, the entire html of a page loaded in part from jquery

i've this problem for days...
I have to load from php the entire html of a page.
On this page there is a jquery function that is called when all the page is loaded. This function loads other html into page, so i have to get all the html loaded ( the part loaded with jquery too). I can know that i get all the page trying to find some tag loaded only from jquery. ( for example: tag input with name XXX, tag input with attribute multiple, etc. )
so i try:
$html = file_get_contents("http://wwww.siteToScrape.com");
if (strpos($html, 'multiple') !== false) {
echo 'found';
} else {
echo 'not found';
}
but result is 'not found'.
Then i downloaded simple html dom and i try:
include 'simple_html_dom.php';
$html = file_get_html("http://wwww.siteToScrape.com");
if (strpos($html, 'multiple') !== false) {
echo 'found';
} else {
echo 'not found';
}
but result still remain 'not found'.
so i think to get some php script what emulate browser ( so can load jquery too ) and i downloaded PHP Scriptable Web Browser and i try:
require_once('browser.php');
$browser = new SimpleBrowser();
$p = $browser->get('http://wwww.siteToScrape.com');
if (strpos($p, 'multiple') !== false) {
echo 'found';
} else {
echo 'not found';
}
but result is still again 'not found'.
I don't know how to do it.. can someone help me??? thanks!!!!
The problem is that you are trying to mix server and client.
PHP runs on the server
Javascript (and therefor also jQuery) runs in the client browser.
There's no easy way to run the javascript using PHP. As far as I know, it's not even possible. Other languages, such as Java might be able to do what you are trying to do.
You should look at another way to do this.
This is also the reason why webcrawlers never gets affected by stuff you do using javascript. This is a nice thing to keep in mind when developing. Your dynamic loading will not be indexed by these crawlers at all.
As far as I know, this is not possible "with only PHP". Javascript runs on the client instead of the server and therefore it would not be possible without some sort of a browser emulator environment.
Edit: You could put javascript in the web page itself which would fetch the innerHTML of the whole web page after it was fully generated and then use an ajax call to send that to your server. You would have to stay within the limitations of the same-origin-policy (which doesn't allow you to make ajax calls to domains other than where the host web page came from).
Like the others have said, jquery is javascript, and is typically executed by the client (web browser) rather than the server.
PHP, being a server-side language, has no javascript interpreter.
The easiest way that I know of to run javascript using PHP is via web-testing tools, which often integrate a headless browser. You could check out mink, which has a back-end for the zombie node.js headless browser.
There's also the phantomjs headless browser with various PHP interfaces like this one, which I found with a quick google search.
In the more resource-intensive arena, there's also selenium, which has PHP interfaces as well.

how to check if the request came from mobile or computer in php

i need to check if the request came from a mobile phone device or desktop computer using php please help. thanks
I am using a function to identify mobile browsers in my projects, which can detect almost all major Mobile Operating systems and browsers.
function ismobile() {
$is_mobile = '0';
if(preg_match('/(android|up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone)/i', strtolower($_SERVER['HTTP_USER_AGENT']))) {
$is_mobile=1;
}
if((strpos(strtolower($_SERVER['HTTP_ACCEPT']),'application/vnd.wap.xhtml+xml')>0) or ((isset($_SERVER['HTTP_X_WAP_PROFILE']) or isset($_SERVER['HTTP_PROFILE'])))) {
$is_mobile=1;
}
$mobile_ua = strtolower(substr($_SERVER['HTTP_USER_AGENT'],0,4));
$mobile_agents = array('w3c ','acs-','alav','alca','amoi','andr','audi','avan','benq','bird','blac','blaz','brew','cell','cldc','cmd-','dang','doco','eric','hipt','inno','ipaq','java','jigs','kddi','keji','leno','lg-c','lg-d','lg-g','lge-','maui','maxo','midp','mits','mmef','mobi','mot-','moto','mwbp','nec-','newt','noki','oper','palm','pana','pant','phil','play','port','prox','qwap','sage','sams','sany','sch-','sec-','send','seri','sgh-','shar','sie-','siem','smal','smar','sony','sph-','symb','t-mo','teli','tim-','tosh','tsm-','upg1','upsi','vk-v','voda','wap-','wapa','wapi','wapp','wapr','webc','winw','winw','xda','xda-');
if(in_array($mobile_ua,$mobile_agents)) {
$is_mobile=1;
}
if (isset($_SERVER['ALL_HTTP'])) {
if (strpos(strtolower($_SERVER['ALL_HTTP']),'OperaMini')>0) {
$is_mobile=1;
}
}
if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'windows')>0) {
$is_mobile=0;
}
return $is_mobile;
}
Check the $_SERVER['HTTP_USER_AGENT'] for mobile user agents.
You should check out http://detectmobilebrowser.com/ for already existing scripts to detect for mobile browsers (it just uses the user agents).
You can try The WURFL PHP API or Tera-Wurfl
http://mobiledetect.net/ is another lightweight php class, but you mist keep in mind that checking User-agent is a good but not perfect way, the issue is rules are constantly out-dated and incomplete so you need to change the detection code continuously.
Also check https://modernizr.com/ for another way to detect.
Nowadays, what do you consider "a mobile device"?
User agent parsers will give very good results, except for rare edge cases. The problem is that you have to constantly update them if you store the data locally or depend on the service being online if you use it "in the cloud".
It is better to use a functionality detection library, e.g. Modernizr, send to your server information about the browser capabilities on first visit and serve appropriate content based on what the browser can or cannot do. Or even better, delegate that to Javascript.
The desktop browser usually sends requests with the following header:
Sec-CH-UA-Mobile: ?0
The browser on the mobile device usually sends requests with the following header:
Sec-CH-UA-Mobile: ?1
So, you could check this using code like the following:
if (isset($_SERVER['HTTP_SEC_CH_UA_MOBILE']) &&
$_SERVER['HTTP_SEC_CH_UA_MOBILE']=='?1')
{
...
}

How to determine the browser of the user using PHP?

How to determine the browser of the user using PHP?
So that if the users browser is IE then the variable $alert="onbeforeunload" and if it is not IE, for example Firefox (else) then $alert="onload.
Help is much appreciated.
Thanks
Also please note that I can not install browscap.ini on my PHP server.
See if this code works for you
<?php
function detect_ie(){
return (sizeof(explode("MSIE",$_SERVER['HTTP_USER_AGENT'])) > 1);
}
if (detect_ie())
$event = "onbeforeunload";
else
$event = "onload";
?>
You can't. Not with 100% accuracy. The best method that is to check the user agent, however the user is free not to supply it, or fake it so try to avoid relying on it.
$ua = $_SERVER['HTTP_USER_AGENT'];
If the browser is IE, it should (roughtly) match (Where # is a number)
Mozilla/#.0 (compatible; MSIE #.##;
For which the regex would be something like
'~^Mozilla/[0-9]\.0 (compatible;\s+MSIE~i'
Alternatively you could just check for the string "MSIE" which would be simpler and slightly less strict.
But as #Michal said, there are other (better) implmentations on the get_browser manual page
use $_SERVER['HTTP_USER_AGENT']
Check if it contains "IE" directly followed by a number.
I'd rather do this in javascript itself though.
if (typeof window.onbeforeunload !== "undefined") window.onbeforeunload = myFunc;
else window.onunload = myFunc;
Javascript libraries are much better to detect and handle different browser behaviour. Just let a mature library like jQuery handle this and you'll be fine.

Categories