473,769 Members | 2,102 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

question about database injection

54 New Member
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_esca pe_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_esca pe_string() is as follows and the special characters
are still appearing in the database. i have not used mysql_real_esca pe_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_esca pe_string($user name, $conn), mysql_real_esca pe_string($pass word, $conn), mysql_real_esca pe_string($firs tname, $conn));

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

NOTE = by using this mysql_real_esca pe_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_esca pe_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_gp c is ON, magic_quotes_ru ntime is OFF, magic_quotes_sy base 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 1822
rohypnol
54 New Member
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_esca pe_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_esca pe_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_esca pe_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_quote s_gpc() and get_magic_quote s_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_ran dom_string">
<input type="hidden" id="encrypted_p ass" name="encrypted _pass">
<input type="password" id="pass">
</form>
<script type="text/javascript">
function sha1(text)
{ .. }
function encryptPass()
{
document.getEle mentById('encry pted_pass').val ue = sha1(document.g etElementById(' pass').value + document.getEle mentById('salt' ).value);
document.getEle mentById('pass' ).value = '';
return true;
}
</script>[/php]
In this, "some_random_st ring" should be a random string which you will never change again. For example, you could use "kjhg94um09 3u." 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 Recognized Expert Specialist
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
2029
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 if text, to addslashes() the data. What I have not managed to find out, is does SQL injection threaten the input of data into a database, ie a guestbook, or the reading of a database where the user would not know if the data is being read from...
6
3674
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 what conditions can I use two or more frameworks? Sorry for the beginners question.
8
2516
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 cartTemp where convert(varchar(4000),cartdetails) in (a.prodcode)) as counter from Products a where isOffer = 0 order by prodcode") do until RSMain.EOF
3
1414
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=" & ProductID it outputs error :- Incorrect syntax near 's'. Unclosed quotation mark before the character string ' Where ProductID=4'. I can't see what is wrong can somebody just look through this..
5
1836
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 populated) is from several different tables. To the user, of course, this is not seen. Scenario: After the page is populated, assume a change is made to the form and the user hits update. The page then goes back, reads the database for that record...
4
1622
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 correctly, until I discovered that my new version of PHP 4.4 disabled global variables. I figured out how to make the following php script work correctly, but I don't know if the way I made it work is the accepted way of doing things with $_POST. I...
6
2046
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 2006). I also have a drop-down menu on this page where to filter which month should be shown on the page based on these (text)values by request.querystring. The problem is that (I guess) the value passed by the request.querystring are of wrong format...
2
2227
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 should only begin either letters or numbers, and Underscore character example = user123, 123user, u_ser123, user_123 = completely case insensitive
7
1740
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 mysql_real_escape_string(htmlspecialchars($value)); } and i.e.
0
9579
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10208
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10038
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9857
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8867
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7404
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6662
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5444
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2812
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.