What are available solutions of a browser / mobile phone detection - php

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.

Related

How to fetch data every second from MYSQL database

I'm trying to make a Chat App using HTML, CSS, JS, PHP and Mysql.
I've completed all the functionalities that includes sending a message, receiving a message, displaying users... But the issue i'm facing is that i need to refresh the page every time i received a new message.
I'm looking for a way to auto update data with new data from mysql database.
Code:
<?php
if ($_GET['id']){
$id = $_GET['id'];
$id = preg_replace("/[^0-9]/", "", $id);
$fetching_messages = "SELECT * FROM users_messages WHERE from_user='$id' OR to_user='$id' ORDER BY id";
$check_fetching_messages = $db->prepare($fetching_messages);
$check_fetching_messages->execute();
$messages_all = $check_fetching_messages->fetchAll();
} else {
}
?>
<div id="autodata">
<?php foreach($to_users as $to_user) : ?>
<?php
$to_user_id = $to_user['to_user'];
$to_user_name = "SELECT * FROM users_accounts WHERE id='$to_user_id'";
$check_to_user_name = $db->query($to_user_name);
while ($row_to_user_name = $check_to_user_name->fetch()) {
$id_user = $row_to_user_name['id'];
$username = $row_to_user_name['username'];
$pdp = $row_to_user_name['profile_image'];
}
if ($id_user == $user_id){
} else {
echo '
<form style="height: fit-content;" name="goto'.$to_user_id.'" action="inbox.php">
<div onclick="window.location.replace('."'".'?id='.$to_user_id."'".')" class="inbox_chat_field_user">';
if (empty($pdp)){
echo "<img class='inbox_chat_field_user_img' src='uploads\profile\default.jpg'/>";
} else {
echo "<img class='inbox_chat_field_user_img' src='".$pdp."'/>";
}
echo '
<span class="inbox_chat_field_user_p">'.$username.'</span>
</div>
</form>
<hr class="inbox_separing_hr">';
}
?>
<?php endforeach;?>
</div>
Simply you can't do that, PHP is a server-side language, you can't tell the clients to refresh from PHP.
To accomplish that chat you should consider JavaScript in the browser.
The easiest way is by sending an AJAX request to your server and check if there are new messages every 5 or 10 seconds, and then do what you want with the messages in the response.
If you use jquery in your application you can send ajax request in this way:
$.get( "messages.php", function( data ) {
console.log( "Data Loaded: " + data );
});
and in messages.php script, you can fetch new messages from the database and return them with HTML or JSON format
You may also use FCM service offered by firebase to push your messages to the client directly, Check this package for PHP FCM.
There are other solutions like websockets etc...
It would have been easier for me to directly update your code had you separated business logic from presentation, so I am not going to attempt to do that. Instead I will describe a technique you can use and leave it to you to figure out the best way to use it. You might consider using server-sent events. See the JavaScript class EventSource.
The following "business logic" PHP program, sse_cgi.php, periodically has new output every 2 seconds (for a total of 5 times). In this case the output is just the current date and time as a string. But it could be, for example, a JSON record. Note the special header that it outputs:
<?php
header("Content-Type: text/event-stream");
$firstTime = True;
for ($i = 0; $i < 5; $i++) {
if (connection_aborted()) {
break;
}
$curDate = date(DATE_ISO8601);
echo 'data: This is a message at time ' . $curDate, "\n\n";
// flush the output buffer and send echoed messages to the browser
while (ob_get_level() > 0) {
ob_end_flush();
}
flush();
if ($i < 4) {
sleep(2); # Sleep for 2 seconds
}
}
And this is the presentation HTML that would be outputted. JavaScript code in this case is just replacing the old date with the updated value. It could just as well append new <li> elements to an existing <ul> tag or <tr> elements to an existing <table>.
<html>
<head>
<meta charset="UTF-8">
<title>Server-sent events demo</title>
</head>
<body>
<div id='date'></div>
<script>
var evtSource = new EventSource('sse_cgi.php');
var date = document.getElementById('date');
evtSource.onmessage = function(e) {
// replace old content
date.innerHTML = e.data;
};
evtSource.onerror = function() {
// occurs when script terminates:
evtSource.close();
console.log('Done!');
};
</script>
</body>
</html>
Note that this presentation references the "business logic" scripts that returns the successive dates.
Important Note
It is important to realize that this technique keeps the connection to the server open for the duration until all the data has been ultimately sent and the business logic script ultimately terminates (or the presentation running in the browser issues a call to evtSource.close() to close the connection). So if you have a lot of simultaneous users, this could be an issue.
If your application does not have a limited number of messages to return then the previously described problem can be overcome by having the business logic script return immediately after having sent one message. This will break the connection with the browser, which if it is still there, will automatically attempt to re-connect with the business logic script (note that this reconnection can take a while):
Updated Business Logic
<?php
header("Content-Type: text/event-stream");
# Simulate waiting for next message:
sleep(2);
$curDate = date(DATE_ISO8601);
echo 'data: This is a message at time ' . $curDate, "\n\n";
// flush the output buffer and send echoed messages to the browser
while (ob_get_level() > 0) {
ob_end_flush();
}
flush();
Updated Presentation
<html>
<head>
<meta charset="UTF-8">
<title>Server-sent events demo</title>
</head>
<body>
<div id='date'></div>
<script>
var evtSource = new EventSource('sse_cgi.php');
var date = document.getElementById('date');
evtSource.onmessage = function(e) {
// replace old content
date.innerHTML = e.data;
};
</script>
</body>
</html>

Fallback Javascript with PHP from CDN to Local Storage on Unavailable

I need some help. I would like to create a fallback for my source code. I am using a cdn to host my javascript and css and images. What I am trying to do is create a fallback in php that will say for instance is ip 123.456.789 is not available in 400ms the php will fallback to fetch my local storage at 987.654.321
I was thinking something on the lines of this:
if ip 123.456.789 in 400ms
//show this file from 123.456.789
else
//show this file from 987.654.321
I have my source code hard coded such as:
<script type="text/javascript" src="123.456.789/js/jquery.js"></script>
So if 123.456.789 is not available in 400ms I would like this one to load
<script type="text/javascript" src="987.654.321/js/jquery.js"></script>
I answered my own question a while ago. So decided to share here.
<?php
//debug off by default
error_reporting(0);
//cdn fallback
if (!isset($_GET['aws_cdn'])) {
$cdn_fallback = curl_init('http://123.456.789/'); //Set to CDN IP or URL
curl_setopt($cdn_fallback, CURLOPT_RETURNTRANSFER, true);
curl_setopt($cdn_fallback, CURLOPT_NOSIGNAL, 1);
curl_setopt($cdn_fallback, CURLOPT_TIMEOUT_MS, 400); //How many milliseconds before fallback to local storage
$data = curl_exec($cdn_fallback);
$curl_errno = curl_errno($cdn_fallback);
$curl_error = curl_error($cdn_fallback);
curl_close($cdn_fallback);
if ($curl_errno > 0) { ?>
<script type="text/javascript" src="http://example.com/js/jquery.js"></script>
<?php } else { ?>
<script type="text/javascript" src="http://123.456.789/cdn/js/jquery.js"></script>
<?php }} ?>

Access-Control-Origin Error

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.

Getting the screen resolution using PHP

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; ?>

Does google adsense use PHP?

I found the code below on a website where a google adsense ad usually shows up at, it was in the box the size of a google add, I am curious if this was from google themself or if the site owner used this code? I can't provide a URL as it was a 1 time thing, or randomly happens.
<?php
if (isset($_GET["client"]) &&
isset($_GET["slot"]) &&
isset($_GET["width"]) &&
isset($_GET["height"]))
{
print("<script type=\"text/javascript\"><!--
google_ad_client = \"".$_GET["client"]."\";
google_ad_slot = \"".$_GET["slot"]."\";
google_ad_width = ".$_GET["width"].";
google_ad_height = ".$_GET["height"].";
");
if (isset($_COOKIE["k"])) {
$k = preg_replace("/[^-.]*-25-[^-._]*[._]/","",$_COOKIE["k"]);
$k = preg_replace("/[^-.]*-40-[^-._]*[._]/","",$k);
$k = preg_replace("/-.*/","",$k);
$k = preg_replace("/,.*/","",$k);
print("google_page_url = \"http://insurance.webhop.biz/insurance.php?k=".$k."\";
");
} elseif (isset($_GET["k"])) {
print("google_page_url = \"http://insurance.webhop.biz/insurance.php?k=".$_GET["k"]."\";
");
}
print("//-->
</script>
<script type=\"text/javascript\"
src=\"http://pagead2.googlesyndication.com/pagead/show_ads.js\">
</script>");
}
?>
The only code Google provide for AdSense is a fragment of HTML that loads their JavaScript.
That's the site's code for displaying a Google AdSense unit. It's not provided by Google. All it does is print out the Google AdSense JavaScript code.

Categories