Redirect to page and send custom HTTP headers

2019-01-20 02:40发布

I use the following code to redirect to a page in PHP. I need to set a custom HTTP headers to pass along with the redirect.

header("Location: http://...");

How can I archive this?

3条回答
手持菜刀,她持情操
2楼-- · 2019-01-20 03:30

Just add additional header() calls after or before this one.

header("Location: http://...");
header("Content-Type: text/plain");
查看更多
叛逆
3楼-- · 2019-01-20 03:37

I'm afraid, all the answers are wrong and misleading!

It's impossible to redirect to a page with custom headers set, no matter what language or framework you use. In other words, there's no way to trigger an HTTP redirect and cause the client (browser) to add a custom header.

You might be thinking that using multiple header() calls should work just fine. But it won't. You're setting the custom headers for the response which is instructing the browser to redirect, not for the redirect itself.

The only way for a site to instruct a browser to issue an HTTP request with a custom header is to use Javascript and the XMLHttpRequest object. And it needs CORS implemented on the target server to allow such ajax requests.

Please note that a page can not set HTTP request headers unless it's making an async request using XMLHttpRequest. Meaning that you can't do such redirection with the custom header on the client-side as well.

That's not how the web works.

查看更多
smile是对你的礼貌
4楼-- · 2019-01-20 03:41

Multiple headerDocs calls:

header("Location: ....");
header("Header2: ....");
header("Header3: ....");
...
查看更多
登录 后发表回答