PHP - Is Using Htmlentities() To Sanitize $_posts Adequate Protection?
I have never looked into sanitizing before, Is using htmlentities() good enough to protect against sql injection ?
Thanks. Similar TutorialsHey Guys! I would really like some feedback on the following: I have a site in Portuguese. Php retrieves a lot of POST's with Special Characters and Portuguese Accents (which are expected). With my sanatize function I am having some real problems with the 'htmlentities' for XSS Injection Prevention. htmlentities is changing the accents to strange characters and messes up my database. sanitize( &$_GET ); sanitize( &$_POST ); sanitize( &$_COOKIE ); function sanitize( &$some) { $some = array_map('htmlentities', $some); //XSS Prevention foreach( $some as $key => $value ) { $value = str_replace( '--', '', $value ); $value = str_replace( '/*', '', $value ); $value = str_replace( '"', '', $value ); $value = str_replace( "'", '', $value ); $value = ereg_replace( '[\( ]+0x', '', $value ); if ($value != $some[$key]) { $some[$key] = $value; } } } The only solution I can think of is to take out the 'htmlentities' function, but I would really like to have this as a prevention against XSS, is there any way around this to have both things working? Any ideas, suggestions? Thanks in advance! Folks,
Someone suggested I sanitize user inputs. $primary_website_domain_confirmation = trim($_POST["primary_website_domain_confirmation"]); if (!filter_var($primary_website_email,FILTER_VALIDATE_EMAIL)) { echo "You entered an Invalid Email Address!";
Now, got to add sanitation part. So, where to add it ?
Latter tutorial looks simpler. Let's try copying that. // Remove all illegal characters from email $primary_website_email = filter_var(trim($email, FILTER_SANITIZE_EMAIL)); //Validate Email if (!filter_var($primary_website_email,FILTER_VALIDATE_EMAIL)) { echo "You entered an Invalid Email Address!";
Did I fit in the SANITIZER at the right place or not ? Cheers! For some reason I commented out mysql_real_escape_string on my sanitize function, and I don't remember why I did it. Is it something that is vital and I should un-comment it out? function sanitize($formValue){ if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) { $formValue = stripslashes($formValue); } //$formValue = mysql_real_escape_string($formValue); return $formValue; } II have been told that I should sanitize my inputs, what does that mean? Isn't that what trim does? I would like to sanitize input from users so when it's pulled out of the database and stuck into the page, they can't add malicous code to my page. I have heard of striptags but wonder if there is anything better. thanks Hi guys, do you have any idea on how to sanitize this code? using FILTER_SANITIZE_STRING; FILTER_VALIDATE_IP and ect? Thanks Code: [Select] <form action="rnrequest.php" method="POST"> <table class="txt2"> <tr><td >Song title: </td><td><input type="text" name="song" value="" class=".texta"></td></tr> <tr><td>Artist: </td><td><input type="text" name="artist" value=""></td></tr> <tr><td>Your name: </td><td><input type="text" name="name" value=""></td></tr> <tr><td>Greetings: </td><td><textarea name="greetings"></textarea></td></tr> </table> <input type="submit" name="submit" value="Send"> </form> </div> <?php if (isset($_POST['submit'])) { if (empty($_POST['name'])) { echo "Sorry, you haven't supplied your name<br />"; $reg = "no"; } $sql = "SELECT COUNT(*) FROM request_song WHERE ip='{$ip}'"; $result = mysql_query($sql); if (mysql_result($result, 0) > 0) { echo "Sorry, You already wished for one song, you cannot request for another until the DJ's have seen your request..<br />"; $reg = "no"; } if ($reg == "yes") { $dt2=date("Y-m-d H:i:s"); $sql = "INSERT INTO request_song(song, artist, name, greetings, ip, date) VALUES('{$_POST['song']}', '{$_POST['artist']}', '{$_POST['name']}', '{$_POST['greetings']}','{$ip}', '$dt2')"; mysql_query($sql); } } ?> Folks this one line and any other variations I have tried just nulls my variable Code: [Select] function check_input($value) { echo '<pre>'; echo "Value before = "; echo $value; echo '</pre>'; // Stripslashes //if (get_magic_quotes_gpc()) // { // $value = stripslashes($value); // } // Quote if not a number //if (!is_numeric($value)) // { $value = "'" . mysql_real_escape_string($value) . "'"; <----- //$value = mysql_real_escape_string($value); //$value = mysql_real_escape_string($value); echo '<pre>'; echo "Value after = "; echo $value; echo '</pre>'; // } return $value; } ... // Make a safe SQL $iso_code = check_input($iso_code); $country_name = check_input($country_name); $query = "select * from countries where iso_code = '".$iso_code."' or country like '%".$country_name."%'"; mysql_query($query); echo '<pre>'; echo $iso_code; echo $country_name; echo $query; echo '</pre>'; The result is:- Code: [Select] Value before = UK Value after = '' Value before = United Kingdom Value after = '' ''''select * from countries where iso_code = '''' or country like '%''%' with no mysql_real_escape statement the app work fine. I'm now trying to make my code more robust. Any help would be appreciated. jamie Hi all, I just stumbled upon the 'new' filter function of php and i was wondering if someone could maybe recommend me which to use. for instance if i have a script: <?php $_evilstring = "<script> alert('justin bieber is ruining your sound system')</script>"; $_clean1 = htmlspecialchars($_evilstring); echo 'clean string one = '.$_clean1.'<br />'; $_clean2 = filter_var($_evilstring, FILTER_SANITIZE_SPECIAL_CHARS); echo 'clean string two = '.$_clean2.'<br />'; ?> Both output exactly the same. Now i was wondering if there might be differences in them. For some reason I would like to use the filter function because the name sounds better, but that of course is not very scientific. Anyone with ideas maybe performance, speed, wickedness?? Hi everyone I am trying to secure some of my code using a sanitize function function sanitize($data) { $cdata = strip_tags(addslashes($data)); $cdata = mysql_real_escape_string($cdata); return $cdata; } If I post a form value such as Code: [Select] 'Apple iPod' to a SQL INSERT QUERY using `title` = sanitize($_POST['title']); then my database value looks like Code: [Select] \\\'the ipod\\\' this is odd because there is 3 slashes if I then print that value on a PHP page using print stripslashes($row['title']); it outputs Code: [Select] \'the ipod\' Why can I not get rid of the slashes and why would it be outputting 3 slashes? I have tried all the magic quote ideas and suggestions, but still cannot sort this out. Thanks John Hey all, While the filter itself is functioning properly, the flag doesn't seem to be. Here's how I have it set up: Code: [Select] $UserInput = filter_var($UserInput , FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW); // Test Format 1 $UserInput = filter_input(INPUT_POST, 'UserInput', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW); // Test Format 2 As you can see, I have set up to test methods however, each one fails regarding the flag..or so it's seeming to me. FILTER_FLAG_STRIP_LOW is supposed to strip out anything > 32 in ascii, but it isn't. '&' (38) is greater than 32 but it still displays in the browser. Am I missing something here? This topic has been moved to Third Party PHP Scripts. http://www.phpfreaks.com/forums/index.php?topic=346794.0 I can't seem to get htmlentities working in the code below... echo "<textarea id=\"question" . $questionNo . " name=\"qaArray[\"answerText\"]\" cols=\"60\" rows=\"2\">" . (isset($questionNo) ? "htmlentities($qaArray[\"answerText\"], ENT_QUOTES" : "") . "</textarea>"; I tried using the default single quotes around answerText but that doesn't, nor do my escaped double quotes. What is wrong? Thanks, Debbie Now, I'm trying to figure out some security factors of a website with a login etc. Would I need to add and strip slashes if I'm using htmlentities on anything that the user enters? Wondering about htmlentities() as I have a rich text editor implemented on my website, how would I correctly use htmlentities() as I still want the data which was put into the rich text editor to correctly show, sorry for me being a bit vague, it is late and im tired but hope someone can shine some light on this for me I don't really understand what htmlentities() does and when to use it?! The manual says this... <?php $str = "A 'quote' is <b>bold</b>"; // Outputs: A 'quote' is <b>bold</b> echo htmlentities($str); // Outputs: A &#039;quote&#039; is <b>bold</b> echo htmlentities($str, ENT_QUOTES); ?> 1.) Isn't there a way to print this... Code: [Select] $str = "A 'quote' is <b>bold</b>"; ...as this... Quote A 'quote' is <b>bold</b> That is, WYSIWYG. 2.) When and why would you want this displayed... Quote A 'quote' is <b>bold</b> I am trying to make my code more secure, and I was told to use something like this on all code that comes from the User and needs to be output, but I'm a little lost here... echo ' <div class="userInfo"> <a href="#" class="username"> <strong>' . nl2br(htmlentities($username)) . '</strong> </a>'; Debbie Hi all i was just trying to test out what the effect is of htmlentities() and htmlspecialchars() with an without ENT_QUOTES, but it looks like it's not working as expected. I made a small script to compare the 2 the only thing happends that javascript isn't executed, but i though it would convert special characters into even more special ones I am running on xampp btw if that helps $plain_input = "I am going to hax0r your site, hahaha! <script type='text/javascript'> window.location = 'http://www.google.com/' </script>"; $plain_input2 = htmlentities($plain_input); $plain_input2_ent = htmlentities($plain_input,ENT_QUOTES); echo '<b>htmlentities: </b>'.$plain_input2.'<br />'; echo '<b>htmlentities + entquotes: </b>'.$plain_input2_ent.'<br />'; echo '<hr /><br />'; $plain_input3 = htmlspecialchars($plain_input); $plain_input3_ent = htmlspecialchars($plain_input,ENT_QUOTES); echo '<b>htmlspecialchars:</b> '.$plain_input3.'<br />'; echo '<b>htmlspecialchars + entquotes:</b> '.$plain_input3_ent.'<br />'; echo '<hr /><br />'; this just outputs: Code: [Select] htmlentities: I am going to hax0r your site, hahaha! <script type='text/javascript'> window.location = 'http://www.google.com/' </script> htmlentities + entquotes: I am going to hax0r your site, hahaha! <script type='text/javascript'> window.location = 'http://www.google.com/' </script> htmlspecialchars: I am going to hax0r your site, hahaha! <script type='text/javascript'> window.location = 'http://www.google.com/' </script> htmlspecialchars + entquotes: I am going to hax0r your site, hahaha! <script type='text/javascript'> window.location = 'http://www.google.com/' </script> Think i've got my self a little confused here. htmlentities This function is designed to try and keep clients safe. If the comment the user inputs can only ever be seen by him or her, then in theory is there no need to use htmlentities as any dodgy script would only affect them. Is this correct thinking? I have let say Thai language and inserted into database Code: [Select] <b>บริษัท เอส.เค.ฟู้ดส์ (ประเทศไทย) จำกัด (มหาชน) เป็นผู้นำเข้า-ส่งออกปลาทูน่าบรรจุกระป๋อง ต้องการรับสมัครพนักงานเพื่อรองรับการขยายกิจการ</b> and i retrieve it using this nl2br(htmlentities($array['message'])) the result will completely messed up as the thai language will be converted either. if i ignore the htmlentities then i will have that message in bold how can i achieve the result exactly the same like what has been written (message in thai language with that <b> html tag)?? thanks in advance What do most people prefer to use? htmlspecialchars or htmlentities So, If I want to store something like: Code: [Select] Hello<br /> <b>This is a sentence </b> I would need to use htmlentities() So I could output the HTML after it's stored in the database safely? |