Coderbit
Coderbit

Reputation: 791

HTTP 302 error because of a header()

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???

Upvotes: 5

Views: 28347

Answers (3)

Rayhan Muktader
Rayhan Muktader

Reputation: 2106

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:

  1. delete all your cookies from your computer.
  2. Disable cookies in your browser and try loading your website.

Upvotes: 1

aleation
aleation

Reputation: 4844

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();

Upvotes: 1

Quentin
Quentin

Reputation: 943089

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.

Upvotes: 6

Related Questions