Bill Scheurer
Bill Scheurer

Reputation: 143

Redirect: Header vs. Script - How do they differ?

Facebook examples show two different methods for redirecting a user's browser.

Script: echo("<script> top.location.href='" . $next_url . "'</script>");

Header: header("Location: $next_url");

I have noticed some differences in behavior between them, but do not have enough knowledge of HTTP theory to understand these differences and know which one to use for different cases.

I have a basic sense that the header approach is more of a "hard" call to another page with a clean refresh, and the script approach is closer to a "soft" call (like Ajax) that may work on top of and within the existing page that makes the call.

Can someone give (or point me to) a good explanation of the differences between them, with examples of suitable use cases for each approach? Thanks!

Upvotes: 2

Views: 884

Answers (1)

Pekka
Pekka

Reputation: 449613

This probably has a duplicate somewhere, but I can't find it right now so...

A header() redirect takes place before any page data is output. As the name says, the browser makes a request for a page, and the page's response headers contain the instruction to go to a different address. The browser will usually immediately do so.

A JavaScript redirect takes place inside an already loaded page.

If at all possible, you want to use a header redirect because it makes the browser go to the new resource straight away, without having to render the intermittent page first. Also, it works for clients that have no JavaScript enabled.

Upvotes: 4

Related Questions