开发者

using php to encode characters for mailto in javascript?

开发者 https://www.devze.com 2023-04-04 13:25 出处:网络
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 $cont

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 sim开发者_开发问答ilar which breaks the code.

How can I make this work?


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.


You might want to use addslashes, which escapes the quotes.


Use rawurlencode():

window.location.href = 'mailto:?body=<?php echo rawurlencode($content); ?>';
0

精彩评论

暂无评论...
验证码 换一张
取 消