Format die(); Message in PHP - php

Is there a way to style the output of php's die(); message?
I want to add some HTML and CSS around the error message so that I could use it in a productive environment.

If you're using the actual die() function, it will always print out exactly what text you pass it (which could be HTML, but might be awkward to use).
You could, however, simply make your own function that prints out an error message nicely and then calls exit - that way you don't have to repeat the HTML that you might otherwise pass to die() every time.
function die_nicely($msg) {
echo <<<END
<div id="critical_error">$msg</div>
END;
exit;
}

<?php
if('1'=='1')
echo '<font color=red>';
die('Its true');
echo 'its false';
?>
<?php
if('1'=='1')
{
echo '<font color=red>Itss true too.</font>';
exit();
}
echo 'its false';
?>
Both above are working, just to clear your doubts. :)

You can add html to the string you are feeding to die, but even easier is just echoing out the html that you want before you call die.

Yes, you can do like this,
die("<div>Error: ".mysql_error()."</div>");

Why not to change die() to its wrapper?

Related

End a php tag without die() or exit()

I was wondering if PHP has a function that allows me to end a process before it reaches the "?>" tag, example:
<?php
echo 'first';
endphptag();
echo 'second';
?>
third
<?php
echo 'fourth';
?>
Then the output should be:
first
third
fourth
I know that some people consider this as something useless, but I want to do it for a validation script on an iframe instead of use the die or exit function because it kills the whole script, I just want to end a part of it.
Normally I use if - else instead, but I want to avoid them because the processes are large and I want something more readable, by the way I use if - die in my ajax scripts and I want to use something like this in my iframes too, Thank's!
Well, I just wanted to know if PHP already had a proper function for it (it seems not), so I think I will just leave it with if - elses, because is not really worth to use more process for make it "more readable" (ex: try - catches uses too much resources, I'm not going to go-tos neither). My doubt was only for that, I will only use this procesdure in my ajax files using the die function (I don't know if it is recommended, but I think there's no problem because PHP should have it for some reason)
Exceptions is what you are looking for:
try {
// code
} catch (Exception $e) {
// handling
}
You put your code inside the try block and you end it throwing an exception with throw new Exception();, and it exits only the rest of the code inside the try block.
Your code would then be:
<?php
try {
echo 'first';
throw new Exception();
echo 'second';
} catch (Exception $e) {}
?>
third
<?php
echo 'fourth';
?>
I'm going to throw this out there and duck, but if you really need to do this, then goto is actually not a bad option:
<?php
echo 'first';
goto endofblock;
echo 'second';
endofblock:
?>
Or you could avoid the "evil" of goto with a faux-loop. To the compiler they basically look the same, but other programmers won't club you to death for using goto
<?php
do {
echo 'first';
break;
echo 'second';
} while (false)
?>
Why do you not use switches and cases?
http://php.net/manual/en/control-structures.switch.php
If I were you, I would omit the end-php tag. Most coding standards advise against it, for reasons that are too lengthy to explain here.
But that aside, go ahead and use the if/else or the switch/case control structures. Take the large parts of the validation process out of the inline code and package them in functions or class methods if you're using OOP.
See also this note about GOTO ;-) http://xkcd.com/292/
The PHP interpreter works with the file as a single unit, the <?php tag just specifies portions of text (outside the tag) to ignore, just like comments. The tag does not border any portion of code.
So in your case, I think the goto statement might be the right option. Or, if you could put the code into a function, you could use return.

Best way to return html from php function?

So I asked a similar question earlier and I'm only more confused now, so I'll ask it in a different way...
What I'm trying to do is abstract my php and put the bits of html, used in my validator as error messages, into functions that return the html to the spot where they are needed in the page.
What I have right now is:
<section>
<?php
if($errMsg)
{
errMsg();
}
?>
</section>
<?php
function errMsg()
{
?>
<section>
<p>O crap! There was an error</p>
</section>
<?php
}
?>
But in my previously mentioned question, I was told doing it this way is a 'dirty hack' and its better to use return in situations like this. But to use return I'd need to assign all of the returning html to a var and to do that I would need to put the html in a string. I'd rather avoid putting more than two lines of html in a string because of the pain in the butt number of quotes needed to do so.
So I'm thinking I either use the heredoc syntax or ob_start/ob_get_clean functions. What I'd like to know is.
1 Do I even need to bother with abstracting my code like this?
2 If so, which way is the best practices way to do it? And/Or
3 Should I just give up on web development and go back to pizza delivery? :-\
1: You don't need to, but you can if it's done properly.
2: To do this, i recommend you to use the EOF in your PHP error func, it looks like this :
function errMsg()
{
$error = <<<EOF
<section>
<p>O crap! There was an error</p>
</section>
EOF;
}
I wouldn't return any HTML. Simply return the error message from the function and then build the html in a more appropriate place. For example the inside the template.
Yes definitely, you have no flexibility with the way you are doing it.
You should separate all of your HTML from your PHP ideally, at least functions - the only place it is remotely acceptable is within a view which uses PHP just to display the output of the functions.
Pizza! Just kidding, but there can never be enough pizza!?
Take a look at the Zend framework http://framework.zend.com/manual/en/zend.application.quick-start.html they forward error messages which aren't caught to an error handler, which then uses its own view to render the error.
Or w/o a framework:
try{
//do work here and throw exception on error
}
catch (Exception $e)
{
//do error logging/display error
//or preferably load another class which handles your error and produces output
}
You could just do this:
<?php if($errMgs){ ?>
<section>
<p><?php echo errMsg(); ?></p>
</section>
<?php } ?>
Generally, I try my best not to echo out HTML via PHP. Why? Because if a designer needs to work on my code, I don't want him/her worrying about what HTML my functions are spitting out.
Move the html code into a separate file, error.php. After that you just capture the output:
function errMsg()
{
ob_start();
include '/path/to/error.php';
return ob_get_clean();
}
// ...
echo errMsg();
First off, I agree with the posts above. Don't format, just have the function return the bare error message and if you need to format it appropriately where you want to display it.
Secondly, I always find that it is useful to be able to turn error and testing messages on and off quickly. As the majority of my code is object orientated and I might only want to have messages popping from an object at a time, I normally have something like this in my classes:
class userObject
{
public $history;// = historyObject;
public $userName;
public $userRelation;
public $userCode;
private $mySQLAccessData;
private $isDebug=false;
public function makeHistoryObject($KPI, $KPIType)
{
if($this->isDebug){echo "Having a go at creating ".$this->userName.".<br>";}
$this->history = new historyObject($this->userCode, $KPI, $KPIType);
}
}
I slip a private element in which I leave as false by default. If I need to debug or make changes, I set it to true and all my error/logging messages are neatly displayed on screen. I know that this isn't directly answering your question, but I do find that it is so handy it might be worth it for you when you start. It certainly beats commenting out and then uncommenting potentially dozens of messages. You can leave these outputs in the object without worrying and have them displaying all the detail you need.
If you may at some point have number of errors, then do like this
<?php
$errors = array();
if (!$item = getItem($id)) {
addError("No item $id");
}
if (!updateUser($user, $id)) {
addError("Can not update user");
}
if (!updateItemPicture($id, $picture)) {
addError("Can not add picture to $id");
}
function addError($error) {
global $errors; $errors []= $error;
}
function hasErrors() {
global $errors; return count($errors);
}
function printErrors() {
if (!hasErrors()) return;
print "<ul class='errors'><li>" . join("</li><li>", $errors) . "</li></ul";
}
printErrors();
?>
This is in case you are not using object oriented way. And assuming that all errors are not fatal and caught in try {} catch () {} blocks.

How do you format php error messages? they don't respect css

Whenever PHP outputs an error message it disregards css and a beautifully designed page by outputting the message at the top of the page removing anything that stands in its way.
for example
some code} else {
echo "error, please do something!";
How do I get it to (or ask it nicely) to output the text inside a div that already exists inside my css so that it will obey the formatting and alignment rules that comes with that div.
You can use the following php.ini settings:
error_prepend_string = "<div class='error'>"
error_append_string = "</div>"
Or something to that effect.
EDIT
Actually, I just realized the "error" you're talking about involves an echo/print out. Here's the problem.
You're printing (echoing) the string error DIRECTLY TO the output buffer (which sends the HTML to the browser when you're finished running all your code). echo() and print() sends what you are echoing/printing straight out, unless it's in an output_buffer block (I won't confuse you with details on that).
So, you're managing your regular html/text output in such a way as to NOT print the page content out to the output buffer, but in this case you are using an echo, which sends the string data directly to the buffer AT THAT MOMENT.
For instance:
Your problem in a simple example
<?php
$mystr = "<html>";
$mystr .= "<body><h1>Hello World</h1></body></html>";
echo "<head></head>";
echo $mystr;
?>
Which would give me on output to the browser:
<head></head><html><body><h1>Hello World</h1></body></html>
I am storing the string data, but echoing the HEAD block before I echo the other html data.
What I need to do instead:
<?php
$mystr = "<html>";
$mystr .= "<head></head>";
$mystr .= "<body><h1>Hello World</h1></body></html>";
echo $mystr;
?>
Which would give me on output to the browser:
<html><head></head><body><h1>Hello World</h1></body></html>
I am storing the string output (your error, in this case) until I need to output it later. This is what you need to know, and accomplish in your code.
I would investigate error_reporting(0)/display_errors, error_get_last, and set_error_handler.
http://www.php.net/manual/en/function.error-reporting.php
http://www.php.net/manual/en/errorfunc.configuration.php#ini.display-errors
http://php.net/manual/en/function.error-get-last.php
http://www.php.net/manual/en/function.set-error-handler.php
So that you could stop sending all errors immediately to the output buffer (which is why it's at the top of the page), and then capture, store and present your errors.
error_reporting(0);
set_error_handler('phpLogError');
function phpLogError() {
$error = error_get_last();
if ($error['type'] == 1) {
//do your stuff
}
}
function phpGetLoggedErrors() {
// return your prettified html errors
}
Or, in other words...
php_error_handle.php
<?php
$GLOBAL['_logged_php_errors'] = array();
error_reporting(0);
set_error_handler('phpLogError');
function phpLogError() {
global $_logged_php_errors;
$error = error_get_last();
if ($error['type'] == 1) {
$_logged_php_errors[] = "<span>$error</span>";
}
}
function phpGetLoggedErrors() {
global $_logged_php_errors;
return "<ol><li>".implode('</li><li>',$_logged_php_errors)."</li></ol>";
}
?>
other.php
<?php
require_once 'php_error_handle.php';
// other stuff, pages included/required, etc...
Just make sure this require_once happens at the first line of code.
Extending #mario above, I've used this at the top of my php file (in dev, not production of course!) which works great. Even in Wordpress admin files!
ini_set('error_prepend_string',"<div class='error'>") ;
ini_set('error_append_string',"</div>") ;
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
Try...catch
http://php.net/manual/en/language.exceptions.php
You can make the error echo in your own css.
echo '<div class="yourerrorclass">error, please do something!</div>';
If it is in the wrong place in the output, that is because you output the error too soon. The entire HTML is outputted sequentially by PHP. If you output the error before any of the other HTML, the error will be on the top of the page and will actually make your HTML invalid.
Displaying errors to screen should be entirely suppressed when running in production, instead log them to file for checking, and fixing. There are details, and the suggested settings in the php.ini file.

Will php code exit after echo for ajax?

I am running a typical php-engined ajax webpage. I use echo to return a html string from the php code. My question is, if I have some other code after the echo, will those code get executed? Or echo behaves similar to exit, which immediately return and stop running the php code? Thanks.
No, echo in no way exits, you normally have more than one echo in a script. exit does take a string argument that it will output before exiting, however, so you can do:
exit("your string here");
and it will output the string and exit
No, echo would not. To exit after echoing things, you'd say
echo "Dear me, good bye!"; exit();
echo will simply return text to ajax javascript part; however the code after or before echo/echos will execute
No. PHP scripts are rendered in their entirety unless you explicitly exit them. ANY output on a script will be passed back to the ajax function if it was called through ajax.
echo 'This gets outputted<br />';
echo 'As does this';
If you must use a single file and you want your script to exit after performing ajax request with out having to add extra vars to your ajax url or evaluate vars to exit, i would suggest creating a function that performs your ajax, have the function return true on success, then do:
if(ajaxFunction($paramOne, $paramTwo)){exit();}

How Can I Display Static HTML After I've Used die() in a PHP Block?

Let's say I have some code like this:
<html>
<head><title>Title</title></head>
<body>
<?php
if (!$someCondition){
die();
}
else{
#Do something
}
?>
</body>
<html>
I hope the purpose of this code is straightforward. If a certain condition is met (ie can't connect to database), then the program should die, but otherwise it should execute. My problem arises when the die() function is executed. It stops right there, and sends only the first three lines to the browser, but not the last two lines.
Is there a funciton that I can use instead of die() so that the php chunks will stop executing, but the static HTML text is still sent through?
Decouple your program logic from presentation. Read about MVC, templates.
In simplest form it goes like that:
<?php
function logic() {
if (!$someCondition) {
return 'display_empty_page';
} else {
return 'display_other_stuff';
}
}
presentation(logic());
For other cases, where die() or such is unavoidable (e.g. fatal error or 3rd party code dying), there's hack involving output handler:
ob_start('myhandler');
function myhandler($page) {return $page.' extra markup';}
die();
Although I recommend using that only for diagnostic/debugging purposes.
You should be separating out your header and footer into an separate files and functions. This makes the UI much easier to maintain and keeps things consistent for rendering the view. Couple that with using Exception handling and you're golden.
<?php
printHeader(); // outputs the html header
try
{
if (some condition)
{
throw new Exception("It Died...");
}
// More processing here that should not execute if the above condition is true
// ...
}
catch (Exception e)
{
echo $e->getMessage();
}
printFooter(); // outputs the html footer
?>
Pass the die a parameter of the static text.
For example change this:
<html>
<head><title>Title</title></head>
<body>
<?php
if (!$someCondition){
die();
}
else{
#Do something
}
?>
</body>
<html>
To this:
<html>
<head><title>Title</title></head>
<body>
<?php
if (!$someCondition){
die("OMG RED ALERT!!!!</body></html>");
}
else{
#Do something
}
?>
</body>
<html>
I would probably use exceptions. Wrap everything in a try / catch block, then throw a new exception on an error condition like a database failure. You could do nothing in the catch block (like an empty die() method), but it would be better to present an error message to the user here.
Here's a pretty good guide on exception handling in PHP5 in case you're not familiar with them or you need to brush up on what's changed since PHP4.
Have you looked into using register_shutdown_function (php.net) to finish loading the page? It should be able to handle die() and exit().
If you look at the PHP Documentation you'll see that "Equivalent to exit()" - ie calling it terminates your program and doesn't really give you much of a chance to do anything. Even outside of ZF, there's not a whole lot you can do when an application die()s. The solution is to use Exceptions.
An uncaught exception is essentially the same thing as a die() (other than the stack trace that gets generated). What an exception gives you is the ability to put it in a try/catch block, giving you the opportunity to correct the error and continue on with the program (or display a friendly error message and generate a log). Assuming you're using Zend_Controller_Front, you can check out the Zend Framework Quickstart to see how they make a default error handler that will catch uncaught exceptions and display an appropriate error message.
One method, which works but is not exactly what I'm looking for, would be to replace die() with die("</body></html>"). If the text to return were more complicated than that, it could, say, be stored in a variable. Is there anything better than this?
die() might not exactly be what you want here. Why not replace
if (!$someCondition) {
die();
} else {
/* do stuff */
}
with
if ($someCondition) {
/* do stuff */
} else {
/* output error message/redirect/output nothing/whatever */
}
or throw/catch an exception?
If you're working with PHP4, or just don't want to bother with exceptions, then you could use this technique:
<html>
<head><title>Title</title></head>
<body>
<?php
do {
if (!$someCondition){
break;
} else {
#Do something
}
} while (0);
?>
</body>
<html>
.. though some people seem quite opposed to using this style, appropriately commented, I don't see any issues with it. I'd say it's much better than duplicating your "footer" code in each of your die() statements.
<html>
<head><title>Title</title></head>
<body>
<?php
if (!$someCondition){
header ("location:error_page.php?erro_message='This error occured'");
die();
}
else{
#Do something
}
?>
</body>
<html>
error_page.php
header
echo $_GET[$error_message];
footer

Categories