0

I want to generate a simple html form and add some text box to it, then I want to define some php variables and use them as value for text boxes but when I try to use them it does not work and the value of variable would not be set for the text box. Would you please tell me about the correct syntax and the way for doing this

<?php
$foo = 123;
?>

<html>
    <head>
    </head>
    <body>
        <form Id='Form' Method='post' Action='http://example.com'>
            fooElement<input type='text' name='fooElement' value='<?= $foo ?>'/>
        </form>
    </body>
</html>

How can i set the value of foo variable as the value for foo element?

1
  • As a side note, don't use short tags. Read this question Commented Sep 18, 2011 at 11:57

4 Answers 4

2

Are you sure that your short_open_tag is on?

If not try to use <php echo $foo;?>

You have missing ? symbol.

<?php
$foo="sample"
?>

My advice: Be attentive while writing code. Try to check your code once more for typos and etc. before asking on SO. And learn this basics

Sign up to request clarification or add additional context in comments.

Comments

2

tag missing

<?php
$foo = 123;
?>

Comments

1

It depends on your server configuration. Sometimes short tags like <?php=$foo?> are allowed, sometimes they aren't. It's generally safer to just do <?php echo $foo; ?> instead.

3 Comments

Short form looks like <?= ?> not <?php= ?>.))
Could be either if short_open_tag is on I'm guessing? Didn't put it in there because its been so long since I'd done short tags haha. Thanks for that :)
There are 2 ways: 1. <?=$foo?> 2. <?php echo $foo; ?> First requires short_open_tag to be on
1

echo $foo is not safe. it if contains ', anything after it will not be seen and will open doors for cross site scripting.

what I would suggest is to do small cleanup e.g. $foo = preg_replace("/'/", "&#39;", $foo), given you input the value as you mentioned above. e.g.

<input name='bar' value='<?=$foo?>'> 

I personally do not like this approach and would rather use templates or if you have to have html code in php then:

echo "<input name='bar' value='$foo'>";

as for text areas, do not forget to translate < and > to &lt; and &gt; to be on the safe side.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.