为什么我们在网页中的任何其他内容之前调用session_start()? [英] Why do we call session_start() before any other content in the web page?

查看:174
本文介绍了为什么我们在网页中的任何其他内容之前调用session_start()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么我们要在网页中的任何其他内容之前调用session_start()?

I want to know why do we call session_start() before any other content in the web page?

推荐答案

让我尝试描述一下HTTP协议的工作原理.

Let me try to describe, how HTTP protocol works.

来自浏览器的请求如下:

Request from browser looks like this:

GET /somefolder/somescript.php HTTP/1.1
Host: www.yourhost.com
Connection: keep-alive
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
User-Agent: Your_Useragent
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp;q=0.8
Referer: http://testreferer.com/
Accept-Encoding: gzip, deflate, sdch, br
Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4,bg;q=0.2
Another-Header: Value1
Another-Header1: Value2

服务器发出的请求几乎是这样的:

And request from server looks almost like this:

HTTP/1.1 200 OK
Cache-Control: max-age=21600
Strict-Transport-Security: max-age=15552000; includeSubdomains; preload
Content-Security-Policy: upgrade-insecure-requests
Some-Other-Header: Value1
And-Another-Header: Value2\n\n
<YOUR WEBPAGE CONTENTS>

因此,第一台服务器最后发送标头和\n\n,然后才开始发送网页内容. 但是session_start()正在发送它自己的"标头,但是当它们已经完成发送时,您将无法发送任何标头!

So first server is sending headers and \n\n in the end, and just then starting to send your webpage contents. But session_start() is sending "it's own" headers, but you can't send any headers when they're already finished sending!

示例:

<?php
Header("SomeCoolHeader: Value1"); //Sending custom headers
session_start(); //Sending session header
Header("AnotherHeader: Value2"); //Sending custom headers

echo "Some text"; //Header sending automatically finished and sent some html text
?>

示例2(有错误):

<?php
Header("CustomHeader1: Value1"); //sending custom headers

echo "Some text"; //Header sending automatically finished and sent some html text

Header("CustomHeader2: Value2"); //Cannot add header information - headers already sent
?>

示例3(有错误):

<?php
Header("CustomHeader1: Value1"); //sending custom headers

echo "Some text"; //Header sending automatically finished and sent some html text

session_start(); //Cannot add header information - headers already sent
?>

如果您还有任何问题,可以在评论中问我.

If you're still have any questions - you can ask me in comments.

这篇关于为什么我们在网页中的任何其他内容之前调用session_start()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆