[nycphp-talk] Encoding text/html for mailto:

Dan Cech dcech at
Fri Aug 10 10:18:34 EDT 2007

Ben Sgro (ProjectSkyLine) wrote:
> Hello All, 
> I've created a "Mail this section" option for a FAQ/Information Center type page I'm working on.
> It enables visitors to email themselves the contents of a particular section. But I'm running into trouble
> when foreign/non a-zA-Z0-9 characters are present in the code (which is being pulled from the database).
> Heres' a code snippet:
>             $body .= "<a href=\"mailto:?Subject=Information Center&body="
>                   . html_entity_decode(strip_tags(
>                     str_replace(array("&", '"', "\\"), "", $dbObject->result['body']))) . "\""
>                   . " class=\"email\">Email this section</a>";
> Let me reformat that, heh:
> $body = "<a href=\"mailto:?Subject=Information Center&body=". $dbObject->result['body'] . "\">Email me</a>";
> So, what can I use on $dbObject->result['body'] to clean/strip away the text? You can see I was messing
> with a few different options..I know & will break it, as well as " ... but lets just clear out everything (HTML, and all other characters EXCEPT aA-zZ 0-9 and maybe .,-
> Any help, greatly appreaciated!

Personally, I think you're probably approaching this the wrong way.

Not only are you going to be generating huge links (which will cause all
kinds of grief), but your email will be horribly formatted and the user
still has to email it to themselves manually from their own mail
client...very confusing.

Why not have the link trigger a server-side process to send the mail?

You may need an input for the user to enter their email address, but
then you can format the mail in any way you like, using whatever
character set is appropriate for the content.

For bonus marks, attach it as a nicely formatted pdf!

As an aside, when creating any kind of url, there are 2 forms of
formatting you need to consider.

1. urlencode any query strings

2. html encode the entire url to make it html-safe

for example:

echo '<a href="'. htmlspecialchars('test.php?arg1='. urlencode('val1')
.'&arg2='. urlencode('value 2 with some odd characters & +')) .'">link</a>';

I define functions h() and u() as shortcuts for htmlspecialchars and
urlencode respectively, as I use them everywhere.

If you did want to make your current approach work, you would want to do
something like:

$body = '<a href="'. h('mailto:?Subject='. u('Information Center')
.'&body='. u($dbObject->result['body'])) .'">Email me</a>';



More information about the talk mailing list