How do you keep a session alive through multiple output buffers and Gzip?
I recently realized that my modification to my website has caused sessions to stop carrying between page reloads. After doing a little investigating, I noticed this line in the session_sta开发者_JAVA技巧rt()
manual at PHP.net:
If a user uses ob_gzhandler or similar with ob_start(), the function order is important for proper output. For example, ob_gzhandler must be registered before starting the session.
The problem is, I call session_start()
very early on in my page. I thought maybe adding the Gzip handler at the beginning, but that won't work because I open and clean several output buffers throughout the process of script execution (usually 3 or 4 per page load). At the end of the page, I combine all the buffers by inserting them into each other and filling in data then open a final output buffer with Gzip handler and echo the final result to the page. Now the question: How can I continue to accomplish the Gzip compression through PHP and keep sessions working on the side? I tried just reopening the session again after opening the final output buffer but that had no effect. Opening an additional output buffer at the beginning just causes a content encoding error at the browser. Any ideas?
Here's a very simplified snippet of code for visualization. Sorry, my code spans over several pages of lengthy coding, so I can't paste everything.
session_start(); // The session is started early on for data
...
ob_start(); // Start an output buffer
echo "some content here"; // Some stuff is processed and sent
$data = ob_get_clean(); // That data is stored for later
...
ob_start(); // Another output buffer is started
echo "some other stuff"; // Different content for another piece of the page is sent
$moredata = ob_get_clean(); // That data is also stored for later use
...
ob_start(); // Another output buffer
echo $data.$moredata; // The data so far is more or less "combined" into the final template
$final = ob_get_clean(); // All of this is stored for final output
// Some other final touches are made to the final data here
ob_start("ob_gzhandler"); // Start the Gzip handler
echo $final; // Send the final output
Grab the session id after calling session_start()
with:
$id = session_id();
Then, at the end of your code, reconstitute the session using:
session_id($id);
精彩评论