Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using PHP variables inside HTML tags?

Tags:

I am pretty new to php but I'm stuck on this problem... Say i wait to put a link to another site with a given parameter, how do I do it correclty?

This is what i have now:

<html>
<body>
<?php
  $param = "test";

  echo "<a href="http://www.whatever.com/$param">Click Here</a>;
?>

</body>
</html>
like image 734
Jasper Avatar asked May 25 '11 20:05

Jasper


People also ask

Can you use PHP variable in HTML?

PHP is a powerful programming language that powers more than 70% of the websites in the world. When creating PHP web applications, you will need to inject PHP variables into HTML.

Can you use variables in HTML?

Use the <var> tag in HTML to add a variable. The HTML <var> tag is used to format text in a document. It can include a variable in a mathematical expression.


2 Answers

Well, for starters, you might not wanna overuse echo, because (as is the problem in your case) you can very easily make mistakes on quotation marks.

This would fix your problem:

echo "<a href=\"http://www.whatever.com/$param\">Click Here</a>";

but you should really do this

<?php
  $param = "test";
?>
<a href="http://www.whatever.com/<?php echo $param; ?>">Click Here</a>
like image 131
nicolaas Avatar answered Oct 12 '22 03:10

nicolaas


You can do it a number of ways, depending on the type of quotes you use:

  • echo "<a href='http://www.whatever.com/$param'>Click here</a>";
  • echo "<a href='http://www.whatever.com/{$param}'>Click here</a>";
  • echo '<a href="http://www.whatever.com/' . $param . '">Click here</a>';
  • echo "<a href=\"http://www.whatever.com/$param\">Click here</a>";

Double quotes allow for variables in the middle of the string, where as single quotes are string literals and, as such, interpret everything as a string of characters -- nothing more -- not even \n will be expanded to mean the new line character, it will just be the characters \ and n in sequence.

You need to be careful about your use of whichever type of quoting you decide. You can't use double quotes inside a double quoted string (as in your example) as you'll be ending the string early, which isn't what you want. You can escape the inner double quotes, however, by adding a backslash.

On a separate note, you might need to be careful about XSS attacks when printing unsafe variables (populated by the user) out to the browser.

like image 22
Nick Avatar answered Oct 12 '22 01:10

Nick