I am trying to server device specific layout and also content based on the browser viewport. I have a heavey site and I am not using Media Queries for some specific reasons primarily page load speeds. I need to accomplish this task in this manner only.
OK the situation is like this…..
I have 2 files index.php and viewport.php both residing in a folder http://localhost/test/
To get the browser viewport and convert the values to PHP variable, I am using the following script:
<?php
if (isset($_GET['width'])) {
$layoutType = $_GET['width'];
if ( $layoutType >= 240 && $layoutType <= 600 ) {
$layoutType = 'mobile';
} else if ($layoutType >= 601 && $layoutType <= 900 ) {
$layoutType = 'tablet';
} else {
$layoutType = 'desktop';
}
} else {
echo "<script language='javascript'>\n";
echo " location.href=\"${_SERVER['SCRIPT_NAME']}?${_SERVER['QUERY_STRING']}"
. "&width=\" + document.documentElement.clientWidth;\n";
echo "</script>\n";
exit();
}
?>
My questions:
Q1. How can I store $layoutType as a Session Variable so that I can use it multiple times? What would be the correct syntax for it?
Q2. How can I run the file viewport.php from index.php and get only the $layoutType and no other data. This is because by using the <?php require_once ?> method I am getting my URL like this:http://localhost/test/index.php?&width=1600. I want the URL to display like http://localhost/test/ only. What will be the correct syntax I need to use in my index.php file?
Q3. Skipping the Ajax part is there a way to get rid of index.php?&width=1600 from the URL? I tried via .htaccess but it gives me the error saying “The page is not redirecting properly”
Please note: I do not intend to use and JavaScript Libraries like jQuery and MooTools as this is the only JavaScript function in my entire website and it wont make sense to load an entire library for it.
Firstly, PHP happens server side, so once the page loads the only way to use PHP again (without loading a page) is to make an ajax call, presumably to another php page that performs a certain function and returns a value.
If you want to store a value as a session variable so that it can be used continuously, you can do the following:
I would probably not use this method and actually look at ways to do this with JavaScript/JQuery instead. But this is how you have asked to do it.
For your example, I have not used JQuery at all, but I would as the include is only about 19kb or so and it makes life SO much easier.
Example:
index.php
js/viewport.js
your php file to set the session the parameter is passed from your ajax call:
set_session.php
layout1.php
layout2.php
layout3.php
This method means you dont have to pass parameters around in your URL. it will all be hidden.