What's the Best Practice to Set HTML Attribute via PHP

What's the best practice to set html attribute via PHP?

You always want to HTML-encode things inside HTML attributes, which you can do with htmlspecialchars:

<span title="<?php echo htmlspecialchars($variable); ?>">

You probably want to set the second parameter ($quote_style) to ENT_QUOTES.

The only potential risk is that $variable may already be encoded, so you may want to set the last parameter ($double_encode) to false.

Set an HTML attribute with PHP

When the user submits the data...

Do you mean there's a $_POST or $_GET request? If so, this would make a little more sense

<input id="username"
name="username"
placeholder="Username"
value="<?php echo isset($_GET['username']) ? $_GET['username'] : '' ?>">

If $_GET['username'] isn't present, you will just get value="" which is perfectly fine


Writing HTML via PHP by hand is a total chore. To combat this, I've written a utility called htmlgen which makes it quite a bit more tolerable

<?php
use function htmlgen\html as h;

h('input#username', [
'name'=>'username',
'placeholder'=>'Username',
'value'=>isset($_GET['username']) ? $_GET['username'] : ''
]);

// => <input id="username" name="username" placeholder="Username" value="someuser">

What is the best practice to use when using PHP and HTML?

There are varying opinions on this. I think there are two good ways:

  • Use a templating engine like Smarty that completely separates code and presentation.

  • Use your second example, but when mixing PHP into HTML, only output variables. Do all the code logic in one block before outputting anything, or a separate file. Like so:

    <?php $content = doSomething();
    // complex calculations
    ?>
    <html>
    <body>
    <?php echo $content; ?>
    <div id="some_div">Content</div>
    </body>
    </html>

Most full-fledged application frameworks bring their own styles of doing this; in that case, it's usually best to follow the style provided.

Modify html attribute with php

Is there any simplier way for this or should I do it with DOM?

Do it with DOM.

Here's an example:

<?php
$html = '<a href="http://example.com" rel="nofollow external">test</a>';
$dom = new DOMDocument;
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$nodes = $xpath->query("//a[contains(concat(' ', normalize-space(@rel), ' '), ' external ')]");
foreach($nodes as $node) {
$node->setAttribute('href', 'http://example.org');
}
echo $dom->saveHTML();

What are the best practices for PHP syntax when used within HTML?

In PHP templates, that's exactly the way I do it, too (foreach/endforeach).

But really, when it comes to syntax, this is simply a matter of preference. Thus, no "best practice". Go with what you like and - more importantly - stick to it!

I'm sure there are good reasons for either approach.

I don't know if it is a good practice to put values from database in html id attribute

I was going to put it as a comment but got a bit big:

The chances at vulnerabilities will depend on how you process those values before/after presenting them to the user (and I'm sure that you are applying fixes for them):

  • As Michael said in a comment, there's a possibility for XSS if you don't sanitize the values before you write them on your HTML;
  • Also, take into account that these IDs are in the client's side, you will need to sanitize them properly before using them in the database to avoid possible SQL injection;
  • Finally, even if you sanitize them and they are correct, you'll need to double check that the values are valid and compatible. For example, imagine your ID being idOfRow_idOfForeignKey_idOfCurrentUser with a value of 1_23_45, but I change it somehow to 1_34_78. What would happen then? Is the code ready for that or will I be updating somebody else's record?

I don't know if the way IDs are displayed on the post can be considered as a good practice, personally I wouldn't do it that way, and even if I did, I'd follow some rules:

  • Never trust user input. And what better way to explain it than with humor: http://xkcd.com/327/... Sanitize all input, use parameterized queries.
  • Never trust your own input. Even if you think you are the source, the values that you are reading from the database may have been provided by a user through a web form. Sanitize all output.
  • Verify that the data provided is valid. Even if you sanitize the data, it comes from an "unknown" user, they may have changed the IDs manually. E.g.: double check that the user ID that is performing the operation has permissions to do so.
  • Put the values in the right place. Why put the current user ID in the tag ID? It should be somewhere else: a session variable, or if you want to have it available on the client side, a hidden input/variable; and for the other IDs, they probably should go in the href or in a data- attribute.
  • Provide the least possible information to the user. Users do not need to know your IDs, they don't need to know data tables/column names... A "good person" will not need them, a "bad person" may use them against you.

I tried to focus on the ones that would apply to the example in the question (although they'd apply to any project), and probably missing something.

Add attribute to HTML tag depending on inner pattern using PHP

A regex is not the correct tool for this job. Stick with the DOM parser approach. Here's a quick solution using DOMDocument class.

Use getElementsByTagName('*') to get all the tags, and then use in_array() to check if the tag name is in the list of disallowed tags.

Then use a regex with preg_match() to check if the text content follows the {foo:bar} pattern. If it does, add the new attributes one by one, setAttribute() method:

// An array containing all attributes
$attrs = [
'class' => 'foo'
/* more attributes & values */
];

$ignored_tags = ['body', 'head', 'html', 'link', 'script'];

$dom = new DOMDocument;
$dom->loadXML($html);

foreach ($dom->getElementsByTagName('*') as $tag)
{
// If not a disallowed tag
if (!in_array($tag->tagName, $ignored_tags))
{
$textContent = trim($tag->textContent);

// If $textContent matches the format '{foo:bar}'
if (preg_match('#{\s*[^>]*:\s*[^>]*\s*[^}]}#', $textContent))
{
foreach ($attrs as $attr => $val)
$tag->setAttribute($attr, $val);
}
}
}

echo $dom->saveHTML();

Output:

<section class="foo"> 
{foo:bar}
</section>

Best practice for structuring HTML header in PHP

Not to troll, but you're describing the need for a PHP content management system, like WordPress or Drupal. That's exactly what they do.

There's no performance advantage to using PHP in the architecture you describe as opposed to creating separate HTML pages and including header and footer in them. Maybe it saves a few minutes over the course of a month, but you lose most of the automation features that make content so manageable. Plus CSS is a headache, and databases are more challenging. etc, etc.

php code within value attribute for html

I believe it needs to look as follows:

<...value="<?= $first_name.' '.$last_name ?>" readonly>


Related Topics



Leave a reply



Submit