I am creating a portfolio. I have an admin page setup with PHP. I want users to post content from the admin panel to the main page. This I can do, but I'm a bit stuck when thinking of ways to post "text features" like images, and bolded text. In HTML, this would be simple enough.
<img alt="A pretty kitten" src="src/img.png">
But would it really be smart to let users use HTML when posting something, and if not, why, and are there any good alternatives?
No, it's definitely not a good idea to let users use html in their post. That makes your application vulnerable to XSS Attacks
Cross-site scripting (XSS) is a type of computer security vulnerability typically found in web applications. XSS enables attackers to inject client-side scripts into web pages viewed by other users. A cross-site scripting vulnerability may be used by attackers to bypass access controls such as the same-origin policy.
Back to your question. There are several ways to approach this problem and one of the simplest solutions is to use a different tags for the HTML ones, use htmlentities()
on the user posted content before storing it into the database. And to actually show the formatted content to the users you parse the tags that you made into their HTML variant.
Example user input:
<b>This is a normal text</b> [b]and this is a bold text[/b]
After you pass that string trough the htmlentities()
function the standard HTML <b></b>
tags will be interpreted as a plain text and will not actually bold the text when displaying the content.
To make the second part of the sentence bold however you'll have to use a function that will parse the [b][/b]
tags into a <b></b>
ones.
Here is an example of how you can do that:
function formatString($string) {
$string = preg_replace('/\[b\]/', '<b>', $string);
$string = preg_replace('/\[\/b\]/', '</b>', $string);
return $string;
}
Allowing anybody to post ANY HTML to your site, is a huge risk. They can do cross site scrpting, forward users to inappropriate pages, include illegal content etc.
As already noted in comments, many CMS offer solutions for this. If you do not want to use a CMS, you might also want to take a look at BBCode. There should be some libraries out there for interpreting BBCode and for BBCode editors. Also, don't underestimate the fact that many users are familiar with this.
BBCode allows users to stylize their text, post images and so on, but prevents the evil stuff.
One option available to you is allowing users to post a limited subset of HTML. Various methods exist for this, but my favorite is HTML Purifier (no affiliation, just a fan), which allows (via an extensive config) a safe whitelist of only certain HTML tags, attributes, etc.
i.e. you could allow <img src="">
but not <img onclick="">
.