PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 6, 2022

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

 July 06, 2022     buffering, ob-start, php, phpmailer     No comments   

Issue

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!


Solution

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.



Answered By - Synchro
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing