tuespetre
tuespetre

Reputation: 1887

PHP header not keeping query string

I have a strange issue. It almost seems like a bug.

if ($object->error) {Form::BuildReturn(); header ("location:$url");}

Now if I echo the value of $url, I get the correct value: /projects/view/112/?edit-note=105

But when the script executes, it takes me to /projects/view/112/.

Here's the weird part though: I can try to echo or print something right after the header and then it will take me to /projects/view/112/?edit-note=105 like I want it to. Example:

if ($object->error) {Form::BuildReturn(); header ("location:$url"); echo 0;}

I've tried searching this for about half an hour now using terms like 'PHP header query string', 'PHP header get values', and so on. I hope there is some actual solution to this rather than using a hacky workaround that generates 'cannot modify header information' warnings...

Upvotes: 0

Views: 2846

Answers (5)

dotoree
dotoree

Reputation: 2993

You could use a redirection function with meta tag. That will keep query string

function redir($url, $time = 0) {
  echo '<meta http-equiv="refresh" content="', $time, ';URL=', $url, '">';
  die;
}

Upvotes: 0

Madara&#39;s Ghost
Madara&#39;s Ghost

Reputation: 174997

You should always exit after you pass a Location header, to prevent the rest of the page from showing. Also, it should fix your problem.


Also, the correct form of the Location header would be:

header("Location: $url"); //Has space and capital L

I don't think it would matter really, only for older browsers maybe?

Upvotes: 1

James C
James C

Reputation: 14159

The correct syntax is:

header("Location: $url");

There's a space in there and a capital L, I'm not sure that'll make much difference.

For the moment I'd suggest doing some low level debugging. Use wget, curl, the developer mode in your browser or a plugin that will echo all of the HTTP headers and then post up exactly what's being returned in the server headers (if the results don't allow you to figure it out anyway).

Upvotes: 1

Raj
Raj

Reputation: 22946

Add

exit(0);

after the header for the redirect.

Because the code continues to run even after the header call. You need to explicitly exit the script for the redirect. This is discussed more here.

Upvotes: 2

Dion
Dion

Reputation: 3345

Try adding exit; after redirecting. That stops executing the current file.

Upvotes: 2

Related Questions