Im using PHP to track the clicks of all mailto links by rewriting the mailto: to my script and then setting the header of the referring page.
Initially I just had:
header("location: mailto:email#address.com");
...but this has an undesirable effect in IE8: it opens 2 email windows. So, in my attempt to resolve that issue I am now using:
header("Status: 200");
header("location: http://mypage.com");
header("Refresh: 0; url=mailto:email#address.com");
This works fine in IE but not chrome. I threw the "status" in there hoping to solve the mystery.
Other than detecting the browser and issuing different commands, what else could one do?
A location header should be accompanied by a 30X status code (like 302), not 200.
Check this out > http://php.net/manual/en/function.header.php
Especially those two parts:
The second special case is the
"Location:" header. Not only does it
send this header back to the browser,
but it also returns a REDIRECT (302)
status code to the browser unless the
201 or a 3xx status code has already
been set.
<?php
header("Location: http://www.example.com/"); /* Redirect browser */
/* Make sure that code below does not get executed when we redirect. */
exit;
?>
You send 200 and 302 at same time, and also you didn't follow the exit; rule.
You can play with my suggestions (especially the exit; part).
!!! Note !!! There was a bug in the past that makes the Chrome not to work if header("Status: 200"); wasn't set first, but not sure if it's fixed yet.
it would probably be better to use some AJAX to handle your problem here, and if your going to use AJAX use JQuery its just easier
firstly though mailto is not a preferred method on the web any more its too clunky and relies upon the default email client of the user being set up which in most cases you cannot rely upon.
So to address that have a link that is styled to look like your button.
once you have this use JQuery to send an ajax request to a PHP script that performs the counting and then if you wish upon receipt handle the success with a redirect (I only include that because I am unsure what your redirect achieves).
Its clean quick and the user will not notice a difference apart from your site will probably experience a speed increase :) hope this helps
Header location redirects the browser, so the other headers are ignored. You should send this header always as the last one. Also it's not good idea to execute any PHP code after you send the redirect.
You probably want to do this:
On first page:
header("Status: 200");
header("location: http://mypage.com");
exit();
On the http://mypage.com:
header("Refresh: 0; url=mailto:email#address.com");
The weird thing about chrome: it accepts the following header refresh.
<meta http-equiv="refresh" content="4; url=page.php" />
<button value="go further">
I place a button below this refresh for the browsers who does not support any type of header refresh.
Related
if I validate html or register web in any serch engine, I get 302 error.
The reason is a header() function. If I take it away, everything is fine with 200 OK status.
So the main problem is that I need this redirection for web to be multilingual.
The logic is next. When user enters the web page for the first time index.php - require_once a file with a function:
function cookies() {
if (!isset($_COOKIE["lang"])){
setcookie('lang','ukr', time()+(60*60*24*31));
header('Location: index.php');
}}
cookies();
so the user sees a page already filed with a deafault language.
If there would be no redirection from require_once file the data from mysql won't be downloaded and user won't see any text.
The question: should I leave this with HTTP 302 or rebuild the whole site/logic not to have any redirects at index page???
302 is not an error. It is the status code for "Found" (aka "The document you asked for is over here"). PHP will insert this for you automatically if you add a Location header (unless insert a status manually, but you don't want a 301 here)
This is the expected response if you are telling people to go and get a different document based on their language preferences.
It is odd to redirect from index.php to index.php though. Presumably you should just return the appropriate document directly instead of redirecting.
I got it. It's actually pretty simple.
The validators don't accept cookies. So they get stuck in a an infinite loop.
You can test this:
delete all your cookies from your computer.
Disable cookies in your browser and try loading your website.
Whenever You use header("location: .... you will get a 302, it's a status and not an error, it's telling the browser that the site has redirected the page:
http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
Read those validators and engines and see if having the 302 is a problem for whatever you are trying to do, normally it shouldn't be.
A dirty way would be to force the header, personally I don't encourage this and don't know what side-effects could it have really, but it could be a quick workaround to trick those engines:
function cookies() {
if (!isset($_COOKIE["lang"])){
setcookie('lang','ukr', time()+(60*60*24*31));
header('Location: index.php');
header('HTTP/1.1 200 OK'); // <--- Forcing the header status
}}
cookies();
using JS : (in <head> tag)
<script>window.location="https://stackoverflow.com";</script>
using PHP : (in <head> tag)
header('Location: https://stackoverflow.com');
end();
Which one I should use ? or another ?
and what about using <meta>?
<meta http-equiv="refresh" content="0;url=https://stackoverflow.com"/>
Many good answers , I don't know which answer I will accept, Thanks so much
The result is same for all options. Redirect.
<meta> in HTML:
Show content of your site, and next redirect user after a few (or 0) seconds.
Don't need JavaScript enabled.
Don't need PHP.
window.location in JS:
Javascript enabled needed.
Don't need PHP.
Show content of your site, and next redirect user after a few (or 0) seconds.
Redirect can be dependent on any conditions if (1 === 1) { window.location.href = 'http://example.com'; }.
header('Location:') in PHP:
Don't need JavaScript enabled.
PHP needed.
Redirect will be executed first, user never see what is after. header() must be the first command in php script, before output any other. If you try output some before header, will receive an Warning: Cannot modify header information - headers already sent
A better way to set the location in JS is via:
window.location.href = 'https://stackoverflow.com';
Whether to use PHP or JS to manage the redirection depends on what your code is doing and how. But if you're in a position to use PHP; that is, if you're going to be using PHP to send some JS code back to the browser that simply tells the browser to go somewhere else, then logic suggests that you should cut out the middle man and tell the browser directly via PHP.
It depends on how and when you want to redirect the user to another page.
If you want to instantly redirect a user to another page without him seeing anything of a site in between, you should use the PHP header redirect method.
If you have a Javascript and some action of the user has to result in him entering another page, that is when you should use window.location.
The meta tag refresh is often used on download sites whenever you see these "Your download should start automatically" messages. You can let the user load a page, wait for a certain amount of time, then redirect him (e.g. to a to-be-downloaded file) without Javascript.
PHP redirects are better if you can as with the JavaScript one you're causing the client to load the page before the redirect, whereas with the PHP one it sends the proper header.
However the PHP shouldn't go in the <head>, it should go before any output is sent to the client, as to do otherwise will cause errors.
Using <meta> tags have the same issue as Javascript in causing the initial page to load before doing the redirect. Server-side redirects are almost always better, if you can use them.
The first case will fail when JS is off. It's also a little bit slower since JS must be parsed first (DOM must be loaded). However JS is safer since the destination doesn't know the referer and your redirect might be tracked (referers aren't reliable in general yet this is something).
You can also use meta refresh tag. It also requires DOM to be loaded.
window.location.href = 'url';
is beter than
header('location:url');
because the header command is mustly return an error "Warning: Cannot modify header information - headers already sent"
using js window.location.href = 'url';
this is beter
I need to redirect users if I don't want them to be able to access a certain page. How reliable is header('Location: ../acc/login.php'); for example? Can browsers ignore 302 errors, and is this the right way? Thanks in advance!
It depends a lot what you're trying to do. Technically spoken, header() is somewhat reliable. Only somewhat, because many PHP users have problems with it and to not get it to work.
PHP will prevent it from working if output has been already send to the browser. A drastic example:
<protected page content here>
<?php
header('Location: login-first.php');
exit();
?>
This would not work at all. You would eventually see even an error message with a warning.
Headers - by design - need to be send out before any other content (response body). They can not be send any longer if the response body has already started and PHP can't help you then in that case.
However, if you send headers before the response body, that function will work. Also the risk obviously to mess something up is not that drastic any longer, too:
<?php
header('Location: login-first.php');
exit();
?>
<protected page content here>
You can rely on header(), but make sure you called die(), exit() or return after that. Otherwise, script will continue its execution, which is potential security issue.
The browser can ignore header('Location: '); forwarding.
That is why you should always return after a call to a header() forward so the rest of your code does not execute should the browser not honor the forwarding.
It is the correct way to do things tho.
I would send the header command and then the exit command "exit()" (to stop running the php code on the server) before displaying the rest of the page. This way the user would never be sent the page content even if they ignored the 302 redirection.
And yes the user can ignore the 302 redirection:
http://www.webmasterworld.com/html/3604591.htm
header is 100% reliable.
However header('Location: ../acc/login.php') will be evaluated in the browser to a real location on your website, and ../acc/login.php wil not form a url that is valid!
This is really weird.. I have the following redirect in a file:
header('Location: http://google.com');
It doesn't work. The page loads and the user is not redirected. However, if I add a die() statement below that line, like this:
header('Location: http://google.com');
die('what the heck is going on here?');
Then the redirect magically starts working!
I'm at a total loss as to why this is happening, and I have no idea how to debug it.
Can anyone give me any advice on this?
You are supposed to exit after sending a location header. Sending any header does not affect the flow of the script so any code after it still executes. If anything causes a different response status code to be set the redirect will not happen at all.
A Location header by itself does nothing - only together with the proper 30x response code it will cause a redirect. PHP sets this response code manually when sending a Location header but your code might modify it.
Probably your script isn't ending after the header call.. Make sure you end the script.
So I know the general rule of thumb is after doing a header redirect in PHP, you should call exit() to avoid having extra code running, but I want to know if you put code after the redirect header, if it will always run?
I was doing some research on various ways of tracking referrals in Google Analytics and came across this post: Google Analytics Tips & Tricks – Tracking 301 Redirects in Google Analytics
It recommends doing something like this:
<?
Header( “HTTP/1.1 301 Moved Permanently” );
Header( “Location: http://www.new-url.com” );
?>
<script type=”text/javascript”>
var gaJsHost = ((“https:” == document.location.protocol) ? “https://ssl.” : “http://www.”);
document.write(unescape(“%3Cscript src=’” + gaJsHost + “google-analytics.com/ga.js’ type=’text/javascript’%3E%3C/script%3E”));
</script>
<script type=”text/javascript”>
try {
var pageTracker = _gat._getTracker(“UA-YOURPROFILE-ID”);
pageTracker._trackPageview();
} catch(err) {}</script>
From the way I've always understood the header() function, it's up to the browser and it can run the redirect whenever it wants to. So there's no guarantee the JavaScript would actually begin or finish executing prior to the redirect occurring.
PHP's documentation for the header() function indicates the reason for exiting after a redirect is to "make sure that code below does not get executed when we redirect." That doesn't sound like they guarantee all following code will run, just that it could happen.
Regardless, I found a different way to actually manage the tracking, but I wanted to see if I could find out how exactly header() worked in this situation..
Thanks for your help.
Using the header function in PHP only adds to the headers of the response returned by the server. It does not immediately send any data and does not immediately terminate the connection. Any code after the header call will be executed.
In particular, it's a good idea to add a response body even after doing a 301 redirect so that clients that do not support the redirect also get some descriptive response. Infact according to the HTTP 1.1 specification Section 10.3.2 -
Unless the request method was HEAD, the entity of the response SHOULD
contain a short hypertext note with a hyperlink to the new URI(s). If
the 301 status code is received in response to a request other than
GET or HEAD, the user agent MUST NOT automatically redirect the
request unless it can be confirmed by the user, since this might
change the conditions under which the request was issued.
It's a race condition. Once the redirect header is sent to the browser, the browser will close the current connection and open a new one for the redirect URL. Until that original connection is closed and Apache shuts down the script, your code will continue to execute as before.
In theory, if there was a sufficiently fast connection between the client/server, and there was no buffering anywhere in the pipeline, issuing the header would cause the script to be terminated immediately. In reality, it can be anywhere between "now" and "never" for the shutdown to be initiated.
The HTML after your Location line doesn't run inside PHP; it would run in the browser. It's up to the browser whether or not to execute the Javascript that you've included on that page; PHP has nothing to do with it.
To me, the PHP docs imply that any PHP below the header() when you send a redirect will continue to run. But it 'runs' in the PHP interpreter, dumping JS to the browser. There's no relation between what it says in the PHP docs and whether or not the JS gets run by the browser.
EDIT:
Well, as Anupam Jain pointed out, looks like that browsers do not terminate connection without getting the response body and it sounds sensible. So i rethinked my answer
That doesn't sound like they guarantee all following code will run
Exactly More likely it's a warning in case there is some sensible code that shouldn't be executed. A private page contents for example. So, beside sending header you have to also make sure that no sensitive content were sent and exit looks like quite robust solution. So, I'd phrase it as "make sure that sensible code below does not get executed when we redirect."
So there's no guarantee the JavaScript would actually begin or finish executing prior to the redirect occurring.
Exactly It seems it has nothing to do with script execution but rather with browser's will to execute anything after getting 3xx response. I think I'm gonna test it, but you can test it as well too.
I have noticed that the code does still execute and multiple headers based on if statements can cause a "redirect loop error". i made it a habit to now add in die("Redirecting..."); after every header redirect and have not see the problem persist.