Codeigniter 2.1 - insert HTML page into database - php

I am trying to create mini CMS, where user can create new page and then that page become part of menu. Is it smart to insert full pages into database or there is better way to do so? Also I am having a bit of the problem with a tag when I am inserting.
Code for now:
For inserting page into db:
public function strana_insert()
{
$this->admin_login_check();
$clear = $this->str->clean_request();
$char = array('\n', '\n');
$strana = str_replace($char, '<br>', $clear['opis']);
$kljucna_rec = str_replace( ' ', '_', mb_convert_case($clear['naziv'], MB_CASE_LOWER, "UTF-8") );
$data = array(
'naziv' => $clear['naziv'],
'strana' => htmlspecialchars($strana, ENT_QUOTES , "UTF-8"),
'kljucna_rec' => $kljucna_rec,
'datum_kreiranja' => date("Y-m-d H:i:s")
);
$this->str->save($data);
$this->save_routes();
redirect('admin');
}
Code for clean_request function:
public function clean_request()
{
foreach($_POST as $key=>$value) :
$clean[$key]=mysql_real_escape_string(trim($value));
endforeach;
return $clean;
}
When I insert page with a tag I get following result:
www.example.com
After updating page everything between *\ * is deleted. What is going on here?

You can use Codeigniter's active class to insert this OR use the following method.
before inserting HTML data to database do this :
$html_for_db = addslashes($html_content);
and insert $html_for_db to database.
While displaying this content,
echo stripcslashes($data_from_db);
stripcslashes() - Un-quote string quoted with addcslashes
More info : http://php.net/manual/en/function.addslashes.php

it's because of escape function!!
htmlspecialchar change your code to just a simple string!!
if you'd like to save as html you should save the code without escaping!
BTW, This isn't an smart way to create a static pages, You may like to create a layout and simply let users put content in it ;)

If you want to store html in your DB I recommend using htmlpurifier to clean up your html code and also strip out unwanted html tags.
http://htmlpurifier.org/
There is also a helper which makes using htmlpurifier within CodeIgniter really easy: https://github.com/refringe/codeigniter-htmlpurifier
After you cleaned your input string with htmlpurifier you should use Codeigniters Active Record class to insert your data (http://ellislab.com/codeigniter/user-guide/database/active_record.html). This way the framework will do the escaping.

You have to prevent two types of attacks here: SQL injection and cross-side scripting. You considered both and used htmlspecialchars() against XSS and mysql_real_escape_string() against SQL injection.
But you used them in the wrong order. You first have to use htmlspecialchars, because that's the thing you want to store/output. To put it savely into the database you have to wrap it into its mysql_real_escape_string-ized presentation before storing it or use parameter binding instead.

Related

How to properly clean html post to save in mysql

I'm trying to create a blog system, I'm at a point where i want to save the blog post data into mysql but little confuse how to clean or sanitize the data here is what I've tried
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
return $data;
}
Now when i posted blog data through ajax it looked like
<h1 class="text-center">
Write the titles of article here
</h1>
then i clean the post data & echo it
echo $title = mysqli_real_escape_string($connecDB, test_input($_POST['page__title']));
Then here is what I got in response
\r\n Write the titles of article here\r\n
I want to know why I'm getting these \r\n in the response how can i get rid of them which is the best way of cleaning html post
Note: i want to save the data as html in mysql
I already have a regex that will find style & script tags & remove it, i also tried removing strip slashes & tried adding strip_tags also but still I'm getting \r\n
You're getting \r\n because mysql_real_escape_string() replaces control characters with the corresponding escape sequences. This function is only intended for use when you're going to substitute the variable into a MySQL query, it shouldn't be used for outputting in HTML. The proper function to sanitize for HTML output is htmlentities().
$title = test_input($_POST['page__title']);
echo htmlentities($title);
If you want to retain line breaks in the output, you should also use nl2br().
echo nl2br(htmlentities($title));

Insert strings with apostrophes into database by php

I want to post data into database in safe mode.
For example if i want to add this title to database:
$title = " here is title 'here is title' here is title ";
notice it has apostrophes.
I use this function to make string safe:
function stringsafe($string)
{
$string = strip_tags(trim(addslashes($string)));
return $string;
}
as you see it's adding slashes before apostrophes to make it safe.
I tried to remove slashes when i show the data by stripslashes, it's working but it's has some problems. Is there anyway to post data into database?
On a side note, in fact the general rules of thumb is that, you shouldn't alter user input at all. You should store whatever user input as it is, into your database, so that you can retain user input as original as possible, and only escape it when you need to display or use it.
In your case, yes you are right you have to prevent it from being injected, but you are altering the original input by adding slashes into the original input, which is not very favoured. What if my title contains a string like this <My 21st Birthday Party!> and you stripped it away?
Try using Prepared Statements instead so you can insert any data into your database, without the worries of injection. And only when you need the data to be displayed on a HTML page or console, you escape them accordingly such as htmlentities.

PHP - String Clean

I'm starting a comment system for my website. The problem is I want to use an HTML editor, but is not fully necessary.
My problem is with the security. How to secure the user input that I save in database? Because I show that input on my website and I want to prevent XSS, SQL Injection and other things like that. But I still want my users to be able to write any characters.
For example, daniweb uses and HTML EDITOR (wysiwyg .
I also tried
function bstring( $value )
{
$value = htmlentities( $value, ENT_QUOTES );
$value = strip_tags( $value );
$value = mysql_real_escape_string( $value );
return (string)$value;
}
If you use mysqli
you can use this:
$mysqli->real_escape_string($value);
It
Escapes special characters in a string for use in an SQL statement
If you want to allow the user to input HTML tags but disallow him to use certain tags like Scripts, you should just implement some form of whitelisting for tags.
$allowed_tags = "<b><i><br>"; // Some safe examples
$value = strip_tags( $value, $allowed_tags );
Allways know when and why to use which filter:
mysql_real_escape_string - Protects your SQL against injection - Allways needed if no connector with proper parameter binding is used
strip_tags - Removes unwanted tags from unsafe output you show on your page. Can be used to counter XSS attacks - See above
htmlspecialchars - Encode html tags so that they will no longer work. Protects agains XSS but also removes HTML functionality - You dont want this as you actually want users to use HTML tags
htmlentities doesnt provides security
you need to strip the html using replace
following a list what tags you want to forbid and what tags you want to allow
function bstring($str){
//forbid your tags here
$forbidden_tags = array('script', 'body', 'html');
for($i = 0; $i < count($forbidden_tags); $i++){
$tag = '%<'.$forbidden_tags[$i].'.*?</'.$forbidden_tags[$i].'>%i';
$result = preg_replace($tag, 'NOT ALLOWED', $str);
}
return $result;
}
You can use Doctrine: http://en.wikipedia.org/wiki/Doctrine_%28PHP%29
One of Doctrine's key features is the option to write database queries in a proprietary object oriented SQL dialect called Doctrine Query Language (DQL). Actual SQL queries are generated by Doctrine only (that would protect from SQL Injection and other things like that).
official site: http://www.doctrine-project.org/
read this about security: http://www.doctrine-project.org/2014/02/21/security_in_doctrine.html

Specifying some part of the page to be interpreted as plain text

I am beginner in web development, I am developing a site that allows user to post various discussions and others comment and reply on it. The problem I am facing is, the user can post almost anything, including code snippets and any other thing which might possible include single quotes, double quotes and even some html content.
When such posts are being posted, it is intervening with the MySQL insert query as the quotes are ending the string and as a result the query is failing. And even when I display the string using php, the string is being interpreted as html by the browser, where as I want it to be interpreted as text. Do I have to parse the input string manually and escape all the special characters? or is there another way?
You need to read up on a few things
SQL Injection - What is SQL Injection and how to prevent it
PHP PDO - Using PHP PDO reduces the risk of injections
htmlentities
The basic premise is this, sanitize all input that is coming in and encode everything that is going out. Don't trust any user input.
If possible, whitelist instead of blacklisting.
EDIT :
I you want to display HTML or other code content in there, users need to mark those areas with the <pre> tag. Or you could use something like a markdown variation for formatting.
Use PDO, prepared statements and bound parameters to insert / update data, eg
$db = new PDO('mysql:host=hostname;dbname=dbname', 'user', 'pass');
$stmt = $db->prepare('INSERT INTO table (col1, col2) VALUES (?, ?)');
$stmt->execute(array('val1', 'val2'));
Edit: Please note, this is a very simplified example
When displaying data, filter it through htmlspecialchars(), eg
<?php echo htmlspecialchars($row['something'], ENT_COMPAT, 'UTF-8') ?>
Update
As noted on your comment to another answer, if you want to maintain indentation and white-space when displaying information in HTML, wrap the content in <pre> tags, eg
<pre><?php echo htmlspecialchars($data, ENT_COMPAT, 'UTF-8') ?></pre>
Look at mysql_real_escape_string and htmlentities functions in PHP manual.
You can also read the Security chapter in PHP manual.
To avoid the breaking of queries in database (which means you're not escaping them, leaving big holes for sql injection) you use mysql_real_escape_string($string) on the value before passing it to the query string, enclosing it in quotes also.
Ex. $value = mysql_real_escape_string($value); // be sure to have an open connection before using this function.
$query = "select * from `table` where value = '".$value."'";
As for displaying in html, you should at least echo htmlentities($string) before outputting it to the browser.
Like echo htmlentities($mystring, ENT_QUOTES)`;
Edit:
To preserve withe spaces, you can use nl2br function (which converts linebrakes to the html equivalen <br />) or go for a little deeper $string = nl2br(str_replace(" ", " ", $string));, but html code would look a bit ugly, at least for me
Reference: htmlentities and mysql_real_escape_string. nl2br
use mysql_real_escape_string. It is a good practice to use this on all user inputs to prevent SQL Injection attacks.

PHP HTML Entities

I want to display on screen data send by the user,
remembering it can contain dangerous code, it is the best to clean this data with html entities.
Is there a better way to do html entities, besides this:
$name = clean($name, 40);
$email = clean($email, 40);
$comment = clean($comment, 40);
and this:
$data = array("name", "email," "comment")
function confHtmlEnt($data)
{
return htmlentities($data, ENT_QUOTES, 'UTF-8');
}
$cleanPost = array_map('confHtmlEnt', $_POST);
if so, how, and how does my wannabe structure
for html entities look?
Thank you for not flaming the newb :-).
"Clean POST", the only problem is you might not know in what context will your data appear. I have a Chat server now that works via browser client and a desktop client and both need data in a different way. So make sure you save the data as "raw" as possible into the DB and then worry about filtering it on output.
Do not encode everything in $_POST/$_GET. HTML-escaping is an output-encoding issue, not an input-checking one.
Call htmlentities (or, usually better, htmlspecialchars) only at the point where you're taking some plain text and concatenating or echoing it into an HTML page. That applies whether the text you are using comes from a submitted parameter, or from the database, or somewhere else completely. Call mysql_real_escape_string only at the point you insert plain text into an SQL string literal.
It's tempting to shove all that escaping stuff in its own box at the top of the script and then forget about it. But text preparation really doesn't work like that, and if you pretend it does you'll find your database irreparably full of double-encoded crud, backslashes on your HTML page and security holes you didn't spot because you were taking data from a source other than the (encoded) parameters.
You can make the burden of remembering to mysql_real_escape_string go away by using mysqli's parameterised queries or another higher-level data access layer. You can make the burden of typing htmlspecialchars every time less bothersome by defining a shorter-named function for it, eg.:
<?php
function h($s) {
echo(htmlspecialchars($s, ENT_QUOTES));
}
?>
<h1> Blah blah </h1>
<p>
Blah blah <?php h($title); ?> blah.
</p>
or using a different templating engine that encodes HTML by default.
If you wish to convert the five special HTML characters to their equivalent entities, use the following method:
function filter_HTML($mixed)
{
return is_array($mixed)
? array_map('filter_HTML',$mixed)
: htmlspecialchars($mixed,ENT_QUOTES);
}
That would work for both UTF-8 or single-byte encoded string.
But if the string is UTF-8 encoded, make sure to filter out any invalid characters sequence, prior to using the filter_HTML() function:
function make_valid_UTF8($str)
{
return iconv('UTF-8','UTF-8//IGNORE',$str)
}
Also see: http://www.phpwact.org/php/i18n/charsets#character_sets_character_encoding_issues
You need to clean every element bevor displaying it. I do it usually with a function and an array like your secound example.
If you use a framework with a template engine, there is quite likely a possibility to auto-encode strings. Apart from that, what's simpler than calling a function and getting the entity-"encoded" string back?
Check out the filter libraries in php, in particular filter_input_array.
filter_input_array(INPUT_POST, FILTER_SANITIZE_SPECIAL_CHARS);

Categories