JanneFiH
JanneFiH

Reputation: 1

Variables as address in a mailto link

I would like to use an email value from my database, but when printed it doesn't use the email value or anything after it. Have I missed a ' or " somewhere? It's working other places in the code, but with this link it wont'.

echo '<div align="center"><a href="mailto:"' . $row["email"]. '"&subject=Subject&body=Body"><img src="email.png"</a></div>';

Outcome link: mailto:

Thanks in advance!

Upvotes: 0

Views: 132

Answers (2)

Theodore R. Smith
Theodore R. Smith

Reputation: 23259

Your quotes are misaligned.

Use this:

// Greatly hinder spammers from ripping the email from your site.
// Converts "[email protected]" to "hi&commat;hi&period;com" but still works 100% as good for end-user.
$escapedEmail = htmlentities($row['email'], ENT_HTML5);

echo <<<HTML
    <div align="center"><a href="mailto:{$escapedEmail}&subject=Subject&body=Body"><img src="email.png" /></a></div>
HTML;

Heredocs are by far and away the best way to handle this, as you don't have to worry about inter-nested single/double quotes, lots of ".", etc., which are ugly AF and tend to create LOTS of unintended bugs, as your code just bit you with.

Another way to do it is to use printf(), but it's not as performant and slightly harder to read:

printf('<div align="center"><a href="mailto:%s&subject=Subject&body=Body"><img src="email.png" /></a></div>', $escapedEmail);

Upvotes: 0

Creative Akshara
Creative Akshara

Reputation: 33

You closed the href and thats why it ended at mailto:

It should be

echo '<div align="center"><a href="mailto:'. $row["email"] .'&subject=Subject&body=Body"><img src="email.png"></a></div>';

Upvotes: 1

Related Questions