Archive

Posts Tagged ‘email’

A Useful Error Controller Class For Zend Framework Applications

December 23rd, 2008 7 comments

One useful function of any application is to report on any errors that occurred. Zend Framework comes with a nice error controller system that you can activate by creating an ErrorController class.

The following is an ErrorController class that I use. It detects what sort of error occurred and displays a message to the user. It will also email a detailed report of the error to the server admins.

class ErrorController extends Zend_Controller_Action
{
  public function errorAction()
  {
    // Ensure the default view suffix is used so we always return good
    // content
    $this->_helper->viewRenderer->setViewSuffix('phtml');
 
    // Grab the error object from the request
    $errors = $this->_getParam('error_handler');
 
    switch ($errors->type) {
      case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
      case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
        // 404 error -- controller or action not found
        $this->getResponse()->setHttpResponseCode(404);
        $this->view->message = 'Page not found';
        $this->view->code  = 404;
        if ($errors->type == Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER) {
          $this->view->info = sprintf(
                      'Unable to find controller "%s" in module "%s"',
                      $errors->request->getControllerName(),
                      $errors->request->getModuleName()
                    );
        }
        if ($errors->type == Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION) {
          $this->view->info = sprintf(
                      'Unable to find action "%s" in controller "%s" in module "%s"',
                      $errors->request->getActionName(),
                      $errors->request->getControllerName(),
                      $errors->request->getModuleName()
                    );
        }
        break;
      case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
      default:
        // application error
        $this->getResponse()->setHttpResponseCode(500);
        $this->view->message = 'Application error';
        $this->view->code  = 500;
        $this->view->info  = $errors->exception;
        break;
    }
 
    // send a mail to let someone know that there was a problem!
    $config = Zend_Registry::get('configuration');
    $tr = new Zend_Mail_Transport_Smtp($config->smtp);
    Zend_Mail::setDefaultTransport($tr);
 
    $mail = new Zend_Mail();
    $emailBody = "An error occurred in the system. The error message contained the following output:\n\n";
    $emailBody .= $this->view->message." (".$this->view->code.")\n\n";
    $emailBody .= "Zend Error Type: ".$errors->type."\n\n";
    $emailBody .= "REQUEST_URI: ".$_SERVER['REQUEST_URI']."\n\n";
    if ( isset($_SERVER['HTTP_REFERER']) ) {
      $emailBody .= "HTTP_REFERER: ".$_SERVER['HTTP_REFERER']."\n\n";
    }
    $emailBody .= "Stack trace: \n\n". $errors->exception->getTraceAsString()."\n\n";
 
    // find the user to blame!
    $username = Zend_Auth::getInstance()->getIdentity();
    $emailBody .= "This error was created by ".$username.".";
 
    $mail->setBodyText($emailBody);
    $mail->setFrom('anAddress@example.com', '');
    $mail->addTo($config->adminEmail, $config->adminName);
    $mail->setSubject('An Error Occured');
    // Email
    $mail->send();
 
    $this->view->title = 'Error!';
    $this->view->heading = 'Error!';
 
    // pass the environment to the view script so we can conditionally
    // display more/less information
    $this->view->env   = $this->getInvokeArg('env');
 
    // pass the actual exception object to the view
    $this->view->exception = $errors->exception;
 
    // pass the request to the view
    $this->view->request = $errors->request;
  }

This error controller relies on certain options that have been set up in your configuration file. Add the following options to your configuration file to get these options working.

smtp = my.smtpserver.com
adminEmail = admin@example.com
adminName = 'Your name'

To enable this just call the throwExceptions() function of the Zend_Controller_Front and pass it a value of false. This will cause the framework to look for an error controller rather than try to print out things.

$frontController = Zend_Controller_Front::getInstance();
$frontController->throwExceptions(false);

Finally, you need to add a view so that your errors will be displayed nicely. This will display more if the environment is set to 'test'.

<h3>Error has happened. Inside this application. Sorry about that.</h3>
<p><?=$this->message ?> (<?=$this->code ?>) </p>
<?
if( $this->env == 'test' ) {
 if ( isset($this->info ) ) { ?>
<? if ( 404 == $this->code ) { ?>
  <p><b>Reason:</b> <?= $this->info ?></p>
<? } elseif (500 == $this->code) { ?>
  <p>Bad server, naughty server!<br />No donut for you!</p>
  <p><img src="<?=$this->baseUrl();?>/images/donut.jpg" /></p>
  <h4>Exception information:</h4>
 <p><b>Message:</b> <?= $this->info->getMessage() ?></p>
 <h4>Stack trace:</h4>
 <pre><?= $this->info->getTraceAsString() ?></pre>
<? } ?>
<? } ?>
<? } ?>

Mask Email With ASCII Character Codes In PHP

April 28th, 2008 No comments

Hiding your email address in an image is the best way of encrypting your email, but if your server doesn’t support the GD2 library, or if you don’t want to use it, then you might want to look at a different way of doing this.

The easiest way to encrypt your email address is to turn every character into the ASCII code equivalent and use this to display the text in HTML by putting a &# in front of each character. Here is a function that takes a string and turns it into HTML encoded text.

function maskEmail($email){
 $hiddenEmail = '';
 $length = strlen($email);
 
 for($i = 0;$i<$length;$i++){
  $hiddenEmail .= "&#".ord($email[$i]).";";
 }
 
 return $hiddenEmail;
}

To use this just feed an email address into it.

$hiddenEmail = maskEmail("example@example.com");
echo $hiddenEmail;

This produces the following output in the source code (the browser will display this string as the email address you put in.

&#101;&#120;&#97;&#109;&#112;&#108;&#101;&#64;&#101;&#120;&#97;&#109;&#112;&#108;&#101;&#46;&#99;&#111;&#109;

This can be easily added to a anchor tag to make an email link.

echo '<a href="mailto:'.$hiddenEmail.'" title="Email me">'.$hiddenEmail.'</a>';

Categories: PHP Strings Tags: , , , ,

Common Regular Expressions

March 24th, 2008 No comments

Here are some of the regular expressions that I frequently use.

Find a blank line
^$

Spaces
[ \t]+
You can use this to break a text string apart into words.

Date
\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}
This will match anything in the format mm/dd/yyyy, or even dd/mm/yyyy.
[A-Z][a-z][a-z] [0-9][0-9]*, [0-9]{4}
Will match a formatted date, such as Mar 24, 2007.

Time
([1-9]|1[0-2]):[0-5]\d(:[0-5]\d(\.\d{1,3})?)?
This will match HH:MM or HH:MM:SS or HH:MM:SS.mmm.

IP Address
(((\d{1,2}|(1\d{2})|(2[0-4]\d)|25[0-5]))\.){3}((\d{1,2}|(1\d{2})|(2[0-4]\d)|25[0-5]))
This also checks to see that the IP address is within the range 0.0.0.0 to 255.255.255.255.

Email Address
([\w\-\.]+)@((\[([0-9]{1,3}\.){3}[0-9]{1,3}\])|(([\w\-]+\.)+)([a-zA-Z]{2,4}))
This is using a simple mechanism, the following expression uses the RFC standard for an email address format and so should match %99.99 of all email addresses.
[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?

Complete URLs
https?://(\w*:\w*@)?[-\w.]+(:\d+)?(/([\w/_.]*(\?\S+)?)?)?
This will match virtually any URL.

HTML Comments
<!-{2,}.*?-{2,}>

Inline Comments
//.*
This will match inline comments in C, PHP, Java, JavaScript etc.

Simple PHP Script To Hide An Email Address In An Image

March 4th, 2008 No comments

Spam is a problem. You want to allow people who genuinely want to get in touch to see your email address, but doing this invariably leads to you getting thousands of spam emails.

One solution is to hide your email address in an image, but it can be a pain to create an image for every email address you need. A better solution is to use the PHP GD functions to create an image at runtime so that your email address is displayed, but is completely unreadable to spammers.

To to this you will need to create an image tag on your website, here is an example.
<img src="image.php?text=moc.edocniklat@hcet" alt="Hidden Email" />

This calls the image.php file and passes a single parameter called text. This parameter is the email address you want to display, but it is written backwards. The script first turns the string around and then adds the string to an image. Because the script returns the correct header for an image type (Content-type: image/png) it will be displayed as an image on the browser.

<?php
 if(isset($_GET['text'])){
  // get string
  $text = $_GET['text'];
 }else{
  // set default
  $text = 'liame';
 };
 // reverse string
 $text = strrev($text);
 $textLength = strlen($text);
 $textHeight = 10;
 
 // create image handle
 $image = ImageCreate($textLength*($textHeight-1),20);
 
 // set colours
 $backgroundColour = ImageColorAllocate($image,255,255,255); // white
 $textColour = ImageColorAllocate($image,0,0,0); // black
 
 // set text
 ImageString($image,$textHeight,0,0,$text,$textColour);
 
 // set correct header
 header('Content-type: image/png');
 
 // create image
 ImagePNG($image);
?>

This is a fairly simple mechanism to create an image, and you will need to have the GD functions installed on your server or it will just return an error. Here is an example of the script in action.

Hidden Email

To further customise the look of the image you can change the colours stipulated in the variables $backgroundColour and $textColour to fit in with the colour scheme of your own site.

Categories: PHP Tags: , , , ,

PHP Email Validation Function

February 7th, 2008 No comments

Every time you accept any input from a use you should attempt to validate it. This is to stop users trying to break the site and also corrects silly mistakes that users might introduce to their input.

Before sending off an email to a new user congratulating them on signing up it is best to validate that email address. Here is function that does this.

function validateEmail($email){
  $reg_exp = '/^[A-z0-9][\w.-]*@[A-z0-9][\w\-\.]+\.[A-z0-9]{2,3}$/';
  if(preg_match($reg_exp,$email)==true){
    return true;
  }else{
    return false;
  }
}

This can be used in the following way.

$email = "nothing@nothing.com";
if(validateEmail($email)){
  echo 'Email valid!';
}

The regular expression used here seems to work with most email addresses. If you mind you are having trouble then have a look at the email section in the Regular Expressions Library. You could convert this function to check for anything that you like by using any regular expression that you want just by changing the $reg_exp variable.

Categories: PHP Tags: , , ,