KRA
KRA

Reputation: 381

PHP String Concatenate issue

Output of below PHP string is not correct. It's displaying additional ( "> ) at end. Please help that what wrong I am doing?

$part2 = HTMLentities('<input type="hidden" name="custom" value="<?php print($_SESSION["muser"]."-".$_SESSION["mpass"]);?>">');
print $part2;

Thanks, KRA

Upvotes: 1

Views: 415

Answers (3)

Nick Pickering
Nick Pickering

Reputation: 3185

I think this is more of what you're looking for:

$part = '<input type="hidden" name="custom" value="' . htmlentities($_SESSION['user'] . '-' . $_SESSION['mpass']) . '" />';

You've got a lot of poor PHP syntax in your example.

  • We use <?php tags to escape out of HTML into PHP. When you have a PHP file, one way you could think about it is that you really have an HTML document - but one that you can add <?php tags to write PHP code in. In you're example you are trying to print HTML from within PHP, which can get admittedly complex. You are already in a PHP block, so you don't need to use the opening <?php tag.
  • When concatenating strings to store in a variable, you don't need to use the print function. The print function is used to write text to the screen. You can just use the variables name as in the example I wrote to combine the strings.
  • htmlentities is used to render any HTML in your string into text. We use htmlentities to keep unknown (user-entered) data from modifying our HTML. It would be a good idea to use htmlentities on the $_SESSION variables like I did above to make sure they don't break our input tag with invalid HTML. Using it on the entire string would just print your HTML as if it were raw text.

Here's a way to write it from outside of a PHP block:

<?php
    // initial PHP code
?>

<input type="hidden" name="custom" value="<?php echo htmlentities($_SESSION['user'] . '-' . $_SESSION['mpass']) ?>" />

<?php
    // continue PHP code
?>

Upvotes: 0

Ja͢ck
Ja͢ck

Reputation: 173542

If you're already in PHP mode, you should just use string concatenation instead of <?php ?> syntax; this example splits up the html creation and the escaping part.

$html = '<input type="hidden" name="custom" value="' . htmlspecialchars($_SESSION["muser"] . "-" . $_SESSION["mpass"]) . '">';

$part2 = htmlentities($html);
print $part2;

Upvotes: 3

TerenceJackson
TerenceJackson

Reputation: 1786

It is because there is an additional > at the end. Try this:

$part2 = HTMLentities('<input type="hidden" name="custom" value="<?php print($_SESSION["muser"]."-".$_SESSION["mpass"]);?>"');
print $part2;

Upvotes: 0

Related Questions