Easy Email Address Encoder
While there are countless solutions to protecting email addresses from page scanners, here's an easy helper to add another line of defense.
This handy helper takes a normal email address and scrambles it up into a mix of text, decimal, and hexadecimal characters.
Add the following code to views/helpers/mailto.php (you will need to create the file).
Add the helper to your controller like so:
In your view, you can do this:
Download code
or this:
Download code
or this:
Download code
or just this:
Download code
You'll get something like:
Download code
See?
Easy.
Add the following code to views/helpers/mailto.php (you will need to create the file).
Helper Class:
Download code
<?php
class MailtoHelper extends AppHelper
{
function encode($mail, $text="", $class="", $params=array())
{
$encmail ="";
for($i=0; $i<strlen($mail); $i++)
{
$encMod = rand(0,2);
switch ($encMod) {
case 0: // None
$encmail .= substr($mail,$i,1);
break;
case 1: // Decimal
$encmail .= "&#".ord(substr($mail,$i,1)).';';
break;
case 2: // Hexadecimal
$encmail .= "&#x".dechex(ord(substr($mail,$i,1))).';';
break;
}
}
if(!$text)
{
$text = $encmail;
}
$encmail = "mailto:".$encmail;
$querystring = "";
foreach($params as $key=>$val)
{
if($querystring){
$querystring .= "&$key=".rawurlencode($val);
} else {
$querystring = "?$key=".rawurlencode($val);
}
}
return "<a class='$class' href='$encmail$querystring'>$text</a>";
}
}
?>
Add the helper to your controller like so:
Controller Class:
Download code
<?php
class MyController extends AppController
{
var $name = 'MyController';
var $helpers = array('Mailto');
}
?>
In your view, you can do this:
Download code
<?php e($mailto->encode($mail, $text, 'test foo', array('subject'=>'subject', 'body'=>'body'))) ?>
or this:
Download code
<?php e($mailto->encode($mail, $text, 'test foo')) ?>
or this:
Download code
<?php e($mailto->encode($mail, $text)) ?>
or just this:
Download code
<?php e($mailto->encode($mail)) ?>
You'll get something like:
Download code
<?php e($mailto->encode('example@example.com')) ?>
// outputs <a class='' href='mailto:example@example.com'>example@example.com</a>
See?
Easy.
Comments
Question
1 problems
but how can i get it to work
just adding a file 'mailto.php' in the views folder didnt work
it says:
Fatal error: Call to a member function encode() on a non-object in ...\cake\app\views\posts\index.thtml on line 24
And it claims, that $mailto is not set or something.
How do i know that anyway - that $mailto is the object now?
i'm still kinda new to CakePHP^^
thx, mark
Comment
2 Wrong file location
Comment
3 oh yeah
but i didnt know, that i had to put it in the controller -> array (...)
etc.
after another half n hour i figured it out.
for newbys there is no explanation on this page here^^
thx anyway
Comment
4 Updated for clarity
Comment
5 This is awesome