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

Time:03-09

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!

CodePudding user response:

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.

  • Related