This is the first time I've used this place, so forgive me if I'm being completely stupid here.
Basically, I'm coding a system where User A signs an institution up to the service, receiving a verification code for members of that institution, and then User B, part of that institution, enters the unique verification code to register.
The code for signing up User A works - it assigns a unique auto-incrementing ID (sid, or uid in the database) and a random verification code (verification) - and I am satisfied with it (aside from security concerns, but I need to learn how to deal with those).
My problem is that whenever anyone tries to sign up as a User B, and use the verification code, the system rejects it, and says that the verification code does not match the one under that particular sid. I have a feeling it's to do with the code I am using to look up the verification id, but I don't know where I'm going wrong.
The current code:
$getsid = mysql_query(
"SELECT *
FROM schools
WHERE uid='$sid'");
while($row = mysql_fetch_array($getsid)) {
$origver = $row['verification'];
}
if ($pwd != $conf) {
header('Location: register.php?error=1');
}
elseif ($ver != $origver) {
header('Location: register.php?error=2');
}
else {
Just for further information, $ver is the verification number entered by User B, which is meant to match with $origver.
It seems you must add some debug statements, in order to see what's going on
var_dump($sid);
$getsid = mysql_query(
"SELECT *
FROM schools
WHERE uid='$sid'");
while($row = mysql_fetch_array($getsid)) {
var_dump($row);
$origver = $row['verification'];
}
var_dump($pwd, $conf);
if ($pwd != $conf) {
header('Location: register.php?error=1');
Related
I am creating a site where invited users will be directed to a register once their email is validated against a master list of users and (2) returning users will be directed to a different page once validated against a master list of users. Initially the master list of users will only have email addresses for the invited users. Upon registration, users will enter the rest of the information, including First Name (fname).
What I need to do with this piece of code is check if the first name is NULL, if so direct user to "registration.html"; whereas if a first name is present for that user then the user should be directed to "overview.html".
My code is clearly not working properly, as regardless of fname being NULL or XYZ users are directed to "overview.html".
$query = "SELECT email, fname FROM registration WHERE email='$email'";
if (fname = "NULL") {
header('location: registration.html');
} else {
header('location: overview.html');
}
Thanks for your help!
I'm assuming you didn't paste the whole code here. How did you fetch the row?
One thing I can point out though, in PHP = is assignment.You want to use == which is the comparison operator.
Also, unquote "NULL", as you're currently comparing it to a string 'null'.
Hope that solves it.
EDIT: seeing your other comments, here's what the code should look like, assuming you have the email stored in a variable called $email and a PDO connection stored in $dbc.
$q = "SELECT email, fname FROM registration WHERE email = ?";
$stmt = $dbc->prepare($q);
$stmt->execute(array($email));
if($stmt->rowCount() == 1){ //you probably have unique email accounts
$row = $stmt->fetch();
if (is_null($row['fname'])) {
header('location: registration.html');
} else {
header('location: overview.html');
}
}
I apologise for the simpleton question but I am having a complete blank, hence why the wording of the title is vague.
I have built a simple PHP/MySQL user favouriting system that works fine, except for one part. Once the user has favourited another user, I cannot think for the life of me how to show the user that they have already favourited that user.
This is what I have so far:
if (($user_data['username'] == $profile_data['username']) === false) {
if () { ?>
// Favourite user
<?php } else { ?>
//See whether favourited or unfavourite user
<?php } } ?>
The table structure of favourites is simply two columns, favouritee being the profile favourited and favouriter being the current user favouriting. This table is joined to a main users table and the columns are populated by username strings.
EDIT
This is what I have got so far:
$username = $user_data['username'];
$favouritee = $profile_data['username'];
$check_fav = mysqli_query("SELECT `id` FROM `favourites` WHERE (`favouritee` = '$favouritee' AND `favouriter` = '$username')");
if (mysqli_num_rows($check_fav) == 1) {
// Favourite user
} else {
//See whether favourited or unfavourite user
}
(Posted on behalf of the OP):
Working code:
if (($user_data['username'] == $profile_data['username']) === false) {
$username = $user_data['username'];
$favouritee = $profile_data['username'];
$check_fav = mysqli_query("SELECT `id` FROM `favourites` WHERE (`favouritee` = '$favouritee' AND `favouriter` = '$username')");
if (mysqli_num_rows($check_fav) == 1) {
// Favourite user
} else {
// Unfavourited/check
}
}
To find whether a user has favourited another user, assume $myUsername as the logged-in user's username from the session, and assume $otherUsername coming from a profile page of another user (or perhaps a paged list of users).
SELECT 1 FROM favourite
WHERE favouriter = :favouriter AND favouritee = :favouritee
You can then inject parameters $myUsername into :favouriter and $otherUsername into :favouritee and if you get a row, you already have a favourite connection, and if you get zero rows, there is no favourite connection.
This is just the raw query, so of course you'll need to add PHP database code around this. If you're not familiar with this, take a look at the docs for PDO or MySQLi at php.net - both sections will give enough information to get you up and running.
That said, assuming usernames are stored in the user table, I'd be inclined to switch the two columns in the favourite table to integer foreign keys - it'll be faster and will save disk space. I'd call these from_user_id and to_user_id to make it clear what they are foreign keys of, and the direction of the favourite.
I have a website for my school I am designing.
I am struggling how to work this for my script, but there are two sections to the website. If a teacher logs in, from the table lesson_teachers, it should redirect them to lesson.php. If a student logs in, from the table users, it redirects them to home.php.
I think the select query for the teachers table may be something like this:
SELECT id FROM lesson_teachers WHERE username='$user_login' AND password='$md5password_login' LIMIT 1
I am trying to fit that select statement into my login script below, so that people with usernames and passwords in both tables can log into one script.
if (isset($_POST["user_login"]) && isset($_POST["password_login"])) {
$user_login = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["user_login"]); // filter everything but numbers and letters
$password_login = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["password_login"]); // filter everything but numbers and letters
$md5password_login = md5($password_login);
$sql = mysql_query("SELECT id FROM users WHERE username='$user_login' AND password='$md5password_login' LIMIT 1"); // query the person
//Check for their existance
$userCount = mysql_num_rows($sql); //Count the number of rows returned
if ($userCount == 1) {
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
}
$_SESSION["id"] = $id;
$_SESSION["user_login"] = $user_login;
$_SESSION["password_login"] = $password_login;
exit("<meta http-equiv=\"refresh\" content=\"0\">");
} else {
echo 'That information is incorrect, try again';
exit();
}
}
Your user table should either have a roles relation or at least a tinyint 1 field (0 for student, 1 for teacher) in your user table so you don't have to use 2 tables to achieve this.
Pretending I agreed with the query, this is what it might look like:
SELECT id, level FROM users WHERE username='$user_login' AND password='$md5password_login' LIMIT 1
where level is 0 for student, 1 for teacher. Any data relevant to either student or teacher on its own could be stored in a relation table.
Then you could say:
if($row['level'] == 1)
{
header('Location: /teacher-url');
exit;
}
else
{
header('Location: /student-url');
exit;
}
Now for the extra nuggets:
Please don't use this method for comparing passwords. You could basically login as another user accidentally or by happenstance if you were trying to hack since it strips characters. So "pa_s$sw==0ord" turns into "password"
Just run a sha1 (or better) encryption comparison on the posted input versus the stored sha1 encrypted password in the DB. That's the best real comparison to user passwords vs input.
And storing a password in $_SESSION just plain makes no sense. Why would you ever use it like this? Perhaps if you tell we can point you in a better direction.
And as Elias said, use PDO or mysqli. They will sanitize correctly amid the many many other reasons to use them over mysql_ functions.
I should add that we are all aware of how to actually answer your question. We know you want to know HOW to do it with what you've got. But we refuse. Because this habit should be cleaned before it becomes a nightmare. Not trying to be deliberately rude or anything, but a well planned database structure and use of PDO or mysqli will save you tons of time in both database and code. Look into relation tables, the concept of "roles" and sanitizing user input. From that you can construct the user system in a way that makes sense.
Firstly, you will only find 1 match per user/password pair,
so instead of
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
}
you can simply do
$row = mysql_fetch_array($sql);
$id = $row["id"];
As for the teach/student redirect, you will need a hidden variable in the login from to identity type= teacher or student
then based on this variable, you can do
if ($type=='student')
header('location:home.php');
if ($type=='teacher')
header('location:lession.php');
after setting your session variables.
Can anyone tell me why this code is not working?? Any silly mistakes I made?
The Problem:
There is a login page. In the Login page i type in the ID and password and click enter. Once i click enter it will run the next file which is login_now.php. In my database, I have 2 entries. First entry the position is manager and 2nd entry position is staff. Logging in with manager is very successful while logging in with staff is a total failure...failure as in it never do what it should do it just return me back to log in page.
This is the code that is in login_now.php and this is what it suppose to do when enter button is clicked:
$query = "select * from emp where EID = '$myeid' and PASS = '$mypassword'";
//run the query
$result = mysql_query($query, $conn);
$row = mysql_fetch_assoc($result);
//found a record?
if (mysql_num_rows($result) > 0 and $row['POSITION']=="manager")
{
$_SESSION['eid'] = $myeid; //remember name as a session variable
$_SESSION['password'] = $mypassword; //remember password as a session variable
header('Location: welmanager.php'); //redirect user to index
}
elseif (mysql_num_rows($result) > 0 and $row['POSITION']=="staff")
{
$_SESSION['eid'] = $myeid; //remember name as a session variable
$_SESSION['password'] = $mypassword; //remember password as a session variable
header('Location: welstaff.php'); //redirect user to index
}
else
{
header('Location: login.php'); //kick back to login
}
Let me know if more codes in the login.php should be shown here. Thanks in advance.
A minor error may locate in if condition.
if (mysql_num_rows($result) > 0 and $row['POSITION']=="manager")
You have to use or condition rather than and,
if (mysql_num_rows($result) > 0 || $row['POSITION']=="manager")
Without wanting to jump on the bandwagon, the comments about session management being a solved problem are right - even if you chose not to use it, you can learn a lot from how they do it. Look at CakePHP, the Zend Framework, Symphony, even PEAR.
Secondly - SQL Injection! Even if this is not exposed to the wider internet, you can't necessarily guarantee that none of your staff are malicious.
Thirdly, it appears you store your passwords in plain text; this is a big nono. People often re-use their passports; someone who can steal your user records (using SQL Injection) can try those passwords on online banks etc. Read up on hashing passwords.
Fourthly, don't store the password in plaintext anywhere - but certainly not in the session object. You've already cover that...
The actual code looks syntactically okay, but there are some odd things.
if (mysql_num_rows($result) > 0 and $row['POSITION']=="manager")
Doesn't make sense! If there are no results, logically the $row array should be empty.
You're also not really distinguishing between legit "there's no match for username/pwd" situations and bugs such as having STAFF rather than staff in the type column.
I'd refactor it as:
$result = mysql_query($query, $conn);
$row = mysql_fetch_assoc($result);
if (mysql_num_rows($result) == 0)// no match!
{
header('Location: login.php'); //kick back to login
}
//Maybe put in a catch for more than 1 record too - that would be a data bug.
$_SESSION['eid'] = $myeid; //remember name as a session variable
switch($row['POSITION']){
case "manager":
header('Location: welmanager.php'); //redirect user to index
break;
case "staff":
header('Location: welstaff.php'); //redirect user to index
break;
default:
echo ("Found unknown staff type. Error.");
}
Now you can see whether your record really isn't found - i.e. the username/pwd combo didn't match - or whether the user profile isn't of type "staff".
I'm using this code as part of an email confirmation script. It works great, except I can't figure out a way to distinguish between when somebody has provided an invalid email address vs when they have simply refreshed the page (ie. already confirmed their account). The only think I can think of is putting a time stamp field in the users table that always gets updated, but I'm hoping there is a better way. I thought REPLACE would do the trick, but, while email is unique, it is not the primary key.
if (isset ($email, $token, $correctToken)){
$success = FALSE; //Set the $success variable so that we don't get an error when testing for it later
if ($token == $correctToken) {
$confirm = mysql_query("UPDATE users
SET conf = 'TRUE'
WHERE email = '$email'");
if (mysql_affected_rows() == 1) {
echo "Thank you! Your email address is confirmed and your account is actived.";
$success = TRUE;
}
}
if (!$success) {
echo "There was a problem with the confirmation. Try the link in your email again or contact us at Support#WiseRenters.com";
// Send email to admin to notify of error
exit;
}
}
Thanks in advance for the advice!
Billy
EDIT: The $email and $token variables are provided through $_GET or $_POST, in case that wasn't obvious.
A redirection would stop them from refreshing - but what if they click the link in their email again?
You should check if the current user is activated or not.
$sql = "SELECT id, conf FROM users WHERE email = '{$email}'";
$exec = mysql_query($sql) or die(mysql_error());
list( $id, $conf ) = mysql_fetch_row($exec);
if( $conf ) {
// Redirect them to their profile with a message saying "your account has already been activated"
header("Location: /profile?already_activated");
exit;
}
// your code
$confirm = mysql_query("UPDATE users
SET conf = 'TRUE'
WHERE id = '{$id}'");
In response to your comment:
Keep in mind this will only add an additional query for a user who has not activated yet. If they have activated then the redirect occurs and the page is still running only 1 query.
To optimize this a bit, you can select the user ID and confirmation status based on the email address. Then, if they do need to be activated, you can activate them based on user ID instead of email. Since an integer key is much faster, the combined time of the 2 queries will be about the same as the 1 query where you are updating based on a string column. I updated the code to reflect this.
Also, this page will probably not be accessed very frequently. Any optimizations from here would really be micro- and not really that helpful.
By the way I hope you are using mysql_real_escape_string on the email, and that conf is a boolean true/false not a string 'true'/'false'.