Page 1 of 1

Best Way to Clear All HTML From Current Page

Posted: Fri Jul 04, 2014 8:19 am
by chris98
I'm working on exceptions for my site, and if an exception occurs, no matter how far down the page it is in my PHP code, I'd like to completely remove all HTML above from the page without redirecting the page. Is this possible? And how?

This is the kind of thing I have so far, I really have no idea how I could make this go away:

Code: Select all

<?php include '******.php';
require_once('/home/********.php');
ob_start();
$test = 'tets';
include '**********.php';
try
{


	$sql = "SELECT 1, 2 FROM table WHERE column = :id";
	$ps = $shn_conf->prepare($sql);
	$ps->execute(array(':id'=>$test));

}
catch(PDOException $e)
{
	error_log($e);
	error_msg();
}


echo "completed script!";
ob_flush();
In my error_msg() function, I have exit; at the end to stop any further script, but how can I get rid of the HTML at the start of the script without redirecting the page?

error_msg()

Code: Select all

function error_msg()
{
	ob_end_flush();
	ob_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta name="ROBOTS" content="NOINDEX, FOLLOW" />
   <title>Database Error</title>
   <link href="http://*********/css/database.css" rel="stylesheet" type="text/css" />
</head>
  <body>
      <div id="main">
        <div id="formheader"><h2>Database Error</h2></div>
        <div id="formbody">
            <table align="center"> 
              <tr><td colspan="2">The server encountered a database error and was unable to complete your request, please reload this page in a few seconds. <br /><br />If the error persists contact the <a href="MAILTO:<?php echo $_SERVER['SERVER_ADMIN'] ?>">server administrator</a> and inform them of the time the error occurred, as well as anything you might have done that may have caused the error.
<br /><br />More information is available in the server error log.</td></tr>
            </table>  
          </form>
        </div>
      </div>
  </body>     
</html>
<?php
	ob_flush();
	exit;
}

Re: Best Way to Clear All HTML From Current Page

Posted: Fri Jul 04, 2014 2:29 pm
by Christopher
In general, you want to gather the output into a Response variable or object that is displayed at the very end of the script. That way you can short-circuit the page output.

Re: Best Way to Clear All HTML From Current Page

Posted: Fri Jul 04, 2014 6:36 pm
by requinix

Code: Select all

function error_msg()
{
   ob_end_flush();
That ob_end_flush() will output everything in the buffer. If you don't want that then use ob_end_clean.

Re: Best Way to Clear All HTML From Current Page

Posted: Sat Jul 05, 2014 10:09 am
by chris98
ob_end_clean worked perfectly, thank you very much for solving that one!