PHP Safely structure user input's output - php

I have a PHP project that allows users to submit an article / tutorial and before I insert the data to my database I do
$content1 = htmlspecialchars($userscontent);
$content = htmlentities($content1, ENT_QUOTES);
for safety purposes and when I output the data from my database I decode it. Now I want that text to be structured and not just written on one line and I also want to add the ability to add images to the articles and I have no idea which is the best way to go about this.
Any help is appreciated.

Could you not just use the decode?
$result1 = html_entity_decode($result, ENT_QUOTES);
$result = htmlspecialchars_decode($result1);
References:
Html entity decode
Htmlspecialchars decode
Although, I would definitely recommend doing what #CD001 says and use the HtmlPurifier library.

Related

Save line breaks (in database)

Is there any possibility in PHP to save new lines in an textarea into a sql database?
I mean without typing in html commands like br ?
If not, how its done here? And how i can install it into my programm?
Thanks for help!
$descriptionraw = mysqli_real_escape_string($conn, $_POST['setdescription']);
$description = nl2br($descriptionraw);
The premise of this question is flawed, as the newlines are stored in the database already.
At least as long as you haven't done anything to remove them prior to saving the input, that is.
The question should be how to display the newlines in HTML pages, and for this you have a couple of methods.
Either use a <pre> tag around the output. This will cause the text to be showns preformatted, and thus include the newlines as actual content. The bad side about this is that the text won't break normally, and as such can (and will) break out of the natural flow of your page.
Or use nl2br() or a custom nl2p() function, when echoing the content to the browser. This translates the newlines into <br> (or <p>) tags, and will follow the normal flow of your site's layout. Which makes this the recommended method.
PS: This line is wrong:
$description = nl2br($descriptionraw);
This is function to format output to a HTML-compatible viewer, a database is not. Using nl2br() and similar functions before you save stuff to the database will only cause you headaches, especially if you ever want to view the data in something that is not equipped to handle HTML code. (Such as the native MySQL client.)
Quick and dirty examples, using PDO:
First for saving the data:
$input = filter_var ($_POST['input'], FILTER);
$stmt = $db->prepare ("INSERT INTO `table`(`input`) VALUES (:data)");
$stmt->exec (array (':data' => $input));
Then for displaying it:
$output = '';
$res = $db->exec ("SELECT `input` FROM `table`");
foreach ($res->fetchArray () as $row) {
$output .= nl2br ($row['input']);
}
echo $output;
User php function nl2br
echo nl2br("This\r\nis\n\ra\nstring\r");

How to insert wysiwyg edited text into database

The Idea
I have a forum in my project and i'm trying to implement wysiwyg editor to post questions and answers. Actually the project is already completed and now i'm trying to implement NicEdit wysiwyg editor to all the required textareas. I'm using the following lines of prior to database insertion of posted data :
$post_body = $_POST['post_body'];
$post_body = nl2br(htmlspecialchars($post_body));
$post_body = mysqli_real_escape_string($db_conx,$post_body);
Problem
When I insert the posted data I'm getting the following output :
Conclusion
I want to know how to insert the wysiwyg edited content into the database. Apart from this, please suggest me some nice wysiwyg plugins which are easy to embed in my project. Currently, i'm using NicEdit which is pretty easy to embed but with limited functionalities.
Why don't you decode it with: htmlspecialchars_decode() before echoing?
That may solve your problem.
Edit:
You could do strip_tags() and allow only few markup tags.
Eg:
// Allow <p> and <a>
echo strip_tags($text, '<p><a>');
Thus you could strip risky tags like <script>
Don't do this:
$post_body = nl2br(htmlspecialchars($post_body));
That is how you create an HTML representation of plain text. You are asking people to submit HTML, not plain text.
(Do, however, implement a whitelist based, HTML aware XSS filter such as HTML Purifier)

Storing HTML in MySQL

I'm storing HTML and text data in my database table in its raw form - however I am having a slight problem in getting it to output correctly. Here is some sample data stored in the table AS IS:
<p>Professional Freelance PHP & MySQL developer based in Manchester.
<br />Providing an unbeatable service at a competitive price.</p>
To output this data I do:
echo $row['details'];
And this outputs the data correctly, however when I do a W3C validator check it says:
character "&" is the first character of a delimiter but occurred as data
So I tried using htmlemtities and htmlspecialchars but this just causes the HMTL tags to output on the page.
What is the correct way of doing this?
Use & instead of &.
What you want to do is use the php function htmlentities()...
It will convert your input into html entities, and then when it is outputted it will be interpreted as HTML and outputted as the result of that HTML...For example:
$mything = "<b>BOLD & BOLD</b>";
//normally would throw an error if not converted...
//lets convert!!
$mynewthing = htmlentities($mything);
Now, just insert $mynewthing to your database!!
htmlentities is basically as superset of htmlspecialchars, and htmlspecialchars replaces also < and >.
Actually, what you are trying to do is to fix invalid HTML code, and I think this needs an ad-hoc solution:
$row['details'] = preg_replace("/&(?![#0-9a-z]+;)/i", "&", $row['details']);
This is not a perfect solution, since it will fail for strings like: someone&son; (with a trailing ;), but at least it won't break existing HTML entities.
However, if you have decision power over how the data is stored, please enforce that the HTML code stored in the database is correct.
In my Projects I use XSLT Parser, so i had to change to   (e.g.). But this is the safety way i found...
here is my code
$html = trim(addslashes(htmlspecialchars(
html_entity_decode($_POST['html'], ENT_QUOTES, 'UTF-8'),
ENT_QUOTES, 'UTF-8'
)));
And when you read from DB, don't forget to use stripslashes();
$html = stripslashes($mysq_row['html']);

(PHP) Simple HTML DOM parser: HTML symbols

I'm trying to get usernames from this website and this is what I've done:
$div = $html->find('div[class=micro-home-recent-review review-item]');
for ($i=0; $i<count($div); $i++){
$username = $div[$i]->find('div[class=tooltip-fullname]', 0)->find('b', 0)->plaintext;
// I've tried using iconv but apparently it doesn't work
$username = iconv(mb_detect_encoding($username), "UTF-8", $username);
$query = "INSERT INTO users ('name') VALUES ($username)";
$pdo->query($query);
}
Then the newly inserted records in my database are:
As you can see, most of the names are recorded with HTML symbols, which can be displayed normally on browsers, but get messed up when shown as JSON. The same problem happens when I tried to get reviews, and below is the sample JSON of a review:
I need the JSON to show data in my Android app, therefore this problem needs to be solved or the data won't be displayed properly. What could be a possible solution for this? I really need your help and suggestions.
try to use html_entity_decode() function.
use htmlentities_decode() that will solve your problem.

How to decode mysql_real_escape_string

I have saved some information in database with MySQL, now i want to show them, cause it contains some tags like <div>, <p>, etc. I just want them showed as raw html code, anyone can tell me how? i try to use `html_entity_decode(), but it does not work.
Example:
<div><b>Prénom/Nom : </b>tantantan tan</div>
<div><b>Pseudonyme : </b>nickname</div>
<div><b>Résidence principale : </b>69001 Lyon 1er</div>
<div><b>Autre résidence : </b> Place bellecours 69002 Lyon 2e</div>
====== in fact , i need to do in this way.
#using serialize() method
$data = serialize($_SESSION);
$sql = "Insert into sessioninfo `data` values('$data')";
and then
# I assume you can retrieve the data from database and assign to the following variable
$data = unserialize($row['data']);
perfectly resolve my problem. thanks everyone.
This is not an mysql_real_escape_string data but html_specialchars() encoded data
you can do the reverse with htmlspecialchars_decode()
Try html_entity_decode:
echo html_entity_decode($string);
Would recommend not to apply htmlspecialchars when you save the database.
The sanitize should be applied when sending output, if necessary.

Categories