PHP - How Do I Sanitize My Inputs?
II have been told that I should sanitize my inputs, what does that mean?
Isn't that what trim does? Similar TutorialsFolks,
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! 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); } } ?> 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; } 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 How is it possible, in PHP, to display an error message next to a form input text field if a user is attempting to submit a form with empty fields? Moreover, how is it possible to remove the same error message when the user fills in the input field with the required data and/or refreshes the page? I have 2 files that I am working with: application.php and process.php.
application.php mainly has the HTML of the form. I am very new to learning PHP (I started learning it last week) and I have been searching for hours for a clear answer. I have already tried different methods for generating the error message including: using empty(), !isset, $_POST["name"] = "", etc, and have tried using session_start();, $row, echo, print, and other variables to try and display error message on the page, and I have tried using unset();, and = null, to try and remove the error message once the input field has been filled but all to no avail. Either the method I try only half works, or nothing works, and I cannot pinpoint which is the part that is not working. I only have 2 files to work with, and as an example of what I want to do is:
1. If the first name field is empty when the user clicks submit, an error message should appear next to the input. Is this possible with PHP? 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?? 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 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 have never looked into sanitizing before, Is using htmlentities() good enough to protect against sql injection ? Thanks. Hey 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! Does anyone have any idea why my inputs shrink (to default height and weight) after i press submit button? I use css width and height for inputs. All other settings (border, background color etc.) remain like they should. For form submit i use PHP self function where i check if submit button has been pressed and then perform the form action. Thank you Hi! I wanna know what is the best way to secure my inputs? Now I'm using something like this function: public function z($var) { $result1 = htmlspecialchars($var); $result = mysqli_real_escape_string($this->conn, $result1); return $result; } but I don't know how secure it is from all inputs... It couldn't be that with that my site is completely secure... So I wanna know what else I should use... I found something about PHP sanitize filters and similar... Same for mail, should I use that for e-mail, what should I use for e-mails as I think this 2 codes will brake character @ necessary for emails. Any suggestion is welcome Thanks Hello All, I'm working on this project, and everything was great but the last part is screwed. The procedure is supposed to be, you choose a hotel ---> book a room ---> confirm the booking and enter your details --> get redirected to paypal Everything is fine except for the confirmation part, where you're supposed to confirm the room you booked, number of nights and so on, all the info is right, except for the booked room, where it should show you the price for the room multiplied by the number of night... instead it gives "Total Price = 0" So anyone can give me an example on how can I make it show the result of multiplying 2 inputs by a user? Variables are $nrooms $newdate Here is the code I wrote Code: [Select] <?php $dbo = new DB(); $hotelObj = new hotelManager(); $hotelID = $_POST['hotelid']; $datein = $_POST['datein']; $dateout = $_POST['dateout']; $roomid = $_POST['roomid']; $roonsNo = $_POST['roomsNo']; $pr = $_POST['pr']; $_SESSION['hotelID'] = isset($_POST['hotelid']) ? $_POST['hotelid'] : $_SESSION['hotelID']; $_SESSION['datein'] = isset($_POST['datein']) ? $_POST['datein'] : $_SESSION['datein']; $_SESSION['dateout'] = isset($_POST['dateout']) ? $_POST['dateout'] : $_SESSION['dateout']; $_SESSION['roomid'] = isset($_POST['roomid']) ? $_POST['roomid'] : $_SESSION['roomid']; $_SESSION['nrooms'] = $_POST['nrooms']; $roomsarray = explode(",",$_POST['roomid']); $_SESSION['roomsarray'] = isset($_POST['roomid']) ? explode(",",$_POST['roomid']) : $_SESSION['roomsarray']; $roonsNo = $_POST['nrooms']; $_SESSION['nrooms'] = isset($_POST['roomnum']) ? explode(",",$_POST['roomnum']) : $_SESSION['nrooms']; /********************** hotels ************************/ /******************************************************/ echo "<table width=95% border=0 align=\"center\" cellpadding=\"0\" cellspacing=\"0\"> <tr><td valign=\"top\">"; echo "<table>"; echo "<tr>"; echo "<td valign=top>"; $imageqry=mysql_query("SELECT * FROM `hotelphotos` where hotel_id='".$_SESSION['hotelID']."' LIMIT 1"); $image=mysql_fetch_array($imageqry); $imagename=$image['attachmentName']; echo "<img src=\"foxmaincms/webroot/files/small/$imagename\"/>"; echo "</td>"; echo "<td>"; $result=$hotelObj->getHotelbyID($_SESSION['hotelID']); $row = mysql_fetch_array($result); echo "<table>"; echo "<tr><td valign=top><strong class=subtitle3>".$row['name']."</strong></td></tr>"; echo "<tr><td class=text valign=top>".$row['location']."</td></tr>"; echo "<tr><td class=text valign=top>check-in Date: ".$_SESSION['datein']."</td></tr>"; echo "<tr><td class=text valign=top>check-out Date: ".$_SESSION['dateout']."</td></tr>"; echo "<tr><td class=text valign=top>"; $newdate = $_SESSION['dateout'] - $_SESSION['datein']; $totalprice = $nrooms * $newdate; echo "</td></tr>"; echo "<tr><td class=text valign=top>Total Price: ".$totalprice."</td></tr>"; echo "</table>"; ?> I'm working on an online php program that can have a few hundred form inputs. Mainly just numbers from 1 to 50,000 depending on the field. I wanted to use cookies so the user can keep the data entered on their browser but i found out the hard way that the browsers have a limitation that I've exceeded. Does anyone have any ideas? Hey guys I have a lot of inputs from my form. Is there a way I can do like a for each or something instead of of having to write $myusername = stripslashes($_POST['name'); $mypassword = stripslashes($_POST['pass']); $myusername = mysql_real_escape_string($myusername); $mypassword = mysql_real_escape_string($mypassword); .... for all 16 fields? thanks I have a form with several text fields. For example (sorry, no code insert option on my phone) Quote<form method="post"> Enter value1 :<input type="text" name="str1"><br/> Enter value2 :<input type="text" name="str2"><br/> <input type="submit" > I would like to scan the INPUTS to determine which fields were left empty. Using !isset (to the best of my knowledge) would require that I list each input individually. Is there a PHP alternative that, similar to JavaScript, would allow me to evaluate every INPUT or TEXT field to then list those left empty? I recently read another post which stated:
Unfortunately, you should verify every received string as being valid UTF-8 before you try to store it or use it anywhere. PHP's mb_check_encoding() does the trick, but you have to use it religiously. There's really no way around this, as malicious clients can submit data in whatever encoding they want, and I haven't found a trick to get PHP to do this for you reliably.
Seems like a lot of work. How important is really doing so? Can the DB be configured in some kind of strict mode which will error upon anything which isn't, and I can deal with it as an exception?
I was wondering if anyone knows a way where you can submit a form but content of the input fields will not be cleared? The reason why I want to achieve this effect is because I have a form and I want to user to be able to preview the results before properly submitting the form. Therefore I will have two submit buttons, one to preview and one to submit. Thanks for any help. |