Does google adsense use PHP? - 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.

Related

i want to customize my automatic download function to be unautomatic just redirect to download page

i would like to customize my function, currently, when i click download it automatically download mp3 file, but i want it just to redirect to the download page and let the user click download themselves, so i don't want it be auto download, how should i correct my code please help this is my code thank
In short, i want to close force download, this is my website you could try it, www.vox79.com
and here is my download helper code this link(http://www.vox79.com/page/35-code)
function download_mp3()
{
$query = decode(urlencode($this->input->get("q",TRUE)));
$data = json_decode(searchYoutube($query));
$artist = urldecode($this->input->get("a",TRUE));
$track = urldecode($this->input->get("t",TRUE));
setDownload($artist,$track,'','mp3');
$videoID = get_video_id($data);
$video = "https://www.youtube.com/watch?v=".$videoID;
$download_service = $this->config->item("download_service");
$download_service = str_ireplace("%youtube_url%", $video, $download_service);
$download_service = str_ireplace("%youtube_video%", $videoID, $download_service);
if($videoID == '')
{
redirect("http://www.youtube.com/results?search_query=$query",'location');
}
else
{
redirect($download_service,'location');
}
}
if($videoID == '')
{
header('Location: http://www.youtube.com/results?search_query=$query');
}

What are available solutions of a browser / mobile phone detection

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.

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.

Javascript X/Y Coordinates into database?

Ive been asking this question over and over many times in a bad way, so ill try to make it clearer.
I have a page with HTML that has an Attack and Restart Link on the page, the restart link appears after you win.
These links are JavaScript:
<script type="text/javascript">
<!--
function attack() {
window.location = "attack.php?attack=1";
}
function restart() {
window.location = "battle.php?id=1&status=start";
}
-->
</script>
I want to make it so that once the person has clicked one of these link, (using javascript) it gets the X/Y coords of where the clicked the link and inserts it into the database with the following values:
id
ip
username
x
y
restart
For the id, ip, username and restart I could easily use MYSQL and PHP, but I dont know how to insert Javascript information into the database, which would be the X/Y coords.
Using the Insterstellar_coder's X/Y javascript snippet, you could use javascript to make an ajax call to a php script. The ajax call would contain all the parameters as arguments and the php script on the server could get these arguments and do the database insertion.
Edition (20111016211256-0400): added files to show a solution (as far as I understand correctly the issue):
I've worked only the attack part. the restart part is similar.
No AJAX part was needed since I did piggyback on your attack and restart php files.
index.html:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>index</title>
<script type="text/javascript" charset="utf-8">
// get continous mouse move events and keep the coordinates in tempX and tempY
// stolen from http://javascript.internet.com/page-details/mouse-coordinates.html
var IE = document.all?true:false;
if (!IE) document.captureEvents(Event.MOUSEMOVE)
document.onmousemove = getMouseXY;
var tempX = 0;
var tempY = 0;
function getMouseXY(e) {
if (IE) { // grab the x-y pos.s if browser is IE
tempX = event.clientX + document.body.scrollLeft;
tempY = event.clientY + document.body.scrollTop;
}
else { // grab the x-y pos.s if browser is NS
tempX = e.pageX;
tempY = e.pageY;
}
if (tempX < 0){tempX = 0;}
if (tempY < 0){tempY = 0;}
return true;
}
var ip = "10.0.0.1";
var username = "me";
var id = "1";
function Coordinates(x,y) {
this.x = x;
this.y = y;
}
function attack(e) {
window.location = "attack.php?attack=1&x="+tempX+"&y="+tempY+"&ip="+ip+"&username="+username+"&id="+id;
}
function restart() {
window.location = "battle.php?id=1&status=start";
}
</script>
</head>
<body id="index" onload="">
<input type="button" name="attack" value="attack" id="attack" onClick="attack();">
<input type="button" name="restart" value="restart" id="restart" onClick="restart();">
</body>
</html>
attack.php
<?php
$METHOD = '_' . $_SERVER['REQUEST_METHOD'];
foreach ($$METHOD as $key => $value) {
$$key = $value;
}
$log = array("attack" => $attack, "x" => $x, "y" => $y, "ip" => $ip, "username" => $username, "id" => $id);
//print_r($log);
try {
// assuming you use mongodb locally
$m = new Mongo();
$db = $m->mydb;
$logs = $db->logs;
$logs->insert($log, true);
} catch (Exception $e) {
echo $e;
}
?>
You can get the pageX and pageY coordinates from the event object. Here is some rough code.
$('yourlinkid').click(function(e){
var x = e.pageX; // x coordinate
var y = e.pageY; // y coordinate
});
There's an epic library for this called Touché. It gives you a lot of information about the user interaction with the page (e.g clicking, dragging). You can also specify callbacks for AJAX purposes if you want to send data to the database or maybe do something else.
Here's the demo

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

Categories