I'm using session variables in an SQL query that updates either wins or losses whenever called. I've looked over similar questions, but they are using mysql as opposed to mysqli. What is the correct manner for using php variables in a mysqli query?
Here's what mine looks like:
$sqlQuery = "UPDATE users SET wins=wins+1 WHERE username == $_SESSION['username']";}
the resulting sql query should look like this:
UPDATE users SET wins=wins+1 WHERE username = 'user_name';
so we need to prepare it correctly:
$sql = sprintf(
"UPDATE users SET wins=wins+1 WHERE username = '%s';",
$_SESSION['username']
);
but please, use a proper database connector (PDO, mysqli) and escape the username.
Related
I wrote a SQL query for checking name in php, but it does not work.
I have no assumptions how to fix it, but I assume it's just mistake in syntax.
$username = $_POST["username"];
$nameCheckQuery = "SELECT username FROM users WHERE username '" . $username . "';";
$nameCheck = mysqli_query($db, $nameCheckQuery) or die("2: Name check query failed");
I receive error log on query.
The reason it's failing is likely due to you missing a = after username.
This code is open to SQL injection and you should use prepared statements.
The most basic of a prepared statement looks something like this:
$stmt = $db->prepare("SELECT * FROM users WHERE username = ?");
$username = $_POST['username'];
$stmt->bind_param('s', $username);
$result = $stmt->execute();
The main problem of your query is that you forget to insert = next to WHERE username.
You have to write:
$nameCheckQuery = "SELECT username FROM users WHERE username ='" . $username . "';";
Right now it works but......
The query you are using is not preventing a SQL INJECTION attack (one of the most used attack against database).
Please take a look at the ways you can connect to the database:
use PDO (it works with 12 database type);
use MSQLI (it works only with MYSQL database and you are using it);
In other word, if you are planning that you will move your application in another database type please consider to use PDO, instead.
Using PDO preventing SQL injection you have to prepare the SQL statement like this:
$stmt = $pdo->prepare("SELECT username FROM users WHERE username = ?");
$stmt->execute([$_POST['username']]);
$arr = $stmt->fetch();
For Starter, please use this escape string:
$username = $mysqli->real_escape_string($_POST["username"]);
Simply do it like this and don't get confused with quotes.
You can still print php variables inside single quote like this.
$nameCheckQuery = "SELECT username FROM users WHERE username = '$username'";
or to edit your code, this is how you can achieve it.
$nameCheckQuery = "SELECT username FROM users WHERE username ='" . $username."'";
Just to answer your question, it is Vulnerable to Sql Injection.
Reasons why Sql Injection occurs:
SQL Injection occurs when an attacker is able to send their own instructions to your database and the database executes those instructions. This occurs when a PHP developer has taken input from a website visitor and passed it to the database without checking to see if it contains anything malicious or bothering to clean out any malicious code.
SQL Injection can allow an attacker to access all of your website data. They can also create new data in your database which may include links to malicious or spam websites. An attacker may also be able to use SQL Injection to create a new administrative level user account which they can then use to sign-into your website and gain full access.
SQLi is a serious vulnerability because it is easy to exploit and often grants full access immediately.
This is how you can achieve it, which provides detailed functionality.
https://stackoverflow.com/a/60496/6662773
I'm using ORM layer in databases all the time, so I don't mind about SQL injections, but a friend gave me this task and I still have no idea how to solve it.
I know the PHP script just checks if the return of the query is != null (username matching to entered username & password is found).
The query itself in PHP looks like:
$sql = "SELECT name FROM users WHERE name='".$name. "' AND password='".$password. "'";
What's the best way to archieve a return of this query != null OR retrieving valid login data (username & password). The password is stored plain in database. I know storing plain is bad and I know using PDO is good, but I have no idea how to solve this funny task he gave me, maybe because I use PDO all the time.
Say we have these two input variables:
$name = "iam";
$password = "aninjection";
Which results in this query:
$sql = "SELECT name FROM users WHERE name='iam' AND password='aninjection'";
And let's say now we add this to the $password variable:
$password = "aninjection' OR 1='1";
Which results in:
$sql = "SELECT name FROM users WHERE name='iam' AND password='aninjection' OR 1='1'";
This query will now result in true and show every name from the user table.
This is of course a basic example. We could also do more harm by dropping entire tables.
If you wanted to retrieve passwords you would inject
$name = "whatever";
$password = "' OR '1'='1' UNION ALL SELECT password from users;--";
This would then make the query
SELECT name FROM users WHERE name='whatever' AND password='' OR '1'='1' UNION ALL SELECT password from users;--'
See this answer for how an attacker would start to work this out from injecting into the query.
The question is, I have an ID, username and a password for each user.
What is the syntax to get the ID based on a specific username and password.
I have this code but it doesn't seem to work :S
$dbusername=$row['user']; //php
$dbpassword=$row['password']; //php
$userID = mysql_query("SELECT [$dbusername], [$dbpassword]' FROM users WHERE ID = $_GET[id]");
mysql_query("UPDATE users SET lastactivity = ".time()." WHERE ID = ".$userID);
mysql_query with a SELECT statement returns a resource type, not the value you expect to have it. You need to use more commands there. Please check the documentation. It has several examples.
NEVER use mysql_* functions, always use PDO or mysqli.
Example: http://br2.php.net/manual/en/pdostatement.fetch.php
mysql_query doesn't return columns from the database. It returns a query object. You must then fetch rows from the database based on the query object. Please read the mysql documentation carefully. Better still, stop using mysql and use mysqli instead. http://php.net/manual/en/book.mysqli.php
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Best way to prevent SQL Injection in PHP
I just found that my website is vunerable.
Since it's connected to a DB and have functions like: Register, Change Password, Notices, etc... and SUPOSING it's fully vulnerable.
What should I look for into the code in order to start making it safe?
I mean, I did some researches and everywhere, everyone says different things about security.
"Use PDO."
"Use mysql_real_escape_string."
"Use addslashes."
What exactly should I look for??
"$_POST" and "$_GET" variables??
"$_SESSION" variables?
SQL querys?
$sql = "select * from user";
$sql = "update user set user="new_user_name";
$sql = "insert into user (user) values ('userid')";
What should I do in each case?
Please, help me to know what and where I must go.
Thank you.
Following are the points to be considered for making safe php application.
USE PDO or mysqli
Never trust any inputs. Consider every variable viz $_POST, $_GET, $_COOKIE, $_SESSION, $_SERVER as if they were tainted. Use appropriate filtering measure for these variables.
To avoid XSS attack use php’s builtin functions htmlentities,
strip_tags, etc while inserting the user input data into the
database.
Disable Register Globals in PHP.INI
Disable “allow_url_fopen” in PHP.INI
Don’t allow user to input more data than required. Validate input to
allow max number of characters. Also validate each field for
relevant datatypes.
Disable error reporting after Development period. It might give
information about database that’ll be useful to hackers.
Use one time token while posting a form. If token exist and matches
the form post is valid otherwise invalid.
Use parametrized database queries
Use stored procedures
You can google for each point for more details.
HOpe this helps
What you should look for: Any data send from the client/user. Sanitize/escape this data.
PDO can sanitize queries (using PDO::prepare) and supports multiple SQL systems.
For MySQL, use MySQLi. mysqli_real_escape_string is the function to use for sanitizing data if you are using MySQL.
None of the SQL queries you provided are actually vulnerable to SQL injection.
SQL injection vulnerabilities happen because SQL input is not properly escaped.
For example:
$sql = "select * from users where user_id =" . $_GET['user_id'];
Consider if I passed in the following:
http://some_server.com/some_page.php?user_id=123%20or%201=1
The query when executed would end up being:
select * from users where user_id = 123 or 1=1
To fix this, use parameterized queries:
$query = "select * from users where user_id = ?"
When you bind the user_id value to the query, the data access layer will escape the input string properly and the following would be executed:
select * from users where user_id = '123 or 1=1' which would not return any rows, preventing the injection
If using PHP and the mysql extension:
$sql = "select * from users where user_id = '" . mysql_real_escape_string($_GET['user_id']) . "'";
Keep in mind you need to escape ALL input that is going into a SQL query:
$sql = "select id_column from some_table where id = 1";
$stmt = mysqli_query($conn, $sql);
if($stmt === false) die(mysqli_error($conn) . "\n");
while($row = mysqli_fetch_assoc($conn, $stmt) {
$sql = "update some_other_table set some_value = 'new value' where some_column = '" . mysqli_real_escape_string($conn, $row['id_column']) . "'";
....
}
This is because values you select from the database might include characters that are not safe for execution in a SQL statement, like the name "O'Hara" or example.
}
I've been using PDO.
An example for that in your case:
<?php
$stmt = $dbh->prepare("insert into user (user) values (?)");
$stmt->bindParam(1, $name);
$name = 'ValueHere';
$stmt->execute();
?>
I searched before posting this but didn't find an answer to my question.
I have a table in a database which stores queries such as (with the php variable stored in the database):
select * from accounts where type = 'client'
select * from accounts where user_id = $userid
select * from accounts where name = '$name'
I assumed that when I pulled that particular query from the database that PHP would recognized the variable and replace it but it treats it as regular text.
Is there a way to have PHP replace the $__ with an actual variable that exists? I think maybe the eval() function perhaps??
What you might try is using it as a prepared statement. So instead, if your database stored queries looked like this:
select * from accounts where type = 'client'
select * from accounts where user_id = ?
select * from accounts where name = ?
and you use PDO prepared statements like this:
$pdo = new PDO($dsn, $user, $pass);
$statement = $pdo->prepare($secondOfTheAboveQueries);
$statement->execute(array($userId));
$account = $statement->fetch();
You could also use prepared queries with named variables like user_id = :userid instead of questions marks if you have to process a few statements at a time with various variables.
You may also want to consider stored procedures which work similarly. An explanation for both can be found here:
http://php.net/manual/en/pdo.prepared-statements.php
Assuming that you pull the query from a database:
$string = ''; // Assign the real userID
while ($fetch = mysql_fetch_array($query)) {
$newQuery = str_replace('$userid', $string, $fetch['your_row_name']);
}
I'm not sure if this will work, but this is what i would try first...
sprint seems to work well. instead of storing them as $variable, I can use %s, etc.