Related
I am creating a phonegap application for various mobile platforms and I was wondering what is a current best solution of browser/mobile phone detection?
Should I go with a server or a client side detection or could I use css solution through a media types screen width?
Changes:
06.03.2013 - Addad a few comments inside a WURFL chapter
Intro :
There are few available solutions but I will only name open-source ones, at least solutions mostly used with a jQuery/jQuery Mobile. Also be warned, this topic has the potential to start a war. On one side we have a proponents of server side detection with their community maintained databases and on the other side we have client side advocates with their browser sniffing.
Server side:
WURFL -
Created in 2002, WURFL (Wireless Universal Resource FiLe), is a
popular open-source framework to solve the device-fragmentation
problem for mobile Web developers and other stakeholders in the mobile
ecosystem. WURFL has been and still is the de facto standard
device-description repository adopted by mobile developers. WURFL is
open source (AGPL v3) and a trademark of ScientiaMobile.
Good :
Very detailed detection, you would probably get more data then is really needed.
Good platform support, api's are available for Java, PHP and .Net.
Bad :
Not always up to date, heavy dependency on community
In case of iPhone there's no way of knowing an iOS version, so media type queries to detect pixel ratios.
Fee only for a non commercial usage, older version are still free for commercial usage but they can only use database updated up to WURFL EULA changes.
It can be found here: http://wurfl.sourceforge.net/apis.php
PHP example :
<?php
// Include the configuration file
include_once './inc/wurfl_config_standard.php';
$wurflInfo = $wurflManager->getWURFLInfo();
if (isset($_GET['ua']) && trim($_GET['ua'])) {
$ua = $_GET['ua'];
$requestingDevice = $wurflManager->getDeviceForUserAgent($_GET['ua']);
} else {
$ua = $_SERVER['HTTP_USER_AGENT'];
// This line detects the visiting device by looking at its HTTP Request ($_SERVER)
$requestingDevice = $wurflManager->getDeviceForHttpRequest($_SERVER);
}
?>
<html>
<head>
<title>WURFL PHP API Example</title>
</head>
<body>
<h3>WURFL XML INFO</h3>
<ul>
<li><h4>VERSION: <?php echo $wurflInfo->version; ?> </h4></li>
</ul>
<div id="content">
User Agent: <b> <?php echo htmlspecialchars($ua); ?> </b>
<ul>
<li>ID: <?php echo $requestingDevice->id; ?> </li>
<li>Brand Name: <?php echo $requestingDevice->getCapability('brand_name'); ?> </li>
<li>Model Name: <?php echo $requestingDevice->getCapability('model_name'); ?> </li>
<li>Marketing Name: <?php echo $requestingDevice->getCapability('marketing_name'); ?> </li>
<li>Preferred Markup: <?php echo $requestingDevice->getCapability('preferred_markup'); ?> </li>
<li>Resolution Width: <?php echo $requestingDevice->getCapability('resolution_width'); ?> </li>
<li>Resolution Height: <?php echo $requestingDevice->getCapability('resolution_height'); ?> </li>
</ul>
<p><b>Query WURFL by providing the user agent:</b></p>
<form method="get" action="index.php">
<div>User Agent: <input type="text" name="ua" size="100" value="<?php echo isset($_GET['ua'])? htmlspecialchars($_GET['ua']): ''; ?>" />
<input type="submit" /></div>
</form>
</div>
</body>
</html>
If you want to customize this code, change configuration parameters inside a wurfl_config_standard.php file.
Modernizr - Server -
Modernizr is a great way to find out about your user's browser
capabilities. However, you can only access its API on the browser
itself, which means you can't easily benefit from knowing about
browser capabilities in your server logic. The modernizr-server
library is a way to bring Modernizr browser data to your server
scripting environment.
Good :
Like WURFL very detailed detection, but we need to take into consideration that it is build with a different purpose the WURFL.
Bad :
Only supported on PHP, but sometimes this will be enough.
Example :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Modernizr Server Example</title>
</head>
<body>
<?php
include('modernizr-server.php');
print 'The server knows:';
foreach($modernizr as $feature=>$value) {
print "<br/> $feature: "; print_r($value);
}
?>
</body>
</html>
It can be found here: https://github.com/jamesgpearce/modernizr-server
Client side:
Modernizer -
aking advantage of cool new web technologies is great fun, until you
have to support browsers that lag behind. Modernizr makes it easy for
you to write conditional JavaScript and CSS to handle each situation,
whether a browser supports a feature or not. It’s perfect for doing
progressive enhancement easily.
Good :
Only client side, server side component don't exist
Fast but still large for a javascript framework with its 12kb. Because of its modularity it can become smaller, depending on your needs.
Bad :
Can do only so much, less info then server side detection.
Modernizr itself is a great way to find out about your user’s browser capabilities. However, you can only access its API on the browser itself, which means you can’t easily benefit from knowing about browser capabilities in your server logic.
It can be found here: http://modernizr.com/
Example :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Modernizr Example</title>
<script src="modernizr.min.js"></script>
</head>
<body>
<script>
if (Modernizr.canvas) {
// supported
} else {
// no native canvas support available :(
}
</script>
</body>
</html>
JavaScript based browser sniffing
It is arguable that this may be (academically) the worst possible way
to detect mobile but it does have its virtues.
Good :
Simple
Bad :
Where to begin
Example :
<script type="text/javascript">
var agent = navigator.userAgent;
var isWebkit = (agent.indexOf("AppleWebKit") > 0);
var isIPad = (agent.indexOf("iPad") > 0);
var isIOS = (agent.indexOf("iPhone") > 0 || agent.indexOf("iPod") > 0);
var isAndroid = (agent.indexOf("Android") > 0);
var isNewBlackBerry = (agent.indexOf("AppleWebKit") > 0 && agent.indexOf("BlackBerry") > 0);
var isWebOS = (agent.indexOf("webOS") > 0);
var isWindowsMobile = (agent.indexOf("IEMobile") > 0);
var isSmallScreen = (screen.width < 767 || (isAndroid && screen.width < 1000));
var isUnknownMobile = (isWebkit && isSmallScreen);
var isMobile = (isIOS || isAndroid || isNewBlackBerry || isWebOS || isWindowsMobile || isUnknownMobile);
var isTablet = (isIPad || (isMobile && !isSmallScreen));
if ( isMobile && isSmallScreen && document.cookie.indexOf( "mobileFullSiteClicked=") < 0 ) mobileRedirect();
</script>
This may not be the best solution but i use this function for my personal use in javascript.
By the way #Gajotres thanks for deep and useful information.
function mobilMi()
{
if( navigator.userAgent.match(/Android/i) ||
navigator.userAgent.match(/webOS/i) ||
navigator.userAgent.match(/iPhone/i) ||
navigator.userAgent.match(/iPod/i)||
navigator.userAgent.match(/iPad/i)
){
return 1;
}
else
return 0;
}
I've code something like this to get the device os type... the $test will be the string of the user agent
if (preg_match("/linux/i", $test) && preg_match("/android/i", $test)) {
$device_type = 'Android';
} else if (preg_match("/windows phone/i", $test)){
$device_type = '<font size="6">Windows Mobile</font>';
} else if (preg_match("/windows nt/i", $test)){
$device_type = 'Windows';
} else if (preg_match("/linux/i", $test)){
$device_type = 'Linux';
} else if (preg_match("/macintosh/i", $test)){
$device_type = 'Macintosh';
} else if (preg_match("/iphone/i", $test)){
$device_type = 'iPhone';
} else if (preg_match("/ipad/i", $test)){
$device_type = 'iPad';
} else if (preg_match("/symbian/i", $test)){
$device_type = 'Symbian';
} else if (preg_match("/blackberry/i", $test)){
$device_type = 'Blackberry';
} else
$device_type = 'None';
I think you need to know the pattern and get the keyword. Using WURFL sometimes doesnt get what you want.
I'm trying to call a PHP function on an ASP.Net CMS. I'm hosting the PHP file on a different domain and I'm getting the following error.
XMLHttpRequest cannot load url. Origin url is not allowed by Access-Control-Allow-Origin.
I've added header('Access-Control-Allow-Origin: *'); to the PHP file as per some suggestions in other threads on this site, but it hasn't made a difference for me.
Here is my code:
HTML
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.post('http://10.254.2.54/adobe%20air/application/Pulse/data.php', {
'text': $("#preceda").text()
},
function(response){
$("#details").html(response);
});
});
</script>
</head>
<body>
<div id="preceda">
32384
</div>
<br />
<div id="details"></div>
</body>
</html>
PHP
<?php
header('Access-Control-Allow-Origin: *');
if ( isset($_POST['text']) ){
$q = addslashes(trim($_POST['text']));
}
// Connection script
$serverName = "***";
$uid = "***";
$pwd = "***";
$connectionInfo = array("UID"=>$uid, "PWD"=>$pwd, "Database"=>"***");
$conn = sqlsrv_connect($serverName, $connectionInfo);
if($conn === false)
{
echo "<error>Connect Failure</error>";
die(print_r(sqlsrv_errors(), true));
}
function checkQuery($theQuery, $theSQL)
{
if($theQuery === false)
{
echo "<error>Query Failure: ".$theSQL."</error>";
die(print_r(sqlsrv_errors(), true));
}
}
// Get the data
$tsql = "SELECT * FROM VG_LD_DS.dbo.VU_LearnAchievePreceda WHERE userID = '".$q."'";
$stmt = sqlsrv_query($conn, $tsql);
checkQuery($stmt, $tsql);
$i = 0;
while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
{
if($i == 0)
{
$names = array($row);
}
else
{
array_push($names, $row);
}
$i = 1;
}
header('Access-Control-Allow-Origin: *');
foreach ($names as $name) {
echo $name['telstraID'];
}
?>
This stuff is fairly new to me, so any advice or suggestion are appreciated.
Thank you :)
I had the same issue, here's my solution:
create a js file at the domain as the php api.
use the <script type="text/javascript" src="path to js file"></script> tag
call your functions inside that script
as it is in the same domain as the .php you won't run into the cross-domain restriction problem ;)
If your code really is:
$.post('data.php', ...
Then it should work fine. However, in your description of the problem it appears that you're trying to do this instead:
$.post('http://some.other.domain.com/data.php', ...
This is not allowed because it breaks the browser's same origin policy (which cannot be overridden by the programmer, only the user and even then only in some browsers). XMLHttpRequest can only be made to url's of the same domain.
The standard work around for this is to proxy the request through your ASP server. So for example you'll make a request like:
$.post('data.asp', ...
And data.asp is simply a script that fetches the data.php response via HTTP. There are no restrictions server side. Depending on the server, you can even do this without any scripting by using proxy or redirect modules in the server config. For example, you can configure Apache with mod-rewrite to proxy the page like this:
RewriteRule /data.php http://some.other.domain.com/data.php [P]
There are other solutions that doesn't require proxying such as the script tag hack (otherwise known as jsonp, google it). Some libraries like YUI can do cross domain ajax call by using Flash modules to bypass the browser's same origin policy. Flash generally doesn't have restriction of same origin policy which is why you can embed youtube videos on your website.
I have a simple script of code that reads a PHP file and when it get's changed it's supposed to say CHANGED on the page which I will change to refresh the page or change the content. For now, it shows the content, the function repeats once or twice and then it just shows nothing. Any help?
Here is the code:
<?php
$handle = fopen("../chat/real/chatserver.php", "r");
$contents = fread($handle, filesize("../chat/real/chatserver.php"));
fclose($handle);
$newcontents = $contents;
echo $contents;
?>
<script type="text/javascript">
checkchanged();
function checkchanged() {
document.write("<?php $handle = fopen('../chat/real/chatserver.php', 'r');
$newcontents = fread($handle,filesize('../chat/real/chatserver.php'));fclose($handle);?>");
document.write("<?php if(!($contents==$newcontents)){echo 'Changed';} ?>");
setTimeout('checkchanged()',3000);
}
</script>
Link to example
Thanks for the help
This is because you can't include PHP in your JavaScript in order to execute it by the client. Yes, you can include PHP values, but that's it. Have a look at the source code in your browser:
<script type="text/javascript">
checkchanged();
function checkchanged() {
document.write("");
document.write("");
setTimeout('checkchanged()',3000);
}
</script>
As you can see, the function document.write gets called with an empty string "". This is because everything that is in <?php ?> gets executed on the server, not on the client, before the resulting page gets sent to the client.
Since every PHP code is parsed only once $contents==$newcontents will be true, so you'll never see Changed.
To achieve something like a chat server you'll need new http request. Have a look at AJAX.
I need to find the screen resolution of a users screen who visits my website?
You can't do it with pure PHP. You must do it with JavaScript. There are several articles written on how to do this.
Essentially, you can set a cookie or you can even do some Ajax to send the info to a PHP script. If you use jQuery, you can do it something like this:
jquery:
$(function() {
$.post('some_script.php', { width: screen.width, height:screen.height }, function(json) {
if(json.outcome == 'success') {
// do something with the knowledge possibly?
} else {
alert('Unable to let PHP know what the screen resolution is!');
}
},'json');
});
PHP (some_script.php)
<?php
// For instance, you can do something like this:
if(isset($_POST['width']) && isset($_POST['height'])) {
$_SESSION['screen_width'] = $_POST['width'];
$_SESSION['screen_height'] = $_POST['height'];
echo json_encode(array('outcome'=>'success'));
} else {
echo json_encode(array('outcome'=>'error','error'=>"Couldn't save dimension info"));
}
?>
All that is really basic but it should get you somewhere. Normally screen resolution is not what you really want though. You may be more interested in the size of the actual browser's view port since that is actually where the page is rendered...
Directly with PHP is not possible but...
I write this simple code to save screen resolution on a PHP session to use on an image gallery.
<?php
session_start();
if(isset($_SESSION['screen_width']) AND isset($_SESSION['screen_height'])){
echo 'User resolution: ' . $_SESSION['screen_width'] . 'x' . $_SESSION['screen_height'];
} else if(isset($_REQUEST['width']) AND isset($_REQUEST['height'])) {
$_SESSION['screen_width'] = $_REQUEST['width'];
$_SESSION['screen_height'] = $_REQUEST['height'];
header('Location: ' . $_SERVER['PHP_SELF']);
} else {
echo '<script type="text/javascript">window.location = "' . $_SERVER['PHP_SELF'] . '?width="+screen.width+"&height="+screen.height;</script>';
}
?>
New Solution If you need to send another parameter in Get Method (by Guddu Modok)
<?php
session_start();
if(isset($_SESSION['screen_width']) AND isset($_SESSION['screen_height'])){
echo 'User resolution: ' . $_SESSION['screen_width'] . 'x' . $_SESSION['screen_height'];
print_r($_GET);
} else if(isset($_GET['width']) AND isset($_GET['height'])) {
$_SESSION['screen_width'] = $_GET['width'];
$_SESSION['screen_height'] = $_GET['height'];
$x=$_SERVER["REQUEST_URI"];
$parsed = parse_url($x);
$query = $parsed['query'];
parse_str($query, $params);
unset($params['width']);
unset($params['height']);
$string = http_build_query($params);
$domain=$_SERVER['PHP_SELF']."?".$string;
header('Location: ' . $domain);
} else {
$x=$_SERVER["REQUEST_URI"];
$parsed = parse_url($x);
$query = $parsed['query'];
parse_str($query, $params);
unset($params['width']);
unset($params['height']);
$string = http_build_query($params);
$domain=$_SERVER['PHP_SELF']."?".$string;
echo '<script type="text/javascript">window.location = "' . $domain . '&width="+screen.width+"&height="+screen.height;</script>';
}
?>
PHP is a server side language - it's executed on the server only, and the resultant program output is sent to the client. As such, there's no "client screen" information available.
That said, you can have the client tell you what their screen resolution is via JavaScript. Write a small scriptlet to send you screen.width and screen.height - possibly via AJAX, or more likely with an initial "jump page" that finds it, then redirects to http://example.net/index.php?size=AxB
Though speaking as a user, I'd much prefer you to design a site to fluidly handle any screen resolution. I browse in different sized windows, mostly not maximized.
Easiest way
<?php
//-- you can modified it like you want
echo $width = "<script>document.write(screen.width);</script>";
echo $height = "<script>document.write(screen.height);</script>";
?>
I found using CSS inside my html inside my php did the trick for me.
<?php
echo '<h2 media="screen and (max-width: 480px)">';
echo 'My headline';
echo '</h2>';
echo '<h1 media="screen and (min-width: 481px)">';
echo 'My headline';
echo '</h1>';
?>
This will output a smaller sized headline if the screen is 480px or less.
So no need to pass any vars using JS or similar.
You can check it like below:
if(strstr(strtolower($_SERVER['HTTP_USER_AGENT']), 'mobile') || strstr(strtolower($_SERVER['HTTP_USER_AGENT']), 'android')) {
echo "mobile web browser!";
} else {
echo "web browser!";
}
This is a very simple process. Yes, you cannot get the width and height in PHP. It is true that JQuery can provide the screen's width and height. First go to https://github.com/carhartl/jquery-cookie and get jquery.cookie.js. Here is example using php to get the screen width and height:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="js/jquery.cookie.js"></script>
<script type=text/javascript>
function setScreenHWCookie() {
$.cookie('sw',screen.width);
$.cookie('sh',screen.height);
return true;
}
setScreenHWCookie();
</script>
</head>
<body>
<h1>Using jquery.cookie.js to store screen height and width</h1>
<?php
if(isset($_COOKIE['sw'])) { echo "Screen width: ".$_COOKIE['sw']."<br/>";}
if(isset($_COOKIE['sh'])) { echo "Screen height: ".$_COOKIE['sh']."<br/>";}
?>
</body>
</html>
I have a test that you can execute: http://rw-wrd.net/test.php
Use JavaScript (screen.width and screen.height IIRC, but I may be wrong, haven't done JS in a while). PHP cannot do it.
Fully Working Example
I couldn't find an actual working PHP example to "invisibly" (without URL parameters) return client screen size, and other properties, to server-side PHP, so I put this example together.
JS populates and submits a hidden form (scripted by PHP from an array of JS properties), POSTing to itself (the data now available in PHP) and returns the data in a table.
(Tested in "several" browsers.)
<!DOCTYPE html>
<html>
<head>
<title>*Client Info*</title>
<style>table,tr{border:2px solid gold;border-collapse:collapse;}td{padding:5px;}</style>
</head>
<body>
<?php
$clientProps=array('screen.width','screen.height','window.innerWidth','window.innerHeight',
'window.outerWidth','window.outerHeight','screen.colorDepth','screen.pixelDepth');
if(! isset($_POST['screenheight'])){
echo "Loading...<form method='POST' id='data' style='display:none'>";
foreach($clientProps as $p) { //create hidden form
echo "<input type='text' id='".str_replace('.','',$p)."' name='".str_replace('.','',$p)."'>";
}
echo "<input type='submit'></form>";
echo "<script>";
foreach($clientProps as $p) { //populate hidden form with screen/window info
echo "document.getElementById('" . str_replace('.','',$p) . "').value = $p;";
}
echo "document.forms.namedItem('data').submit();"; //submit form
echo "</script>";
}else{
echo "<table>";
foreach($clientProps as $p) { //create output table
echo "<tr><td>".ucwords(str_replace('.',' ',$p)).":</td><td>".$_POST[str_replace('.','',$p)]."</td></tr>";
}
echo "</table>";
}
?>
<script>
window.history.replaceState(null,null); //avoid form warning if user clicks refresh
</script>
</body>
</html>
The returned data is extract'd into variables. For example:
window.innerWidth is returned in $windowinnerWidth
You can try RESS (RESponsive design + Server side components), see this tutorial:
http://www.lukew.com/ff/entry.asp?1392
You can set window width in cookies using JS in front end and you can get it in PHP:
<script type="text/javascript">
document.cookie = 'window_width='+window.innerWidth+'; expires=Fri, 3 Aug 2901 20:47:11 UTC; path=/';
</script>
<?PHP
$_COOKIE['window_width'];
?>
I don't think you can detect the screen size purely with PHP but you can detect the user-agent..
<?php
if ( stristr($ua, "Mobile" )) {
$DEVICE_TYPE="MOBILE";
}
if (isset($DEVICE_TYPE) and $DEVICE_TYPE=="MOBILE") {
echo '<link rel="stylesheet" href="/css/mobile.css" />'
}
?>
Here's a link to a more detailed script: PHP Mobile Detect
Here is the Javascript Code: (index.php)
<script>
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "/sqldb.php", true);
xhttp.send("screensize=",screen.width,screen.height);
</script>
Here is the PHP Code: (sqldb.php)
$data = $_POST['screensize'];
$pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$statement = $pdo->prepare("UPDATE users SET screen= :screen WHERE id = $userid");
$statement->execute(array('screen' => $data));
I hope that you know how to get the $userid from the Session,
and for that you need an Database with the Table called users, and an Table inside users called screen ;=)
Regards KSP
The only way is to use javascript, then get the javascript to post to it to your php(if you really need there res server side). This will however completly fall flat on its face, if they turn javascript off.
JS:
$.ajax({
url: "ajax.php",
type: "POST",
data: "width=" + $("body").width(),
success: function(msg) {
return true;
}
});
ajax.php
if(!empty($_POST['width']))
$width = (int)$_POST['width'];
This can be done easily using cookies. This method allows the page to check the stored cookie values against the screen height and width (or browser view port height and width values), and if they are different it will reset the cookie and reload the page. The code needs to allow for user preferences. If persistant cookies are turned off, use a session cookie. If that doesn't work you have to go with a default setting.
Javascript: Check if height & width cookie set
Javascript: If set, check if screen.height & screen.width (or whatever you want) matches the current value of the cookie
Javascript: If cookie not set or it does not match the current value, then:
a. Javascript: create persistent or session cookie named (e.g.) 'shw' to value of current screen.height & screen.width.
b. Javascript: redirect to SELF using window.location.reload(). When it reloads, it will skip the step 3.
PHP: $_COOKIE['shw'] contains values.
Continue with PHP
E.g., I am using some common cookie functions found on the web. Make sure setCookie returns the correct values.
I put this code immediately after the head tag. Obviously the function should be in a a source file.
<head>
<script src="/include/cookielib.js"></script>
<script type=text/javascript>
function setScreenHWCookie() {
// Function to set persistant (default) or session cookie with screen ht & width
// Returns true if cookie matches screen ht & width or if valid cookie created
// Returns false if cannot create a cookies.
var ok = getCookie( "shw");
var shw_value = screen.height+"px:"+screen.width+"px";
if ( ! ok || ok != shw_value ) {
var expires = 7 // days
var ok = setCookie( "shw", shw_value, expires)
if ( ok == "" ) {
// not possible to set persistent cookie
expires = 0
ok = setCookie( "shw", shw_value, expires)
if ( ok == "" ) return false // not possible to set session cookie
}
window.location.reload();
}
return true;
}
setScreenHWCookie();
</script>
....
<?php
if( isset($_COOKIE["shw"])) {
$hw_values = $_COOKIE["shw"];
}
PHP works only on server side, not on user host. Use JavaScript or jQuery to get this info and send via AJAX or URL (?x=1024&y=640).
The quick answer is no, then you are probably asking why can't I do that with php. OK here is a longer answer. PHP is a serverside scripting language and therefor has nothing to do with the type of a specific client. Then you might ask "why can I then get the browser agent from php?", thats because that information is sent with the initial HTTP headers upon request to the server. So if you want client information that's not sent with the HTTP header you must you a client scripting language like javascript.
For get the width screen or the height screen
1- Create a PHP file (getwidthscreen.php) and write the following commands in it
PHP (getwidthscreen.php)
<div id="widthscreenid"></div>
<script>
document.getElementById("widthscreenid").innerHTML=screen.width;
</script>
2- Get the width screen through a cURL session by the following commands
PHP (main.php)
$ch = curl_init( 'http://hostname/getwidthscreen.php' );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
$result = curl_exec( $ch );
print_r($result);
curl_close( $ch );
Well, I have another idea, thanks to which it is 90% possible in a very simple way using pure PHP. We will not immediately know the exact screen resolution, but we will find out whether the user is using a computer (higher resolution) or a phone (lower resolution) and thanks to this we will be able to load specific data.
Code example:
$user_agent = $_SERVER['HTTP_USER_AGENT'];
if (strpos($user_agent, 'Windows') !== false) {
//PC, high resolution
//*note for phone is: Windows Phone
} elseif (strpos($user_agent, 'Mac') !== false) {
//PC, high resolution
} else {
//mobile, small resolution
//Android, iOS, Windows Phone, Blackberry OS, Symbian OS, Bada OS, Firefox OS, WebOS, Tizen OS, KaiOS, Sailfish OS, Ubuntu Touch, HarmonyOS, EMUI, OxygenOS, One UI, Magic UI, ColorOS, MiUI, OxygenOS, ZenUI, LG UX, FunTouch OS, Flyme OS, OxygenOS, Samsung One UI, Android One, Android Go, Android TV, Android Auto, Fuchsia OS.
}
Then, a great solution to complete the verification is to throw a cookie and check the data using PHP.
//JS:
function setCookieResolution() {
// Get screen resolution
if (!getCookieValue("screen_resolution")) {
var screenResolution = window.screen.width + "x" + window.screen.height;
// Create cookie with resolution info
document.cookie = "screen_resolution=" + screenResolution + ";path=/";
}
}
setCookieResolution();
//PHP:
if (isset($_COOKIE["screen_resolution"])) {
$currentValue = $_COOKIE["screen_resolution"];//example: 1920x1080
$parts = explode("x", $currentValue);
if(count($parts) == 2 && is_numeric($parts[0]) && is_numeric($parts[1])) {
$width = (int)$parts[0];
$height = (int)$parts[1];
} else {
// handle error
}
}
In PHP there is no standard way to get this information. However, it is possible if you are using a 3rd party solution. 51Degrees device detector for PHP has the properties you need:
$_51d['ScreenPixelsHeight']
$_51d['ScreenPixelsWidth']
Gives you Width and Height of user's screen in pixels. In order to use these properties you need to download the detector from sourceforge. Then you need to include the following 2 lines in your file/files where it's necessary to detect screen height and width:
<?php
require_once 'path/to/core/51Degrees.php';
require_once 'path/to/core/51Degrees_usage.php';
?>
Where path/to/core is path to 'Core' directory which you downloaded from sourceforge. Finally, to use the properties:
<?php
echo $_51d['ScreenPixelsHeight']; //Output screen height.
echo $_51d['ScreenPixelsWidth']; //Output screen width.
?>
Keep in mind these variables can contain 'Unknown' value some times, when the device could not be identified.
solution: make scalable web design ... ( our should i say proper web design) formating should be done client side and i did wish the info would be passed down to server but the info is still usefull ( how many object per rows kind of deal ) but still web design should be fluid thus each row elements should not be put into tables unless its an actual table ( and the data will scale to it's individual cells) if you use a div you can stack each elements next to each other and your window should "break" the row at the proper spot. ( just need proper css)
<script type="text/javascript">
if(screen.width <= 699){
<?php $screen = 'mobile';?>
}else{
<?php $screen = 'default';?>
}
</script>
<?php echo $screen; ?>
How do I find out the ISP provider of a person viewing a PHP page?
Is it possible to use PHP to track or reveal it?
If I use something like the following:
gethostbyaddr($_SERVER['REMOTE_ADDR']);
it returns my IP address, not my host name or ISP.
This seems to be what you're looking for, it will attempt to return the full hostname if possible:
http://us3.php.net/gethostbyaddr
EDIT: This method no longer works since the website it hits now blocks automatic queries (and previously this method violated the website's terms of use). There are several other good [legal!] answers below (including my alternative this this one.)
You can get all those things from the following PHP codings.,
<?php
$ip=$_SERVER['REMOTE_ADDR'];
$url=file_get_contents("http://whatismyipaddress.com/ip/$ip");
preg_match_all('/<th>(.*?)<\/th><td>(.*?)<\/td>/s',$url,$output,PREG_SET_ORDER);
$isp=$output[1][2];
$city=$output[9][2];
$state=$output[8][2];
$zipcode=$output[12][2];
$country=$output[7][2];
?>
<body>
<table align="center">
<tr><td>ISP :</td><td><?php echo $isp;?></td></tr>
<tr><td>City :</td><td><?php echo $city;?></td></tr>
<tr><td>State :</td><td><?php echo $state;?></td></tr>
<tr><td>Zipcode :</td><td><?php echo $zipcode;?></td></tr>
<tr><td>Country :</td><td><?php echo $country;?></td></tr>
</table>
</body>
There is nothing in the HTTP headers to indicate which ISP a user is coming from, so the answer is no, there is no PHP builtin function which will tell you this. You'd have to use some sort of service or library which maps IPs to networks/ISPs.
Why not use ARIN's REST API.
<?php
// get IP Address
$ip=$_SERVER['REMOTE_ADDR'];
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, 'http://whois.arin.net/rest/ip/' . $ip);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
// execute
$returnValue = curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
$result = json_decode($returnValue);
echo <<<END
<pre>
Handle: {$result->net->handle->{'$'}}
Ref: {$result->net->ref->{'$'}}
Name: {$result->net->name->{'$'}}
echo "OrgRef: {$result->net->orgRef->{'#name'}}";
</pre>
END;
// eof
https://www.arin.net/resources/whoisrws/whois_api.html
Sometimes fields change, so this is the improvement of the above post.
<body>
<table align="center">
<?
$ip=$_SERVER['REMOTE_ADDR'];
$url=file_get_contents("http://whatismyipaddress.com/ip/$ip");
preg_match_all('/<th>(.*?)<\/th><td>(.*?)<\/td>/s',$url,$output,PREG_SET_ORDER);
for ($q=0; $q < 25; $q++) {
if ($output[$q][1]) {
if (!stripos($output[$q][2],"Blacklist")) {
echo "<tr><td>".$output[$q][1]."</td><td>".$output[$q][2]."</td></tr>";
}
}
}
?>
</table>
</body>
You can obtain this information from ipinfo.io or similar services.
<?php
/**
* Get ip info from ipinfo.io
*
* There are other services like this, for example
* http://extreme-ip-lookup.com/json/106.192.146.13
* http://ip-api.com/json/113.14.168.85
*
* source: https://stackoverflow.com/a/54721918/3057377
*/
function getIpInfo($ip = '') {
$ipinfo = file_get_contents("https://ipinfo.io/" . $ip);
$ipinfo_json = json_decode($ipinfo, true);
return $ipinfo_json;
}
function displayIpInfo($ipinfo_json) {
var_dump($ipinfo_json);
echo <<<END
<pre>
ip : {$ipinfo_json['ip']}
city : {$ipinfo_json['city']}
region : {$ipinfo_json['region']}
country : {$ipinfo_json['country']}
loc : {$ipinfo_json['loc']}
postal : {$ipinfo_json['postal']}
org : {$ipinfo_json['org']}
</pre>
END;
}
function main() {
echo("<h1>Server IP information</h1>");
$ipinfo_json = getIpInfo();
displayIpInfo($ipinfo_json);
echo("<h1>Visitor IP information</h1>");
$visitor_ip = $_SERVER['REMOTE_ADDR'];
$ipinfo_json = getIpInfo($visitor_ip);
displayIpInfo($ipinfo_json);
}
main();
?>
GeoIP will help you with this: http://www.maxmind.com/app/locate_my_ip
There is a php library for accessing geoip data: http://www.maxmind.com/app/php
Attention though, you need to put the geoip db on your machine in order to make it work, all instructions are there :)
You can't rely on either the IP address or the host name to know the ISP someone is using.
In fact he may not use an ISP at all, or he might be logged in through a VPN connection to his place of employment, from there using another VPN or remote desktop to a hosting service halfway around the world, and connect to you from that.
The ip address you'd get would be the one from either that last remote machine or from some firewall that machine is sitting behind which might be somewhere else again.
I've attempted to correct Ram Kumar's answer but whenever I would edit their post I would be temporarily banned and my changes were ignored. (As to why, I don't know, It was my first and only edit that I've ever made on this website.)
Since his post, his code does not work anymore due to website changes and the Administrator implementing basic bot checks (checking the headers):
<?php
$IP = $_SERVER['REMOTE_ADDR'];
$User_Agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:33.0) Gecko/20100101 Firefox/33.0';
$Accept = 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8';
$Accept_Language = 'en-US,en;q=0.5';
$Referer = 'http://whatismyipaddress.com/';
$Connection = 'keep-alive';
$HTML = file_get_contents("http://whatismyipaddress.com/ip/$IP", false, stream_context_create(array('http' => array('method' => 'GET', 'header' => "User-Agent: $User_Agent\r\nAccept: $Accept\r\nAccept-Language: $Accept_Language\r\nReferer: $Referer\r\nConnection: $Connection\r\n\r\n"))));
preg_match_all('/<th>(.*?)<\/th><td>(.*?)<\/td>/s', $HTML, $Matches, PREG_SET_ORDER);
$ISP = $Matches[3][2];
$City = $Matches[11][2];
$State = $Matches[10][2];
$ZIP = $Matches[15][2];
$Country = $Matches[9][2];
?>
<body>
<table align="center">
<tr><td>ISP :</td><td><?php echo $ISP;?></td></tr>
<tr><td>City :</td><td><?php echo $City;?></td></tr>
<tr><td>State :</td><td><?php echo $State;?></td></tr>
<tr><td>Zipcode :</td><td><?php echo $ZIP;?></td></tr>
<tr><td>Country :</td><td><?php echo $Country;?></td></tr>
</table>
</body>
Note that just supplying a user-agent would probably suffice and the additional headers are most likely not required, I just added them to make the request look more authentic.
If all these answers are not useful then you can try API way.
1.http://extreme-ip-lookup.com/json/[IP ADDRESS HERE]
EXAMPLE: http://extreme-ip-lookup.com/json/106.192.146.13
2.http://ip-api.com/json/[IP ADDRESS HERE]
EXAMPLE: http://ip-api.com/json/113.14.168.85
once it works for you don't forget to convert JSON into PHP.
I think you need to use some third party service (Possibly a web service) to lookup the IP and find the service provider.
go to http://whatismyip.com
this will give you your internet address. Plug that address into the database at http://arin.net/whois
<?php
$isp = geoip_isp_by_name('www.example.com');
if ($isp) {
echo 'This host IP is from ISP: ' . $isp;
}
?>
(PECL geoip >= 1.0.2)
geoip_isp_by_name — Get the Internet Service Provider (ISP) name
http://php.net/manual/ru/function.geoip-isp-by-name.php
A quick alternative. (This website allows up to 50 calls per minute.)
$json=file_get_contents("https://extreme-ip-lookup.com/json/$ip");
extract(json_decode($json,true));
echo "ISP: $isp ($city, $region, $country)<br>";
API details at the bottom of the page.
This is the proper way to find a isp from site or ip.
<?php
$isp = geoip_isp_by_name('www.example.com');
if ($isp) {
echo 'This host IP is from ISP: ' . $isp;
}
?>