Passing HTML to Database in Textarea

I’m updating a field in my database via a textarea box. It works perfectly unless there are html tags in the box. Is there an easy solution to this problem?

Hey, what do you know, I eliminated that function altogether and it works perfectly now. I think it was clashing with the rteSafe function that came with the Editor I downloaded.

Thanks for all of your help guys. Sorry I’m too dumb to figure out most of what you are telling me. I’m trying though, God Bless me.

The mysqli_real_escape_string function needs a link identifier (you need to have already established a connection to the database) as the first parameter, the second parameter is the string you want to escape. It needs to have a connection to the database open as it takes into account the character set of the connection which has been established to the database.

The mysqli extenstion requires a established conmnection to the database. Just doing a quick search about PDO it establishes a connection to the database when you create an instance of it so a good rule of thumb would be that to escape or prepare a statement with mysql, mysqli or PDO you need to have a connection to the database established.

Okay, I’m really out of my depth here. All I know to try at this point is to change mysql_real_escape_string to mysqli_real_escape_string, It didn’t work, but it did give me a different error.

Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given in /home2/paulmcra/public_html/siteBuilding/artcarNation/scripts/includes/functions.inc.php on line 80
I tried adding another parameter, an empty string, but that didn’t work either. I got this error instead.

Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, string given in /home2/paulmcra/public_html/siteBuilding/artcarNation/scripts/includes/functions.inc.php on line 80
Where do I go from here?

Apparently mysql_real_escape_string requires you to still be connected to a mySQL database to function… which is really annoying… so you’ll have to connect to the database BEFORE calling loadfromurl.

Which may be time to switch to mysqli or PDO… there’s a reason the normal mysql_ functions should have gone the way of the dodo a good six years ago – and that anyone is writing new software with them is more a testament to web-rot and outdated books than anything else.

Thank you everybody for your help in this matter.

I have been trying to implement 'deathshadow60’s suggestion and have run into a problem.

The page loads fine at first, but then returns an error when I submit the form.

The error goes…

Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Access denied for user ‘paulmcra’@‘localhost’ (using password: NO) in /home2/paulmcra/public_html/siteBuilding/artcarNation/scripts/includes/functions.inc.php on line 85

Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: A link to the server could not be established in /home2/paulmcra/public_html/siteBuilding/artcarNation/scripts/includes/functions.inc.php on line 85
line 85 is the following.

 return mysql_real_escape_string($str);

I also had to fix the code in a couple of places before it would work on my page. isarray is actually is_array and I added curly braces after the first line of the loadfromurl function.

Tell me, please if my “fixes” were correct or are they a part of the problem?

The code as it currently stands is as follows.

function sanitize($str){
    if (get_magic_quotes_gpc()) $str=stripslashes($str);
    if (function_exists('mysql_real_escape_string')) {
        return mysql_real_escape_string($str);
    } else return addslashes($str);
}

function loadfromurl($sRequestName,&$sVariable,$sDefault='')
{
    if (isset($_REQUEST[$sRequestName])) {
        if (is_array($_REQUEST[$sRequestName])) {
            $sVariable=array();
            foreach($_REQUEST[$sRequestName] as $key => $value) {
                $sVariable[$key]=sanitize($value);
            }
        } else $sVariable=sanitize($_REQUEST[$sRequestName]);
        return true;
    } else {
        $sVariable=$sDefault;
        return false;
    }
}

As always, thank you for your assistance.

If you’re using mysqli, there is no such function and you should be using prepared queries instead.

you could use htmlentities() to sanitize html and prevent malicious code from being executed

That sounds interesting and helpful, I’ll look into it, but I don’t think it addresses my problem, exactly.

I just realized that something is happening when I submit the form that is converting the input of the textarea box and causing a problem.

For instance, The contents of the textarea box as follows…

<p>Ken Duffy of El Cerrito California is a tireless chronicler of the west coast artcar scene. He’s finally gotten all of his pictures up from this year’s events.</p>

<p>Click on over to Flickr to vieiw the <a class=“article” href=“http://www.flickr.com/photos/ken_duffy/sets/72157627413212064/”>full set</a>. While you’re there you might want to spend some time perusing some of the rest of his over 21,000 photos, many of them artcar related.</p>
returns a SQL result of…

UPDATE news_TBL SET news_story=’
Ken Duffy of El Cerrito California is a tireless chronicler of the west coast artcar scene. He’s finally gotten all of his pictures up from this year’s events.
Click on over to Flickr to vieiw the full set. While you’re there you might want to spend some time perusing some of the rest of his over 21,000 photos, many of them artcar related.
’ WHERE newsID=28
As you can see, the html code has executed in the SQL string. So I’m thinking I need something that will keep the html tags from executing. How can I do that?

htmlentities() will turn tags into < or > but I don’t think the problem lies in html being executed (but storing executable markup is a BIG security risk), it is probably the single or double quotes.

try using filter_var($text, FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_HIGH) or the mysql_real_escape_string($text) to add slashes to the quotes

Thank you Charles for your help, but I’ve tried all of your suggestions in as many different configurations as I know how and they all came up short in one way or another.

I finally figured out that the problem lies somewhere in the records that were created by inputting data directly into the database. Some of those records won’t update and I don’t exactly know why.

If I wipe the data and input new data it updates fine so I am going to just consider that a glitch for right now.

Moving on, I have installed a text editor into my form, much the same as the text editor that I am using to post on this message board.

I am having difficulty passing the post value of the text editor into my SQL statement.

Here’s the section of code that I believe is the most relevant.

var rte1 = new richTextEditor('rte1');
<?php
//format content for preloading
if (!(isset($_POST["rte1"]))) {
    $content = $news_story;
    $content = rteSafe($news_story);
} else {
    //retrieve posted value
    $content = rteSafe($_POST["rte1"]);
}
?>
rte1.html = '<?=$content;?>';

And here is the SQL statement

$SQL = "UPDATE news_TBL SET ";
$SQL .= "news_date='$news_date' ";
$SQL .= ",news_headline='$news_headline' ";
$SQL .= ",news_author='$news_author' ";
$SQL .= ",news_story='$news_story' ";
$SQL .= "WHERE newsID=$newsID";

Can you please tell me what changes I need to make to pass the value of the text editor into the ‘news_story’ field of my table?

Thank you.

how are you assigning the value to $news_story?

I’m setting the variable with the POST

$news_story = $_POST['news_story'];

I’m also calling a function that retrieves the value from the post/get

loadfromurl("news_story", $news_story, "");

I’m probably being redundant.

Here is the function

function loadfromurl($sRequestName,&$sVariable,$sDefault)
{
    extract ($GLOBALS);
// DESCRIPTION:
// Loads a variable from the URL/POST Request object. If Request object does not equal
// something, leave it as set, or set as default if default value is given
// INPUTS/OUTPUTS:
// sRequestName = Request object name
// lVariable = Variable to set
// lDefault = Default value
// RETURN VALUE:
// False if variable was set to the default, else True
//*******************************************************************************
    $sValue = "";
    $function_ret=true;

    if(isset($_POST[$sRequestName]) )
    {
        $sValue = $_POST[$sRequestName];
    } elseif (isset($_GET[$sRequestName]))
    {
        $sValue = $_GET[$sRequestName];
    }
    
    // Check the length of the requested value
    // If equals something, convert value to string and set variable
    if (strlen($sValue) > 0)
    {
        if (is_array($sValue)) {
            $sVariable=$sValue;
        } else {
            $sVariable=stripslashes($sValue);
        }
        
    } else    { 
        // Else, see if variable is initialized
        // If not initialized, set variable to default
        if (empty($sVariable)==true)
        {
            $sVariable=$sDefault;
            $function_ret=false;
        } 
    } 

  return $function_ret;
}

If you don’t mind me asking, why are you using extract ($GLOBALS);? It just seems like a weird way to set variables. rather than extracting you should work with the $GLOBALS like an array ex $GLOBALS[‘variable’] = $_POST[‘value’]. Alot of unpredictable things can happen when extracting globals but if you really want to extract it, I would suggest setting a FLAG to prevent collisions.

Using extract on either is like having register globals on which is a BAD idea. It also can make it difficult for another coder to trace where global variables being used in a complex script are coming from. This can also be a problem when coming back to code you did a significant time prior and finding where certain variables in the global scope came from. There is no substitute for simply grabbing the values out of $_POST, $_GET, $_REQUEST or $_COOKIE that you want to use in the script. That way no wildcard data makes into your global scope and you can validate your data accordingly.

ALWAYS use either prepared statements or an escape string function designed for the database you are using. Never use entity encoding to encode content headed for a database table. It just makes the input more bloated and doesn’t add to security in the least. entity encoding on output from the db is fine if that is what is needed, but don’t put entity encoded data in the db, it’s not necessary.

Why you didn’t try to use mysql_real_escape_string ?

andyPp has it right in that said function is what you SHOULD be using… that or a MODERN SQL interface like PDO or mySQLi where you have prepared queries – which auto-sanitize for you.

Your function sets a whole bunch of extra variables for nothing and has a lot of unneccesary logic flow… like if you want either get or post – that’s what $_REQUEST is for… first order of business would be to clean up the function:


function loadfromurl($sRequestName,&$sVariable,$sDefault)
	if isset($_REQUEST[$sRequestName]) {
		$sVariable=(
			isarray($_REQUEST[$sRequestName]) ?
			$_REQUEST[$sRequestName] :
			stripslashes($_REQUEST[$sRequestName]);
		}
		return true;
	} else {
		$sVariable=$sDefault;
		return false;
	}
}

Though that doesn’t really address your problem; for that, I’d suggest something more like this:


function sanitize($str){
	if (get_magic_quotes_gpc()) $str=stripslashes($str);
	if (function_exists('mysql_real_escape_string')) {
		return mysql_real_escape_string($str);
	} else return addslashes($str);
}

function loadfromurl($sRequestName,&$sVariable,$sDefault='')
	if (isset($_REQUEST[$sRequestName])) {
		if (isarray($_REQUEST[$sRequestName])) {
			$sVariable=array();
			foreach($_REQUEST[$sRequestName] as $key => $value) {
				$sVariable[$key]=sanitize($value);
			}
		} else $sVariable=sanitize($_REQUEST[$sRequestName]);
		return true;
	} else {
		$sVariable=$sDefault;
		return false;
	}
}

The sanitize function detecting if magic quotes are screwing with you, using mysql_real_escape_string if available, addslashes if not… I think that might be part of where you were messing up – you were doing stripslashes only, when you should be ADDING them if that’s being sent to a database! Stripping them only… uhm… that’s going to screw up any markup.

Also, was unsure what you were having for array data – so I set it up to sanitize all array entries as I assume they are string values.

I’d be tempted to take it one step further, and have it set to return FALSE or the proper value, just like all other PHP functions.


function sanitize($str){
	if (get_magic_quotes_gpc()) $str=stripslashes($str);
	if (function_exists('mysql_real_escape_string')) {
		return mysql_real_escape_string($str);
	} else return addslashes($str);
}

function loadfromurl($sRequestName)
	if (isset($_REQUEST[$sRequestName])) {
		if (isarray($_REQUEST[$sRequestName])) {
			$sVariable=array();
			foreach($_REQUEST[$sRequestName] as $key => $value) {
				$sVariable[$key]=sanitize($value);
			}
			return $sVariable;
		} else return sanitize($_REQUEST[$sRequestName]);
	} else return false;
}

But that really hinges on how you’re calling it.

Still, I think that’s your biggest problem here – you’re stripping slashes when if “magic quotes” is off you shouldn’t be, and nowhere are you adding them to make it safe to send to your queries.