Sql Injection Prevention (passing Numerical Data Across Pages). - PHP/mySQL

free web hosting
Free Web Hosting > Computers & Tech > Programming > Scripting > PHP

Sql Injection Prevention (passing Numerical Data Across Pages). - PHP/mySQL

Chesso
Even if your building something as simple as a basic news page for your website, if your passing along url variable strings like (mysite/index.php?page=1), you may be vulnerable to SQL injection attacks.

For cases like these (passing numerical data in url strings), I have a handy dandy little function to thwart these attempts silly:

CODE
// For checking if value is a number, if not return 1.
function isNum($val)
{
  if (!is_numeric($val)) { $val = 1; }
  return ($val);
}


I have this function, within my functions.php file, which I use as an include in files where I need access to the function, and use it like so:

CODE
</php
.....
include 'functions.php';
....
$page = isNum($_REQUEST['page']);
?>


So if someone decided to pass along (mysite/index.php?page=1P, or anything non numeric at all), it will be reset to 1. This will halt anything other than the intended numeric data (or a static base numeric value) getting in.

Of course 1, might not be the desired alternative numeric value, so you could modify the function to be something like this:

CODE
// For checking if value is a number, if not return 1.
function isNum($val, $alt)
{
  if (!is_numeric($val)) { $val = $alt; }
  return ($val);
}


Which would basically allow you to specify an alternative numeric value, so if the url sent one isn't, it will use our alternative, here's an example of it's use:

CODE
</php
.....
include 'functions.php';
....
$page = isNum($_REQUEST['page'], 1);
?>


So if $_REQUEST['page'] is anything other than valid numeric data, in this case, it will become 1.

I hope this information is of use to you all smile.gif

P.S. Feel free to comment/suggest etc, also if you know any other little things like this to help out against SQL Injection (or even XSS etc), I would be more than happy to read them, I am very interested in the subject of preventing these kinds of things (especially without going overboard).

 

 

 


Reply

miCRoSCoPiC^eaRthLinG
Good tip... anyone who's into designing a blog/CMS/Forum software or just a plain web-site which uses a navigation method based on URL encoded variables should implement such a check from ground up. If this trick is kept on mind and integrated into the core of the system, it can save many tears later on wink.gif

Reply

TavoxPeru
Another way to prevent Sql Injection attacks is by using the mysql_real_escape_string() php function if you use the mysql php extension or the mysqli_real_escape_string() php function if you use the mysqli php extension, both functions do the same thing, escapes special characters in a string for use in a SQL statement and are very helpful, i use it always, and as you i code a little function and included it in every page that works with databases.

Visit MySQL - SQL Injection Prevention to see a good explanation with examples of this issue.

Best regards,





Reply

Chesso
Yup I do the same for string data that's parsed.

Numerics I use this function, it's smaller, faster and if it ain't a pure numeric value (I don't want it) tongue.gif.

On all string data in my custom function I perform strip_tags, str_replace (if I don't want \r\n for single line strings etc), mysql_real_escape_string() etc.

One thing I haven't determined yet is how to avoid indirect injections (like form data). It's one thing that came up using a vulnerability scanner even after using the above techniques, though I suspect it's less likely to be taken advantage of.

Reply

TavoxPeru
Another article that i find relating Sql Injection attacks can be read at SQL Injection Attacks: Are You Safe?, this one is a bit older but may be can help.

Best regards,

Reply

TavoxPeru
More articles with a lot of examples:All of them are very complete.

Best regards,

Reply

sparkx
Very nice Tutorial. I just need a little more help. I wan't to stop sql injections from form inputs (post inputs) is there a way so I can make it so only the charictors a-z A-Z and 0-9 can be entered? I tried preg_match but I found out if you have just one letter in it then return will work (example: - doesn't work but a- does). How would I make it so a- would not return and come up with an error message. That would really help make my website secure. I really don't want my site to get hacked lol.
Thanks,
Sparkx

Reply

TavoxPeru
QUOTE(sparkx @ Jun 5 2007, 12:42 PM) *
Very nice Tutorial. I just need a little more help. I wan't to stop sql injections from form inputs (post inputs) is there a way so I can make it so only the charictors a-z A-Z and 0-9 can be entered? I tried preg_match but I found out if you have just one letter in it then return will work (example: - doesn't work but a- does). How would I make it so a- would not return and come up with an error message. That would really help make my website secure. I really don't want my site to get hacked lol.
Thanks,
Sparkx

Well you have a lot of options to do that, one way is to check on the client side all your form inputs with a javascript function, if the data is correct you submit your form otherwise you show your error message. For example:
CODE
<html>
<head>
&lt;script type="text/javascript">
function isAlphaNumeric(str){
  var re = /[^a-zA-Z0-9]/g
  if (re.test(str)) return false;
  return true;
}

function checkForm(TheForm){
    var nf = TheForm.elements.length-1;
    var f = TheForm;
    for(i=0; i < nf; i++) {
        e = f.elements[i]; // element
        v = e.value; // element value
        if (v != "" && isAlphaNumeric(v) ) continue;
        else { e.focus(); alert('Error'); return false; }
    }
    return true;
}
function Check(elem) {
    var v = elem.value;
    if ( v!= "" && isAlphaNumeric(v) ) { alert("Correct value"); return true; }
    else { alert("Incorrect value"); elem.focus();return false; }
}
</script>
</head>
<body>
<form action="page.php" name="a" onsubmit="return checkForm(this)" method="post">
<p>Text to validate with onsubmit: <input type="text" name="aText" value="" size="10" maxlenght="5" /><br />
Text to validate with onblur: <input type="text" name="aText1" value="" size="10" maxlenght="5" onblur="Check(this)"/><br />
<input type="submit" name="submit" value="Submit" />
</p>
</form>
</body>
</html>

Take in mind that this is a very simple working example so you must adjust it basically to show the error messages.

Best regards,

 

 

 


Reply

Chesso
Keep in mind javascript (being client side), can be modified by the user if they know how.

A more secure method is to check server side (validation through a PHP script or some such), just make sure you strip out anything dangerous before validating any input.

Reply

sparkx
Well I tried this. I know it doesn't work all the time but is it good enough in most cases? Code:
CODE
//STOPING ALL POSSIBLITIES
$var=$_POST['var'];
$no_good = array("'", '"', ">", "<", ";"); //Possible charictors used in injections
$var2 = str_replace($no_good, "", $var);
if($var!=$var2){
echo("Invalid Charictors Used.");
exit();
}
//CONVERT TO HTML
$var=$_POST['var'];
$no_good = array("'", '"', ">", "<"); //Possible charictors used in injections
$no_good2 = array("&quot;", '&quot;', "&gt;", "&lt;");
$var2 = str_replace($no_good, $no_good2, $var);

Which one do you recomend for safe results. If I do convert to html can they do html on my site or would it just be displayed and no action taken?
Thanks,
Sparkx

Reply


Got an Opinion! Express your Views! (no registration):-
Add your Reply/ Opinion/ Views/ Comments/ Suggestion/ Questions/ Queries etc.
Posts with decent grammar & English will be accepted and please refrain from profanities.
For asking a Question, We recommend you to sign-up (for free) so that you can track the topic easily.

Nature of your Post*: Opinion/ Reply/ Comments
Question/Query
Feedback to us.
       
Name   Email
Title/Question*

(Maximum characters: 10,000)
You have characters left.
Confirm Code:

Recent Queries:-
  1. mysqldb injection prevention - 235.00 hr back. (1)
  2. sql injection prevention: data type validation - 242.29 hr back. (1)
  3. mysql sql injection prevention - 339.10 hr back. (1)
Similar Topics

Keywords : sql injection prevention passing numerical data pages php mysql

  1. PHP & MySQL: Displaying Content From A Given ID - (6)
    Okay so I got this sample link (not working): http://www.acosta.com/joo.asp?id=654 Now suppose
    I have a PHP file that would use MySql in order to get all values in the row where id 654 is found.
    Here's a sample DB: Table: demnyc ______________________________________ | id |
    Name | Age | Email | *----------------------------------------------------* | 1
    | Albert | 17 | no email |
    *----------------------------------------------------* | 2 | YaPow | 888 |
    no email | |__________...
  2. Reading Xml Data - Within PHP (2)
  3. Need Help With A PHP - MySQL Registration Script - Wont INSERT into the database (13)
    hey well can some one helpme make this code work it won't INSERT INTO THE DATABSE CODE
    <?php # register1.php # common include file to MySQL include("DB.PHP");
    $Username=$_POST['Username'];
    $Password=$_POST['Password'];
    $Name=$_POST['Name']; $Last=$_POST['Last'];
    $Sex=$_POST['Sex']; $Month=$_POST['Month'];
    $Day=$_POST['Day']; $Year=$_POST['Year&...
  4. [PHP + MySQL] Encrypting Data - To protect the password of your DB, for example. (9)
    Hi! This is my 2nd code of PHP + MySQL. This code is VERY simple: it encript the data in the
    MySQL DB. Here we go! ------------------------------------------------------------------------
    CODE <?php $password = "abc"; $new_password = md5($password);
    echo $new_password; ?> The password "abc" was codfied using md5() This will be:
    900150983cd24fb0d6963f7d28e17f72 CODE <?php $normal_pass = "abc";
    $encripted_pass = "900150983cd24fb0d6963f7d28e17f72"; if(md5($norm...
  5. Letting Users Add Mysql Data With Php - (1)
    I'm curious as to the best methods of letting users submit data to a MySQL database, displaying
    that data, and removing any unwanted tags etc. from it. Currently, there's a handful of PHP
    functions that I know of to help with this: mysql_real_escape_string() - perhaps the best known
    and most commonly used function, it should be used in pretty much any MySQL query. It escapes
    characters that have SQL significance. QUOTE(php.net) ...which prepends backslashes to the
    following characters: \x00, \n, \r, \, ', " and \x1a I like...
  6. User Authentication Session Handling Problems - Authorization server variables not staying across pages (14)
    This is quite a bit of problem I am facing, and I cannot point exactly where I am going wrong. I
    have been lurking around here at the Asta Host forums with regard to login and user authentication
    scripts and I have got as far as this: - Starting a session - Registering a session variable -
    Using the variable to check if the user is authenticated or not. - Authenticating the user through
    MySQL database - Logging of the user, by setting the session variable to un-authenticated I have
    been able to achive the following things too that I think is not related to this proble...
  7. Php, Sql Lite: Storing Session's Data? - how so store session in SQLITE? (1)
    normally, in windows, session data is saved in the location as directed by the "session.save_path"
    directives. they only show how to store session data in file. is it possible to store it inside the
    SQLite? anyone?...
  8. Mysql Question(inserting Number From A Textfield) - (3)
    Hey! I am trying to do a "Admin give EXP script". But I can't make it work. The value is
    not updating, but the update query is correct.( I think:P) I think the fault is here: CODE
    $expcomp=$givexpp['exp'] += $givexp; The $givexp is the
    variable for the amount of Xp the admin wants to give. the $givexpp is the variable for the
    user info (in this case, the experince he already have). The datatype for the XP in the database is
    INT. So I have no idea if it can take data from a normal textfield. If you need to see all...
  9. Making A Link = Mysql_query - (8)
    Hey! I will try to make this as clear as possible. how can I make the following. I have a
    list, of all members on my site. If I press on a members name(link), I will come to his profile. To
    come to his profile, I need to get out some vaule from the database, but to get out some value from
    the database, I must tell the code, how it should know who the user is (hard to understand?). To do
    that, I must add a mysql_query in the code ( I think), like "SELECT user FROM dbname WHERE
    user=link".. This is just how I think it works. I know it is kinda wrong.. but I don'...
  10. Making Something In Mysql Happen Only Once - (10)
    Hey! I know I am asking alot. But much is happening theese days. Sorry if I disturb with my
    questions. The thing I am trying to do is: Ex. If the user becomes level 2, he should get 5 skill
    points. I can't do this: CODE if($userlevel=5){ mysql_query("UPDATE
    user SET skillpoints =$points+5");} because then it would update everytime the code
    was loaded. I hope you understand what I am trying to do. If not, tell me /smile.gif"
    style="vertical-align:middle" emoid=":)" border="0" alt="smile.gif" /> and i'll try to explain...
  11. Warning: Mysql_result(): Supplied Argument Is Not A Valid Mysql Result Resource In ... - This Is for My attack Script. (4)
    Hey. I am making a "Version 2.0" For my attack script, but I can't make it work. This is the
    error I am gettin: Warning: mysql_result(): supplied argument is not a valid MySQL result resource
    in And here is the code: CODE $dbQueryHealth = mysql_query("SELECT
    temphealth FROM characters WHERE user =".
    $_POST['atkuser']."");           $currentHealth =
    mysql_result($dbQueryHealth, 0);         $dbQueryExp =
    mysql_query("SELECT exp FROM characters WHERE user = ".$...
  12. Warning: Mysql_num_rows() - What is the error :S (1)
    Hey! I've made a register script.. Some time ago it worked. And I ain't sure if I
    changed something since then.. The error I am getting is this: Warning: mysql_num_rows(): supplied
    argument is not a valid MySQL result resource in /home/feelay/public_html/regcheck.php on line 31
    Here is the code on theese lines: CODE $sqlCheckForDuplicate = "SELECT username FROM
    user WHERE username = '". $username ."'";                 if(
    mysql_num_rows( mysql_query( $sqlCheckForDuplicate ) ) == 0 )      ...
  13. Getting Certain Parts Of A Record - The character data (17)
    Ok I need help on this puzzling problem. At first I thought that this person stored the dates in the
    MySQL database like this: August 27, 2007 That kinda freaked me out a little, because string dates
    are hard to manipulate. Then I found out that he stored both th string data and numerical date,
    which I found a little bit odd, but it was like this: 2007-08-27 I need to build a PHP program to
    manipulate the data, but I need to access the year, month and day respectively by themselves. I
    think that isolating the first 4 characters for the year, last 2 characters for da...
  14. Anyone Know Of A Really Good Mysql Class? - Looking for something easy but full featured. (4)
    Generally speaking, when I write a script, it either utilizes the MySQL class of the parent system
    (like Mambo or Joomla) or I use basic functions and snippets to perform the database queries I need.
    I really like the Joomla database class as it allows you to simply pass a regular query string to
    it and the data is returned without the need for extra work! The Invision Power Board (IPB)
    database class which is what is used for this forum is kind of a pain to use since it wants the
    query string in a non-MySQL standard format. Nonetheless, it does work and I could u...
  15. Extracting Mysql Maths Using Php - (2)
    Right, this is a really simple thing and it has me completely stumped. I'm working on this mini
    maths function and for some reason i cannot seem to do some simple math process using mysql. This is
    the code: (php btw), now assume that $date is actually a defined mysql date variable already
    successfully extracted. $sql = mysql_query("SELECT TO_DAYS('CURDATE()') -
    TO_DAYS('$date')"); while ($row = mysql_fetch_array($sql)){ $diff =
    $row ; } Can anyone spot what im doing wrong becuase im just thrown by it....
  16. Too Many Connections? - mysql_connect() (4)
    I uploaded my PHP game yesterday, and most of my friends tried it out. After a while, I tried to
    play as well but it said that mysql_connect() had too many connections already. Can anyone tell me
    how to increase the amount of connections or maybe the total amount of connections allowed?...
  17. Php/mysql And Manual Page Caching? - (4)
    I am hopefully about to attempt this on the news page of my new site. Every bit counts as far as
    I'm concerned and not having "news" portion of my news page re-php and re-mysql everything where
    there is no chance seems like a waste. I'm looking for good articles, information or tips on
    the process (if I fail to find any good information as I'm looking through now). The way I see
    it right now, I have most of my page split up in header, content (some static html in here before
    dynamic contend and then a little more static html to close it off) and then a foo...
  18. Php Mysql Errors - Fetching arrays (2)
    I am deciding to make a Multiplayer Online RPG type game. I will be building it off of PHP and MySQL
    to ensure makimum compatibility with Astahost's services (and it makes it easier /wink.gif"
    style="vertical-align:middle" emoid=";)" border="0" alt="wink.gif" />). I have a database setup with
    1 table to hold user data and I have the login system setup properly as well as the registration
    form (obviously). All games of course have something similar to gold, units and points. Because
    this is a turn-based game, I have turns. Now for the problem: I am trying to echo ...
  19. Retrieving Data And Displaying In Boxes - How do I make a grid of boxes? (6)
    I have successfully setup a MySQL Database with a few tables in it to store user input!
    /smile.gif" style="vertical-align:middle" emoid=":)" border="0" alt="smile.gif" /> /biggrin.gif"
    style="vertical-align:middle" emoid=":D" border="0" alt="biggrin.gif" /> Woohoo! Now the
    problem is displaying the data. I want 4 boxes echoing across with 3 rows down so that makes 12
    boxes (12 of the most recent records). I have no clue how to do this because I cannot use the
    W3Schools example of echoing into a table. Here is the code I used but it echoes the same
    information a...
  20. Proper Way To Grab User Data? - (1)
    I'm working on a script where there is a custom user profile and I was wondering if there was a
    more efficient way to grab data stored in a database than this method: CODE $sql =
    "SELECT * FROM users WHERE `access_name` = \""  .$active_user.
    "\""; $row = mysql_fetch_array(mysql_query($sql)); //Link
    the two tables together; grab the most common thing that is the *SAME* $user_id =
    $row['id']; $sql2 = "SELECT * FROM content WHERE `cid` =
    \&#...
  21. How To Show Serial Nums In PHP Table For Contents Of MySQL DB - Serial Numbering for output contents of mysql in php table (4)
    Hello there, I'm looking for some education. How would you show the serial numbering for
    outputted contents of mysql database. I used a table created in PHP to output content (i.e. an
    alumni database) and I created a column for S/N, so that at a glance anyone can tell how many
    members have registered. Thanks house. Neyoo...
  22. Re-order MySQL Table - (11)
    Hello you all, I've got a question /smile.gif" style="vertical-align:middle" emoid=":)"
    border="0" alt="smile.gif" /> Let's say I have a database width the table "news". It contains
    about 10 items which is ordered by the field "id". Now from my admin page i do this: CODE
    <?PHP mysql_query("DELETE FROM news WHERE id=4"); ?> And a few days later
    i do: CODE <?PHP mysql_query("DELETE FROM news WHERE id=7"); ?> Now
    there are two gaps in the table => 1, 2, 3, 5, 6, 8, 9, 10 (no 4 and 7). It want to real...
  23. Need MySQL Alternative To The Syntax "or die()" - (8)
    Hello again /smile.gif" style="vertical-align:middle" emoid=":)" border="0" alt="smile.gif" />
    I'm facing a problem with PHP and MySQL... I want, when a MySQL error occurs, to let the script
    continue. Here's the script: CODE $query = "SELECT * FROM menus ORDER BY id
    ASC"; $menus_result = mysql_query($query) or
    die("Error!"); while(
    $menu=mysql_fetch_array($menus_result) ) {    echo
    $menu['name']."<br />"; } Now if the table "menus" doesn&...
  24. Data Passing - Re An Assignment For School - Please Help :) - (8)
    I'm working on a small assignment due tomorrow and am having some trouble. I have a functioning
    form that you input the data on one php page, and then it does a little math and displays the result
    on a new page. The assignment is to make this work on ONE page, and to add some error handling.
    I'm having trouble with the basics of passing the data that has been input on the form, back to
    itself. I am stuck with a few questions but I'll start with one. I have the data passing back
    to itself so that when I start the error checking, the fields won't have ...
  25. Send XML Data To PHP Page - (0)
    Hi, i'm trying to send my xml file "xmlDoc" to a php page so I can save it. Does anyone have the
    code for this?...
  26. Need An Alternative To $http_post_data For PHP4 - (5)
    Hi, my client's host site currently hosts just 4.0. I tried using the
    file_get_contents("php://input") and $HTTML_post_data php file to save the XML file from Flash
    but when loaded, it returns nothing. I need hlep...
  27. Storing Data Into Xml With A Php Form - Need Help! (2)
    Hi, I just learned how to read an xml file with PHP. The problem now is that I don't know how to
    write onto it. I would like to read my news content and be able to add more to it when another story
    comes up but I don't know how to write into the xml via PHP. All I know how to do is to edit the
    XML file itself manually. Can anyone help me?...
  28. Need Help With Php/mysql And Web Servers Such As Asta's. - (4)
    Within my site I have built my own basic forum using PHP/Mysql, I always test locally now both using
    EasyPHP and WAMP5 which both give me no problems what so ever. But when I tryed to run the exact
    same code on Asta's hosting services (and possible another I used to use) when creating a new
    thread or adding a reply to an existing one it *sometimes* adds an additional thread/reply as a
    Guest (someone not signed in) with an empty message. This would lead me to believe that somehow the
    page is being refreshed and the variables sent to the database update php file are ...
  29. How Do You Create A Secure Loging? - with PHP and mySQL (4)
    I've read a few articles, and looked up the code of certain files and some of them seem to work
    differently. I'm trying to create a login script, which would require PHP and mySQL to run,
    however, I'm not quite sure how to approach it since I'm only just learning PHP. I'd
    like to know, what is the most secure and effective login? I've heard you can add a salt to
    encrypted passwords, etc, and well as using sessions (sid). It's just like to know what methods
    are best for creating a secure login script. Thank yo ufor readin this. ...
  30. MySQL & PHP coding - (9)
    So it seems as though the php docs make it very clear that mysql and mysqli functions will all
    connect to the database as a latin1 client. Although i have my server set up with utf8 databases,
    tables and fields and the default client connection is utf8, php still connects as latin1. My
    xhtml forms and pages are all utf-8, so when i post utf8 data and insert it into the database the
    connection assumes that incoming data is latin1 and the data that gets placed in the database is
    invalid. phpMyAdmin seems to be able to view, add, edit, and retrieve utf8 strings in the d...



Looking for sql, injection, prevention, passing, numerical, data, pages, php, mysql

Searching Video's for sql, injection, prevention, passing, numerical, data, pages, php, mysql
PHP &
MySQL:
Displaying
Content From
A Given ID
Reading Xml
Data Within
PHP
Need Help
With A PHP -
MySQL
Registration
Script Wont
INSERT into
the database
[PHP +
MySQL]
Encrypting
Data To
protect the
password of
your DB, for
example.
Letting
Users Add
Mysql Data
With Php
User
Authenticati
on Session
Handling
Problems
Authorizatio
n server
variables
not staying
across pages
Php, Sql
Lite:
Storing
Session'
s Data? how
so store
session in
SQLITE?
Mysql
Question(ins
erting
Number From
A Textfield)
Making A
Link =
Mysql_query
Making
Something In
Mysql Happen
Only Once
Warning:
Mysql_result
(): Supplied
Argument Is
Not A Valid
Mysql Result
Resource In
... This Is
for My
attack
Script.
Warning:
Mysql_num_ro
ws() What is
the error :S
Getting
Certain
Parts Of A
Record The
character
data
Anyone Know
Of A Really
Good Mysql
Class?
Looking for
something
easy but
full
featured.
Extracting
Mysql Maths
Using Php
Too Many
Connections?
mysql_connec
t()
Php/mysql
And Manual
Page
Caching?
Php Mysql
Errors
Fetching
arrays
Retrieving
Data And
Displaying
In Boxes How
do I make a
grid of
boxes?
Proper Way
To Grab User
Data?
How To Show
Serial Nums
In PHP Table
For Contents
Of MySQL DB
Serial
Numbering
for output
contents of
mysql in php
table
Re-order
MySQL Table
Need MySQL
Alternative
To The
Syntax
"or
die()"
Data Passing
- Re An
Assignment
For School -
Please Help
:)
Send XML
Data To PHP
Page
Need An
Alternative
To
$http_p
ost_data For
PHP4
Storing Data
Into Xml
With A Php
Form Need
Help!
Need Help
With
Php/mysql
And Web
Servers Such
As
Asta's.
How Do You
Create A
Secure
Loging? with
PHP and
mySQL
MySQL &
PHP coding
advertisement




Sql Injection Prevention (passing Numerical Data Across Pages). - PHP/mySQL



 

 

 

 

ADD REPLY / Got an Opinion! a humble request :-) RAPID SEARCH! Free Hosting [X]
Express your Opinions, Thoughts or Contribute more info. to help others.
Ask your Doubts & Queries to get answers, So that "Together We can help others!"
Register FREE for AD-FREE forum, Create your own topics, Ask Questions, track topics, setup subscriptions & notifications and Get a Free Website w/ Email and FTP.
500MB Space *No Ads*, CPanel, FTP, PHP, MySQL, EMails - 100% FREE