Skip to content
Advertisement

What is the purpose of the ob_ functions in php? (ob_start(), ob_get_contents(), etc.)

I’ve read the PHP documentation, but it fails to give any practical examples.

I’m using some open source code, and it contains this email function. I’m trying to understand why these ob_XXX() functions are here and what they do (because I need to use PHPMailer instead of mail()). When I print the return value before the return, it’s always empty.

// Send using PHP mail() function
ob_start();
mail($to,$subject,$message,$headers);
$tmp = trim(ob_get_contents());
ob_end_clean();
return (strlen($tmp)) ? $tmp : true;

I understand that it’s something to do with output buffering, and while I have some idea of what buffering is, I’m not sure why it is being used here. Thanks!

Advertisement

Answer

If you say this in PHP:

echo 'Hello';

it will result in the string Hello being sent to the browser more or less immediately. This is fine in contexts where you’re outputting stuff directly, but sometimes you want to use that workflow, but capture the output instead of sending it to the browser. So instead, you can do this:

ob_start();
echo 'Hello';
$tmp = ob_get_contents();
ob_end_clean();

This will result in nothing being sent to the browser, but $tmp will now contain Hello.

This is useful in email because what you might want to do is render a template to a string, and then use that as an email message body rather than sending it to a browser.

With PHPMailer, you might use that workflow to create a message body, and then pass it to PHPMailer:

$mail->Body = $tmp;

The example you posted is a bit strange, because the mail() function doesn’t typically output anything anyway, so it will capture nothing.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement