/    Sign up×
Community /Pin to ProfileBookmark

Why should session_start() and setcookie() be set before <html> tag?

I see everywhere note: setcookie() should be called before <html>

or session_start() should also be before any thing even line break & UTF-8 encoding doesn’t work for these functions.

  • 1.

    Is there any other way so that I can set cookie in code whenever I want?

  • 2.

    Are there any drawbacks of using session.auto_start in php.ini instead of using session_start() everytime?

  • to post a comment
    PHP

    2 Comments(s)

    Copy linkTweet thisAlerts:
    @Stephen_PhilbinAug 02.2007 — You have to use setcookie() and session_start() before sending any output because of the way the http works. Cookies (including session cookies) are sent in the headers of http requests and the headers of http requests come before the content of a web document. By default, PHP php starts, and then continues to send output (document content) as soon as it is found or generated my PHP.

    So obviously, if PHP starts sending document content, it has already sent the http headers. Once the headers are sent you can't rewind time to change the headers to add in cookie data and then resend the whole thing.

    You can get round this by using the [url=http://devzone.zend.com/manual/ref.outcontrol.html]output control functions[/url]: they allow you to control when output begins to be sent and so allow you to alter the headers of a request after output has been generated. Though, thinking ahead a little and planning your script can usually eliminate the need for bothering with any of that stuff.

    EDIT:

    Whoops. I forgot to answer your second question. The only drawback (that I'm aware of) to enabling session autostart is that you will be unable to use PHP5's __autoload() feature for automatically loading classes when using OOP.
    Copy linkTweet thisAlerts:
    @SH100authorAug 02.2007 — Thank you.
    ×

    Success!

    Help @SH100 spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 5.5,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @Yussuf4331,
    tipped: article
    amount: 1000 SATS,

    tipper: @darkwebsites540,
    tipped: article
    amount: 10 SATS,

    tipper: @Samric24,
    tipped: article
    amount: 1000 SATS,
    )...