PHP - Block Sql Injection Attacks
Hey Guys,
Hope you are all having a great day I was hoping somebody could help me with preventing my blog from being attacked by SQL Injection. I made a simple blog in using PHP and MySQL but I keep getting spam comments (even though I use re-captcha) and some files were overwritten on my web server. For all my input I use mysql_real_escape_string but I still get the problem. I found a video on youtube that showed how to enter stuff on the address bar like "order by 2--" and "union all select...." after passing a variable etc, and all of the things in the video could be replicated on my site I am guessing that is my problem, but the video did not tell me how to resolve the issue and I am sick of having to delete hundreds of spam comments per day and check my web server for uploaded files. How can I stop people adding these commands to the address bar and getting data from my database? I really need your help Thanx, Jen Similar TutorialsHello People, Been reading up on these and trying to understand them more. Say I have a file called page.php?id=12345 and when users hit the page I run this code in the background: $id = $_GET['id']; $query = "UPDATE tbl SET live = '1' WHERE id = '".$id."'"; That page is not open to any attack right? Even though i'm using $_GET. Am I right in thinking that attacks only happen on online forms. So for example there is no way an attacker could somehow output all the data in my table tbl Thank yo Hey guys, I am having a problem with making a system where it is turn based attacks. I want it so a user can attack a monster and the monster can attack back, the output I want is like. Code: [Select] You hit the monster for 5. The monster hit you for 7. You hit the monster for 3. The monster hit you for 6. and so on. I have been going at this for ages and cannot get what I want. I had problems such as: The monster attacking when it should be dead. Even when the monster was dead the user would still attack. This is the code I have now that is maybe totaly wrong, thats why I need your guys help! Code: [Select] $monster_hp = 10; $userhp =10; for ($i=1,$n=1; $i<=$monster_hp, $n<=$userhp; $n+=$damtaken, $i+=$damdone){ $damtaken = 1*rand(1,3) + rand(1,4) + 1 + 1; $damdone = 1*rand(1,2) + rand(1,2) + 1 + 1; echo "You hit the monster for $damdone.<br />"; echo "The monster hit you for $damtaken. <br />"; } The output for that is: Code: [Select] You hit the monster for 5. The monster hit you for 7. You hit the monster for 5. The monster hit you for 5. That is wrong due to the monster having 10 hp and I have hit him for 10hp overall. I know that thats because the echo is in the loop so it has to run but I have tried so many ways to get this to work and cannot do it. If I die, it should stop with the monsters attack and a message saying "The monster has killed you", if I win it should stop his next attack and say "You have killed the monster". Please help me guys, you have helped me before so I know how good some of you are. Thank you so much for anyhelp that is givin. Ruddy. I am having a wamp issue so I can't try these out right now. According to the book I'm learning php with, I can easily avoid injection attacks this way:
$a= stripslashes($a);
$a= mysql_real_escape_string($a);
What concerns me is the repetition of the variable, $a. Does it matter? Intuitively, it should.
$a changes. By the time $a hits mysql_real_escape_string it is slash-free. So it is a totally different "value" but still contained in the original variable which may have had slashes...just has me concerned a bit.
I know PDOs are the best way. I'm not there yet, unfortunately.
Edited by baltar, 23 May 2014 - 10:36 AM. I'm confused, can this result in css/sql injection? Code: [Select] if(isset($_GET['action'])){ if($_GET['action'] == 'details'){ $cupID = $_GET['cupID']; $ergebnis = safe_query("SELECT gameaccID, name, start, ende, typ, game, `desc`, status, checkin, maxclan, gewinn1, gewinn2, gewinn3 FROM ".PREFIX."cups WHERE ID = '".$cupID."'"); $ds=mysql_fetch_array($ergebnis); ... Some german fellow was explaining, translate to English briefly: "$ CupID is not escaped. NEN here I could just "; DROP TABLE` cups `Paste and your table is no longer available eez. Or I could inject javascript, your current session read out, accept it and act as an admin ... " I am trying to understand what he means by this... is this query vulnerable to an injection and why/how? Based on the comments on my previous question, took some tutorials on how to avoid injections on query. Does the code below prevents against it in any way.? Secondly, can you recommend a good article that writes well in how to secure input data by users. Please be kind with your comments.😉😉. Thankks in advance.
The code works fine. <?php include 'db.php'; error_reporting(E_ALL | E_WARNING | E_NOTICE); ini_set('display_errors', TRUE);  if(isset($_POST['submit']))  {     $username = $_POST['username']; $password =  ($_POST['password']); $sql = "SELECT * FROM customer WHERE username = ?"; $stmt = $connection->prepare($sql); $stmt->bind_param('s', $username); $stmt->execute(); $result = $stmt->get_result(); $count =  $result->num_rows;   if($count == 1)              { while ($row = $result->fetch_assoc())  {   if ($row['status'] == 'blocked')  {  echo'your account is suspended'   session_destroy();   exit();  }  else if($row['status'] == 'active') { if($username !== $row['username'])  { echo '<script>swal.fire("ERROR!!", " Username is not correct. Check Again", "error");</script>'; } if($password !== $row['password']) {  echo'<script>swal.fire("ERROR!!!", "Your Password is Incorrect. Check Again.", "error");</script>';     } if($username == $row['username'] && $password == $row['password']) { header('Location:cpanel/'); else { } }//if count }//while loop }//submit ?>  Will this prevent a SQL injection? I am guessing the answer is no because it is too simple. // retrieve form data ========================================== $ama = $_POST['ama']; // Check for alphanumeric characters ===================================== $string = "$ama"; $new_string = preg_replace("/[^a-zA-Z0-9\s]/", "", $string); // echo $new_string; // Send query =========================================================== $query = "SELECT * FROM members WHERE ama='$new_string'"; if (!mysql_query($query)){ die('Error :' .mysql_error()); } I want to know which part of my script has the hole..as i can find lots of php script and even folder can be injected into my public_html how they do that, and which part need to be checked? is that the upload part <enctype> or what?? thanks in advance i just want to ask this simple question let say i have this basic query $place=$_GET['place']; mysql_query("SELECT * FROM table WHERE place='$place'"); this is a nice target for sql injection.. but what if i replace the whole special characters that could be added $replacethis=array("-","`"); $withthis=array("",""); $place=str_replace($replacethis,$withthis,$_GET['place']); mysql_query("SELECT * FROM table WHERE place='$place'"); Are they still able to do the basic sql injection by trying to get the error by adding special character although i didn't use mysql_real_escape_string() ?? then what if i protect the file by changing the setting of the permission to either 644 or 755? thanks in advance I'm trying to use dependency injection to pass a database connection to an object but I'm not sure why it's not working. I have my "dbClass" below that connects to a MySQL database. Code: [Select] class dbClass { public $db; function __construct() { $this->db = mysql_connect("localhost","username","password") or die ('Could not connect: ' . mysql_error()); return $this->db; } } Then I have my "baseClass". This is the class that I want to feed to connection too. Code: [Select] class baseClass { public $mysql_conn; function __construct($db) { $this->mysql_conn = $db; $rs = mysql_select_db("webdev_db", $this->mysql_conn) or die ('Could not connect: ' . mysql_error()); } } And this is my index.php file. The error I'm getting is "supplied argument is not a valid MySQL-Link resource". However I tripled checked and my db connection details are definately correct. Code: [Select] $db = new dbClass(); $baseclass = new baseClass($db); Thanks for any help. Hello, I have a video game site - mostly vBulletin which is fine but there are a few extra bits to the site that I have done myself. I'm pretty new to PHP so my code isn't great. Anyway, I wanted to test my code for SQL Injection but I looked on Google and most of the tools seemed to come from hacker sites etc which I'm not downloading. I eventually found an addon for Firefox called SQL Inject Me and ran that. It said everything was alright but when I checked my MySQL tables they were full of junk code it had inserted. One of my pages doesn't even have any visible fields. It's just a page with a voting submit button and some hidden fields so how does it inject the code into the tables? The insert page code is: Code: [Select] $db = mysql_connect("localhost", "username", "password"); mysql_select_db("thedatabase",$db); $ipaddress = mysql_real_escape_string($_POST['ipaddress']); $theid = mysql_real_escape_string($_POST['theid']); $gamert = mysql_real_escape_string($_POST['gamert']); $serveron = mysql_real_escape_string($_POST['serveron']); $check= mysql_query("select * from voting2 where ipaddress='$ipaddress'"); $ipname = mysql_fetch_assoc($check); if($ipname['ipaddress'] == $ipaddress) { echo 'It appears you have already voted. Click <a href="vote.php">here</a> to return to the votes.'; } else { mysql_query ("INSERT INTO voting2 (theid,ipaddress,gamert,serveron2) VALUES ('$theid','$ipaddress','$gamert','$serveron')"); echo 'Your vote has been added. Click <a href="vote.php">here</a> to view the updated totals.'; } How can I make it safer against SQL injection? Thanks Hi, I'm sure many of you heard of "pastebin", if not the short of it, is that you can submit your code (+100 languages), and you can display it to your friends via a link with syntax highlighting available. So, One way to store the code is surely in txt files, but I would really prefer to have it stored in a mysql database. My only concern is people trying to run a sql injection, so how do i get around all this? I don't want the user's content to be changed, but I don't want SQL injections either.. is this even possible at all? Any tips appreciated, also if you could think of another alternative than txt files and mysql. (I'm putting this in PHP since it's not a question specific to MySQL or other DB stuff.)
I have a page that uses the GET id to find a product. GET variables are sanitized, and the SQL string is escaped even though it's expecting a number only. So the code seems safe to me. I'm getting some error_log results that appear to be hack attempts:
SELECT Hi, I am using parameterized queries on my code, here's the relevant part Code: [Select] $params=$_POST['ITGtable']; $tsql2 = "SELECT COLUMN_NAME, DATA_TYPE, ORDINAL_POSITION, COLUMN_DEFAULT, CHARACTER_MAXIMUM_LENGTH, IS_NULLABLE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME=?"; /* Execute the statement with the specified parameter value. Display the returned data if no errors occur. */ $stmt2 = sqlsrv_query( $conn, $tsql2, $params); if( $stmt2 === false ) { echo "Statement 2 could not be executed.\n"; die( print_r(sqlsrv_errors(), true)); } else { $qty = sqlsrv_fetch_array( $stmt2); } Do I really have to sanitize $_POST['ITGtable'] for apostrophe, semicolon, etc, to avoid SQL injection problems? Or just with above code I should be safer (I did not say safe) against SQL injection? And if the answer is "No", what could be the sanitize code of function? I am using sqlsrv and MS-SQL database engine; most of the functions we have for sanitize inputs on MySQL are not available for MS-SQL. Thanks in advance, Does this code have mySQL Injection vulnerability?
$query = "DELETE FROM `$table` WHERE `$column` IN('".implode("','",$array)."')";using php5, would this make the code more safe... foreach($array as $key=>$a){ $array[$key] = mysql_real_escape_string($a);} $query = "DELETE FROM `$table` WHERE `$column` IN('".implode("','",$array)."')";or is there another way to make the code safe? ok here is my comment protection >< very basic and simple but i just got htmlentitied lol =[ how do i protect against that? Code: [Select] if (isset($_POST['submit'])) { $comment= trim(stripslashes(mysql_real_escape_string($_POST['comment']))); this is my registration protection, sql can still get though >< it doesnt work ? Code: [Select] $_POST['pass'] = md5($_POST['pass']); if (!get_magic_quotes_gpc()) { $_POST['pass'] = trim(stripslashes(mysql_real_escape_string($_POST['pass']))); $_POST['username'] = trim(stripslashes(mysql_real_escape_string($_POST['username']))); } Hey Guys! I have the following Working php script (receives the variables from Flash) //LOGIN! if ($action == "login") { //retreive data from flash $username=mysql_real_escape_string($_POST['Username']); $password=mysql_real_escape_string($_POST['txtPassword']); $result = mysql_query("SELECT name, activated from buyers WHERE email = '$username' AND password = md5('$password')"); $cant = 0; while($row=mysql_fetch_array($result)) { echo "name$cant=$row[name]&activated$cant=$row[activated]&"; $cant++; } echo "cant=$cant&"; if (mysql_num_rows($result) > 0) { echo "status1=exists"; } else { echo "status1=Incorrect Login"; } } As you can see I have used mysql_real_escape_string for the variables $username and $password that are coming from Flash. I would really appreciate some guidence if this is the only safe code I need in this script? For example: Does $action == "login" need also mysql_real_escape_string ?? That variable $action is also coming from flash (but is not inputted by a user) Any ideas? Thanks in advance, Cheers! Trying to make my code more secure. This is what I currently have, which is not secure by any means: Code: [Select] $query1 = "SELECT COLUMN_NAME, DATA_TYPE, ORDINAL_POSITION, COLUMN_DEFAULT, CHARACTER_MAXIMUM_LENGTH, IS_NULLABLE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='$table'"; // Run PRO query $qresult1 = sqlsrv_query($dbPRO, $query1); if ($qresult1 === false) { exitWithSQLError('Retrieving schema failed.'); } This is how I changed it, Code: [Select] $query1 = "SELECT COLUMN_NAME, DATA_TYPE, ORDINAL_POSITION, COLUMN_DEFAULT, CHARACTER_MAXIMUM_LENGTH, IS_NULLABLE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME=?"; $params = array(1, $table); // Run PRO query $qresult1 = sqlsrv_query($dbPRO, $query1, $params); if ($qresult1 === false) { exitWithSQLError('Retrieving schema failed.'); } but I'm getting this error: Code: [Select] SQL-Status: 22018 Code: 245 Message: [Microsoft][SQL Server Native Client 10.0][SQL Server]Conversion failed when converting the nvarchar value 'sysrscols' to data type int Please notice I am using sqlsrv_query function because my database engine is MS-SQL 2008. That's why I'm a bit confused. Most documentation online is pointed to MySQL. exitWithSQLError is a customized function of mine, so please ignore. Any help or hints is appreciated, Thanks, Hi all, I thought instead of just simple do all the security stuff automatically, why not see for myself what the it can do. So I made a simple table besides the other tables named delete_me, made a form and started testing. But for some reason I can get that table to drop. this is what i did on the front end with help from he http://en.wikipedia.org/wiki/SQL_injection in all 3 fields (firstname, lastname email) put a value and in the last one i put: but nothing happend. if someone knows what i am doing wrong please tell me because I think it's vital in order to protect yourself one needs to know what he or she is up against. been wondering about this for a while do I need to put the escape on each WHERE? or do i really only need to put it on the $_POST i can probably understand why i need it on $_GET also after WHERE. So wondering about the session id. Code: [Select] <?php mysql_query("UPDATE systems SET homes= $homes + '".mysql_real_escape_string($_POST['homes'])."' WHERE address = '".mysql_real_escape_string($_GET['planet'])."' AND id = '".($_SESSION['user_id'])."'"); ?> |