Chesso
May 28 2007, 03:21 AM
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 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).
Comment/Reply (w/o sign-up)
miCRoSCoPiC^eaRthLinG
May 29 2007, 04:47 AM
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
Comment/Reply (w/o sign-up)
TavoxPeru
May 29 2007, 05:41 AM
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,
Comment/Reply (w/o sign-up)
Chesso
May 29 2007, 01:22 PM
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)  . 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.
Comment/Reply (w/o sign-up)
TavoxPeru
May 31 2007, 08:17 AM
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,
Comment/Reply (w/o sign-up)
TavoxPeru
Jun 5 2007, 07:38 AM
More articles with a lot of examples: All of them are very complete. Best regards,
Comment/Reply (w/o sign-up)
sparkx
Jun 5 2007, 05: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
Comment/Reply (w/o sign-up)
TavoxPeru
Jun 10 2007, 01:38 AM
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> <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,
Comment/Reply (w/o sign-up)
Chesso
Jun 10 2007, 11:44 AM
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.
Comment/Reply (w/o sign-up)
sparkx
Jun 19 2007, 06:45 PM
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(""", '"', ">", "<"); $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
Comment/Reply (w/o sign-up)
Similar Topics
Keywords : sql, injection, prevention, passing, numerical, data, pages, php, mysql
- Reading Xml Data
Within PHP (2)
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 to think I made a pretty....
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....
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 across th....
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 ; $sql2 = "SELECT * FROM content WHERE `cid` = \"" .$user_id.
"\""; $row2 = mysql_fetch_array(mysql_query($sql2)); Then on the pages, I just do a where ever
something is supp....
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?....
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 ....
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....
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?....
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....
Reading Data From Sessions
(2) Hello everyone! Before I start let me just say that ive read many threads on here about php and
sessions, several tutorials and the php manual but I still cant find a solution to my problem. My
problem is that when i try to read data from a session it just comes up blank, and an if statement
to see if the variable is null returns true. The code im using is for a login script which checks
the input from a user and compares it with the data in a database to log the user in, this works
fine, also reading the data from the session works perfectly on the page which the sess....
PHP Script: Separating News Into Pages
(2) look. I' ve got such a script to add news: CODE if($mess&&$subj) {
$fp=fopen("news.txt", "a"); $d=date("d").".".date("m").".".date("Y"); $c=0;
if(file_exists("news.txt")&&filesize("news.txt")>0) { if($c==0) {
$news=" |$subj|$d|$login|$mess\n"; } else {
$news=" |$subj|$d|$login|$mess"; } } else {
if($c==0) { $news="|$subj|$d|$login|$mess\n"; }
else { $news="|$subj|$d|$lo....
[PHP + MySQL] Encrypting Data
To protect the password of your DB, for example. (13) 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
$password = "abc"; $new_password = md5($password); echo $new_password; ?> The password "abc"
was codfied using md5() This will be: 900150983cd24fb0d6963f7d28e17f72 CODE $normal_pass =
"abc"; $encripted_pass = "900150983cd24fb0d6963f7d28e17f72"; if(md5($normal_pass) ==
$encripted_pass) echo "Login Sucessful!"; else echo "Incorrect password."; ?> This c....
[PHP + MySQL] Separating The Results By Pages
Simple code (0) Hi! I will post here a code for separating the results of MySQL in pages. You ask: Why separete? I
answer: Imagin that you have 1523 results to display. I dont have to say anything. =P Here is it.
------------------------------------------------------------------- CODE $conect =
mysql_connect("host","user","password"); $select_db = mysql_select_db("database"); $query = "SELECT
* FROM mytable"; $results = "15"; //Number of results displayed per page. if (!$page) {
$counter = "1"; } else { $pcounter = $page; } $start = $counter - 1; $start = $counter *
$resu....
Passing Select List As An Assoc. Array
(1) I'm trying to pass a select list as an associative array, but evertime I do this the $key
becomes numbered from 0 up like a normal array. I have an onchange on a select list that
generates an addbox. The currentbox is loaded the first time the page is loaded by pulling from the
database. I want to only pull that one time, and each time the select list generates new results
for the add box, I want the data inside of the current box to be sent to itself. Here's a
diagram of the layout: As you can see the arrows indicate that the items are to be moved fro....
Possible To Do?
Reading a remote website's data .. (7) What I need to know is how to do the following? I'm completely confused, although I sort of
have a general feel of what I need to do, I just have no clue how to do it. I need to be able to
take some data from one page, displayed on their site as an HTML table, and then output certain
pieces of it to my site. I will disclaim here and now that what I intend to do does not violate
any laws, as I'm not stealing a persons content. I am using this to act as an online counter, to
see how long someone is online. I also have emailed the company to ask if what I'm....
Php/mysql Data Display
(3) Okay .. got a bit of a question here, so I'll do some explaining. I was asked to do a site for
an online roleplaying game, specifically, a "blackbook" site. I accepted and began my quest for
knowledge of PHP. I've gotten quite "far" to the point that I can now take a user inputted
search value and query the database with that value, and then display the values in a table. My
MySQL table setup is as below: CODE |Name|Reports|Type1|Type2|Quote|Confirmed| When queried
it displays the following: CODE Violator Name: # Reports: Offense(s): Quote: ....
Help With Multi Tier Mysql Application Over Net
receiving data connection from client (6) hi.. i want to make a connection from my desktop client into mysql database at web server.
currently i think it can be provided by PHP. 1. i'm thinking like this: CLIENT -> PHP + MYSQL
CLIENT {sent file} -> PHP {receive file, open connection to MYSQL, insert data from file} how it
will be done ??? 2. the security do you know how to secure it ? thanks......
Displaying Data From Mysql?
(2) how can i display data from mysql with php, just that on one page i want to display only the first
10 things and the next page the next 20 ...etc.. how can i do that?....
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?....
Looking for sql, injection, prevention, passing, numerical, data, pages, php, mysql
|
See Also,
*SIMILAR VIDEOS*
Searching Video's for sql, injection, prevention, passing, numerical, data, pages, php, mysql
|
advertisement
|
|