简体   繁体   中英

Best practice for outputting larger amounts of dynamic HTML from PHP

What is the best practice for exporting larger amounts of HTML from a database in PHP? I am building a very simple, dynamic CMS and have intentions of loading the input type, id, etc from the MySQL database.

My question is using just an echo like the sample code provided below the absolute best method for displaying the HTML assuming I have collected the information from the database?

for ($x = 0; $x < 3; $x++)
    {
        echo '
            <div class="form-group">
                <label for="exampleInputPassword1">Password</label>
                <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
              </div>
        ';
    }

I'd probably be asking some hard questions around sanitization and html encoding, this could be opening yourself up to XSS

Are you in full control of the HTML or can the user enter it?

Can you use markdown or some other language to html to help prevent attackers running malicious css/js?

If not you may need something heavy handed like HTML Purifier which will likely suck up performance

In terms of output I'd recommend requiring a separate PHP file and using it as a "template" file since PHP is a templating language.

Other developers will probably chime in and recommend a made up language (DSL) to render what will essentially become PHP at some stage, those languages should offer htmlspecialchars on variables by default and caching in exchange for their DSL

This could be preferable if you're not really sure what you're doing

If you are outputting predefined blocks of things what you could do is store those blocks in your database as function names, then on output call those functions dynamically via db to render the blocks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM