PHP - Sql Injection Prevention, Question.
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! Similar TutorialsHi 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'])."'"); ?> Hi, I'm trying to understand any how I can block all users trying to view my website through proxies. With the following code, what I have done is a quick version through php (with headers and ports) and not the firewall which isn't exactly the best way but still stops a lot of them. <?php $user_ip = $_SERVER['REMOTE_ADDR']; $headers = array('CLIENT_IP','FORWARDED','FORWARDED_FOR','FORWARDED_FOR_IP','VIA','X_FORWARDED','X_FORWARDED_FOR','HTTP_CLIENT_IP','HTTP_FORWARDED','HTTP_FORWARDED_FOR','HTTP_FORWARDED_FOR_IP','HTTP_PROXY_CONNECTION','HTTP_VIA','HTTP_X_FORWARDED','HTTP_X_FORWARDED_FOR'); foreach ($headers as $header) { if (isset($_SERVER[$header])) { header("Location: /proxy-not-allowed/"); die; } } $queryIP = "SELECT `user_ip_address` FROM `my_table` WHERE `user_ip_address` = :user_ip_address AND `user_blocked` = :user_blocked LIMIT 1"; $queryIP1 = $pdo->prepare($queryIP); $queryIP1->execute(array(':user_ip_address' => $user_ip, ':user_blocked' => 'No')); $queryIP2 = $queryIP1->rowCount(); if ($queryIP2 === 0) { $ports = array(80, 81, 553, 554, 1080, 3128, 4480, 6588, 8000, 8080); foreach ($ports as $port) { $connection = @fsockopen($user_ip, $port, $errno, $errstr, 0.1); if (is_resource($connection)) { header("Location: /proxy-not-allowed/"); die; } } } ?> The headers script blocks any proxy sending those headers while the ports script blocks those using any assigned ports I add. I have tested this which seems to be good, though it won't block all proxies due to the assigned one I have. Is this the best way to go about blocking scripts if I don't have access to the firewall? What I am trying to do is allow users to view my HTTPS website normally and block all proxies. Even if I have some users blocked, I do not want them to be cheeky and use a proxy or even register on my website through a proxy. I was thinking of just using the 443 port as my website is https (is that wise?). Any advice would be great. Edited January 4, 2019 by Cobra23 I have a question about Cross-Site Request Forgeries (CSRF). Somewhere in the processing of my form, I check: if (isset($_SESSION['token']) && $_POST['token'] == $_SESSION['token']) { // all other code omitted } else { // no place for bad guys here } So basically, if the token is good then the form continues to check for errors, valid data, etc... I was wondering; is there a point in checking the token again each time I check something else? For example: // above code omitted if (isset($_SESSION['token']) && $_POST['token'] == $_SESSION['token']) { // all other code omitted // check to see if there were any errors if (count($errors) >= 1) { $valid = false; } else { // all other code omitted if ($sent == $allowed) { if ($addNew == true) {// Should I be checking the token each time, or am I being redundant?? // all other code omitted } } } } else { // no place for bad guys here } Hi all, last few days i searched my butt of on articles about this topic but most don't seem to provide a solution, more a general idea of what it is. So i thought i mix up some functions and asks you guys to see if this could be a working example to prevent directory traversal and the prevention of including remote files. So the files should be on my server. What i try to do is to retrieve a $_GET['variable'] which stands for a filename and afterwards include this file name if the file exists. Any tips and tricks are welcome. if (file_exists(basename(realpath($_GET['filenamehere'])))){ echo 'file exists'; }else{ echo 'file doesn\'t exist'; } thanks in advance!
$sql="SELECT COUNT(*) as conflicts
how do I get the value of the conflicts im now very clueless 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? 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. 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()); } 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 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. 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 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 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 ?>
Well, I just want to know, if I add mysql_real_escape_string and strip_tags to a checkbox, does this mean it is 100% protected from SQL injection and XSS attack? For example: Code: [Select] <input type=checkbox' name="checkbox"/> $checkbox = mysql_real_escape_string(stip_tags($_POST['checkbox'])); 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, How can you protect mysql injection? (from inserting different statements into the input field) Thanks |