I want to find out a more efficient way of going about this function:
<?php
function zipError($title, $desc) {
echo '<style type="text/css">';
echo 'body { margin:0;font-family:Arial, sans-serif;font-size:13px;background:#DDD;color:#1A1A1A; }';
echo 'h1 { color:#FFF;font-family:Arial;font-weight:bold;text-align:center; }';
echo 'h2 { color:#1C1C1C;font-family:Arial;font-weight:bold;text-align:center;padding-bottom:4px;border-bottom:1px solid #AAA; }';
echo '#error#head { background:#1C1C1C;padding:10px;;border-bottom:5px solid #FFF; }';
echo '#error#content { border:1px solid #AAA;background:#FFF;padding:20px;width:780px;margin:30px auto; }';
echo 'p { text-align:center;padding:10px;color:#1A1A1A;font-family:verdana; }';
echo '</style>';
echo '<title>' . $title . '</title>';
echo '<div id="error head"><h1>An error has occurred.</h1></div>';
echo '<div id="error content"><h2>'.$title.'</h2><p>'.$desc.'</p></div>';
}
This code is used to throw an error. For example:
die(zipError('Session Not Found', 'Your session has not been found! Please re-login now!'));
Although this gets the job done, I'm trying to learn, so therefore I want to make this function more efficient, and not hard coded. Any ideas?
that's look like error template, I will do something like this:
create sparate error tamplate: e.g error.php:
<html>
<head>
<style>
//style here...
</style>
<title><?= $title?></title>
</head>
<body>
//and soon ...
</body>
and a function:
public function zipError($title, $desc){
include('error.php');
}
and usage:
... die(zipError('Session Not Found', 'Your session has not been found! Please re-login now!'));
Now, You can edit/change your error template easily as long as it keep echoing $title
and $desc
and any other parameter you want to.
The first thing I would do is to drop out of PHP for all the HTML code and jump back in for the echoing of data. It just makes it a bit more readable from a maintenance point of view.
Next, use a separate CSS file so that it can be shared. It could be its own little file or incorporated into a larger one.
That's about it really. There isn't really a lot of php to optimize to be honest
Either
echo "Output text/HTML using one statement
instead of many, which can include
line breaks and can span multiple lines";
OR
Only drop into PHP to output variables like <?=$var?> or <?php echo $var; ?>
Also, die and exit output the parameter passed - in this case the return value of zipError(). So either return the string from zipError rather than echoing it, or make things easier when calling the function and exit inside the function instead of wrapping the call with die().