PhpRiot
Download This Article
Download this article in PDF format with all listings and files.

Price: $5.00 AUD
(Approx. $4.10 USD)

More information
Browse Articles
Ajax (4), APC (1), CAPTCHA (1), CSS (3), Debugging (1), File Upload (1), Google (3), Google Maps (2), JavaScript (12), JSON (2), MVC (1), MySQL (7), onbeforeunload (1), OOP (1), PHP (28), PhpDoc (1), PostgreSQL (6), Prototype (11), Reflection (1), RFC 1867 (1), Robots (1), Scriptaculous (1), SEO (1), Sessions (1), SimpleXML (1), Smarty (5), SOAP (1), SPL (1), Templates (2), W3C (1), XHTML (1), Zend Framework (1), Zend_Search_Lucene (1)

PhpRiot Newsletter
Your Email Address:

An Introduction To PHP Sessions

How Can I Send Headers Then Start A Session?

Earlier we mentioned that you cannot send anything to the browser before session_start(). This is because when you set a header, you cannot do it twice. When you send text to the browser, headers are sent also.

However, PHP does provide a method to set headers, send text, and still be able to start your session. The ob_start() function allows you to buffer your output till you are ready to send content to the browser.

Listing 24 ob.php (listing-24.php)
<?php
 
  // make it or break it
  error_reporting(E_ALL);
 
  // begin output buffering
  ob_start();
 
  // send a header
  header ("Pragma: no-cache");
 
  // send some text to the browser
  echo 'This is a line of text';
 
  // then we start our session
  session_start();
 
  // set the value of the session variable 'foo'
  $_SESSION['foo']='bar';
 
  // flush the buffer
  ob_end_flush();
 
?>

Run this snippet of code and it will output the text

Listing 25 Browse output from using output buffering (listing-25.txt)
This is a line of text

First we sent a header with the no-cache, then echoed some text and finally started a session and set a session variable.

In This Article


Tagged in ,