PHP: how to determine if the browser supports javascript in PHP? - php

I am building an AJAX deep-linked site.
I want PHP to load all the HTML code of the page if the user is trying to access the site with a Javascript non-supported browser or if it is a search crawler. Basically PHP will return the whole page.
On the contrary, when the user is trying to access the site with Javascript supported browser, I want PHP to return only the template code, and let Javascript (AJAX) take care of the rest. Basically PHP will only load design elements and let Javascript populate them with content.
I looked into PHP's get_browser() function, however it seems it is not such a reliable tool. What is the industry's practice see if the browser supports Javascript or it is a search crawler using PHP?
Background:
Why I want the site to have this behavior.
Since I want the home page to load just by loading the address: example.com, which does not send any query to PHP, PHP returns the HTML code of the home page. This however causes issues when the user tries to load the following page: example.com#foo. So, for this example, PHP will return the home page and once the home page is loaded, Javascript (AJAX) will change the content around so that it shows proper content for #foo. This will make the user to see the home page, therefore load time will be slower and user-experience will not be so nice. However if my PHP script can figure out that if the use with Javascript supported browser is trying to load the page, it will only return the template of the web site, which has no content) and the javascript will populate that template with content whatever is supposed to be displayed for #foo. On the other hand, if the Javascript non-separated browser or a crawler will try to access the page example.com#foo, home page will be returned.
I am using SWFaddress (http://www.asual.com/swfaddress/) library for the deep-linking.
Edit
Thank you guys. I did not think of using <noscript></noscript> before.
Here is what I decided to do. PHP by default will load pages such as example.com or example.com#foo (which is essentially the same as example.com from PHP's point of view since fragments by definition are not sent to the server) blank (just visual template) with <noscript> tag inside for the content of the home page. This way users with javascript will not see the home page and AJAX will populate the content of the page according to the #foo fragment. On the other hand, search crawlers and users without javascript will see a home page.
Thank you again. I think this is pretty simple and elegant solution. If you have any further suggestions, please post a comment or another answer.

You can't do this using PHP. What you can do though is use a noscript tag to redirect to another php page if they don't have javascript:
<noscript>
<meta http-equiv="refresh" content="0; URL=nojavascript.php">
</noscript>

It's not possible to accomplish this in the way you're trying to do it.
It's rare that someone has JS turned off and doesn't know it.
PHP doesn't get passed anything after #, only javascript can do anything with that. So even if PHP could determine if the browser has javascript turned on then it still couldn't read # anyways.

You could include a link inside some <NOSCRIPT> tags that point the user to something like example.com#foo?javascript=disabled.
Unfortunately, browsers do not report whether JS is enabled or not, so there's no way to know from a simple HTTP GET whether or not you should send JS reliant pages.

You should just build an AJAX query that sets a session variable for javascript enabled.
Run this AJAX query before any other information on the site is loaded and then do a simple redirect to the actual site.
You could do something like this pseudo code:
Index.php:
ajax(check_js.php);
redirect(main_page.php);
check_js.php
$_SESSION['js_enable'] = true;
main_page.php
if($_SESSION['js_enable'] == true) {
//execute page
} else {
header("Location: no_js_error.php");
}

Instead of the server trying to sniff our the user's settings, how about using unobtrusive javascript in the first place? This way, the page will degrade gracefully (to the desired state) if JS is not available.

Related

Block access for non-javascript users

I have a webpage written in PHP, HTML and, first of all, JavaScript. I want to block (deny access page and show a message) access my webpage for person who doesn't have enabled JavaScript in browser settings or doesn't support it, because then my page isn't correcly displayed and there are a lot of bugs (also security bugs !). I know that there is possible to write <noscript> statement in HTML, but then something other than this text is dispalyed and it also is removable (e.g. by Inspector function is browsers), I said that without JS my page contains bugs. So, my question : is there any way to block access* for users which doesn't support JS to my page using PHP ? Any other suggestions are welcome :)
*Block access means - deny access main page and show a message
This is not possible to do in a truly secure way.
Yes, you could just serve a page that is blank, and then use JS to actually load the content (e.g. via AJAX), but the problem is that JS must load that code from somewhere, and an attacker could do that too. But here's the real problem:
Users have control over their browsers. JS is client side code. An attacker may choose to run, not run, or change and then run your JS. An attacker may even run their own JS to call or replace your functions. Any security that relies on your JS is broken by default.
So while you could (and people do) show a warning message over your page that is then hidden by JS code, or use JS to load your content, it won't ever be secure.
If you really really really need this. I said three really because I think most of the time you can choose alternative to this.
Set a cookie using JavaScript and pass it along with your request to server and validate the cookie on your server with the passed request. If you are able to verify the cookie Your client has JS else not.
Better way would be to redirect js and non js users from single point. say in your index.html file you have have javascript code that will redirect your clients or visitors to different url. That way you know those users have js enabled else they would not be redirected.
You can make a "sub" page that loads its entire content via AJAX. This will not stop people from hitting your URLS directly though. Don't trust the client.
Other answers and comments already include a lot of details on why you really can't technically block access using Javascript, however, a simple workaround to do something only when JS is enabled, is to call a JS function after DOM loads:
<script type="text/javascript">
window.onload = do_something();
</script>
</body>
</html>
do_something() then could include simple things like switching block element visibility, e.g., hide the non-JS message, plus launch AJAX loader or do something else from the stuff that has been already suggested above.

Including php to another php and keeping included?

I'm looking for a solution similar to the php include method, except like at html's iframe tag, if I click a hyperlink on the included php, I don't want the browser to navigate the whole tab to the new url, but only navigating the included page without getting the parent page change/disappear.
UPDATE:
okay, thanks for the quick answers, seems like I didn't ask the right question:) so here is some background info: the whole page itself is a single-file website using the exactly same javascript+hiddendivs page changing method than that you just wrote. my problem is: I'm using a flat-file CMS to keep my News page managable by people having no coding knowledge. so I made an own template for the CMS only showing the news themselves. Then I embedded the CMS's index.php to my parent index.php with php include method and it looks really well, except my problem is, when I click "earlier posts", it navigates to the CMS's index.php and loads earlier news in there. I'd like it to load earlier news without navigating anywhere, just like at html's iframe method. (I will use iframe if there is no other solution, but its configuration would be really complicated if I wanted to stay cross-browser supportive)
From the action described it sounds like what you're looking for is not actually PHP but client side JavaScript. AJAX can perform exactly what you describe and there's a very easy library called jQuery to help you do this, with minimal effort.
http://api.jquery.com/jQuery.get/
http://api.jquery.com/jQuery.ajax/
You can bind your button to a JavaScript function which can then fire AJAX, grab the result of your other PHP page and display to the user in a .class or #id in the HTML, without leaving the current page.
If the behaviour your looking for is more advanced and "app like" you can also consider entire MVC JavaScript frameworks such as Backbone.js or Ember.js
The best thing you could possibly do is use jquery/javascript and manipulate a div (or the iframe) to where it navigates to X link when interacted with. You can actually change the url of an iframe using jquery and have it re-load to any url that you want. Reload an iframe with jQuery is a good example of how to do that. And for interacting with and digging through the contents of an iframe, instead of just changing the attributes of it, take a look at http://developer.vimeo.com/player/js-api.
Do keep in mind that the 2nd link is for a media player, BUT it still shows (and in a very simple way) how to interact well with iframes. You could use jquery to insert an id or class to the links in the page originally loaded into the iframe, then have the script on the 'parent page' navigate the iframe to one of the links when it's clicked. Just toy around with it some and have fun with it; a learning experience doesn't always have to be like a personal hell. I'll check back later and see how things turn out!
To do this you must understand what you are dealing with.
The *.php page loaded into user's browser is a processed and parsed page.
This parsing occurs at the server-side, and processed by the PHP processor on the server.
Now, after a *.php file is processed any interaction with it is lost. The only thing a user (client-side) sees is the result of this processing. Hence, to communicate with this page an information must be sent.
Normally, browsers send information on requesting a page. That is how the HTTP protocol works.
Since the user is the client-side, he must send relevant information (headers, variables, etc.) by the rules of the protocol. This means, a user must request the page and by this request the data will be sent.
AJAX technology allows you to open an HTTP request dynamically, on the background, while the page is still running with no need to refresh. It sends the relevant data according to protocol's convention and allows you to trigger a callback function to handle the answer when it arrives from the server.
Here you can find a beginner's tutorial, that will provide the necessary information for you to start.
P.S.
I would strongly recommend you not to use common external libraries like jQuery, node.js, Backbone.js etc. at the beginning. These libraries are tools that were created to simplify code writing for advanced developers. They may confuse you and mess up your programming logic and learning path.
Good luck!
Sounds like you want new content to appear on the page, without the user being directed to a new page. You can achieve this with jQuery. This is a quick example.
HTML:
<p>
Page 1 Page 2 Page 3
</p>
<div>
<div id="content1">
This is page 1.
</div>
<div id="content2">
This is page 2.
</div>
<div id="content3">
This is page 3.
</div>
</div>
jQuery:
$('#content2, #content3').hide();
$('a').click(function() {
var id = $(this).attr('id');
$('#content' + id).show().siblings().hide();
});
Live Example: http://jsfiddle.net/VxZKs/1

Bot friendly ajax page

I'm trying to code a seo friendly ajax portfolio right now. My goal is to provide javascript effects to users and normal html to bots/users without js.
Files:
index.php (starting point of my program)
aboutme.php (contains html code for "about me")
contact.php (contains html code for "contact")
The idea:
User visits index.php and clicks on "About me" -> loading animation appears -> aboutme.php gets loaded with ajax -> history.pushstate rewrites the url to aboutme.php.
-> When the user shares the current website url on fb/twitter/g+ the bots will get the correct title, body etc., as it is the normal html page without any javascript.
But my problem is: If other users open that page, they see directly the content. But I want to show them a loading animation first until the data got loaded with ajax (similar as they click on a link).
How can I achieve such an approach? Thank you very much!
Best way to do this, create a javascript file. Write the link tag into "head" part. This will make the javascript file downloaded before content. Javascript shows the animation, but at the same time browser will be downloading the content already in the background. On "document ready" event, stop animation.
This will let bots to access the content directly. Because javascript won't work for them.
To make your ajax content crawlable see https://developers.google.com/webmasters/ajax-crawling/, Bing supports this as well. Or use the HTML5 pushState, see http://www.seomoz.org/blog/create-crawlable-link-friendly-ajax-websites-using-pushstate, https://github.com/blog/760-the-tree-slider etc.
I've always thought this is more effort than its worth(generally), but to answer your question:
index.php, aboutme.php, contect.php should deliver full html.
certain links should have js event handlers intercept the click, and instead of loading aboutme.php, they load aboutme-content-only.php in the background. then update the dom and push state etc...
this way the site can easily degrade for those users who are first time visitors, as well as those whose browsers dont support push state or javascript.
I think that it is not a problem at all, keep your href of links as usual, then using JavaScript or jQuery change the default behavior of clicking link to load the linked contents with ajax.

Make a #-tag javascript link word for non javascript

Using the following tutorial I want my website to use AJAX to load the content (but also want to be able to use the back button etc. etc):
http://www.queness.com/post/328/a-simple-ajax-driven-website-with-jqueryphp
Ofcourse if someone has javascript disabled the website should also work (without Ajax).
The problem however comes when a javascript enabled user sends a link to a non javascript enabled user. Because javascript is disabled it will not handle the #-tag correctly and will just go to the homepage (so linking directly to pages from a javascript user to non-javascript user is impossible). Is there a way to resolve this issue (preferably php or htacces).
HTML5 gives us methods to alter the URL without refreshing the page https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history#Adding_and_modifying_history_entries
This means you can update something without a page refresh but still give the user a url they can bookmark or send to someone else. These urls will work without JavaScript, as long as you have pages at those locations or are catching them with mod_rewrite or similar.
https://github.com/browserstate/history.js is a great little pollyfill which will use the HTML5 history stuff if the browser supports it, otherwise (Internet Explorer) it changes the hash of the url.
Basically, three steps:
code your "a" tags just normal: <a href='about'>About us</a>
in your javascript code, intercept all click events on <a> tags and navigate to # + this.href. So when they click the above url, you navigate to site.com/#about instead of site.com/about
in your javascript code, have a timer function that reads the hash value form the current location and loads a corresponding url (with # removed) via ajax
Since you code your html just as usual, the site remains fully accessible for non-js users, and, more important, for search engines' bots.
In response to the comments I can suggest the following:
redirect your home page via javascript from just site.com to site.com/js/
when <a href='about'> is clicked, navigate to site.com/js/#about
on the "js" page, have something like <a id=about href="/about">click here</a> for non-js users
Why not just build your application normally and then add the AJAX on top, rather than going the other way round and causing more work for yourself?
Ask yourself, why do you need AJAX page transitions? Does your app actually need them, or is it just because you've seen it on another site, like Twitter?

Stop or interrupt php script for particular time

Can I Stop or interrupt PHP script for particular time?
I would like to implement logic like below:
on mydomain.com/index.php there will be flash appear showing some intro of a product for suppose 20 sec. Once it complete, on same index.php page the home page of site will appear.
I am not aware about flash (action script).
Is it possible in PHP or Javascript ?
Usually "splash pages", as the're called, are made up of a seperate page.
In flash you can use the following code (Actionscript 3). Put it int the last frame, or use an event listener to redirecrect when the file is finished. The actual redirect looks like this:
getURL("http://www.woursecondpagehere.com", "_self")
Where you place it is up to you.
EDIT: I think that this is a reliable solution because this guarantees (if implemented correctly) that the page won't move until Flash is done. CSS and Javascript will work fine too.
There isn't a need to interrupt PHP in the scenario given. Though I think what you want is to load the rest of the HTML after a certain event occurs.
If thats the case then you can use AJAX to load the additional HTML from the server. Or you can use CSS to hide that content and show it after a certain point.
The META Refresh tag is probably not what you want since it will redirect the user after 20 seconds, regardless of how long it took to load your Flash file, then play it. Since the speed of the user's connection cannot be reliably predicted, you will probably end up with a poor user experience.
What you want to do is definitely possible but it will involve some interaction between the Flash object and the rest of your page. If you could do as Moshe suggested and simply have the Flash object redirect the user's browser to your actual home page with content on it, that would be easier.
If you insist on keeping everything on the same page, one way to do it is to call a Javascript function from the Flash object once it's finished playing. The function you call should be written to hide the Flash object and/or it's container and display the container () with all of your content that you're ready to show.
See this Codefidelity blog post for a quick tutorial on how to call JS functions from Flash.
Also, to clarify, you won't be interrupting or changing when your PHP script runs. That runs on the server before the page is created and sent back to the user's browser. All you need to do is structure the HTML/CSS of your page to have two DIVs: one with the Flash object in it and the other with all your normal page content. However, set the CSS to only show the DIV with the Flash object, then finally use Javascript to hide that DIV and show the one with the content in it.
Try this,
write the your flash (splash screen) <embede> code in index.html and simply use javascript redirect function with javascript timer functions to redirect to index.php where you actual content is there.
something like...
window.location = "http://your.domain.name/index.php"
or
location.href = "http://your.domain.name/index.php"
use setTimeout() to call redirect after specified time.

Categories