Jump to content

if and form


marsheng

Recommended Posts

I'm new to this. Coming from a traditional language - HTML PHP etc is quite a challenge.  The main issues I have is the mixing of HTML and PHP code. How and when??

 

I'm using a $_SERVER["PHP_SELF"] form and I want to display options depending on whether the user just entered the form or adding data. $status is used to determine what has happened. Needless to say that the if line crashes.

    <form action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>  method="post">
           <?php
            if ($status ==0) {
                LicenceNo: <input type="text" name="LicenceNo" />        
                <input type="submit" value="Enter">
            }
         ?>
    </form>    
Edited by marsheng
Link to comment
Share on other sites

You should avoid mixing PHP and HTML whenever possible, because jumping in and out of PHP mode leads to spaghetti code and the kind of syntax errors you're currently struggling with.

 

A good structure for beginners is the following: Put all business logic (i. e. the code which does the heavy lifting) on top of the script. Then switch to HTML mode and only use small PHP snippets to generate dynamic HTML markup. Note that everything between <?php and ?> must be valid PHP code. You cannot randomly insert HTML elements.

<?php

// the business logic goes here; after you're done, leave PHP mode and start the HTML document

function html_escape($raw_input, $encoding)
{
    return htmlspecialchars($raw_input, ENT_QUOTES | ENT_SUBSTITUTE, $encoding);
}

$age = 44;

?>
<!-- at this point, use PHP only to generate HTML -->
<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Title</title>
    </head>
    <body>
        <?php if ($age >= 21): ?>
            <p>Your age is <?= html_escape($age, 'UTF-8') ?>. You may proceed.</p>
        <?php else: ?>
            <p>You're too young to visit this page.</p>
        <?php endif; ?>
    </body>
</html>

Also note that you must HTML-escape all PHP values before you can safely insert them into an HTML context. If you don't do that, you'll quickly end up with security vulnerabilities and invalid markup all over the place. It's also recommended that you use the verbose syntax for control structures when you're in an HTML document. This is butt-ugly, but it's at least somewhat readable.

 

Given those extreme limitations, you should seriously consider not mixing PHP and HTML at all. There are specialized template engines like Twig which have a far prettier syntax and support auto-escaping of variables. For example, this is how the Twig version would look like:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Title</title>
    </head>
    <body>
        {% if age >= 21 %}
            <p>Your age is {{ age }}. You may proceed.</p>
        {% else %}
            <p>You're too young to visit this page.</p>
        {% endif %}
    </body>
</html>

Right now, the idea of learning yet another language may be scary, but Twig is actually very simple and intuitive. So once you understand the basics, give it a try.

 

Using $_SERVER['PHP_SELF'] is actually superfluous and ill-advised. Just leave out the action attribute entirely. Then the form input will be reliabily submitted to the current page.

Edited by Jacques1
  • Like 2
Link to comment
Share on other sites

Let me see if I have this correct. I have not see this before.

<?php if ($age >= 21): ?>
<p>Your age is <?= html_escape($age, 'UTF-8') ?>. You may proceed.</p>
<?php else: ?>
<p>You're too young to visit this page.</p>
<?php endif; ?>

So we are running down an HTML page doing the bits and we encounter an <?php> if statement. The HTML code now tells/requests the server to run this bit of code and somehow it returns a 'flag' to let the HTML document know whether execute the next bit of code or not.

 

The server must wait in limbo to process the rest of the statements and is finally terminated when it gets <?php endif; ?>

Yes ?

Link to comment
Share on other sites

The server must wait in limbo to process the rest of the statements and is finally terminated when it gets <?php endif; ?>

Yes ?

 

No, no. When the script is executed, PHP parses the entire content and turns it into a tree structure. Everything between <?php ?> tags is treated as code, everything else is output and equivalent to an echo statement (the output is typically HTML markup, but it could be anything else). So PHP "sees" the structure of the script. It doesn't have to "wait" for anything.

 

The tree is then turned into byte code and executed.

 

This is a pretty standard approach for scripting languages. The fact that you can embed PHP code into documents is really just a syntax quirk. You might as well write that as pure code:

<?php 

function html_escape($raw_input, $encoding)
{
    return htmlspecialchars($raw_input, ENT_QUOTES | ENT_SUBSTITUTE, $encoding);
}

$age = 44;

if ($age >= 21)
{
    echo '<p>Your age is '.html_escape($age, 'UTF-8').'. You may proceed.</p>';
}
else
{
    echo "<p>You're too young to visit this page.</p>";
}

It's just harder to read when you have complex HTML documents.

Edited by Jacques1
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.