PHP - Trying To Sanitize Mysql Query
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 Similar TutorialsHere is my code: // Start MySQL Query for Records $query = "SELECT codes_update_no_join_1b" . "SET orig_code_1 = new_code_1, orig_code_2 = new_code_2" . "WHERE concat(orig_code_1, orig_code_2) = concat(old_code_1, old_code_2)"; $results = mysql_query($query) or die(mysql_error()); // End MySQL Query for Records This query runs perfectly fine when run direct as SQL in phpMyAdmin, but throws this error when running in my script??? Why is this??? Code: [Select] You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '= new_code_1, orig_code_2 = new_code_2WHERE concat(orig_code_1, orig_c' at line 1 If you also have any feedback on my code, please do tell me. I wish to improve my coding base. Basically when you fill out the register form, it will check for data, then execute the insert query. But for some reason, the query will NOT insert into the database. In the following code below, I left out the field ID. Doesn't work with it anyways, and I'm not sure it makes a difference. Code: Code: [Select] mysql_query("INSERT INTO servers (username, password, name, type, description, ip, votes, beta) VALUES ($username, $password, $name, $server_type, $description, $ip, 0, 1)"); Full code: Code: [Select] <?php include_once("includes/config.php"); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title><? $title; ?></title> <meta http-equiv="Content-Language" content="English" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link rel="stylesheet" type="text/css" href="style.css" media="screen" /> </head> <body> <div id="wrap"> <div id="header"> <h1><? $title; ?></h1> <h2><? $description; ?></h2> </div> <? include_once("includes/navigation.php"); ?> <div id="content"> <div id="right"> <h2>Create</h2> <div id="artlicles"> <?php if(!$_SESSION['user']) { $username = mysql_real_escape_string($_POST['username']); $password = mysql_real_escape_string($_POST['password']); $name = mysql_real_escape_string($_POST['name']); $server_type = mysql_real_escape_string($_POST['type']); $description = mysql_real_escape_string($_POST['description']); if(!$username || !$password || !$server_type || !$description || !$name) { echo "Note: Descriptions allow HTML. Any abuse of this will result in an IP and account ban. No warnings!<br/>All forms are required to be filled out.<br><form action='create.php' method='POST'><table><tr><td>Username</td><td><input type='text' name='username'></td></tr><tr><td>Password</td><td><input type='password' name='password'></td></tr>"; echo "<tr><td>Sever Name</td><td><input type='text' name='name' maxlength='35'></td></tr><tr><td>Type of Server</td><td><select name='type'> <option value='Any'>Any</option> <option value='PvP'>PvP</option> <option value='Creative'>Creative</option> <option value='Survival'>Survival</option> <option value='Roleplay'>RolePlay</option> </select></td></tr> <tr><td>Description</td><td><textarea maxlength='1500' rows='18' cols='40' name='description'></textarea></td></tr>"; echo "<tr><td>Submit</td><td><input type='submit'></td></tr></table></form>"; } elseif(strlen($password) < 8) { echo "Password needs to be higher than 8 characters!"; } elseif(strlen($username) > 13) { echo "Username can't be greater than 13 characters!"; } else { $check1 = mysql_query("SELECT username,name FROM servers WHERE username = '$username' OR name = '$name' LIMIT 1"); if(mysql_num_rows($check1) < 0) { echo "Sorry, there is already an account with this username and/or server name!"; } else { $ip = $_SERVER['REMOTE_ADDR']; mysql_query("INSERT INTO servers (username, password, name, type, description, ip, votes, beta) VALUES ($username, $password, $name, $server_type, $description, $ip, 0, 1)"); echo "Server has been succesfully created!"; } } } else { echo "You are currently logged in!"; } ?> </div> </div> <div style="clear: both;"> </div> </div> <div id="footer"> <a href="http://www.templatesold.com/" target="_blank">Website Templates</a> by <a href="http://www.free-css-templates.com/" target="_blank">Free CSS Templates</a> - Site Copyright MCTop </div> </div> </body> </html> 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! I'm restarting this under a new subject b/c I learned some things after I initially posted and the subject heading is no longer accurate. What would cause this behavior - when I populate session vars from a MYSQL query, they stick, if I populate them from an MSSQL query, they drop. It doesn't matter if I get to the next page using a header redirect or a form submit. I have two session vars I'm loading from a MYSQL query and they remain, the two loaded from MSSQL disappear. I have confirmed that all four session vars are loading ok initially and I can echo them out to the page, but when the application moves to next page via redirect or form submit, the two vars loaded from MSSQL are empty. Any ideas? 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); } } ?> 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 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? 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 I have never looked into sanitizing before, Is using htmlentities() good enough to protect against sql injection ? Thanks. 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 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! I have the following MYSQL Query: Basically, the query will not work when i add quotes to the string. I want it to select from e-mails database where subject LIKE '%"$stringservername"%' If I do just '%$SERVERNAME%' it works :S - And the mysql data includes the quotes. I use the $strongservername to add the quotes. $stringservername = ""$servername""; $stringjobname = ""$vjobname""; $queryemails = mysql_query("SELECT * FROM `emails` WHERE `subject` like '$searchstatus' AND `subject` like '%$stringservername%' AND `subject` like '%$stringjobname%' AND `fromemail` = '$matchfrom'"); Any suggestions? Thankyou Hi all, I have a database with 2 tables, 'users' and 'battles'. The site pulls 2 random peoples pictures and lets the user choose who they think would win the battle. So if user1 is using the site it might show pictures for user5 and user3. If the user1 chooses that user5 wins then an entry is made into the 'battles' table like this : voter win lose user1 user5 user3 Any ideas what query I can use so it only shows 2 people that the user hasnt compared before ? As if its doing this : choose 2 id's from 'users' that user1 hasnt compared before Hope that makes sense. Many thanks, Scott Hello, I have a query where i try to search, but i want to put a limitation, but it doesn't seems to be working :/ Here's my code: $result = mysql_query("SELECT * FROM clients WHERE staff = 0 AND username LIKE '%" . $keyword . "%' OR company LIKE '%" . $keyword . "%' ORcontact LIKE '%" . $keyword . "%' OR address LIKE '%" . $keyword . "%' OR email LIKE '%" . $keyword . "%' OR phone LIKE '%" . $keyword . "%' ORDER BY phone"); Alright, so i basically want the user to search in all of those fields, however i want it to filter all "staff" members, so it should only view the "0" ones, meaning the clients, only problem that when i run this, all clients gets displayed, also the staff accounts. Any suggestion? Hi there, I am executing this query in the code below, it executes as I want it except when it gets the title, it doesnt get the title for that row it just gets it from the first row in the table... if that makes sense... what is going on? Code: [Select] <?php require'styles/top.php'; ?> <br> <center><table border='0' width='100%' style='text-align:center; font-weight:bold;'> <tr> <td width='33%'>Subject</td> <td width='33%'>From</td> <td width='33%'>Date</td> </tr> </table></center> <br> <?php $query = mysql_query("SELECT * FROM messages WHERE to_user='$username' ORDER BY message_id DESC") or trigger_error('Error: ' . mysql_error()); $numrows = mysql_num_rows($query); if ($numrows > 0){ while ($row = mysql_fetch_assoc($query)){ $id = $row['message_id']; $from = $row['from_user']; $to = $row['to_user']; $title - $row['message_title']; $content = nl2br($row['message_content']); $date = $row['date']; echo"<center><table border='0' width='100%' style='text-align:center; font-weight:bold;'> <tr> <td width='33%'>$title</td> <td width='33%'>$from</td> <td width='33%'>$date</td> </tr> </table></center> <br>"; } } else echo ''; ?> </div> <div id='left'> </div> <div id='right'> </div> I have 2 tables (see code below) (1) "tbl_users" has all users info, including "user_alias" (VARCHAR) and "user_id" (INT and PRIMARY KEY) (2) "tbl_projects" has all project info, including "project_client" (INT) which i linked to "user_id" from "tbl_users" and displays "user_alias" Code: [Select] CREATE TABLE `tbl_users` ( `user_id` int(11) NOT NULL auto_increment, `user_first` varchar(25) NOT NULL, `user_last` varchar(25) NOT NULL, `user_email` varchar(35) NOT NULL, `user_pw` varchar(12) NOT NULL, `user_role` int(1) NOT NULL, `user_alias` varchar(35) NOT NULL, PRIMARY KEY (`user_id`) ) CREATE TABLE `tbl_projects` ( `project_id` int(11) NOT NULL auto_increment, `project_client` int(1) NOT NULL, PRIMARY KEY (`project_id`) ) So... I managed to display all users and all projects but I want to show all users with ONLY their projects assigned. I mean, when I click on a user, I want to see his or hers contact info and all the projects that specific user is linked to. For instance, i might have project 1, project 2, project 3 and project 4. Project 1, 2 and 4 are linked to user 1 so when i click on user 1 i see projects 1, 2 and 3 (not 4). Code: [Select] <?php require_once('config.php'); mysql_select_db($database, $makeconnection); //this displays all projects $sql_get_projects="SELECT * FROM tbl_projects ORDER BY project_id ASC"; $get_projects = mysql_query($sql_get_projects, $makeconnection) or die(mysql_error()); $row_get_roles = mysql_fetch_assoc($get_projects); $totalRows_get_projects = mysql_num_rows($get_projects); //this displays all users $sql_find_users = "SELECT * FROM tbl_users WHERE user_id = $user_id"; $find_users = mysql_query($sql_find_users, $makeconnection) or die(mysql_error()); $row_get_users = mysql_fetch_assoc($find_users); $totalRows = mysql_num_rows($find_users); ?> Any help would be great!! I have a query which when I run in phpmyadmin it returns the results I want. When I put it into PHP I get no results can someone tell me what I'm doing wrong? Code: [Select] <?php include("config.php"); ?> <?php // sending query $sql = mysql_query("SELECT dayname((date(FROM_UNIXTIME(dateline)))) as 'Day Of Week', date((date(FROM_UNIXTIME(dateline)))) as 'Date', count(*) as 'Number of Opened Tickets', ( select count(ticketmaskid) from swtickets where date(FROM_UNIXTIME(swtickets.lastactivity)) = Date and isresolved=1 ) as 'Number of Closed Tickets' from swtickets where ((date(FROM_UNIXTIME(dateline)) between (DATE_SUB(CURDATE(), INTERVAL (IF(DAYOFWEEK(CURDATE())=1, 9, DAYOFWEEK(CURDATE()))) DAY)) and (DATE_ADD(CURDATE(), INTERVAL (6 - IF(DAYOFWEEK(CURDATE())=1, 8, DAYOFWEEK(CURDATE()))) DAY)) )) group by date(FROM_UNIXTIME(dateline))"); ?> <?php echo $sql; ?> All it returns is: Resource id #4 When in phpmyadmin I get: |