Vonder
Vonder

Reputation: 4059

Page redirection method - Javascript or PHP?

Which way of redirecting from one page to other is more reliable? I need to to have a link that bring the user to blank page where some php code is executed first(in the background) and then it redirects to the target page. I would like to make this seamless, so the user is not aware that he was redirected. I used javascript for that and it worked fine, but with Javascript disabled it simply won't work. Will php redirection work in this case? Can the header() function be used after some other php code has been executed? All advice appreciated.

Upvotes: 1

Views: 885

Answers (5)

Platinum Azure
Platinum Azure

Reputation: 46193

Why not use AJAX to call a script that processes data, and then when that AJAX is complete you can redirect to the external page?

If all your first script does is calculate data and redirect, without returning any real content, then there's not a lot of point in forcing the page to be synchronously loaded and displayed with a normal HTTP request. I assume you are allowed to use JavaScript since that's in your question.

Upvotes: -2

zzzzBov
zzzzBov

Reputation: 179176

yes you can execute code with PHP before a redirect. Just be certain to use the right HTTP status code for the job. (I assume the default 302 will be appropriate, but you never know.)

This method will alert the client's machine of the redirect, but tends to be seamless enough that the average user wont notice.

Upvotes: 0

Peter Porfy
Peter Porfy

Reputation: 9040

PHP redirection will work if you didnt send any output before the header. But yes, its easy to notice that you are redirected.

Upvotes: 0

profitphp
profitphp

Reputation: 8354

Yes, header can be called after you run php code, just be sure you don't output any text. Then send a location header.

Upvotes: 2

Jon
Jon

Reputation: 437544

Redirecting from PHP with header('Location: '.$URL); die; is the most dependable redirect you can do (since it works at the HTTP level).

The only catch is that you cannot redirect this way if you have produced any output already. This is something that you can avoid by simply thinking through your code flow and designing appropriately, but if push comes to shove you can shoehorn it into an existing code base by utilizing PHP's output buffering capabilities (basic example here).

Upvotes: 4

Related Questions