Index.php
$password = hash('sha256', $pass); // password hashing using SHA256
$res=mysql_query("SELECT * FROM users WHERE userEmail='$email'");
$row=mysql_fetch_array($res);
$count = mysql_num_rows($res); // if uname/pass correct it returns must be 1 row
if( $count == 1 && $row['userPass']==$password ) {
$_SESSION['user'] = $row['userId'];
$_SESSION['location'] = $row['userLocation'];
header("Location: home.php");
} else {
$errMSG = "Incorrect Login";
}
Home.php
$query = "SELECT * FROM machines WHERE locatie=".$_SESSION['location'];
$result = mysql_query($query);
Why Does this not work??
I can't figure out why the $_SESSION['locatie'] part does not work??
I thought it has the same value as in the other file.
There is a syntax error in your mysql query.
$query = "SELECT * FROM machines WHERE locatie='".$_SESSION['location']."'";
You want the $_SESSION['location'] value to be carried over to the home.php file, after redirection?
Make sure that $row['location'] has a value, and that session_start() has been invoked on both pages.
Try Checking by debugging the code like this
print_r($row);
If Yes then again do this:
echo $row['userLocation'];
Are you getting this value?
Then If You want to put value into session and den redirect make sure you initialize the session first by writing session_start(); and den add the value like
$_SESSION['location]= $row['userLocation];
But make sure check are you getting value before setting session.?
Better would be to solve if you update your code with print_r($row);
And please stop using sql functions as they are deprecated instead use mysqli and pdo .
Related
In this index page of mine I have an error coming up with the code so I printed off the Query to see if the error is there and strangely enough I get the ID and Password of the query but not the username.
This is the print out:
SELECT * FROM admin WHERE id='3' AND username='' AND password='alan' LIMIT 1You data dont exist in the database
where username field is empty should be Alan
here is my PHP:
<?php
session_start();
if (!isset($_SESSION["manager"])){
header("location: admin_login.php");
exit();
}
$managerID = preg_replace('#[^0-9]#i','',$_SESSION["id"]);
$manager = preg_replace('#[^A-Za-z0-9]#i','',$_SESSION["username"]);
$password = preg_replace('#[^A-Za-z0-9]#i','',$_SESSION["password"]);
include"db_connection.php";
$q = "SELECT * FROM admin WHERE id='$managerID' AND username='$manager' AND password='$password' LIMIT 1";
$sql = mysql_query($q);
echo $q;
$existCount=mysql_num_rows($sql);
if ($existCount ==0){
//header ("location: index.php");
echo "You data dont exist in the database";
exit();
}
?>
Using the following, I was able to successfully echo all three session variables.
Therefore, I am under the impression that either the username session variable is not set (from a previous form/HTML), and/or the form input element is not named or contains a typo.
Since you did not provide additional information in your (original) question in regards to how you are using it (from a form, or other) am submitting the following as a successful test.
I left out the first conditional statement from your code and filled in my own session variables.
<?php
session_start();
$_SESSION["id"] = "3";
$_SESSION["username"] = "FRED";
$_SESSION["password"] = "12345";
$managerID = preg_replace('#[^0-9]#i','',$_SESSION["id"]);
$manager = preg_replace('#[^A-Za-z0-9]#i','',$_SESSION["username"]);
$password = preg_replace('#[^A-Za-z0-9]#i','',$_SESSION["password"]);
echo $_SESSION["id"];
echo "<br>";
echo $_SESSION["username"];
echo "<br>";
echo $_SESSION["password"];
Which echo'ed:
3
FRED
12345
I am questioning this line though, since there is no other reference to it:
if (!isset($_SESSION["manager"]))
since it seems to be related to the word "manager"
$managerID = preg_replace('#[^0-9]#i','',$_SESSION["id"]);
where you might have meant to use:
if (!isset($_SESSION["id"]))
or:
$managerID = preg_replace('#[^0-9]#i','',$_SESSION["manager"]);
I'm kinda new to the OOP(? If this IS OOP, I don't know) language, and I'm trying to make a simple login-proccess, with MySQLi. The problem are, that the code doesn't work. I can't login (and It's not showing me any errors) and I can't register an new account (same problem) - It's like the code are dead or something.
I'm not sure I've done it right, but this is my best, so far. 'cause I'm new to OOP(?).
Index.php:
<?php
if(isset($_POST['submit'])) {
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string(md5($_POST['password']));
$userControl = "SELECT * FROM users WHERE username='".$username."' AND password='".$password."'";
$userControlResult = $mysqli->query($userControl);
if($mysqli->num_rows($userControlResult) > 1) {
$userRow = $mysqli->fetch_assoc($userControlResult);
$dbid = $userRow['id'];
$dbuser = $userRow['username'];
$_SESSION['id'] = $dbid;
$_SESSION['username'] = $dbuser;
header("location: me.php");
die();
} else {
echo "<div class='errorField'>Användarnamnet eller lösenordet är fel!</div>";
}
}
?>
I suppose that if I can solve the first error, I can solve the second too.
Thanks!
Many things I would recommend changing about your code:
Don't use mysql_real_escape_string() if you're using mysqli. You can't mix these APIs.
No need to escape a string returned by md5(), because it's guaranteed to contain only hexadecimal digits.
Don't use mysqli_real_escape_string() anyway -- use parameters instead.
Always check if prepare() or execute() return false; if they do, then report the errors and exit.
You can get a mysqli result from a prepared statement using mysqli_stmt_store_result().
Don't SELECT * if you don't need all the columns. In this case, you already have $username so all you really need to fetch is the id column.
No need to check the number of rows returned, just start a loop fetching the rows (if any). Since you exit inside the loop, your "else" error clause will be output only if the loop fetches zero rows.
Consider using a stronger password hashing function than MD5. Also, add a salt to the password before hashing. Read You're Probably Storing Passwords Incorrectly.
Example:
<?php
if(isset($_POST['submit'])) {
$username = $_POST['username'];
$password = md5($_POST['password']);
$userControl = "SELECT id FROM users WHERE username=? AND password=?";
if (($userControlStmt = $mysqli->prepare($userControl)) === false) {
trigger_error($mysqli->error, E_USER_ERROR);
die();
}
$userControlStmt->bind_param("ss", $username, $password);
if ($userControlStmt->execute() === false) {
trigger_error($userControlStmt->error, E_USER_ERROR);
die();
}
$userControlResult = $userControlStmt->store_result();
while($userRow = $userControlResult->fetch_assoc()) {
$_SESSION['userid'] = $userRow["id"];
$_SESSION['username'] = $username;
header("location: me.php");
die();
}
// this line will be reached only if the while loops over zero rows
echo "<div class='errorField'>Användarnamnet eller lösenordet är fel!</div>";
}
?>
A good command to enter at the top of the script (under the
ini_set('display_errors', 1);
This will display any errors on your script without needing to update the php.ini (in many cases). If you try this, and need more help, please post the error message here and I'll be able to help more.
Also, if you are using $_SESSION, you should have
session_start();
at the top of the script under the
Make sure your php is set to show errors in the php.ini file. You'll need to do some research on this on your own, but it's fairly easy to do. That way, you'll be able to see what the error is and go from there.
Hello I am trying to make multiple users in a CMS I made. I have all their data in a table and was using mysql_num_rows check if the records matched and then use session_register() to set a session. I have changed this to PDO commands.
I want to be able to track the user when they are using the CMS so that every record changed can have their usrID attached to it. So that at a later date I can see who made updates and eventually use this to show information about the author etc.
So for example when they use forms to update or add a new record a hidden input with have their session id echo'd into it which will be taken from their user record as they log in.
Is the best way to do this? Have a written the syntax in this login code correctly?
$con = new PDO(DB_DSN, DB_USERNAME, DB_PASSWORD);
$sql="SELECT * FROM $tbl_name WHERE the_username='$the_username' and the_password='$the_password'";
$result = $con->prepare($sql);
$result->execute();
$number_of_rows = $result->fetchColumn();
if($number_of_rows==1){
$info = $result->fetch(PDO::FETCH_ASSOC);
$_SESSION['username'] = $info['the_username'];
$_SESSION['id'] = $info['id'];
header('Location: admin.php');
}else{
echo "Wrong username or password, please refresh and try again.";
}
Would it perhaps be better to put?
if($number_of_rows==1 && $info = $result->fetch(PDO::FETCH_ASSOC)){MAKE SESSION}
Your usage of PDO functions is quite inconsistent, and it leads to some errors.
First of all, you cannot fetch the same data twice. And, as a matter of fact, you don't need such a double fetch at all.
Also, for some reason you are not using prepared statements which are the only reason for using PDO. So, the proper code would be
$sql="SELECT * FROM $tbl_name WHERE the_username=? and the_password=?";
$result = $con->prepare($sql);
$result->execute(array($the_username,$the_password));
# $number_of_rows = $result->fetchColumn(); <- don't need that
$info = $result->fetch();
if($info){
$_SESSION['username'] = $info['the_username'];
$_SESSION['id'] = $info['id'];
header('Location: admin.php');
}else{
echo "Wrong username or password, please refresh and try again.";
}
Yes the code and logic works fine. But don't use session_register() they are deprecated in new version of PHP.
if(isset($_SESSION['admin'])) {
echo "<li><b>Admin</b></li>";
}
<?php
session_name('MYSESSION');
session_set_cookie_params(0, '/~cgreenheld/');
session_start();
$conn = blah blah
$query2 = 'Select Type from User WHERE Username = "'.$_SESSION['user'].'" AND Type =\'Admin\'';
$result2 = $conn->query($query2);
if($result2->num_rows==1) {
$_SESSION['admin'] = $result2;
}
?>
Hi, I'm trying to set this session variable but it doesn't seem to be setting, and i'm wondering if anyone can help. If session['admin'] isset it should echo the admin button.
But i'm not quite sure why? (I do have session start and everything on everypage, it's not a problem with that or any of the "You don't have php tags" I have checked the mysql query, and it does return something from my table. Any ideas please?
Your session_start(); should be at the top of the page before anything to do with the session variables.
From the docs:
When session_start() is called or when a session auto starts, PHP will call the open and read session save handlers.
Edit from comments:
<?php
session_name('MYSESSION');
session_set_cookie_params(0, '/~cgreenheld/');
session_start();
// Moved to start after answer was accepted for better readability
// You had the <?php after this if statement? Was that by mistake?
if(isset($_SESSION['admin']))
{
echo "<li><b>Admin</b></li>";
}
// If you have already started the session in a file above, why do it again here?
$conn = blah blah;
$query2 = 'Select Type from User WHERE Username = "'.$_SESSION['user'].'" AND Type =\'Admin\'';
// Could you echo out the above statement for me, just to
// make sure there aren't any problems with your sessions at this point?
$result2 = $conn->query($query2);
if($result2->num_rows==1)
{
$_SESSION['admin'] = $result2;
// It seems you are trying to assign the database connection object to it here.
// perhaps try simply doing this:
$_SESSION['admin'] = true;
}
?>
Edit 2 from further comments:
You have to actually fetch the fetch the data like this - snipped from this tutorial which might help you out some more:
$query = "SELECT name, subject, message FROM contact";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo "Name :{$row['name']} <br>" .
"Subject : {$row['subject']} <br>" .
"Message : {$row['message']} <br><br>";
}
But having said that, while we are talking about it, you would be better off moving away from the old mysql_* functions and move to PDO which is much better.
Move session_start(); to the top of the page. You are trying to retrieve sessions, where it's not loaded.
EDIT: Try echoing $_SESSION['admin'], if it even contains something. Also try debugging your if($result2->num_rows==1) code by adding echo('its working'); or die('its working'); inside it, to check if $result2 contains exactly 1 row, since currently it seems $result2 contains either more than 1 row or no rows at all.
This code works on my computer, but when I run it on my web host's server, it doesn't. The output is "Incorrect password or email", even though I'm using the correct password. I thought I had made a mistake with the passwords, but the code won't output $r['email'] or $r['passwordHash'], at the top of the while loop. If I use mysql_result on $sql, I get the data out, so something weird must be happening with mysql_fetch_array. Am I missing something here, or is this more likely a unique problem I should address with my host's support staff?
$query = "SELECT * FROM users WHERE user='$email'";
$sql = mysql_query($query);
while($r = mysql_fetch_array($sql)) {
echo $r['email'];
echo $r['passwordhash'];
if($passwordHash == $r['passwordhash']) {
$_SESSION['user_id'] = $email;
echo "started session";
}
else {
echo "Incorrect password or email";
}
}
Use $sql = mysql_query($query) or die (mysql_error()) to check if there's something going wrong with the query.
Alternatively, you could try mysql_fetch_assoc (since I see you're most using associative arrays), to rule out a possible 'bug' of mysql_fetch_array (I doubt that but you could give it a try).
And check that $email is not empty. If it's passed through a sanitizing function (as it should have before being put into the query), see if that function have actually returned a value or just NULL or an empty string.
And, btw, why are you using a while loop? Are you supposed to get more than one record (and passwords) with the same e-mail address?
One thing to check real quick would be PHP and MySQL version on your computer versus the web server. How are you handling the hashes, because that could also cause an issue.
Are you doing something like the following?
$password = md5($password);
If so, are you converting correctly on the web server side?
$password = $_POST['password'];
$passwordHash = md5($password);
unset($password);
$query = "SELECT * FROM users WHERE user='$email'";
$sql = mysql_query($query);
while($r = mysql_fetch_array($sql)) {
echo $r['email'];
echo $r['passwordhash'];
if($passwordHash == $r['passwordhash']) {
$_SESSION['user_id'] = $email;
echo "started session";
}
else {
echo "Incorrect password or email";
}
}