473,378 Members | 1,152 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

question about database injection

i am helping a friend to build a forum website which uses php and mysql database. i am working on the registeration page for the forum website and its validation. i am using php 5.2.5

i am able to validate and do other tasks, however i really need help as i am stuck with regards to database injection.

please answer the following questions. any help will be greatly appreciated.

1. USER NAME VALIDATION

username = eregi("^[a-zA-Z0-9_ ]+$", $username)

with the above validation, a user can enter letters uppercase, lowercase and numbers and underscore with spaces ONLY
ex= 9abc_def OR _abc123 = this IS INCORRECT

however i would like the username to be Letters First(upper or lowercase), followed by numbers and underscore and spaces in the username.

ex= abcd1234 OR ABcd1234 OR Ab_12 OR ab 12_cd OR 123456 OR 123abc = this IS CORRECT

i have used with preg_match as => if( $username == "" || !preg_match('/^[a-zA-Z0-9_]+$/x', $username) ) however its the same as eregi

QUESTION = how can i rewrite username = eregi("^[a-zA-Z0-9_ ]+$", $username) to match the following requirement.
username = abcd1234 OR ABcd1234 OR Ab_12 OR ab 12_cd OR 123456 OR 123abc

also with eregi("^[a-zA-Z0-9_ ]+$", $username) as there is a space if a user has more than 1 space ex= "ab cd 12" it is still

accepting is there a way to restrict to ONE space only ex = "ab cd12"

2. USING mysql_real_escape_string() METHOD

i am able to validate username, first name, phone numbers based on preg_match for these individual ones, however the form consists of some optional fields which i am not validating so if a user enters invalid characters in these optional fields i need to protect from sql injection, presently my code for mysql_real_escape_string() is as follows and the special characters
are still appearing in the database. i have not used mysql_real_escape_string() before so i guess i am missing something

$conn = mysql_connect($hostname, $user, $dbpassword);

$insertquery = sprintf("INSERT INTO tablename (`username`, `password`, `firstname`) VALUES ('%s', '%s', '%s')",

mysql_real_escape_string($username, $conn), mysql_real_escape_string($password, $conn), mysql_real_escape_string($firstname, $conn));

should i be checking for if(get_magic_quotes_gpc()) { } first.

NOTE = by using this mysql_real_escape_string() method php should NOT add slashes or other characters if this happens then the username will be stored in the table differently ex= john`smith instead it should be johnsmith the slashes can be done for other fields like firstname etc as this username and password will be used by a user to login to the forum

please advice about the procedure for mysql_real_escape_string() method

3. QUESTION ABOUT SQL INJECTION

presently if i enter special characters in the form these values are being inserted to the database as it is which is not good. out of the following methods
htmlentities(), addslashes(), trim(), mysql-real-escape-string() which is the best method to use to avoid sql injection
i think mysql-real-escape-string() is the best method.
NOTE = in my php settings magic_quotes_gpc is ON, magic_quotes_runtime is OFF, magic_quotes_sybase is OFF

4. STORING PASSWORDS

as part of the registration for the forum the username and password that the user enters in the registration page will be used as their username and password to login to the forum. presently when i execute the sql insert statement along with other fields for the registration page the value of the password stored in the mysql table is the actual characters that a user entered in the form. in the form the element is defined as <input type="password" name="password"> however in the table the password is stored as the actual characters the user entered in the form. is this a right way of storing the password field from the form.

NOTE = i believe with websites that are forum based using php and mysql, there is a way to pass information to the php file which will automatically pick up the username and password from the table that i have created where i am storing the username and password.

Please comment on storing the password in mysql table and how i can find the php file to which i can pass the value of username and password as a variable by using a function to that php and by including that php file in which i am processing the registration form.

Thanks a lot for reading my post. Any help will be greatly appreciated.
Mar 17 '08 #1
2 1794
1.
You make absolutely no sense. Please give a few examples of valid usernames, which should cover all possible situations (starting with letters/numbers/etc).

2.
mysql_real_escape_string() works only if you have a connection open to the db you're working on. That's because it will ask the MySQL server which characters aren't safe. If you see "weird" chars in the database, that doesn't mean they're weird for MySQL. mysql_real_escape_string() works in association with the MySQL server so they should be fine.

3.
Avoid MySQL injection: sanitize all values when performing queries using mysql_real_escape_string()
Avoid HTML (and JavaScript) injection: sanitize all values before you output them to the user using htmlentities()
You should also see the value of get_magic_quotes_gpc() and get_magic_quotes_runtime(), which should tell you if you need to call stripslashes() on ALL user input BEFORE you use it in any way.

4.
In the end you don't make any sense, again.
For storing passwords, you should always perform a hash with a salt. A very simple method is the following:
- you have a HTML form
- your form has an onsubmit event, which encrypts the password before it's sent
- usually the encryption is done by setting the value of a hidden input field with the hash
- the simplest way to do this is find an implementation of md5 or (preferably) sha1 for javascript, append a salt to the password, perform the encryption and move the result to the hidden field[php]
<form .. onclick="return encryptPass()">
<input type="hidden" id="salt" value="some_random_string">
<input type="hidden" id="encrypted_pass" name="encrypted_pass">
<input type="password" id="pass">
</form>
<script type="text/javascript">
function sha1(text)
{ .. }
function encryptPass()
{
document.getElementById('encrypted_pass').value = sha1(document.getElementById('pass').value + document.getElementById('salt').value);
document.getElementById('pass').value = '';
return true;
}
</script>[/php]
In this, "some_random_string" should be a random string which you will never change again. For example, you could use "kjhg94um093u." This is done to protect the users' password in case you website gets cracked, so the cracker will not be able to find out what the password is and try to use it on other websites where the users might have an account. Also, this ensures the user's real password isn't sniffed on it's way to your server. There's not much you can do on your side, but there are some things you can do for the users, to prevent any major damage from being done to them if your servers are ever cracked.
It is also a good idea to perform another hash on the server side, so if anyone somehow manages to read the contents of the table, they still won't be able to use it. So on the server, when you check user's identity or adding him to the database, you use sha1($_REQUEST['encrypted_pass'] . 'kghwerhg').

All this offers just a little protection, but believe me, it's a lot better than nothing. For the best protection, you store a hash of the password and use https when it comes to registering/authentication, but only few sites actually do this.
Apr 20 '08 #2
ronverdonk
4,258 Expert 4TB
rohypnol

Please enclose your posted code in [code] tags (See How to Ask a Question).

This makes it easier for our Experts to read and understand it. Failing to do so creates extra work for the moderators, thus wasting resources, otherwise available to answer the members' questions.

Please use [code] tags in future.

MODERATOR
Apr 21 '08 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: Dariusz | last post by:
I have been reading a little that you should secure your PHP code to prevent SQL injection into a database (MySQL in my instance), mainly by checking the type of data to be put into a database, and...
6
by: Al Dykes | last post by:
I've just grabbed a PHP book and can deal with the syntax and now I need to decide to learn specific packages and features. Define "framework". What are the major framework flavors ? Under...
8
by: niceguy | last post by:
I'm trying to select records from two tables. the following code works for what i want to to: set RSMain = conn.execute ( "select top 20 product, prodcode, edition, ( select count(id) from...
3
by: Patrick.O.Ige | last post by:
Hi, I have got this SQL below updating a textbox and a checkBox. strSql = "Update Products Set Discontinued=" & chkBoxChecked & ",ProductName = '" & ProductName & "' Where ProductID=" &...
5
by: needin4mation | last post by:
Hi, I have an asp.net 1.1 application that populates data from a database. When the user changes data, they have to hit a button to update the data. The data entry form (same form that is...
4
by: Pete Horm | last post by:
Hi everyone, I have a question about using this variable. I am new to programming and I had a book that was a couple of years old regarding php programming. None of the examples were working...
6
by: Jen | last post by:
Hello. I have a sql statement that should get all the records that match a specific criteria; every record are assigned a textvalue like 12_2006 (as for example this particular month, december...
2
by: Sudhakar | last post by:
A) validating username in php as part of a registration form a user fills there desired username and this is stored in a mysql. there are certain conditions for the username. a) the username...
7
by: Petra Meier | last post by:
Hello, if I use the following function for all my mySql commands in php, am I protected against all SQLinjections and XSS attacks? function sanitize($value){ return...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.