473,599 Members | 3,118 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

question about validation and sql injection


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
b) a user may choose not to have an underscore or numbers sometimes.
example = username

presently my validation for username is

$username = $_POST["username"];
if( $username == "" || !eregi("^[a-zA-Z0-9_]+$", $username) )
{
$error.="User name cannot be blank or has special characters";
}

Question = how can i rewrite this php validation for username to meet
the above criteria or is my validation correct
B) preventing sql injection

till now i have been capturing the form values and directly inserting
into the table without considering sql injection however for this
project as it is for a forum i would like to implement prevention of
sql injection. from what i have read about preventing sql injection
there are several steps that need to be followed,

htmlentities
addslashes
trim
mysql-real-escape-string
magic_quotes_gp c is ON
magic_quotes_ru ntime is OFF
magic_quotes_sy base is OFF

as i have not done preventing sql injection i am not sure what is the
correct process.

Question =

a) please advice a step by step process of how to go about avoiding
the sql injection before the insert sql query is executed starting
from

$username = $_POST["username"]; till the

insert into tablename(field 1, field2) values($value1, $value2) SQL
query is executed which will prevent sql injection even if the user
enters any special characters while filling the form.

b) should i consider the setting of magic quotes as in should it be ON
or OFF or should i ignore it if so should it be
ON or OFF

c) also with the prevention methods if a user types a special
character in the data will that character be written in the table as a
escaped character or how does it store those special characters

d) a very important point here, i have a feature where a user can
check if a username is available or not. so while storing a username
if the username is stored as john\smith in mysql and if the user is
searching for johnsmith this would not match, so even in the table the
username should be stored without slashes as i have to read the
username and compare with what the user has typed to see if they both
are same or different.
please advice if i have missed any other steps to prevent sql
injection.
thanks a lot for your help.
Jun 2 '08 #1
2 2209
Sudhakar wrote:
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
b) a user may choose not to have an underscore or numbers sometimes.
example = username

presently my validation for username is

$username = $_POST["username"];
if( $username == "" || !eregi("^[a-zA-Z0-9_]+$", $username) )
{
$error.="User name cannot be blank or has special characters";
}

Question = how can i rewrite this php validation for username to meet
the above criteria or is my validation correct
You should be using the preg functions instead. I'm not a regex expert,
by any means, but something like:

if ($username== "" || preg_match("/[^a-zA-Z0-9_]/", $username) 0 )
$error.="User name cannot be blank or has special characters";
>
B) preventing sql injection

till now i have been capturing the form values and directly inserting
into the table without considering sql injection however for this
project as it is for a forum i would like to implement prevention of
sql injection. from what i have read about preventing sql injection
there are several steps that need to be followed,

htmlentities
addslashes
trim
mysql-real-escape-string
magic_quotes_gp c is ON
magic_quotes_ru ntime is OFF
magic_quotes_sy base is OFF

as i have not done preventing sql injection i am not sure what is the
correct process.

Question =

a) please advice a step by step process of how to go about avoiding
the sql injection before the insert sql query is executed starting
from

$username = $_POST["username"]; till the

insert into tablename(field 1, field2) values($value1, $value2) SQL
query is executed which will prevent sql injection even if the user
enters any special characters while filling the form.
You need to validate all input. Numeric values need to be validated to
ensure they are really numeric. String values need to be primed with
mysql_real_esca pe_string().
b) should i consider the setting of magic quotes as in should it be ON
or OFF or should i ignore it if so should it be
ON or OFF
Forget magic quotes. It's now more of a hassle then a help. It should
be off.
c) also with the prevention methods if a user types a special
character in the data will that character be written in the table as a
escaped character or how does it store those special characters
That's what mysql_real_esca pe_string() does.
d) a very important point here, i have a feature where a user can
check if a username is available or not. so while storing a username
if the username is stored as john\smith in mysql and if the user is
searching for johnsmith this would not match, so even in the table the
username should be stored without slashes as i have to read the
username and compare with what the user has typed to see if they both
are same or different.
If you've parsed the username above correctly, it won't have a backslash
in it.
>
please advice if i have missed any other steps to prevent sql
injection.
thanks a lot for your help.
You need to understand SQL injection - which is really too much for a
newsgroup posting. Google for "SQL Injection". There are several good
hits out there.

--
=============== ===
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attgl obal.net
=============== ===

Jun 2 '08 #2
Sudhakar escribió:
a) the username should only begin either letters or numbers, and
Underscore character
example = user123, 123user, u_ser123, user_123 = completely case
insensitive
b) a user may choose not to have an underscore or numbers sometimes.
example = username

presently my validation for username is

$username = $_POST["username"];
if( $username == "" || !eregi("^[a-zA-Z0-9_]+$", $username) )
{
$error.="User name cannot be blank or has special characters";
}
You'd better get used to preg_* functions, their old ereg_* equivalent
will be deprecated in PHP 6. Not tested but...

if(
// Check non-empty, only valid chars and 1 to 16 chars
!preg_match('/^[a-z0-9_]{1,16}$/i', $username) ||
// Check at least one letter
!preg_match('/[a-z]/i', $username)
){
$error .= '......';
}

I've added an extra check. Replace 16 with your database field length.
Probably, it could all be done in only one expression but...

B) preventing sql injection
htmlentities
This is used to convert plain text into HTML, it has nothing to do with
SQL injection.
addslashes
This may help to avoid _some_ types of injection in some database
servers like MySQL, but it wouldn't help in Oracle or SQL Server.
trim
I won't even comment on this.
mysql-real-escape-string
This is a valid option for MySQL. Prepared statements are the other way.
magic_quotes_gp c is ON
The same as addslashes(), except that you'll get \'s inserted all around
your input and you'll have to remove it again when not using it for a
SQL query:

<p>Welcome, John O\'Hara!</p>
c) also with the prevention methods if a user types a special
character in the data will that character be written in the table as a
escaped character or how does it store those special characters
Why does it matter how the DBMS stores data internally?
d) a very important point here, i have a feature where a user can
check if a username is available or not. so while storing a username
if the username is stored as john\smith in mysql and if the user is
searching for johnsmith this would not match, so even in the table the
username should be stored without slashes as i have to read the
username and compare with what the user has typed to see if they both
are same or different.
You said users can only have letters, numbers and underscores... If you
also allow backslashes then of course "john\smith " is different to
"johnsmith" or "john_smith " or "john___smi th". My suggestion is that you
add an extra column to the table (possibly indexed) and check against it
as well:

Username StrippedUsernam e
============= =============== =
john_smith123 johnsmith
___123x___ x

$stripper_usern ame = strtolower(preg _replace('/[^a-z]+/', '', $username));


--
-- http://alvaro.es - Álvaro G. Vicario - Burgos, Spain
-- Mi sitio sobre programación web: http://bits.demogracia.com
-- Mi web de humor al baño María: http://www.demogracia.com
--
Jun 2 '08 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

13
1686
by: rcb845 | last post by:
Hi everybody Javascript specialist, I am relatively new in Javascript world. I have a problem to solve and I hope one of you can help me. I am building a validation system, i.e. I want to validate data entered using A normal HTML FORM. Data will be checked using Javascript scripts to Have an immediate status, and to prevent user to keep on in case of error. But some data must be checked against MySql database accessed through
4
2032
by: Mike Dee | last post by:
Hi - I recently took my site live and I'm getting quite a lot of HttpRequestValidationException errors "A potentially dangerous Request.Form value...". I'm seeing quite a lot of these various various places so I'm quite sure this is not something malcious but rather a problem with the way the validation works. Unfortunately it doesn't show me what the offending input was - is there any way I can log this so I can see exactly what...
4
2184
by: ss | last post by:
hi, can anybody gives me a sample code where the sql injection attack is validated. how can i do that in business logic layer and pass the error to the presentation tier I want the sample code
3
1879
by: Jeff | last post by:
....another beginnger question. I have a web application in .net v2 VB that requires multiple reads from sql tables where each read is slightly different - so the sql select statements also differ frequently. I've created a few functions in an .ascx file to handle these reads and send them back to the main code. 2 examples are below. Each works - the first returns a single integer value, the second returns the entire row that contains a...
7
3041
by: e_matthes | last post by:
Hello everyone, I've read enough about email validation to know that the only real validation is having a user respond to a confirmation message you've sent them. However, I want to store the address temporarily, so I want to make sure what is entered is safe to work with. I have a basic understanding of regexps, so I could write one that checks for a simple format like: something followed by @ followed by something followed by .....
7
2704
by: lepage.diane | last post by:
Hello I am a newbie to PHP. Please bear with me. I need to validate the following fields using php. 1. email (needs to be just one e-mail address, and take out stuff like bcc or anything that would be used for e-mail injection vulnerability) 2. Phone number (has to be in the format 555-5555) 3. Phone number area code (has to be limited to 3 characters) 4. Address has to be stripped of all illegal characters like slashes,
5
5154
by: hamsterchaos | last post by:
<asp:RegularExpressionValidator id="valRegEx" runat="server" ControlToValidate="textbox1" ValidationExpression=" " ErrorMessage="* Please only enter alphanumeric values and make sure you are not entering in any apostrophes." display="dynamic">* I need
1
1158
by: runway27 | last post by:
i am using php in order to validate a form where users register. please help me to solve the following validations. 1. name can have spaces. ex= john smith presently the validation i am using is if( $fname == "" || !eregi("^+$", $fname) ) i need the syntax which would accept a-zA-Z WITH A SPACE IN BETWEEN NAMES ex= john smith 2. text can have spaces and special characters ex= ref 100/abcd presently the validation i am using is if(...
2
1816
by: runway27 | last post by:
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("^+$",...
0
7992
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
7904
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8398
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
8400
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
8267
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
6725
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...
0
5438
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
3898
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
1505
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.