I want to get in PHP the height/width of both the screen and the viewport when a user visits a page.
I've tried different ways but they all cause other problems.
My goals:
Get the info on the first load (no jump page, no reload).
Not change the url
Not affect the rest of the PHP that runs on load, or make that PHP run twice
What I've tried so far:
Javascript to get viewport dimensions:
if(!isset($_POST['width']) || !isset($_POST['height'])) {
echo '
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var height = $(window).height();
var width = $(window).width();
$.ajax({
type: \'POST\',
data: {
"height": height,
"width": width
},
success: function (data) {
$("body").html(data);
},
});
});
</script>
';
}
$user_width = $_POST['width'];
$user_height = $_POST['height'];
problems: causes all php to run twice, once on load, once when it returns a value (the second time is about 4 seconds after the first), which makes the rest of the php wacky... also, makes page load very slow
Putting the screen dimensions into the url:
if(isset($_SESSION['screen_width']) AND isset($_SESSION['screen_height'])){
$user_width = $_SESSION['screen_width'];
$user_height = $_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>';
}
problems: changes the url (which affects other code and looks bad compared to expressionless urls which they have now); doesn't return viewport size afaik
I'm a noob. Maybe it's easy to do, but I really don't know. I searched a lot. That's how I got methods above. But I couldn't get them to work for me. Afaik, I haven't seen a solution anywhere to a similar situation.
Thanks :)