php to load variable php file depending on the browser width - php

Hi I am currently using jQuery to load a variable php layout depending on the browser width.
function setLocation(url) {
if (window.location.href.indexOf(url) === -1)
window.location = url;
}
function reloadPage(width) {
width = parseInt(width);
if (width < 701) {
setLocation("yournarrowpage.php");
} else if (width < 900) {
setLocation("yourmediumpage.php");
} else {
setLocation("yourwidepage.php");
}
}
$(function() {
reloadPage($(this).width());
$(window).resize(function() {
reloadPage($(this).width());
});
});
Is it possible to accomplish this with just php?
If yes, how? Please help.
Why do I want to do this when I can simply re-arrange my layout with CSS?
I do not want to use the CSS property #div { display:none } as the issue is that my layouts are loaded with very many images, javascript and also widgets.
I even tried a responsive layout but unfortunately some of the image details are hardly visible in small screens.
Using css property display:none, will still loads the un-displayed content wasting a lot of bandwidth. Lets say for a mobile browser to load 1.5 MB of site and then hide 1.2 MB of it???? Well that may not be a good idea.
For smaller browsers these widgets will not make any sense, hence I would want to load a lighter version of the same.
This is what I think. Please feel free to correct me if I am wrong as I am still a novice when it comes to programming and am still in the learning stage.

Combine CSS media queries and javascript to prevent loading of the larger items/areas you don't want to load...
if ($('window').width() > 1000) {
// load your full functions and stylesheet
}
if ($('window').width() < 1000) {
// load your narrow functions and stylesheet
}
I've recently combined css media queries in a method similar to this, and then added animations to help make the transition less painful.. it's quite nice.

The problem with attempting this in PHP is that you cannot tell the client width from your web server, which means you would have to dip into the request headers.
There is a library to help with device detection using PHP on Google Code.
Finally a word or two of warning. You will need to keep this script up to date in order for it to keep working. The methods it uses to tell what the device is falls under the banner of "browser sniffing", which relies on browsers sending through certain headers, which are subject to change in later versions / new browsers. Also, most of the time, you simply don't want to force mobile users to view a mobile version of your website, so if you do decide to implement things this way, give people an option to view the normal website on their mobiles.

PHP just outputs text to the client. It knows absolutely nothing about the client that the client doesn't tell it.
I say client, because there is no guarantee that the software that initiated the request to your PHP script is even a browser.
You've ruled out CSS, but honestly, if you don't want to use javascript then it's the only other option you have. The selectors in CSS3 are really quite powerful and you can make the same page appear completely different for different browser widths.

Related

php screen width if else statement (no css)

Any idea how to achieve this? Basically I need different div widths for different devices (its complicated and cannot be achieved through css)
if screen width < 786 {
echo div.span3
} else {
echo div.span6
PHP can't get screen width because there is no screen for PHP :) It only executes on server and returns HTML to the browser, so PHP got no direct contact with browser.
Elon Than is correct - PHP doesn't know anything about the browser widths. Maybe what you are looking to achieve can be done with media queries: http://css-tricks.com/css-media-queries/?
Maybe you could display both divs and toggle the display depending upon the screen width?
Hope this helps.
PHP is a server side language, it has no interaction with users browser whatsoever.
Look into JavaScript to achieve what you're trying to do. It can detect screen width, and you can manipulate DOM with it to show the content that is needed.
If browser backwards compatibility is not important look into CSS media queries. (I am not really sure about the browser support, but I reckon it's IE9+)

PHP If statement on browser width w/bootstrap

Ok So I am making a 2.0 version of a my website and completely re-designing the layout I have brought in bootstrap because what I mainly want to do is make the website mobile friendly so basically what I'm trying to do is something along the lines of this and done in php
if(browser-width < 600px && browser-width > 100px) {
<div class="mobileHeader">stuff here</div>;
}elseif(browser-width > 700px) {
<div class="sidebar">stuff here</div>;
};
I hope this makes sense I have been trying to figure this out for awhile to no avail.
You can't access browser width (or any other user properties) with PHP. The only thing possible would be to set the width in a cookie (with JS) and then read it with PHP. However, this works only on the second request, as PHP gets executed before JS.
I do suggest you read something about responsive webdesign and you might find out you don't actually need this.
You cannot know the browser-width in php. You have to do this with javascript. Also even if php had this result, it is static, so what if you resized the window? Php wouldn't detect that. In my opinion you are choosing the wrong tools for your task.
Source to prove my point
The browsers don't report chrome width on the request. So PHP will never know that. You will need to do that with CSS media queries or with JavaScript.

Best way to display large PDF for mobile (web development) site/usage

I need to display a PDF with over 100 pages (yeah it's huge) in a mobile website. This is not going to work and I need to come up with an alternative solution.
I'm using PHP as the backend and jQueryMobile lib as the mobile framework.
I was thinking to convert the PDF to html but then there is the question about how to load each page or load all the pages before hand (as a multi page layout w/ JQM can do).
I was thinking about having each page a AJAX request and loading it this way but wanted to get a fresh point of view on any alternative methods/ideas.
I'm also concerned about connection speed as mobile devices vary from Edge, 3G, 4G, wireless, etc... so making the load time(s) as fast as possible is a must.
UPDATE:
The PDF file size is around 9MB, yeah it's not a lot but for a mobile browser over a slow connection speed this will take some time to display and that's if it doesn't timeout first
Thanks in advance.
I would do something like this, as you're not really providing a PDF (which may require bookmarks, graphics, navigation links, and other complex content), but simply need to load a lot of content and make sure the request isn't so large that the page times out.
Concerns:
Large file size and timeouts
Must serve entire agreement
Step one
Make each page as its own raw-text component. You can do this by either making individual files with each page, or have one PHP script serve out individual pages of the content. Google is littered with PHP that translates PDF into text.
For our purposes, you have one PHP file that serves out content, in this method:
./agreement.php?page=1
Step two
Request content into a div, use recursion to make it load the next page after the first one successfully loads (not before, or later. Asynchronous can be messy like that.).
//Untested code
function loadPages(n) {
$.ajax({
url: './agreement.php',
data: {'page':n},
error : function (){ loadPages(n) }, //Try to load again
success: function (pageData) {
n++;
$('#agreementBox').append(pageData);//Puts data into document
if (n > 100) {return 0;} //Exit recursion on 100th page being appended
loadPages(n); //Recursive call, loads next page after this one has been loaded
}
});
}
loadPages(1); //Call function for the first time.
Concerns
Keep it to simple text, 100 pages of graphical data in the same rendering may become memory-intensive.
Your ajax request may fail for any number of reasons, the error re-try I put in won't cover off all of them, and may go on forever, in cases such as the php script crashes.
Users might hit agree before agreement is done loading.
Style. I use 'magic numbers' in my example, where 100 pages is a hard-coded value and not a constant, don't do that when you go to implement this.

how can I use javascript or php to determine when images are loaded if image tags are dynamically created from database?

I have a page that's very image-intensive. This is by client request - it's a list of merchants with a logo for each one. The list is quite long (over 500), and yes - the client insists on displaying all of them. We do have an ajax typeahead search to help users find what they're looking for without scrolling, so it's not a total disaster.
Here's the issue: the client is just now realizing that it takes a long time to load this page because of all the logos. Even if each one is only a few kb, it still adds up pretty quickly. He's now decided he wants a progress bar to display while the images are loading. I've never done that before, so I starting looking around, and most of the ones I've seen rely on getting an array of img tags and looping through to check the complete property. The problem I'm having (at least I think this is what's causing the problem) is that the image tags are generated by a database query, and I think the javascript to get the image array is loading before the image tags are finished loading. Obviously this isn't an issue on pages where the images are hard-coded.
Can anyone point me in the right direction of how I can implement a progress bar on img tags that get loaded dynamically? My site is written in PHP, so I'm perfectly happy to do something server-side if that would work better.
As pretty much everyone here has noted, this is a nasty problem to have to solve. Accordingly, I propose sidestepping the technical components of it and addressing only the human ones.
Leave everything almost exactly as it is. All you have to do is find or make a throbber (I use http://ajaxload.info/ and it couldn't be easier), and use it as the background image for a CSS selector that only applies to the logos on the page.
Users (and clients who make unreasonable requests!) are far more frustrated by a lack of responsiveness than they are by things taking time. This quick gimmicky fix might be just enough to coax site users to perceive the problem more as the latter than as the former.
CSS Sprites will definitely be a good start in your case. If you got 500 spearate images on one page, then browser will have to start 500 new connections to fetch them, and unfortunately, concurrent connections will be around 20 or something, so... it is not good.
CSS Sprites from css-tricks.com
I'd suggest pre-making and caching of the logos (or their various states), as your own hunch is that the main bottleneck is that "the image tags are generated by a database query". Is this at all possible?
It's better to store a few states or whatever with a naming scheme that makes it possible to fetch the right image, than regenerating them on-the-fly each time. Of course, you'll need a proper cache handling mechanism, so it's not like an easy task, but more often than not, your hunch is helping you in the right direction.
If you're able to boil it down to a few static files per logo, you could also consider using a CDN and/or multiple subdomains, as Michael Mao suggests.
I haven't tested this but something like this might work (its jQuery)
<?php // Do your select image stuff from here ?>
<html>
<head></head>
<body>
<script type="text/javascript">
$(document).ready(function () {
var images = <?php echo json_encode($images); ?>;
$.each(images, function(i, image) {
$(new Image()).load(function () {
$('body').append(this);
alert('Loaded '+i+' out of '+images.length);
}).attr('src', image);
})
});
</script>
Since you already have a javascript search to get people to specific listings faster, how about loading a placeholder static image for all logos and then replacing the placeholder with the correct logos on an as-needed basis? "As-needed" could be determined by JavasScript calculation of window position and any typed input.
Do your just-in-time image loading from multiple subdomain masks to parallelize requests and you should be able to pop the images up somewhat quickly as-needed without bogging down the page by loading unnecessary images.
It's not pretty, but neither is the client's request.
Edit: As far as a progress bar goes, when you determine a window location (or typed-input location), determine how many listings will be in-view, and how many listings to buffer above and below the view. Then you'll have a total number of listings and you can update a JavaScript/HTML progressbar as you dynamically replace the logos within that range.
It would be much easier to answer the question if I could see the complete code but I can remember doing something remotely similar and I ended up using a custom JavaScript object. You could perhaps start with an object like this somewhere in the head of your app:
function Iterator() {
var counter = 0;
this.images = 215; // This number comes from the DB and gives you a total number of images
this.progress = counter / this.images
this.hasMore = function() { counter < this.images }
this.getPicture = function() {
// send a request to the server using counter as a parameter
// upon receiving this request the server should load only ONE image (LIMIT=1 in SQL)
// with OFFSET equal to the value of "counter"
// when the image loads (use whatever JS framework you need for that),
// we increment the counter:
counter++;
}
this.loadPictures = function() {
while this.hasMore() {
this.getPicture()
// You can do something with the "progress" attribute here, to be visualizad by your progress bar
}
}
);
You sure need to instantiate the Iterator object on body load and have it execute the "loadPictures" function.
Please let me know if you have any problems implementing that.
Here's a javascript-only solution that shouldn't require any modification to your server-side code. Using jquery:
$(document).ready(function() {
var loadedSoFar = 0;
//use jquery to get all image tags you want.
//The totalImgs is used to calculate percent and is the length of the jquery array
var totalImgs = $("#imgHolder img").each(function(i, img) {
//if this image has already loaded, add it to loadedSoFar.
if (img.complete)
loadedSoFar++;
else {
//otherwise add a load event for the image.
$(img).load(function() {
loadedSoFar++;
console.log("complete: " + (loadedSoFar / totalImgs * 100) + "%");
});
}
}).length;
});
I wrote this assuming all the images are already in the dom when the document.ready is called. If it is not, move this to a function and call it after the img tags are loaded into the dom from the server (via ajax request for instance).
Basically all it does is find all the imgs in imgHolder (modify the selector to match your situation), and wire the load event so it can update the loadedSoFar count. If the image has already loaded by the time this script runs, the load event would never fire, so increment the loadedSoFar counter right away. The number of total images that need to be loaded will be the length of the jquery object array returned by the selector.
I'll leave it to you to write a progress bar, but I do recommend this plugin: http://t.wits.sg/jquery-progress-bar/
I'd definitely try to avoid the progress bar -- you're going to really struggle with it.
If you really must do it, probably the best you can hope for is to fake it - ie have it show progress on a given amount of time, which you'd set as an approximation of the actual time it takes to load the page. Not foolproof but far easier than trying to actually time the loading progress.
Don't forget also that the progress bar itself will add to the loading time. And you'll need to have the code for it embedded in your actual HTML code; if it's in an external javascript file it could itself be subject to loading delays, which would make the whole excersise pointless.
So as I say, it's probably not worth the effort. What would be worth the effort would be to try to reduce the loading time. If it's noticable enough that you're considering a progress bar then there's something seriously wrong.
There are a whole stack to techniques for speeding up site loading times; it's a whole topic on its own. But I'll try to give you a few pointers. I suggest you also take some time googling for additional and follow-up information, though.
Image optimisation. If you haven't done so already, run all your images through an optimising program. You may find that you can reduce file sizes and thus load-times significantly.
CSS Sprites. One of the main causes of slow loading times is having too many separate HTTP requests. Since a browser can only load a given number of files at once, any files over that number will have to wait till others have finished before they can even begin loading. CSS sprites solves this by combining a number of images into a single file and using CSS to display only the relevant part of it in each spot. This is typically used for groups of related images.
Lazy Load. There is a jQuery plugin called LazyLoad which tells your page to load images only as they are needed. Images that are off the bottom of the viewable page are deferred until the user starts scrolling the page. This means that the images that are visible immediately are loaded first, making the page as a whole appear to load more quickly.
That'll do for now. There's loads more, of course, but all I'm really trying to say is: Optimise to get rid of the speed issue rather than trying to cobble together a band aid solution.
Hope that helps.
there are different ways to speedup image loading especially when you have a lot of them
Sprite - Use sprite where you group a number of images together and use the css background property (FACT: one big image better speed than multiple requested images).
Use the <image/> tag properly. You can add the lowsrc="" attribute to show a low resolution image until the real image aka src="" attribute is fully loaded
Use the ajax, although you may have 500+ images users will never see the full list. So you can load 6 at a time (or Nth at a time) when the document is fully loaded you can add the rest that way u can speed up the loading time as the user will only see some images and by the time they click next set of images they would have been loaded (or wait less) better yet to save broadband only use the ajax when required aka only when they click next or scroll down auto load new images. (look at google images and ajax used while scralling)

Scale down whole website [into iFrame]

I was wondering if there is a (webbased) way to scale down a whole website and put it into an iframe. [including images etc], so that a user would get a fully functional preview of the website (only for websites without frame busting methods of course).
No, there isn't.
The Microsoft propriety zoom property could probably do it, but not in most browsers, and not in pages you can't edit the CSS for.
If you want to provide a preview, provide a thumbnail graphic (which would probably be a lot faster for the user to download in most cases anyway)
Have you tried the following with css?
body {
zoom: 10%;
}
Thats up to javascript or css although it really depends about the browser and its behavior to certain commands.
You can use javascript to specify the iframe src.
document.getElementById('myiframe').src = 'my url';

Categories