Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

echo htmlspecialchars($_SERVER["PHP_SELF"]) from inside PHP echo

Tags:

html

php

i'm trying to create some dynamic content using php so i am echoing html code into my webpage. However when i try to insert a <?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> inside an action tag inside a form, unwanted visible text is printed onto my page most likely due to some sort of parsing error.

my example is as follows below.

echo'<form name="PArtifact" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
     <input name="printArtifactBut" type="submit"  value="Print Artifact">                
     </form>';

The code above will produce "> as visible text. Can someone tell me the correct way to echo htmlspecialchars($_SERVER["PHP_SELF"]) inside an echo?

like image 628
DiscreteTomatoes Avatar asked Oct 26 '25 15:10

DiscreteTomatoes


2 Answers

You already have PHP opened and you are already inside of an echo expression. You just need to concatenate the data:

echo '<form name="PArtifact" method="post" action="' . htmlspecialchars($_SERVER["PHP_SELF"]) . '"></form>';

But as I said in the comments, this is unnecessary because the form action is already this by default.


Other way to achieve what you mean is exit php section:

?>
<form name="PArtifact" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
  <input name="printArtifactBut" type="submit"  value="Print Artifact">                
</form>
<?php
like image 80
Devon Avatar answered Oct 28 '25 06:10

Devon


Your problem is down to a fundamental misunderstanding of how PHP works. There is absolutely no need to have an echo inside an echo; the very concept is a non-sequitur. If you need to call a function within an echo, simply close the string being echo'ed, append the function call to the string using a dot. Then another dot afterward, open the string again with another quote, and carry on where you left off.

echo'<form name="PArtifact" method="post" action="' . htmlspecialchars($_SERVER["PHP_SELF"]) . '">
 <input name="printArtifactBut" type="submit"  value="Print Artifact">                
 </form>';

However in this case, as others have said already, you don't really even need to do this, as the use of PHP_SELF in a form's action attribute is redundant -- that is the default value for action anyway. So for this case you can simply leave that whole bit out:

echo'<form name="PArtifact" method="post" action="">
 <input name="printArtifactBut" type="submit"  value="Print Artifact">                
 </form>';

...and you'll have exactly the same effect that you were wanted anyway.

like image 21
Spudley Avatar answered Oct 28 '25 06:10

Spudley