I am trying to do a simple login with PHP and mysql, and using Sessions as well. I have the code, which should work in theory, however it keeps redirecting me to the login page (refreshing it) instead of taking me to the profile.
$username = $_POST['username'];
$query = "SELECT `confirmcode` FROM `fb_network` WHERE `username` = '$username' AND `status`='Confirmed' ";
$result = mysql_query($query);
if (mysql_num_rows($result) == 1){
$result2 = mysql_query($query);
$row = mysql_fetch_row($result2);
$_SESSION['conf_code'] = $row[0];
$uid = $row[0];
session_register($uid);
header('location:profile.php?conf='.$row[0]);
}
else{
echo 'Wrong username';
}
no it shouldn't work in theory
try this
<?php
$username = mysql_real_escape_string($_POST['username']);
$query = "SELECT `confirmcode` FROM `fb_network`
WHERE `username` = '$username' AND `status`='Confirmed' ";
$result = mysql_query($query) or trigger_error(mysql_error().$query);
if ($row = mysql_fetch_row($result)){
session_start();
$_SESSION['conf_code'] = $row[0];
header('Location: profile.php');
exit;
} else {
echo 'Wrong username';
}
but there can be other issues, from code you didn't post here r other reasons.
as a matter of fact, only debugging can tell you what's the problem for sure
I would use a user defined function and make it to check the login credentials and return true or false from the function.
you can use something like this.
function check_login ($username, $password) {
$query = "SELECT `confirmcode` FROM `fb_network` WHERE `username` = '$username' AND `status`='Confirmed' ";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
if( mysql_num_rows($result) == 0) {
return false;
}
if( mysql_num_rows($result) == 1) {
$_SESSION['loggedin'] = "true";
header('location:profile.php?conf='.$row[0]);
return true;
}
}
and then call the function easily and display the appropriate message.
check the following code..
<?php
session_start();
/** If the User is already Logged in then redirect to login.php **/
if(isset($_SESSION['loggedin'])){
header("Location: login.php");
}
else {
if( check_login($_POST['username'], $_POST['password'])) {
header('location:profile.php?conf='.$row[0]);
}
}
althoough the code is not exact but this might be enough to get you going.
I see that your code has only two options - display "wrong code" or redirect to the other page. no place where you are redirecting to the login page?
You need to initiate the session by sessions_start() before the rest of the code.
If you have any sort of 'test' script on the profile page that re-directs you if you're not logged in, it may be that the above code logs you in, but does not carry the session variable correctly to the profile page...and subsequently sends the user back to log in again.
Make sure the session is properly initiated on each page using the variable and make sure they match on both ends.
You have two main problems:
You are not using session_start to tell PHP to start tracking sessions
You are using session_register. session_register requires register_globals to be on, which it hopefully is not in your environment. It also expects its argument to be a string which is the name of the variable you wish to store. You should instead use $_SESSION['uid'] = $row[0];
You should also read about SQL injection, a very serious and common security flaw that your code exhibits.
Here is a corrected version of your code:
<?php
session_start(); //it's fine to just do this by habit at the top of every page
$username = $_POST['username'];
//I added mysql_real_escape_string - please read about "sql injection", as it is a very serious and common problem!
$query = "SELECT `confirmcode` FROM `fb_network` WHERE `username` = '".mysql_real_escape_string($username)."' AND `status`='Confirmed' ";
$result = mysql_query($query);
if (mysql_num_rows($result) == 1) {
$result2 = mysql_query($query);
$row = mysql_fetch_row($result2);
$_SESSION['conf_code'] = $row[0];
//not sure if this is what you weree going for or not
$_SESSION['uid'] = $row[0];
header('location:profile.php?conf='.$row[0]);
}
else {
echo 'Wrong username';
}
Then in profile.php, to check if someone is logged in:
<?php
session_start();
if( ! isset($_SESSION['uid']))
//Not logged in!
if( $_SESSION['uid'] != $_GET['conf'])
//trying to access someone else's page!
Related
I came across the problem that my session vars aren't remembered when you are linked to another page. This might sound a bit strange. To clear it up a bit, I will explain my problem with some code:
This code is a snippet from 'Login.php'. Here I set the SESSION vars for Email and wachtwoord(Password).
$query = "SELECT * FROM user WHERE Email='$email' AND Wachtwoord='$Wachtwoord'";
$result = mysqli_query($connection, $query) or
die(mysqli_error($connection));
$count = mysqli_num_rows($result);
if ($count == 1){
session_start();
$_SESSION['email'] = $email;
$_SESSION['wachtwoord'] = $Wachtwoord;
$sql = "UPDATE user SET Ingelogd = 1 WHERE Email='$email'";
$ressql = mysqli_query($connection, $sql) or
die(mysqli_error($connection));
}else{
echo "Invalid Login Credentials.";
}
Inside this snippet, the email and wachtwoord session are correctly set(I believe, because I can echo these and get the right output)
But when the user gets redirected to chat.php which contains this php code(indirectly, this code is in 'LoginCheck.php'. Linked to as: Include('../Php/LoginCheck.php');):
Include('connect.php');
//IF ((! $_SESSION['email']= NULL)&&(! $_SESSION['wachtwoord']=NULL)){
$email = $_SESSION['email'];
echo $_SESSION['email'];
$Wachtwoord = $_SESSION['wachtwoord'];
echo $_SESSION['wachtwoord'];
echo 'something';
$sql = "SELECT * FROM user WHERE Email='$email' and Wachtwoord='$Wachtwoord' and Ingelogd=1";
$result = mysqli_query($connection,$sql) or die(mysqli_error($connection));
$count = mysqli_num_rows($result);
if (!$count == 1){
//header('Location: Login.php');
}
//}
When php tries to do something with a SESSION var it gives this error:
Undefined variable: _SESSION in F:\xampp\htdocs\Chives-Functional\Php\LoginCheck.php on line 4
The line, in which $email is declared.
What I want to check is whether the user is still logged in or not.
How can I get this to work? What am I doing wrong? And why isn't it remembered?
Thanks in advance, any help is appreciated!
Kind Regards,
Ps. If more information is required, feel free to ask!
Have you made sure to start the session on top of every page?
session_start();
I have created a website with a functioning login system and in my database in the users table there is a column names type with either standard or admin. I have created a page for the admin only to edit products etc however i'm stuck on how to set it so only the 'admin' can view the page instead of just anyone that is logged in. Heres what I have so far?
admin.php
<?session_start(); ?>
<?php
include 'login.php'; // this includes all my login form and login action
include 'connection.php'; // this is my database connection
$query1 = "SELECT type FROM users";
$result = mysqli_query($query1);
$user = mysqli_fetch_array($result);
$_SESSION['usertype'] = $user['usertype'];
if($_SESSION['type'] = 'admin'){
//admin content here
{
<?php
if ($_SESSION['type']) = 'standard')
{
echo 'you must be an admin to see this page';
}
?>
loginaction.php
<?php
session_start();
include'connection.php';
$email = trim($_POST["email"]);
$password = trim($_POST["password"]);
$password=md5($_POST["password"]);
if (empty($email) or empty($password)) {
header("Location: homepage.php?form=invalid"); //Redirection information
exit;
}
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
echo "E-mail is not valid";
header("Location: homepage.php?email=invalid");
exit;
}
$query = "SELECT * FROM users WHERE email= '$email' AND password = '$password' ";
$result = mysqli_query($connection, $query) or exit("Error in query: $query. " . mysqli_error());
if ($row = mysqli_fetch_assoc($result)) {//Then we have a successful login
$_SESSION["authenticatedUserEmail"] = $email;
$_SESSION['ID'] = $row['ID'];
$_SESSION["password"] = $row['password'];
header("Location: homepage.php");
} else {//Login was unsuccessful
echo "User does not exist";
header("Location: login.php?user=invalid");
}
?>
You are not using comaprisons instead setting values for variables in the conditions where you check for the user type.
if($_SESSION['type'] ='admin'){ `should be` if($_SESSION['type'] == 'admin'){
<? session_start(); ?>
<? php
include 'login.php'; // this includes all my login form and login action
include 'connection.php'; // this is my database connection
$query1 = "SELECT type FROM users";
$result = mysqli_query($query1);
$user = mysqli_fetch_array($result);
$_SESSION['usertype'] = $user['usertype'];
if ($_SESSION['type'] == 'admin') {
//admin content here
}
if ($_SESSION['type']) == 'standard') {
echo 'you must be an admin to see this page';
} ?>
There are other errors in the code such as not putting the curly braces to end the statements correctly. This code should work, however it is a very unsafe code as anyone with sql injection and good programming knowledge will "tear" your website apart and worse, they steal and manipulate your data.
You should use mysql_real_escape_string() to make the input from users sql injection proof to fairly high extent.
Multiple problems seems in your code too, along with the problem mentioned by #Vish in the answers:
$result = mysqli_query($query1);
Expected a connection link as first argument.
Again:
you are trying to fetch type from the user table. But using usertype in mysqli_fetch_array. Seems it is incorrect. And the $_SESSION['type'] variable is really $_SESSION['usertype'] ?
A modified code.
$query1 = "SELECT type FROM users";
$result = mysqli_query($connection, $query1);
$user = mysqli_fetch_array($result);
$_SESSION['usertype'] = $user['type'];
if($_SESSION['usertype'] == 'admin')
{
//admin content here
}
elseif ($_SESSION['usertype']) == 'standard')
{
echo 'you must be an admin to see this page';
}
P.S: Not sure it will solve your problem
I made a lock file to see whether people are logged in on certain pages and I was curious as to if it is actually secure enough to put live or if people can easily bypass this lock.
Here is my code currently:
<?php
session_start();
if ((isset($_POST['user'])) && (isset($_POST['pass']))) {
$_SESSION['user'] = $_POST['user'];
$_SESSION['pass'] = $_POST['pass'];
}
include("config.php");
if ((isset($_SESSION['user']) && (isset($_SESSION['pass'])))) {
$sql = "SELECT count(*) FROM `users` WHERE user = :name and pass = :pass";
$result = $db->prepare($sql);
$result->bindValue(':name', $_SESSION['user']);
$result->bindValue(':pass', $_SESSION['pass']);
$result->execute();
$number_of_rows = $result->fetchColumn();
if ($number_of_rows !== 1){
echo "ERROR - USER AND PASS DO NOT MATCH";
} else { echo "SUCCESS!"; }
} else { echo "YOU NEVER LOGGED IN!"; }
?>
I feel like since it checks the database for a user and password match that there isn't really any way around this but at the same time I'm somewhat new to PHP and don't really know.
you can add this on top of your code.
<?php
session_start();
if(empty($_SESSION['user']) && empty($_SESSION['pass']))
{
header("location:your_login_page.php");
exit();
}
this code automatically redirect user to login page if they are trying to enter in session or registered member area....
For some reason inputs in my login page don't seem to be getting processes correctly. Correct user inputs are getting returned as invalid (wrong password) having had a look through, I can't see anything particularly obvious. But I can only assume the username or password isn't getting passed for some reason. Would someone more experienced be able to take a look and suggest how I can put it right. Thanks guys. P.S My form is OK, so not included.
function logcon($user, $password )
{
$user = mysqli_real_escape_string($this->conn, $user);
$esc_password = mysqli_real_escape_string($this->conn,$password);
$sql = "SELECT * from USERS WHERE username ='{$user}' AND password='{$password}'";
$result = mysqli_query($this->conn, $sql);
$row = mysqli_fetch_array($result);
return $row;
}
Login page.
if(isset($_POST['submit'])){
$user=$_POST['user'];
$password=$_POST['password'];
//To ensure that none of the fields are blank when submitting the form if
if(isset($_POST['user']) && isset($_POST['password']))
{
$user = stripslashes($user);
$password = stripslashes($password);
$db1=new dbmember();
$db1->openDB();
$row=$db1->logcon($user, $password);
if($row[0]==1)
{
session_start();
$_SESSION['user'] = $user;
$_SESSION['password'] = $password;
$_SESSION['loggedin'] = "true";
header("location:index.php");
}
else
{
print ('<div id="error">Acess denied, wrong username or password?</div>');
}
}
else
{
print ('<div id="error">Enter something!</div>');
}
}
It appears you are using the wrong variable name in your query. I would also suggest you look into doing some sort of hashing and salting of your passwords instead of saving them as plain text.
$sql = "SELECT * from USERS WHERE username ='{$user}' AND password='{$password}'";
should be
$sql = "SELECT * from USERS WHERE username ='{$user}' AND password='{$esc_password}'";
And your conditional check seems off, you are checking to see if the first field in the results is = 1 instead of seeing if there is a return.
if($row[0]==1)
Should probably be
if($row)
<?php
$userid = $_POST["userid"];
$pword = $_POST["pword"];
# session
session_start();
# check that session is valid and set
if(!isset($_SESSION['login']))
{
header('Location: login.php');
}
# check that the required values have been entered
$testin1 = ($userid);
$testin2 = ($pword);
if($testin1 == "")
{
print "<hr><h1> No Username Entered, Please return to the Login page</h1></hr>";
}
elseif ($testin2 == "")
{
print "<hr><h1> No Password Entered, Please return to the Login page</h1></hr>";
}
# Connect to database
$connect = mysql_connect ("localhost","root") or die("Error Connecting to SQLServer");
$db = mysql_select_db ("test");
# query
$query = mysql_query ("select username from login where username = '$userid' and pword = '$pword';");
if($query === FALSE)
{
die(mysql_error());
}
$result = mysql_fetch_array($query);
$record = $result['username'] ;
if ($record != null)
# check if session is operational, if so redirect the user to the correct page
{
$_SESSION['login'] = true;
header( 'Location: index.php' ) ;
}
else if ($record == null)
{
header( 'Location: login.php' );
}
?>
Does anyone know where this is not functioning? It seems to be 'error free' however keeps redirecting me back to the login.php page as opposed to the index.php page. any help would be great as i am a relative novice in PHP.
Thanks
You are using mysql_fetch_array(). In order to access a result by the key you need to use mysql_fetch_assoc().
$result = mysql_fetch_assoc($query);
$record = $result['username'] ;
Keep in mind that it is always best to escape any user input with mysql_real_escape_string().
It looks like you might possible be outputting data to the user before the header() is output. You have <HR>s and output (I know that it is only if there is an error) but if you are using those, you could well have <HTML> and the like above the code.
If that is the case, then no other header will function.
(Posting as answer as too long for comment - and might be the issue.
Try this code:
<?php
session_start();
$userid = $_POST["userid"];
$pword = $_POST["pword"];
// check that the required values have been entered
$testin1 = ($userid);
$testin2 = ($pword);
if($testin1 == "")
{
print "<hr><h1> No Username Entered, Please return to the Login page</h1></hr>";
}
if ($testin2 == "")
{
print "<hr><h1> No Password Entered, Please return to the Login page</h1></hr>";
}
// Connect to database
$connect = mysql_connect ("localhost","root") or die("Error Connecting to SQLServer");
$db = mysql_select_db ("test");
// query
$query = mysql_query ("select username from login where username = '$userid' and pword = '$pword';");
if($query === FALSE)
{
die(mysql_error());
}
$result = mysql_fetch_array($query);
$record = $result['username'] ;
if ($record != null)
// check if session is operational, if so redirect the user to the correct page
{
$_SESSION['login'] = true;
header( 'Location: index.php' ) ;
}
else if ($record == null)
{
header( 'Location: login.php' );
}
?>
I looked through and moved a few things around as well as modifying the logic ever so slightly.
The problem seems to be in your session, check $_SESSION['login'] whether it is set or not, because you are checking if !isset() then you are redirecting to login.php page.
Just verify the session variable by debugging your code