phantomJS : Absolute path working, but Relative path giving problems - php

I'm on a Linux web server. The following files are being used to create a screenshot:
ons.php
ong.js
ons2.php
All these files along with phantomJS binary are in the same folder. The folder's permission is 744
ons.php
$forMonth = date('M Y');
exec('./phantomjs ons.js '.strtotime($forMonth), $op, $er);
print_r($op);
echo $er;
ons.js
var args = require('system').args;
var dt = '';
args.forEach(function(arg, i) {
if(i == 1)
{
dt = arg;
}
});
var page = require('webpage').create();
page.open('./ons2.php?dt='+dt, function () { //<--- This is failing
page.render('./xx.png');
phantom.exit();
});
ons2.php
<!DOCTYPE html>
<html>
<head>
<title>How are you</title>
</head>
<body>
<?php
if(isset($_GET['dt']))
{
echo $_GET['dt'];
}
else
{
echo '<h1>Did not work</h1>';
}
?>
</body>
</html>
On opening ons.php in the browser, I'm getting this result:
Array ( ) 0
But no screenshot is being created.
Debugging
On debugging a lot, I found out that it has to do with paths.
--> If I put the following inside ons.js
.
.
.
var page = require('webpage').create();
page.open('http://www.abc.com/ppt/ons2.php', function () { // <-- absolute path
page.render('./xx.png');
phantom.exit();
});
The screenshot is getting created. I want to avoid using absolute paths as the application will be shifted to a different domain pretty soon.
What I don't get is why relative path is not working even if all files are in the same folder. Is my syntax of page.open('./ons2.php....') wrong?

./ons2.php implies a local file. It will not be passed through to the web server, and moreover it will fail outright because you also appended a query string - in the local file system this would be treated as part of the file name, so the file will not be located at all.
You will need to supply an absolute URL for this to work as you expect - but you can determine this dynamically in PHP (using $_SERVER) and pass it in to the JS script as a command line argument.
For example (untested):
ons.php
<?php
// Determine the absolute URL of the directory containing this script
$baseURL = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? 'https' : 'http')
. '://' . $_SERVER['HTTP_HOST']
. rtrim(dirname($_SERVER['REQUEST_URI']), '/') . '/';
$now = new DateTime('now'); // Because all the cool kids use DateTime
$cmd = './phantomjs ons.js '
. escapeshellarg($now->format('M Y')) . ' ' // Don't forget to escape args!
. escapeshellarg($baseURL)
. ' 2>&1'; // let's capture STDERR as well
// Do your thang
exec($cmd, $op, $er);
print_r($op);
echo $er;
ons.js
var args, url, page;
args = require('system').args;
if (args.length < 3) {
console.error('Invalid arguments');
phantom.exit();
}
url = args[2] + 'ons2.php?dt=' + encodeURIComponent(args[1]);
console.log('Loading page: ' + url);
page = require('webpage').create();
page.open(url, function () {
page.render('./xx.png');
phantom.exit();
});
ons2.php remains the same.

Maybe there is an issue in page.render but I don't think so. The most common case of hangs is unhandled exception.
I will suggest you 4 things to investigate the issue :
add an handler to phantom.onError and/or to page.OnError
encapsulate your code in try/catch blocks (such as for page.render)
Once the page is loaded, there is no test on callback status. It's better to check the status ('success' or 'fail')
seems to freeze when calling page.render. Have you tried a simpler filename in the current directory? Maybe the freeze is because of the security or invalid filename (invalid characters?)
Hope this will help you

Related

ng-view outside of index file

I am building a project for a client who has a php site, there is a file that has "template functions". ...so basically, the person has different HTML pages wrapped inside of PHP functions. I need to build a template inside of this person's weird site and I REALLY want to use AngularJs. So at the top of the file is all this stuff, which not exactly sure what it is doing but basically setting where the site is and what template to use.
My question - I am getting Error: $injector:modulerr
Module Error. My Angularjs code is fine I am pretty sure. I have ng-app, and ng-view..just basic stuff in place. Does anyone know possibilities why I am getting this error? I am thinking it must have something to do with this wacky server/php setup. Also any ideas to make it work?
Inside of the php function that loads the template for the site what looks like a basic HTML file with ng-app on the html tags and and ng-view div.
if(!isset($_SESSION)){ session_start(); }
function setup_path_massage(){
if (substr_count($_SERVER['SERVER_NAME'],".") == 1){
$domref = "www." . $_SERVER['SERVER_NAME'] ; }
else {
$domref = $_SERVER['SERVER_NAME'] ; }
list($host,$domain,$ext) = split("\.",$domref);
$domain .= "." . $ext;
$_SESSION['settings']['domain'] = $domain;
#################
if (isset($_SERVER['SUBDOMAIN_DOCUMENT_ROOT'])){
$orig_path_info = realpath($_SERVER['SUBDOMAIN_DOCUMENT_ROOT']);
$pos = strpos($orig_path_info, '/shop/');
}
else {
$orig_path_info = realpath($_SERVER['DOCUMENT_ROOT']);
$pos = strpos($orig_path_info, '/shop/');
}
$shop_path = substr($orig_path_info, 0, $pos)."/shop/";
$Zend_path = $shop_path . 'Zend/library/';
$version = 'v' . substr($orig_path_info, $pos + 7, strpos($orig_path_info, '/', $pos + 7) - ($pos + 7));
set_include_path($shop_path.$version.'/:'.$Zend_path);
return array ($host,$domain);
}
list($host,$domain) = setup_path_massage();
Ok, I was just spazzing out. ...I forgot to attach angular-routes.js and was trying to set up routes.

PHP: Returning string from server to client when json_encode fails

I'm writing an application that sends some data to my server in order to produce a PDF file. To do this I use shell_exec to call on the approapiate latex compilation command. I always show the output of log in the cliente by using the following code in the server(this is oversimpliefied to show the problem):
$log = shell_exec("cd ../../template; pdflatex $texinput;");
$ret["log"] = $log;
echo json_encode($ret);
However every once in a while the log will contain a chararcter that will break the json_encode. That is json_enconde($ret) will be false.
Is there any other way to send the information (as text or maybe as a file) to the client?
EDIT:
Since the output is the output of a Latex compilation it is very difficult to reproduce simply. However, as I've been asked to provide an example, I managed to create this minimal example using the log file (automatically saved by the pdflatex command) and this minimal php script.
This is the PHP script:
$trial = "trial.log";
$handle = fopen($trial,"r");
$data = fread($handle,filesize($trial));
if ($handle === false){
$errors = error_get_last();
$ret["error"] = "Could not open $trial for reading. Type: " . $errors["type"] . " MSG: " . $errors["message"];
return;
}
fclose($handle);
echo "Done reading<br>";
if (json_encode($data) === false){
echo "I've failed";
}
else{
echo "All good";
}
This is the file trial.log
https://www.dropbox.com/s/04ejx5s1mj0ojj2/trial.log?dl=0
I've tested it in my browser and I get the I've failed. However I have bypassed the problem. (See my answer)
So after trying a couple of different things, I went with trying to send the pdflatex generated log file to the client. So instead of returning the contents of the file (which are the same as the contents returned by the command) y returned the path to the log file. Then in my browser I used this code:
// Getting the base URL
var url = window.location.href;
var l = url.length;
while (l--){
if (url[l] == '/') break;
}
url = url.substring(0,l);
// Creating the URL for the log file.
var logfile = url + obj.logfile;
The obj.logfile was the relative path in my server to the log file. Then I used the following to load the file into a text area.
// Loading the log file.
$.ajax({
type: "GET",
url: logfile,
success: function(text) {
document.getElementById("pdflatex_out").value = text;
},
error: function() {
document.getElementById("pdflatex_out").value = "Error. please contact the administrator";
}
});

Using PHP exec() send back information in steps

I am using PHP exec() to install Composer dependencies:
exec('php composer.phar install -d ' . dirname(__DIR__), $out);
This is triggered via an ajax post request. Everything works fine and the return from exec() is printed to the screen.
exit(json_encode($out));
However, what I am after is a way to periodically send data back to the ajax callback so I can render each bit of information rather than render the whole block at once.
Not sure if this is possible though.
I should mention that the servers where this would be ran would not have anything like NodeJS and would very likely be shared hosting.
Security issues of exec'ing on-demand aside, if you are able to write/log the status of the output to a file, you can write a simple AJAX poller (since you prefer not to use WebSockets).
In your exec, try:
add-task.php
$jobId = uniqid();
$outfile = $jobId . "-results.txt";
exec('php composer.phar install -d ' . dirname(__DIR__) . " > $outfile &", $out);
$result = array("jobId" => $jobId);
echo json_encode($result);
Ok, now send that $jobId down to the client, so that they can poll for updates. I'm using a variation of a concept project on github: https://github.com/panique/php-long-polling
server.php
$jobid = isset($_GET['jobid']) ? $_GET['jobid'] : null;
$outputfile = $jobid . "-results.txt";
$lastTimestamp = isset($_GET['timestamp']) ? (int)$_GET['timestamp'] : null;
// get timestamp of when file has been changed the last time
clearstatcache();
$lastModified = filemtime($outputfile);
// if no timestamp delivered via ajax
// or data.txt has been changed SINCE last ajax timestamp
if ($lastTimestamp == null || $lastModified > $lastTimestamp) {
// get content of data.txt
$data = file_get_contents($outputfile);
// put data.txt's content and timestamp of
// last data.txt change into array
$result = array(
'data' => $data,
'timestamp' => $lastTimestamp
);
// encode to JSON, render the result (for AJAX)
$json = json_encode($result);
} else {
// No updates in the file, just kick back the current time
// and the client will check back later
$result = array(
'timestamp' => time()
);
$json = json_encode($result);
}
header("Content-Type: application/json");
echo $json;
Then, in the browser, you just have a tiny client that polls for it's 'jobid' to check on status.
client.js
$(function () {
var jobid = '12345';
function checkForUpdates(timestamp) {
$.ajax({
type: 'GET',
url: 'http://localhost/server.php',
data: {
'timestamp': timestamp,
'jobid': jobid
},
success: function (data) {
var obj = jQuery.parseJSON(data);
if (obj.data) {
// Update status content
$('#response').text(obj.data);
}
// Check again in a second
setTimeout(function () {
checkForUpdates(obj.timestamp);
}, 1000);
}
});
}
checkForUpdates();
});
index.html
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript" src="client.js"></script>
</head>
<body>
<h1>Status:</h1>
<div><pre id="response"></pre></div>
</body>
</html>

How can I use a php file's output with Ajax?

I was following this tutorial.
I need to use a php file's ouput in my HTML file to dynamically load images into a gallery. I call
function setOutput()
{
if (httpObject.readyState == 4)
document.getElementById('main').src = httpObject.responseText;
alert("set output: " + httpObject.responseText);
}
from
function doWork()
{
httpObject = getHTTPObject();
if (httpObject != null) {
httpObject.open("GET", "gallery.php?no=0", true);
httpObject.send(null);
httpObject.onreadystatechange = setOutput;
}
}
However, the alert returns the php file, word for word. It's probably a really stupid error, but I can't seem to find it.
The php file:
<?php
if (isset($_GET['no'])) {
$no = $_GET['no'];
if ($no <= 10 && $no >1) {
$xml = simplexml_load_file('gallery.xml');
echo "images/" . $xml->image[$no]->src;
}
else die("Number isn't between 1 and 10");
}
else die("No number set.");
?>
If the alert is returning the contents of the PHP file instead of the results of executing it, then the server is not executing it.
Test by accessing the URI directly (instead of going via JavaScript).
You probably need to configure PHP support on the server.
Your Server doesn't serve/parse PHP files! You could test your JavaScript code by setting the content of gallery.php to the HTML code you want to receive.

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