Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the role of ob_start() in here

Tags:

php

session_start();
ob_start();
$hasDB = false;
$server = 'localhost';
$user = 'user';
$pass = 'pass';
$db = 'acl_test';
$link = mysql_connect($server,$user,$pass);
if (!is_resource($link)) {   
    $hasDB = false;
    die("Could not connect to the MySQL server at localhost.");
} else {   
    $hasDB = true;
    mysql_select_db($db);
}

a) what does ob_start() exactly do.? i got to understand it will turn output buffering on. with reference to the above code what will be the benefit if i use ob_start() while trying to establish the connection with the database. what output data it will buffer?

thank you..

like image 409
Ibrahim Azhar Armar Avatar asked Dec 21 '10 08:12

Ibrahim Azhar Armar


3 Answers

Normally php sends all text not included in <?php ... ?>, all echos, all prints to the output. Which is send to the err... output: http server (which sends it to a client), console etc.

After ob_start this output is saved in output buffer, so you can later decide what to do with it.

It doesn't affect db connection. It deals with text (mostly) produced by php.

like image 68
royas Avatar answered Sep 27 '22 17:09

royas


Some PHP programmers put ob_start() on the first line of all of their code*, and I'm pretty certain that's what going on here.

It means if they get halfway through outputting the page and decide there's an error, they can clear the buffer and output an error page instead. It also means you never get "couldn't sent headers, output already started" errors when trying to send HTTP headers.

There are a few legitimate reasons to do this, but I'd take it as a sign that they are mediocre programmers who don't want to structure their code in a coherent order - i.e. they should be working out if there are errors or headers to send before they start rendering the page. Don't copy this habit.

(* What makes this an easy habit to fall into is that if output buffering is still turned on when the script end is reached, the buffer is sent to the user, so they don't need to worry about a matching end statement)

like image 30
grahamparks Avatar answered Sep 27 '22 17:09

grahamparks


first of all buffering is usefull for putting http-headers (header function) at any line of code. eg - session cookies. without ob_start you would not be able to add any http-header to response if you already sent some data, e.g. with echo or print functions

like image 44
heximal Avatar answered Sep 27 '22 18:09

heximal