DMP
DMP

Reputation: 543

escape mailto link in php

I have a mailto link in my php code i.e.

<a href="mailto:[email protected]?subject=<?php rawurlencode('Travels & Tours'); ?>&body=this is body">link text</a>

The issue is when it appears in email client e.g outlook the subject line text is changed to Travels &amp; Tours

Upvotes: 0

Views: 1475

Answers (2)

MrWhite
MrWhite

Reputation: 46012

Strictly speaking, you should be using urlencode() to URL encode the URL parameter value, instead of rawurlencode(), which is used to encode the URL-path part of the URL. Whilst these two functions produce similar results, there are differences. Different parts of the URL have different restrictions. Notably (from your example), spaces are encoded as + in the URL parameter value, whereas they are encoded as %20 in the URL-path (although this doesn't really matter in most scenarios).

As well as URL encoding the URL in order to make a valid request, you may also need to HTML entity encode the entire HTML attribute in order to make it valid HTML (however, HTML5 is less strict). (Browsers are, however, quite forgiving and are likely to automatically HTML entity encode the URL as needed. However, this might not always function correctly and for security reasons, you should ensure that whatever HTML you generate is already correctly encoded.)

So, ideally, you should be doing something like the following:

<?php
$subject = urlencode('Travels & Tours');
$body = urlencode('body is body');
$url = htmlspecialchars("mailto:[email protected]?subject=$subject&body=$body");
?>
<a href="<?=$url?>">link text</a>

This results in the following HTML:

<a href="mailto:[email protected]?subject=Travels+%26+Tours&amp;body=body+is+body">link text</a>

However, this may still not resolve your problem and could depend on the browser / email client - since the URL parameters must be correctly HTML entity and URL decoded before being processed by the email client. The above works OK for me using Gmail, but so did your original example (once the PHP syntax was corrected).

Email clients are relatively basic in what they can process and so it is generally the email client that you need to wrestle with. Personally, I would avoid using & in the email subject to begin with.

Upvotes: 2

Amrinder Singh
Amrinder Singh

Reputation: 5532

use html_entity_decode

i.e.

<a href="mailto:[email protected]?subject=<?php html_entity_decode(Travels & Tours) ?>&body=this is body">link text</a>

Upvotes: -1

Related Questions