What is the difference between PHP header and Javascript window.location? - php

So yeah this came to mind randomly when I was teaching someone how to redirect their page. I wasn't really sure what the main difference was... Is there a reason you would use one over the other? I guess if you are not coding in PHP, you would have to use the Javascript window.location to redirect but would you ever use window.location over PHP header if you were developing in PHP? I feel they have very similar functions but perhaps I am missing something.

The browser will process the header redirect right away, whereas the Javascript redirect will not be executed until the page has loaded (or at least enough of it to run the Javascript). Also, it will be the Javascript engine executing the redirect instead of the browser itself.
Doing it via the header will perform better. (slightly anyway...)

PHP's server-side header can send other headers then only Location. Javascripts client-side window.location can be used to read, inspect, and alter (parts of the) current url, including hash. Really, they can do quite different stuff, and about their only overlap is both being able to redirect.

Related

PHP Prevent Direct Access

Is there any possible way to make direct browser access to
http://www.example.com/test.php
Not available when viewing url directly but still allowing
JQuery $.get('http://www.example.com/test.php') function
To read the file? I know this might not be possible because I believe going in my browser and typing http://www.example.com/test.php is basically the same thing on client side as using the $.get() function.. But I didn't know if there was any work arounds for this.
Kinda, have php check for the x-requested-with header. If it is not present, redirect somewhere else.
It doesn't stop someone from sending their own request with said header though.
You are right, using a browser or $.get are basically the same. The only difference is that an AJAX call sets the X-Requested-With header to XMLHttpRequest. This can be added with browser extensions, though, so it is not fool-proof.

Execute php function on user event without using javascript

I assume the answer is: "it is not possible because php is server language not client language", but I would like someone more expert than me to state this and eventually list all possible workarounds...
Question: is it (at all) possible to have a php function executed (only) when the user "clicks" or performs some other kind of action (e.g. mouse-over) in an html page without using any javascript?
(P.S. As a workaround I considered to access an intermediate page containing the php code to be executed when the client action occurs and then redirect as needed but this is not straightforward as far as passing the results of the php code goes.)
In general no. The only workaround regarding mouse-overs I can possibly think of would be a small 1x1 transparent background image that is generated by a PHP script and that is only shown if a user hovers over a certain element.
html:
<div id="mouseover_php">execute php</div>
css:
#mouseover_php:hover {
background-image:url(/path/to/php-script)
}
php:
<?php
// your code
// set http headers to correct content type and to disable caching
// output 1x1 pixel transparent image
But as all modern browsers use pre-fetching and caching (although this can be influenced by setting the Cache Control header) I certainly would not rely on this as an unquestionable indicator for a mouse-over event. So this would be, if anything, a very unclean hack.
Regarding clicks: Here the only possible way is to load an intermediate page, just as you proposed it. As far as I am concerned there is no way to achieve this without AJAX.
This is not possible without making a new request.
You must use a link to send the user to a new page (or the same page -- anything as long as a new request is made), or you must use something like AJAX.
There is actually one very hack-ish way I can think of. It's not exactly pretty, but it should work.
You could use an iframe as the target for a link. Basically instead of a link opening in the same or a new window, it would open in a hidden iframe.
Untested, but in theory:
<iframe name="testframe" id="testframe"></iframe>
Test
Edit: After some rough testing, it looks like chrome will not obey this. IE9 will to some extent though, it seems.

have difficulties using usleep();

I have this:
echo "<font color=\"#000000\">text</font>";
usleep(2000000);
header("location:/otherpage.php");
?>`
Please note that this will be included in an iframe...
The problem is that it isn't echoing the echo statement, but then sleeping for two seconds and then redirecting (which is all correct except for the echo part)...
Anyone have an idea why this is happening?? It's not the iframe because when you go straight to the file (separately from the iframe) the same happens. Could it be the usleep??
Thanks
What you are doing above will not work. First, you would need to do a flush in order to make sure the data was sent. Second, though, and more important, you can't change the header after the flush, which would result in either the header not being sent or the text not being sent.
If all you want to do is change the data after a delay, did you consider doing the following:
header('Refresh: 2; url=http://my.site.com/otherpage.php);
echo "<font color=\"#000000\">text</font>";
This will send the information in the browser, instructing the browser to change to the new URL after 2 seconds.
This won't work since you can't change the header after outputting text.
The only option is to use a meta refresh or javascript when you want to exact replicate this behaviour.
But the output problem you can solve by flushing the buffer but then no redirection is possible as i mentioned before.
Another very important thing is:
DONT USE USLEEP FOR SUCH THINGS.
Why? Because when your script is heavily loaded every request which needs too much time is very bad and you will run out of php threads (depending on your php webserver implementation). So, for such timeouts you should use clientside code (if possible).
It's sleeping while on the server, and then sending the output. Also you can't send headers after echoing something.
You should use javascript or a meta redirect, this will allow you to wait a few seconds before redirecting, and the time and url for both of those can be generated by your php script.
You can't to that. I have a feeling you're misunderstanding the purpose of PHP and it's role as a server-side language.
If you want to "redirect" to another page in PHP, you do so using HTTP headers, which you did. The thing is, those are the headers, so they must be sent before any text body (like an echo statement). You're trying to do something that should be done client-side on the server.
Instead, make an HTML page with some JavaScript code to do the redirection, like that:
<script>
setTimeout(function() {
window.location = "otherpage.html";
}, 2000);
</script>
Expanding my comment into an answer:
It's not possible to redirect like this (outputting some content and then trying to send in a header) because headers must be sent before all content. PHP will also complain about this, using default settings you should see a warning.
Second, the usleep delay might not be observable due to the server buffering the content throughout the sleep and only sending it in one big chunk afterwards. In general, it isn't reliable to make the browser display content "in steps" like this, although it can be made to work more or less if you pile the hacks high enough.
May I suggest that if this kind of behavior is what you need, you should look into making a (series of?) appropriate AJAX call, which can be orchestrated perfectly.
What everyone else said. Just adding that usleep() will make clients hold connections open on your server---it's a very inefficient use of limited server resources. Your PHP should always send everything it can as quickly as possible so your web server can close the connection.

Is it better to echo javascript in raw format with php, or echo a script include that has been minified and gzipped?

Hey guys quick question, I am currently echoing a lot of javascript that is based conditionally on login status and other variables. I was wondering if it would be better to simply echo the script include like <script type="text/javascript" src="javascript/openlogin.js"></script> that has been run through a minifying program and been gzipped or to echo the full script in raw format. The latter suggestion is messier to me but it reduces http requests while the latter would probably be smaller but take more cpu? Just wondering what some other people think. Thanks in advance for any advice.
I would go the first option, even though its an extra request it means the html/php page will be smaller. Also, it is my understanding once the Javascript is cached it won't be requested again whereas the html/php page will be requested every time.
Depending on your javascript functionality you could also add the async="true" to the script include to ensure the page is downloaded first then the javascript.
Include it externally (your first option). Then when you're doing javascript maintenance, you're not doing it inside PHP as well.
Including the raw text is preferred if you do not expect the page loads per user to go much beyond 1. If you expect your users to request your page multiple times, then the external, cacheable include is the right option. This is usually the case.
Echo the script include so that the javascript in in an external file and then the browser's cache can do it's job.

Taking a hashed URL and sending it to a new URL

For example, I'd like to have my registration, about and contact pages resolve to different content, but via hash tags:
three links one each to the registration, contact and about page -
www.site.com/index.php#about
www.site.com/index.php#registration
www.site.com/index.php#contact
Is there a way using Javascript or PHP to resolve these pages to the separated content?
The hash is not sent to the server, so you can only do it in Javascript.
Check the value of location.hash.
There's no server-side way to do it. You could work with AJAX, but this will break the site for non-javascript users. The best way would probably be to have server-side content URLs (index.php?page=<page_id>) and rewrite these locally with JavaScript (to #<page_id>) and handle the content loading with AJAX then. That way you can have your hash-URLs for JS-enabled devices and everybody else can still use the site.
It does however require a bit of redundance because you need to provide the same content twice, once for inclusion via AJAX and once with the proper layout and everything via PHP.
If you just want hash URLs for aesthetic reasons, but don't want to rely on JS, you're out of luck. The semantics of URLs are against you: fragment IDs shouldn't really affect the content the URL is referring to, merely the fragment within that content. AJAX URLs are changing those semantics, but there's no good reason to do that if you don't have to.
I suppose you probably have a good reason, but can I ask, why would you do this? It breaks the widely understood standard of how hashs in URLs are supposed to work, and its just begging for trouble for interoperability with other clients, down the road.
You can use PHP's Global $_REQUEST variables to grab the requested URL and parse out the hashtag...

Categories