can php detect client browser monitor size/resolution? - php

Php can detect IP, hostname, client agent etc. Can php detect client browser monitor size/resolution?

No, it cant. PHP runs on the server, so it cant detect client settings unless you take specific client-side steps to pass the info to the PHP scripts on the server.

Please do note that some of us like our browsers non-maximized. Perhaps you'd be better off trying to detect browser size rather than screen resolution. I assume that the JS to do either would be very similar, but I don't actually know that to be the case.
Also, what is the resolution of a blind man's screen reader?

You'll have to use PHP together with JavaScript, like in this example:
$url = $_SERVER['PHP_SELF'];
if( isset($HTTP_COOKIE_VARS["res"]) )
$res = $HTTP_COOKIE_VARS["res"];
else {
?>
<script language="javascript">
<!--
go();
function go()
{
var today = new Date();
var the_date = new Date("August 31, 2020");
var the_cookie_date = the_date.toGMTString();
var the_cookie = "res="+ screen.width +"x"+ screen.height;
var the_cookie = the_cookie + ";expires=" + the_cookie_date;
document.cookie=the_cookie
location = '<?echo "$url";?>';
}
//-->
</script>
<?php
}
//Let's "split" the resolution results into two variables
list($width, $height) = split('[x]', $res);
//Take the width and height minus 300
$tb_width = $width-300;
$tb_height = $height-300;
//Make the table
print("<table align=center border=1 width=" .$tb_width . " height=" . $tb_height . " >
<tr><td align=center>Your screen resolution is " . $width . " by " . $height . ".<br>
The width/height of this table is " . $tb_width . " by " . $tb_height . ".</td></tr>
</table>");

I was looking for this as well, but found none of these answers really answered the question! Indeed, there is no way for PHP to know the screen resolution since it is running on the server side. Since that information is not passed along in HTTP environment variables, we need another route. Javascript is one alternative.
The example below is a PHP page that checks for a resolution variable being passed in the HTTP request. If it does not find that resolution variable, then it creates a brief bit of JavaScript on the page that passes that variable and the height and width along in a redirect back to itself. Of course, when the page is loaded again after the redirect all the variables will be set and PHP will know the resolution.
<?php
if(!isset($_GET['resolution'])) {
echo "<script language=\"JavaScript\">
<!--
document.location=\"$PHP_SELF?resolution=1&width=\"+screen.width+\"&height=\"+screen.height;
//-->
</script>";
} else {
// Code to be displayed if resolution is detected
if(isset($_GET['width']) && isset($_GET['height'])) {
echo "Width: " . $_GET['width'] . " and Height: " . $_GET['height'] . "<br />";
} else {
echo "Resolution not detected.";
}
}
?>
In the end I found this a pretty unsatisfactory solution. It works, but it is ugly, adding cruft to the URL and requiring a redirect. Still, it may inspire someone to post a better answer. FYI, credit where credit is due, this answer was inspired by this post.

I know this is not the best answer so spare the downvote.
<script>
/*
JAVASCRIPT IS ON TELL THE DEVELOPER#
*/
// GET BROWSER WIDTH AND HEIGHT
var bh=screen.height;
var bw=screen.width;
window.location="?doSubmit=do&js=yes&bh="+bh+"&bw="+bw+"";
</script>
<noscript>
<!--
JAVASCRIPT IS OFF TELL THE DEVELOPER#
-->
<meta http-equiv='refresh' content='0;url=?doSubmit=do&js=off&bh=off&bw=off'>
</noscript>
<?
if($_GET["doSubmit"]=="do"){
// VARS
$bh=$_GET["bh"];
$bw=$_GET["bw"];
$js=$_GET["js"];
// PRINT HTML ?>
<table>
<tr><td><strong>Browser Width:</strong></td><td><?=$bw;?>px</tr>
<tr><td><strong>Browser Height:</strong></td><td><?=$bh;?>px</tr>
<tr><td><strong>JavaScript Detection (y/n):</strong></td><td><?=$js;?></tr>
</table>

Some people require browser size for mobile devoloping. This is essential information in some cases.
Using WURFL and WALL can get around this as most mobiles do not support JS.

Monitor size can't be obtained using JS, you have to make a poll :)

Note, that JS can check the window size of browser, but this size includes user toolbars, scrollbars etc... Real workspase area in browser depends on those toolbars size.

Related

PHP check if file_exists without extension then Ajax a div with appropriate media tag (img or video) based on filepath

First posting here. I know inline php is not preferred but I haven't converted all my scripts to echo json_encoded arrays to work in javascript on the client side...so for now, I have inline php.
I do not know the extension of the user uploaded media because it could be a jpg,mp4,etc and upon upload it goes into a media folder with the user id as an identifier.
When my user first loads the div (and html page), the php script cycles through an array and does a fetch_assoc from sql query to the database each time; It returns the (media_id #) and prints out an li with the respective media displayed next to some other values from the query.
I only know the (media_id) and the file path name without the extension. When the page first loads, everything works great and the file_exists function returns correctly.
THE PROBLEM
When I AJAX the div and do the query again, because the user added a row to the database, the new list prints out with all info, BUT the file_exists function doesn't recognize the exact same paths as before and I don't have an img or video on the page.
I copy/pasted the exact same code from the original div and put it in a file for ajax to re-query and print the new li's.
All variables are the same and when I hard code a test filepath, it prints fine. Maybe there's a caching issue?
THE CODE
<?php
$result=$conn->query($select);
$row=$result->fetch_assoc();
?>
<li>
<?php
if ($row['count']>0) {
echo "<div class='media-container'>";
$pathname = "uploads/".$row["id"]."media1";
$testjpg=$pathname.".jpg";
$testjpeg=$pathname.".jpeg";
$testpng=$pathname.".png";
$testmp4=$pathname.".mp4";
if (file_exists($testjpg)==TRUE || file_exists($testpng)==TRUE || file_exists($testjpeg)==TRUE) {
echo '<img src="'.$pathname.'">';
}if(file_exists($testmp4)==TRUE) {
echo "<video></video>";
}
echo "</div>";
}?>
</li>
I could use some advice on how to fix this and how to print appropriate media tags on unknown media types.
THE OUTPUT
<div class='media-container'>
</div>
DEBUGGING ATTEMPTS
echoing the exact file path of a known image in an <img> tag works fine. putting echo'test'; inside the file_exists case does nothing.
--
Solution (Kind of)
So I've used html's onerror before and I found a workaround, though I'd still like to know why I was getting an error. PSA this uses JQuery but javascript works too:
My Solution
<script>
function img2video(el, src) {
$( el ).replaceWith( '<video class="videoClass"><source src="'+src+'" type="video/mp4"></video>' );
}
</script>
<body>
<img style="width:100%" onerror="img2video(this,'<?php echo$pathname;?>')" src="<?php echo$pathname;?>">
</body>
Alright, so here's the final answer I made to best fit the problem using glob:
Javascript:
function img2video(el,src,place) {
if (place=='type') {
$( el ).replaceWith( '<video controls controlsList="nodownload" disablePictureInPicture style="width:100%;object-fit:contain;" preload="auto"><source src="'+src+'" type="video/mp4"></video>');
}
}
PHP:
<?php for ( $i=1; $i <= $limit; $i++) {
$path ="[DIRECTORY]/".$row["id"]."media".$i;
$path = (!empty(glob($path . '*.{jpg,png,jpeg,avi,mp4}', GLOB_BRACE)[0])) ? glob($path . '*.{jpg,png,jpeg,avi,mp4}', GLOB_BRACE)[0] : false;?>
<div>
<img onerror="img2video(this,'<?php echo$path;?>','type',<?php echo$row["id"];?>,<?php echo$i;?>)" src="<?php echo$path;?>">
</div>
<?php } ?>
I don't know how to mark as duplicate, if someone could help with that. My answer uses Glob_Brace from #Akif Hussain 's response on This Question.

Generate SVG graphic using values from MySQL database table via PHP

i'm trying to echo this
echo $row['positionX'] . " " . $row['positionY'];
as polygone points in a svg graphic code snippet
<polyline points = "...HERE..." fill = "none" stroke = "blue" stroke-width = "3"/>
how do i that?
thanks
There are other ways, depending on requirements or coding style:-
$.getJSON(....) jQuery method where the server echo json_decode($row);, then dynamically draw the polyline from JSON data (eg: RaphaelJS or SnapSVG saves you a bit of coding)
echo "<polyline points=\"$row['positionX'],$row['positionX']\" \/>";
For Single Page Application, use #1 since it is an AJAX call.
For a one time page load, #2 coding is simple enough.
Note: too many <?php echo in a HTML is hard to debug, also recommend moustache templating to help readability and code simplification.
Something like this?
<polyline points = "<?php echo $row['positionX'] . " " . $row['positionY']; ?>" fill = "none" stroke = "blue" stroke-width = "3"/>

Determine browser width with jQuery, then call one (out of two) .php files (from the same directory) to load a line of PHP

I seek a simple way to call a php file using jquery.
The ultimate outcome has to do with a Magento site I am working on:
http://bouquetsco.com/flowersplants.html
^^This page
This page displays products: 3 in a row.
<?php $this->setColumnCount(3); ?>
<?php $this->setColumnCount(2); ?>
^^This php code manually sets the number of product columns.
By default the page displays 3 wide, which looks fine until the browser window re-sizes down to tablet width (760px or so). When the website's design is tablet size (760px or so) I would like to display only two columns of products.
To do this, it seems one must use javascript to determine the window width, then run some php code depending on the browser-window width... like
this...
if ( browser-window-widith > 760) { get '3-column.php' }
else { get '2-column.php' }
This is grossly over-simplified.
What would this code logic look like? How would one write this functionality?
Also, one could change the initial if statement to:
if (browser-window-width < 760) { get '2-column.php' }
else { get '3-column.php' }
====================================
There would exist two .php files (2-column.php, & 3-column.php)
Each contains:
<?php $this->setColumnCount(2); ?>
or
<?php $this->setColumnCount(3); ?>
The code would call one file or another depending on the browser window width, (which would be found by the javascript) and thus result in
3-column product list for displays > 760px
and
2-column product list for displays < 760px
I use this on the login page of my site:
if(!isset($_GET['width']))
{
echo '<script type="text/javascript">window.location = "' . $_SERVER['PHP_SELF'] . '?width="+screen.width+"&height="+screen.height;</script>';
}
else
{
$_SESSION['screen_width'] = $_GET['width'];
$_SESSION['screen_height'] = $_GET['height'];
}
Now the width and height are saved to the current session, and I can do a condition check before displaying the page division.
if($_SESSION['screen_width']>= '1400')
{
$this->setColumnCount(3);
}
else
{
$this->setColumnCount(2);
}
You can use jquery width and some ajax calls.
index.php
<html>
....
<div id="somedivport"></div>
<--! if that script is used the above div will load differently depending on the width-->
</html>
script.js
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
//or use this$(document).width();
$("#somedivport").load(width>$(window).width()?"/3-column.php":"/2-column.php");
});
</script>
Edit for reducing kloc

Add or Remove HTML code on Windows Resize

I'm working on a responsive website. I'm using CSS Media Queries and Adaptive Images (http://adaptive-images.com/) to render each page correctly on different devices.
My problem is that some elements are downloaded by the browser even if there are hidden! For instance, a element with the property {display:none;} is downloaded despite the fact that I don't want it.
So, here is my question: is there a way to add or remove HTML code depending on the device's screen-size?
By reading the code of "Adaptive Images" script, I saw they used a cookie, which stores the screen-size value.
<script>
document.cookie='resolution='+(window.innerWidth)+'; path=/';
window.addEventListener("resize", function() {
document.cookie='resolution='+(window.innerWidth)+'; path=/';
}, false);
</script>
So, I tried to read this cookie with a PHP function:
<?php
$fallback_res = 481;
$res = !empty($_COOKIE['resolution']) ? $_COOKIE['resolution'] :
$fallback_resolution; // Get the viewport resolution in $res variable
?>
It allows me to write a very useful PHP condition :
<?php if(isset($res) AND $res >= $fallback_res) // if viewport >= 481px
{
echo '<video>...</video>'; // Display the video
}
else { //if the screen is smaller
echo ''; // Echo something else
}
?>
It work very well. If the viewport is < 481px, the video is not downloaded. If the viewport is > 481px, the video is downloaded. But it only works, on page load! If I load the page with a 480-wide-opened-browser (=video not loaded), and then resize my browser to higher resolution, there is a big hole in the middle of the page.
What I need is to reload some part of the code on window resize. (Each time I resize the browser window, I want the $res condition to be updated automatically, and the following code as well)
Thanks.
if you combine blow jquery code with ajax , maybe you can do that .
$(window).resize(function() {
if($(window).width() > 480 )
{
#ajax code for download video
#or use .after in jquery
}
})
Html will looks like
<div id="phone">Content For the below 450px </div>
<div id="desktop">Content For the above 450px </div>
Add jQuery
if($(window).width() < 450 )
{
$('#desktop').remove();
}
else
{
$('#phone').remove();
}

Why doesn't PHP appear to store my variables?

I have a page that allows the user to draw an image using HTML5 canvas, convert it into text with JavaScript and post it to a PHP page.
http://dsiextensions.co.cc/chatdraw.php
The page is quite confusing, each text box is for each line of to 100px X 100px canvas. To put the data in the boxes, click "Finish" and then click "Submit" (Sorry that it's really slow).
I've tries making changes to the PHP code and occasionally the variable turns up but more often than not, it doesn't.
Here's the code: (note, only the data in the first box is used at the moment)
<?php
$dstring = $_POST['senddata1'];
$darray = str_split($dstring);
echo $dstring;
print_r($darray);
$x=1;
$y=1;
for ($a=0;$a<100;$a++)
{
if($a%100==0 && $a!=0){
echo '<br />'; //Checks if it is the 100th pixel and adds a new line (not needed at the moment)
$y++;
$x=1;}
//echo $x . ',' . $y . '(' . $a . ',' . $darray[$a] . ')|';
if($darray[$a]!=0){
echo "<input type='button' style='width:15;height:15;background-color:#000' />"; //Black button if it is a black pixel
}
else{
echo "<input type='button' style='width:15;height:15;background-color:#fff' />"; //White button if it is a white pixel
}
$x++;
}
?>
The codes supposed to check if the pixel is black or white and create a coloured button based on that (I'm going to use the image functions later), however $dstring is never echoed and therefore can't be converted to an array. Is there something I'm doing wrong here or is it a server problem?
Thanks
Note that the second PHP line should be spread out on to three lines
Seems to work by my side. Are you sure that data is well posted ? Try to make a print_r($_POST); in your script to see what has been posted

Categories