From here: PHP $_SESSION is server side or local? I understand that session is server side only and client can't tinker with it.
So I assume it is a safe approach to set id from database to client session id and use it as identification to insert into database?
For example I'm doing like this right now for identification on all my page: login.php
$result = mysqli_query($con, "SELECT id, name, password FROM user_data WHERE email_address = '$email' AND status = '1'") or die(mysqli_error($con));
$row = mysqli_fetch_assoc($result);
if (password_verify($password, $row["password"])) {
$userinfo = array();
$userinfo['id'] = $row["id"];
$userinfo['name'] = $row["name"];
$_SESSION['userinfo'] = $userinfo;
header ("Location: insert.php");
}
and on insert.php page
$result = mysqli_query($con,"INSERT INTO client_data (`data`, `id`) VALUES ('$value', ".$_SESSION['userinfo']['id'].")");
$_SESSION['userinfo']['id'] is only as safe as you make it.
Trusting whatever is in it means trusting all the publicly accessible PHP scripts to work correctly, with no possibility to abuse them to set $_SESSION['userinfo']['id'] to something nasty.
That's really a lot of trust.
I don't think that's affordable.
Especially when this can be done more securely using prepared statements quite easily.
if ($stmt = $mysqli->prepare("INSERT INTO client_data (`data`, `id`) VALUES (?, ?)")) {
/* bind parameters for markers */
$stmt->bind_param("s", $value);
$stmt->bind_param("s", $_SESSION['userinfo']['id']);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($result);
/* fetch value */
$stmt->fetch();
/* close statement */
$stmt->close();
}
Using prepared statements will also have the additional benefit of the RDBMS optimizing the queries, making repeated queries faster.
Related
For some reason, the query when run through PHP will not return the results. I have tried both queries in the MySQL command line, and they work perfectly there. Here is the code (mysql_connect.php is working perfectly, to clarify).
<?php
error_reporting(-1);
// retrieve email from cookie
$email = $_COOKIE['email'];
// connect to mysql database
require('mysql_connect.php');
// get user_id by searching for the email it corresponds to
$id = mysqli_query($dbc,"SELECT user_id FROM users WHERE email=$email")or die('couldn\'t get id');
// get data by using the user_id in $id
$result = mysqli_query($dbc,"SELECT * FROM users WHERE user_id=$id")or die('couldn\'t get data');
//test if the query failed
if($result === FALSE) {
die(mysql_error());
echo("error");
}
// collect the array of results and print the ones required
while($row = mysql_fetch_array($result)) {
echo $row['first_name'];
}
?>
When I run the script, I get the message "could not get id", yet that query works in the MySQL command line and PHPMyAdmin.
Your code won't work for 2 reasons - $id will not magically turn into integer, but a mysqli result. And email is a string so it should be quoted.
But...
Why is all of that?
If you want to fetch all the data for user, for certain email, just make you second query fetch data by email and remove the first one:
SELECT * FROM users WHERE email='$email';
And don't forget to escape your input, because it's in cookie. Or, use prepared statements as suggested.
Your query is not valid, you should rewrite it with the following and make sure your you have mysqli_real_escape_string of the $email value before you put it into queries:
SELECT user_id FROM users WHERE email='$email'
Better approach is to rewrite your queries using MySQLi prepared statements:
Here how to get the $id value:
$stmt = mysqli_prepare($dbc, "SELECT user_id FROM users WHERE email = ?");
mysqli_stmt_bind_param($stmt, "s", $email);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $id);
mysqli_stmt_fetch($stmt);
You wrote
mysqli_query($dbc,"SELECT user_id FROM users WHERE email=$email");
that is similar to
mysqli_query($dbc,"SELECT user_id FROM users WHERE email=example#example.com");
but it should be
mysqli_query($dbc,"SELECT user_id FROM users WHERE email='example#example.com'");
so you have to do this
mysqli_query($dbc,"SELECT user_id FROM users WHERE email='$email'");
or better
mysqli_query($dbc, 'SELECT user_id FROM users WHERE email=\'' . $email . '\'');
Beside this minor bug
You should be aware of SQL injection if someone changes the value of your cookie.
I'm really just wanting to check the syntax on this statement and make sure that it's a statement that is safe from sql injection. Could anyone check this for me and let me know?
$lookupusername= $conn->prepare('SELECT * FROM users WHERE ID =":userId"');
$lookupusername->bindParam(':userId', $userid, PDO::PARAM_STR, 12);
$row = $lookupusername->fetch();
$username = $row['username'];
$usercountry = $row['country'];
if ($username == ""){
header('Location: index.php');
}
There's also this statement:
$sql = $conn->query('SELECT description, city, status, state, country, needsusername, howmanypeopleneeded, howmanypeoplesignedup, needs.orgname, needs.ID, titleofneed, expiredate, datesubmitted, datetime FROM needs INNER JOIN follow ON follow.followname = needs.needsusername WHERE follow.username=' . $conn->quote($username) . ' AND needs.christmas="0" AND needs.status="posted" ORDER BY datesubmitted DESC');
while ($frows = $sql->fetch()) {
FINAL CODE:
$lookupusername= $conn->prepare('SELECT * FROM users WHERE ID=:userid');
$lookupusername->bindParam(':userid', $userid);
$lookupusername->execute();
$row = $lookupusername->fetch();
$username = $row['username'];
$usercountry = $row['country'];
I wasn't executing the prepared statement.
I would recommend conn->[execute][1] instead of [query][2]. As that will be a real prepared statement instead of one you need to escape on.
SELECT * FROM users WHERE ID =:userID
then do:
bindParam(':userId', $userId, PDO::PARAM_STR, 12);
In terms of malicious content, assume for a second I pass you a userId that looks like this:
<script>alert('Hi')</script>
Now lets also assume you display my userId to someone that is an admin or another user. I can potentially inject malicious code that will be executed at a later time. So you must still take care to ensure data returned to the user is properly escaped. But for the most part, binding parameters will prevent arbitrary SQL execution.
functional code:
$sql= $conn->prepare('SELECT * FROM users WHERE ID =:userID');
$sql->bindParam(':userId', $userId, PDO::PARAM_STR, 12);
I've been trying to figure out how to insert data received from a form into one table only if the received data exists in another table. If the data doesn't exist it moves onto another query and checks another table for the received data.
This is what I'm trying to do:
function addNewUser($username, $password, $email, $actcode){
$time = time();
$q = "UPDATE ".TBL_RELEASE_CODES." SET code = '$actcode' WHERE code = '$actcode'";
$result = mysql_query($q, $this->connection);
if (!$result || (mysql_numrows($result)) == 0){
$q = "INSERT INTO ".TBL_RELEASE_USERS." VALUES ('$username', '$password', '0', $ulevel, '$email', '$actcode', $time)";
return mysql_query($q, $this->connection);
}
The purpose of this is that when the user submits a special code the system will run checks to see if the code belongs to a certain table.
If it finds the submitted code in a table it will run the insert query associated with the check, if not then it breaks and returns an error saying no match was found.
I'm probably using the code incorrectly as I've been scrounging information from Google searches and testing them out. With no luck yet.
This code is being run off a website using PHP 5 and MySQL.
The first query doesn't do anything -- it sets code to $actcode only in the rows where code is already $actcode. You should use a SELECT, not UPDATE:
$q = "SELECT COUNT(*) FROM ".TBL_RELEASE_CODES." WHERE code = ?";
$stmt = mysqli_prepare($this->connection, $q);
mysqli_stmt_bind_param($stmt, 's', $actcode);
mysqli_stmt_bind_result($stmt, $count);
mysqli_execute($stmt) or die "Query failed: ".mysqli_stmt_error($stmt);
mysqli_stmt_fetch($stmt);
if ($count == 1) {
// Insert into TBL_RELEASE_USERS
} else {
// Return error saying no match found
}
You should also not use the mysql_XXX functions. They're deprecated and make it hard to avoid SQL-injection attacks. My code above uses mysqli_XXX, which supports prepared statements to protect against that. It also has an OO-style API if you like, but I didn't use that above.
I have this code to select all the fields from the 'jobseeker' table and with it it's supposed to update the 'user' table by setting the userType to 'admin' where the userID = $userID (this userID is of a user in my database). The statement is then supposed to INSERT these values form the 'jobseeker' table into the 'admin' table and then delete that user from the 'jobseeker table. The sql tables are fine and my statements are changing the userType to admin and taking the user from the 'jobseeker' table...however, when I go into the database (via phpmyadmin) the admin has been added by none of the details have. Please can anyone shed any light onto this to why the $userData is not passing the user's details from 'jobseeker' table and inserting them into 'admin' table?
Here is the code:
<?php
include ('../database_conn.php');
$userID = $_GET['userID'];
$query = "SELECT * FROM jobseeker WHERE userID = '$userID'";
$result = mysql_query($query);
$userData = mysql_fetch_array ($result, MYSQL_ASSOC);
$forename = $userData ['forename'];
$surname = $userData ['surname'];
$salt = $userData ['salt'];
$password = $userData ['password'];
$profilePicture = $userData ['profilePicture'];
$sQuery = "UPDATE user SET userType = 'admin' WHERE userID = '$userID'";
$rQuery = "INSERT INTO admin (userID, forename, surname, salt, password, profilePicture) VALUES ('$userID', '$forename', '$surname', '$salt', '$password', '$profilePicture')";
$pQuery = "DELETE FROM jobseeker WHERE userID = '$userID'";
mysql_query($sQuery) or die (mysql_error());
$queryresult = mysql_query($sQuery) or die(mysql_error());
mysql_query($rQuery) or die (mysql_error());
$queryresult = mysql_query($rQuery) or die(mysql_error());
mysql_query($pQuery) or die (mysql_error());
$queryresult = mysql_query($pQuery) or die(mysql_error());
mysql_close($conn);
header ('location: http://www.numyspace.co.uk/~unn_v002018/webCaseProject/index.php');
?>
Firstly, never use SELECT * in some code: it will bite you (or whoever has to maintain this application) if the table structure changes (never say never).
You could consider using an INSERT that takes its values from a SELECT directly:
"INSERT INTO admin(userID, forename, ..., `password`, ...)
SELECT userID, forename, ..., `password`, ...
FROM jobseeker WHERE userID = ..."
You don't have to go via PHP to do this.
(Apologies for using an example above that relied on mysql_real_escape_string in an earlier version of this answer. Using mysql_real_escape_string is not a good idea, although it's probably marginally better than putting the parameter directly into the query string.)
I'm not sure which MySQL engine you're using, but your should consider doing those statements within a single transaction too (you would need InnoDB instead of MyISAM).
In addition, I would suggest using mysqli and prepared statements to be able to bind parameters: this is a much cleaner way not to have to escape the input values (so as to avoid SQL injection attacks).
EDIT 2:
(You might want to turn off the magic quotes if they're on.)
$userID = $_GET['userID'];
// Put the right connection parameters
$mysqli = new mysqli("localhost", "user", "password", "db");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
// Use InnoDB for your MySQL DB for this, not MyISAM.
$mysqli->autocommit(FALSE);
$query = "INSERT INTO admin(`userID`, `forename`, `surname`, `salt`, `password`, `profilePicture`)"
." SELECT `userID`, `forename`, `surname`, `salt`, `password`, `profilePicture` "
." FROM jobseeker WHERE userID=?";
if ($stmt = $mysqli->prepare($query)) {
$stmt->bind_param('i', (int) $userID);
$stmt->execute();
$stmt->close();
} else {
die($mysqli->error);
}
$query = "UPDATE user SET userType = 'admin' WHERE userID=?";
if ($stmt = $mysqli->prepare($query)) {
$stmt->bind_param('i', (int) $userID);
$stmt->execute();
$stmt->close();
} else {
die($mysqli->error);
}
$query = "DELETE FROM jobseeker WHERE userID=?";
if ($stmt = $mysqli->prepare($query)) {
$stmt->bind_param('i', (int) $userID);
$stmt->execute();
$stmt->close();
} else {
die($mysqli->error);
}
$mysqli->commit();
$mysqli->close();
EDIT 3: I hadn't realised your userID was an int (but that's probably what it is since you've said it's auto-incremented in a comment): cast it to an int and/or don't use it as a string (i.e. with quotes) in WHERE userID = '$userID' (but again, don't ever insert your variable directly in a query, whether read from the DB or a request parameter).
There's nothing obviously wrong with your code (apart from it being insecure with using non-escaped values directly from $_GET).
I'd suggest you try the following in order to debug:
var_dump $userData to check that the values are as you expect
var_dump $rQuery and copy and paste it into phpMyAdmin to see if your query is not as you expect
If you don't find your problem then please post back your findings along with the structure of the tables you're dealing with
I am trying to select from a mySQL table using prepared statements. The select critera is user form input, so I am binding this variable and using prepared statements. Below is the code:
$sql_query = "SELECT first_name_id from first_names WHERE first_name = ?";
$stmt = $_SESSION['mysqli']->prepare($sql_query);
$stmt->bind_param('s', $_SESSION['first_name']);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows == '1') {
$stmt->bind_result($_SESSION['first_name_id']);
$stmt->fetch();
} else {
$stmt->close();
$sql_query = "INSERT INTO first_names (first_name) VALUES (?)";
$stmt = $_SESSION['mysqli']->prepare($sql_query);
$stmt->bind_param('s', $_SESSION['first_name']);
$stmt->execute();
$_SESSION['first_name_id'] = $_SESSION['mysqli']->insert_id;
}
$stmt->close();
Obviously my code is just determining whether or not the first_name already exists in the first_names table. If it does, it returns the corresponding ID (first_name_id). Otherwise, the code inserts the new first_name into the first_names table and gets the insert_id.
The problem is when a user enters a name with an escape character ('Henry's). Not really likely with first names but certainly employers. When this occurs, the code does not execute (no select or insert activity in the log files). So it seems like mySQL is ignoring the code due to an escape character in the variable.
How can I fix this issue? Is my code above efficient and correct for the task?
Issue #2. The code then continues with another insert or update, as shown in the code below:
if (empty($_SESSION['personal_id'])) {
$sql_query = "INSERT INTO personal_info (first_name_id, start_timestamp) VALUES (?, NOW())";
} else {
$sql_query = "UPDATE personal_info SET first_name_id = ? WHERE personal_info = '$_SESSION[personal_id]'";
}
$stmt = $_SESSION['mysqli']->prepare($sql_query);
$stmt->bind_param('i', $_SESSION['first_name_id']);
$stmt->execute();
if (empty($_SESSION['personal_id'])) {
$_SESSION['personal_id'] = $_SESSION['mysqli']->insert_id;
}
$stmt->close();
The issue with the code above is that I cannot get it to work at all. I am not sure if there is some conflict with the first part of the script, but I have tried everything to get it to work. There are no PHP errors and there are no inserts or updates showing in the mySQL log files from this code. It appears that the bind_param line in the code may be where the script is dying...
Any help would be very much appreciated.
you should validate/escape user input before sending it to the db.
checkout this mysql-real-escape-string()