2

Need some help to add PHP into HTML. I am trying to embed PHP code snippet in HTML however output is showing the snippet itself in the text box instead of evaluating it.

In HTML (register.php), added the below lines of code

<tr>
    <td>
        <?php utils::addControl('Name','label'); ?>
    </td>
    <td>
        <?php utils::addControl('username','text'); ?>
    </td>
</tr>

Here is the source of utils::addControl()

    public function addControl($ctlName, $type) {

    switch ($type) {
        case 'text':
            echo <<<EOT
            <input type='text' name='$ctlName' value='&lt?php echo htmlspecialchars($ctlName); ?&gt'>
   EOT;
            break;
        case 'label':
            echo "<label for id='lbl$ctlName'>$ctlName</label>";
            break;
    }

Output is showing <?php echo htmlspecialchars(username); ?> in the text box.

What should be done in order to get the PHP snippet evaluated properly. TIA.

2
  • Is it a PHP file? The PHP code would evaluate only if the server knows to treat the file as PHP. Commented Oct 7, 2012 at 19:00
  • Are you sure you're running the file on a PHP-enabled server (opposed to just open the local .php file with your browser)? Commented Oct 7, 2012 at 19:04

1 Answer 1

2

Servers are typically only configured for a single pass over a script while looking for PHP…

Source → PHP → Output

Not a double pass:

Source → PHP → PHP → Output

If it did perform a double pass then you would have to jump through hoops if you wanted to include the sequence <?php in the output (or even <? if short tags were turned on).

Write your PHP so it generates that output you want in the first place, don't try to generate PHP from PHP.

$htmlCtrlName = htmlspecialchars($ctlName);
echo "<input type='text' name='$htmlCtlName' value='$htmlCtrlName'>"
Sign up to request clarification or add additional context in comments.

2 Comments

In case it wasn't clear, value='&lt?php echo htmlspecialchars($ctlName); ?&gt' is what PHP passes for displaying by the browser in html. An alternative is to change it for this to do it all in the same line: value='.htmlspecialchars($ctlName).'
Thanks for the insight Quentin. Now I understand why the code snippet was not evaluated.

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.