Hailwood Hailwood -4 years ago 165
Javascript Question

using php to encode characters for mailto in javascript?

I am using

window.location.href = 'mailto:?body=visit http://example.com/?content=link';


which works fine, but the way the link is built is
window.location.href = 'mailto:?body=<?php echo $content; ?>';


now this works fine unless
$content
contains
'
or something similar which breaks the code.

How can I make this work?

Answer Source

Use the rawurlencode function[php docs] to encode any characters in your input that aren't valid in URLs.

<?php $content = "Hello, this' an...\n\nexample!"; ?>
window.location.href = "mailto:?body=<?php echo rawurlencode($content); ?>";
Output:
window.location.href = "mailto:?body=Hello%2C%20this%27%20an...%0A%0Aexample%21";

It is true that you normally would want to use addslashes[php docs] when you're putting something in a quoted string. In this case it would have no effect because the output of rawurlencode doesn't have any characters that need to be escaped with slashes.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download