I register my user, but when I log in after registration I'm told to log in again. Please help.
Here's my code:
<?php
// include function files for this application
require_once('bookmark_fns.php');
session_start();
//create short variable names
if (!isset($_POST['username'])) {
//if not isset -> set with dummy value
$_POST['username'] = " ";
}
$username = $_POST['username'];
if (!isset($_POST['passwd'])) {
//if not isset -> set with dummy value
$_POST['passwd'] = " ";
}
$passwd = $_POST['passwd'];
if ($username && $passwd) {
// they have just tried logging in
try {
login($username, $passwd);
// if they are in the database register the user id
$_SESSION['valid_user'] = $username;
}
catch(Exception $e) {
// unsuccessful login
do_html_header('Problem:');
echo 'You could not be logged in.<br>
You must be logged in to view this page.';
do_html_url('login.php', 'Login');
do_html_footer();
exit;
}
}
do_html_header('Home');
check_valid_user();
// get the bookmarks this user has saved
if ($url_array = get_user_urls($_SESSION['valid_user'])) {
display_user_urls($url_array);
}
// give menu of options
display_user_menu();
do_html_footer();
?>
I tried using this member.php code but it doesn't work the way I want it to. Please help me get the book example to work properly and log me in right after registration
Related
I assume this can simply be done with permissions, but I cannot seem to get it to work. I was trying to make the page check the user for a permission using the code below, otherwise it redirects to home. It always redirects though and I do not know why.
<?php
if(!isset($_SESSION))
{
session_start();
}
if ($_SESSION['permission'] == 0) {
header("Location: ./index.php");
exit;
} else {
if (!isset($_SESSION['authemail'])) {
header("Location: ./index.php");
exit;//Redirect to the index
}
Edit: I added a session dump and both the userID and permission are null. What am I missing from here as I cannot figure it out?
<?php
session_start();
include ('../config/config.php');
/* basic field validation */
$email = trim($_POST["email"]);
$password = trim ($_POST["password"]);
/* check if details are empty, redirect if they are */
if (empty($email) or empty($password)) {
$_SESSION["message"] = "You must enter your email and password";
//Redirect to index
header("Location: ../index.php");
exit;
}
/* sanitise the input */
$email = strip_tags($email);
$password = strip_tags($password);
/* SQL user selection query, with error handling for the SQL */
$query = "SELECT * FROM users WHERE email = '$email' AND password = '$password'";
$result = mysqli_query($mysqli,$query) or exit("Error in query: $query. " . mysqli_error());
/* on query success, set sessions for email and userid */
if ($row = mysqli_fetch_assoc($result)) {
$_SESSION["authemail"] = $email;
$_SESSION["userid"] = $id;
$_SESSION["permission"] = $permission;
/* redirect the user to the secured page */
header("Location: ../loggedin.php");
} else {
/* display error if login was not successful and redirect to index */
$_SESSION["message"] = "Could not log in as $email - $query";
header("index.php");
}
?>
Try to set a flag in the database for someone who is an admin. Then on any specific page that only admins can access you should check this user variable.
if(!$user->isAdmin()){
header("Location: ./login.php");
exit;
}
If you do not have a $user object available, simply call a function that can query the database for the necessary variable.
if(!isUserAdmin()){
header("Location: ./login.php");
exit;
}
Also since both cases of yours redirect to index.php, you can combine the statements:
if($_SESSION['permission'] == 0 || !isset($_SESSION['authemail'])){
header("Location: ./index.php");
exit;
}
Make sure you are debugging to make sure the SESSION values are set/get as expected. Your code is redirecting because one of the conditions is true. Debug and find the bug.
I have created the following scenario.
I have the index.php file which shows the mainpage. On this there are two fields - User Id and password enclosed in a form tag. The submit button calls the login.php file.
Login.php validates the user id, password etc
Once validation is successful, I want the login.php page to take me to MyDashboard.php page (passing the User Id and Password along).
I tried Header in PHP but does not work. I also tried to do a Javascript window.location.href and tried to call it on $(document).ready but nothing happens.
Please help.
--- Edit ----
here is the code after modification
<?php
include_once('./library/Common.php');
$_EmailId = trim($_POST['validemailid']);
$_Password = trim($_POST['password1']);
$_Rememberme = trim($_POST['rememberme']);
// Get the username from the Email Id by searching for #
$_UName= substr($_EmailId, 0, strpos($_EmailId, '#'));
$_Password = md5($_Password);
session_start();
$_SESSION['username'] = $_UName;
$query = "select username, firstname, password_hash,userstatus from users where username = ? and emailid = ?";
$dbconn = new mysqli('localhost', 'root', '','myDB');
if($dbconn->connect_errno)
{
print getHTML('ERROR', "Error in connecting to mysql".$dbconn->connect_error);
}
if(!($stmt=$dbconn->prepare($query)))
{
print getHTML('ERROR',"error in preparing sql statement".$dbconn->error);
}
if(!($stmt->bind_param('ss',$_UName,$_EmailId)))
{
print getHTML('ERROR',"error in binding params in sql statement".$stmt->error);
}
if(!$stmt->execute())
{
print getHTML('ERROR',"Execute failed: (" . $stmt->errno . ") " . $stmt->error);
}
$result=$stmt->get_result();
$row = $result->fetch_assoc();
$_dbpwd = $row['password_hash'];
$_userstatus = $row['userstatus'];
$errstatus = false;
if ($row['username'] != $_UName)
{
print getHTML('ERROR',"User does not exist with the given email id: ".$_EmailId);
$errstatus = true;
}
if(($row['password_hash'] != $_Password) && !$errstatus)
{
print getHTML('ERROR',"Password does not match");
$errstatus = true;
}
if(($row['userstatus'] != 'ACTIVE') && !$errstatus)
{
print getHTML('ERROR',"User is inactive. Please check your email for activation");
$errstatus = true;
}
if(!$errstatus)
{
$_SESSION['firstname'] = $row['firstname'];
$chksession = "SELECT sessionid FROM USERSESSIONS WHERE USERNAME = ? AND ENDDATE IS NULL";
if(!($sessionstmt=$dbconn->prepare($chksession)))
{
print "error in preparing sql statement".$dbconn->error;
exit();
}
$sessionstmt->bind_param('s',$_UName);
$sessionstmt->execute();
$sessionresult=$sessionstmt->get_result();
$sessionrow= $sessionresult->fetch_assoc();
$currdate = date('y-m-d H:i:s');
if($sessionrow['sessionid'] == 0)
{
$insertstmt = $dbconn->query("INSERT INTO USERSESSIONS(USERNAME,STARTDATE,ENDDATE) VALUES ('".$_UName."','".$currdate."',null)");
$insertstmt->close();
}
}
$sessionstmt->close();
$stmt->close();
$dbconn->close();
header("Location :MyDashboard.php");
exit;
?>
--- End of Edit -----
Amit
You should use session variables to store variables within a login session. Passing a password along to other pages is not recommended, nor necessary. Read up on Sessions, and take a look at already existing login scripts. Below is a very simple example, redirecting to the next page using the header() function.
<?php
// Validate user credentials and save to session
session_start();
$_SESSION['userId'] = $userId;
// Redirect to next page
header("Location: dashboard.php");
// Make sure that code below does not get executed when we redirect
exit;
?>
If user authenticated,
In PHP:
header('Location:MyDashboard.php');
Try include()
This function allows you to include code from other php scripts.
The header function is the correct way. As long as you don't have any output before calling the header function, it should work.
http://us3.php.net/manual/en/function.header.php
Post your code, and let's see what it is that isn't working!
Header should work in your condition.
Tou can use following code:
header("Location:filename");
exit();
I'm trying to make a dashboard after my userlogin, however I want it on a different page. But I'm afraid passing data via url might not be necessary caused it can be changed manually. I want to pass $username to my dash.php file. Here's my code:
login.php
<?php
session_start();
//Insert Connection String
require_once 'config.php';
if(!$_SESSION['username']){
if (!isset($_POST['submit'])) {
echo'<form action="login.php?logged=yes" method="post">';
echo'<label> Username</label>';
echo'<input type="text" name="username"/>';
echo'<label> Passowrd</label>';
echo'<input type="password" name="password"/>';
echo'<input type="submit" name="submit" value="Login!"/>';
echo'</form>';
} else {
//handle some errors
//If both fields are empty
if(!$_POST['username'] && !$_POST['password']) {
echo"Try to login without entering any info, genius.";
}
else {
//check if the username exists
if(!empty($_POST['username'])) {
//check if the password exists
if(!empty($_POST['password'])) {
//Put unencrypted username variable
$username = $_POST['username'];
//Encrypt the values
$xusername = md5($_POST['username']);
$xpassword = md5($_POST['password']);
//Check if they exist in the database
$query = odbc_exec($conn, "SELECT * FROM xmember WHERE username='$xusername' AND password='$xpassword'");
$user_rows = 0;
while ($row = odbc_fetch_array($query)) {
$user_rows++;
}
odbc_free_result($query);
if($user_rows == 1) {
echo 'Welcome, '.$_POST['username'];
$_SESSION['username'] = $_POST['username'];
echo "<meta http-equiv='refresh' content='3;url=dash.php'>";
}
else {echo"Sorry, your account information is invalid.";}
}
else {echo"Please put your password";}
}
else {echo"Please put your username";}
}
}
else {echo"what are you doing here?";}
?>
config.php
<?php
/*
Le Change Nickname PHP v1.0 made by Thor KK Klein LOL
CONFIG section
*/
//Set Network Config
$odbc_dsn = "mydb";
$odbc_user = "sa";
$odbc_password = "wh#tTh3!?";
$conn = odbc_connect($odbc_dsn, $odbc_user, $odbc_password);
if(!$conn) {die('Failed to connect to the database!');}
?>
dash.php
<?php
session_start();
require_once 'login.php';//load connection settings and get info
if(!$_SESSION['username']){
echo"Are you kidding me?";
}else {
//Display The Dashboard
//Get user's typical information
//Get user's table row array
echo"Welcome, ".$username;
}
?>
I tried require-once'ing login.php to my dash.php to get the data.. but it doesn't seem to work.
Sinde you store the username in the session variable, you can access it from any file usibg $_SESSION["username"]. If the key is not set, you can redirect the user to your login page.
Your 'dash.php' file could be modified like this:
<?php
require_once("config.php");
session_start();
if(!isSet($_SESSION["username"])) {
// Redirect user to login page
header("Location: login.php");
exit();
}else {
//Display The Dashboard
//Get user's typical information
//Get user's table row array
echo("Welcome, " . $_SESSION["username"]);
}
?>
I'm creating a login page where the user name and password are entered and then checked against the database to see if they match (I have posted on this previously but my code was completely incorrect so I had to start over) Upon clicking the submit button the user should be directed to the homepage (index.php) if the two values match up or an error message should appear stating "Invalid login. Please try again." Very simple basic stuff. Yet, I cannot get any variation to work.
Here is my code without the validation check. I believe this code is right but, if not, could someone please explain as to why. I am not asking anyone to write any code, just explain why it is not working properly.
<?php
function Password($UserName)
{
//database login
$dsn = 'mysql:host=XXX;dbname=XXX';
$username='*****';
$password='*****';
//variable for errors
$options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
//try to run code
try {
//object to open database
$db = new PDO($dsn,$username,$password, $options);
//check username against password
$SQL = $db->prepare("Select USER_PASSWORD FROM user WHERE USER_NAME = :USER_NAME");
$SQL->bindValue(':USER_NAME', $UserName);
$SQL->execute();
$username = $SQL->fetch();
if($username === false)
{
$Password = null;
}
else
{
$Password = $username['USER_PASSWORD'];
}
return $Password;
$SQL->closeCursor();
$db = null;
} catch(PDOException $e){
$error_message = $e->getMessage();
echo("<p>Database Error: $error_message</p>");
exit();
}
?>
Now the validation code. I've googled this and found several hundred ways to do so but this method most closely matches my coding style. It is incomplete and I would like some help as to how to finish it properly and then where to place it within the code above. My assumption is right after this comment: "//check username against password". Now I've seen this version twice and in one version the check is for txtUserName and the other is just username. I believe there should be else statements after each if statement to direct them to the index.php page. Also, the third if statement is the check to see if the password matches the username. No variation of this did I understand. They were far too complex.
function Login()
{
if(empty($_POST['txtUserName']))
{
$this->HandleError("UserName is empty!");
return false;
}
if(empty($_POST['txtPassword']))
{
$this->HandleError("Password is empty!");
return false;
}
$username = trim($_POST['txtUserName']);
$password = trim($_POST['txtPassword']);
if(!$this->($username,$password))
{
return false;
}
}
I know I am asking a lot here. But I am very new to PHP and am really trying hard to learn it. And there is way too much info out there and most of it is not for beginners. Any, and all, help would be greatly appreciated.
To begin with, let's assume that we have a PDO connection, just like you do already, for example with this function:
You can do something like:
// Usage: $db = connectToDataBase($dbHost, $dbName, $dbUsername, $dbPassword);
// Pre: $dbHost is the database hostname,
// $dbName is the name of the database itself,
// $dbUsername is the username to access the database,
// $dbPassword is the password for the user of the database.
// Post: $db is an PDO connection to the database, based on the input parameters.
function connectToDataBase($dbHost, $dbName, $dbUsername, $dbPassword)
{
try
{
return new PDO("mysql:host=$dbHost;dbname=$dbName;charset=UTF-8", $dbUsername, $dbPassword);
}
catch(Exception $PDOexception)
{
exit("<p>An error ocurred: Can't connect to database. </p><p>More preciesly: ". $PDOexception->getMessage(). "</p>");
}
}
So that you can have a database connection like this:
$host = 'localhost';
$user = 'root';
$dataBaseName = 'databaseName';
$pass = '';
$db = connectToDataBase($host, $databaseName, $user, $pass);
So far we have the same stuff as you.
Now, I assume that we're on a PHP page where the user submitted his username and password, to begin with: check if we really received the username and the password, with the ternary oprator:
// receive parameters to log in with.
$userName = isset($_POST['userName']) ? $_POST['userName'] : false;
$password = isset($_POST['password']) ? $_POST['password'] : false;
Now you can validate if those inputs were actually posted:
// Check if all required parameters are set and make sure
// that a user is not logged in already
if(isset($_SESSION['loggedIn']))
{
// You don't want an already logged in user to try to log in.
$alrLogged = "You're already logged in.";
$_SESSION['warningMessage'] = $alrLogged;
header("Location: ../index.php");
}
else if($userName && $password)
{
// Verify an user by the email address and password
// submitted to this page
verifyUser($userName, $password, $db);
}
else if($userName && (!($password)))
{
$noPass = "You didn't fill out your password.";
$_SESSION['warningMessage'] = $noPass;
header("Location: ../index.php");
}
else if((!$userName) && $password)
{
$noUserName = "You didn't fill out your user name.";
$_SESSION['warningMessage'] = $noUserName;
header("Location: ../index.php");
}
else if((!$userName) && (!($password)))
{
$neither = "You didn't fill out your user name nor did you fill out your password.";
$_SESSION['warningMessage'] = $neither;
header("Location: ../index.php");
}
else
{
$unknownError = "An unknown error occurred.". NL. "Try again or <a href='../sites/contact.php' title='Contact us' target='_blank'>contact us</a>.";
$_SESSION['warningMessage'] = $unknownError;
header("Location: ../index.php");
}
Now, let's assume that everything went well and you already have a database connection stored in the variable $db, then you can work with the function
verifyUser($userName, $password, $db);
Like already mentioned in the first else if statement:
// Usage: verifyUser($userName, $password, $db);
// Pre: $db has already been defined and is a reference
// to a PDO connection.
// $userName is of type string.
// $password is of type string.
// Post: $user exists and has been granted a session that declares
// the fact that he is logged in.
function verifyUser($userName, $password, $db)
{
$userExists = userExists($userName, $db); // Check if user exists with that username.
if(!($user))
{
// User not found.
// Create warning message.
$notFound= "User not found.";
$_SESSION['warningMessage'] = $notFound;
header("Location: ../index.php");
}
else
{
// The user exists, here you can use your smart function which receives
// the hash of the password of the user:
$passwordHash = Password($UserName);
// If you have PHPass, an awesome hashing library for PHP
// http://www.openwall.com/phpass/
// Then you can do this:
$passwordMatch = PHPhassMatch($passwordHash , $password);
// Or you can just create a basic functions which does the same;
// Receive 1 parameter which is a hashed password, one which is not hashed,
// so you hash the second one and check if the hashes match.
if($passwordMatch)
{
// The user exists and he entered the correct password.
$_SESSION['isLoggedIn'] = true;
header("Location: ../index.php");
// Whatever more you want to do.
}
else
{
// Password incorrect.
// Create warning message.
$wrongPass = "Username or password incorrect."; // Don't give to much info.
$_SESSION['warningMessage'] = $wrongPass;
header("Location: ../index.php");
}
}
}
And the function userExists($userName, $db) can be like:
function userExists($userName, $db)
{
$stmt = $db->prepare("SELECT * FROM users WHERE USER_NAME = :USER_NAME;");
$stmt->execute(array(":USER_NAME "=>$userName));
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if($result)
{
// User exists.
return true;
}
// User doesn't exist.
return false;
}
Where the function Password is like:
function Password($UserName)
{
$stmt = $db->prepare("Select USER_PASSWORD FROM user WHERE USER_NAME = :USER_NAME;");
$stmt->execute(array(":USER_NAME"=>UserName));
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if($result)
{
return $result['USER_PASSWORD'];
}
// No result.
return false;
}
Again, make sure you're not matching plain text passwords, or basic shai1, md5 encryptiones etc. I really recommend that you take a look at PHPass.
I hope I'm making myself clear.
I haven't been able to trace what's wrong with this code. I am trying to login the user by taking his username and password. Here is what I am trying to do.
index.php:
This file checks if the username cookie is set and displays the file accordingly. This file submits the username and password to a file called validate.php.
validate.php:
<?php
session_start();
include("connector.php");
$var=connect();
if($var==10)
{
$valid=false;
$row= mysql_query('select * from users where username="'.$_POST["username"].'"');
if($row['password']==$_POST["password"])
$valid=true;
if($valid)
{
$_SESSION["username"]=$_POST["username"];
$_SESSION["userid"]=$row['userid'];
echo "<script>document.location.href='./session_creator.php'</script>";
}
else
{
echo "invalid";
}
}
?>
connector.php==>
<?php
$connection=0;
function connect()
{
$dbc = mysql_connect('localhost:3306','root','root');
if (!$dbc)
{
die ('Not connected:'. mysql_error());
return -10;
}
else
{
$connection = mysql_select_db("citizennet",$dbc);
if(!$connection)
{
die("Not connected: ". mysql_error());
return -20;
}
}
return 10;
}
?>
session_creator.php:
<?php
session_start();
setcookie("username",$_SESSION['username'],time()+3600);
setcookie("userid",$_SESSION['userid'],time()+3600);
echo "<script>document.location.href='./index.php'</script>";
?>
the redirected index.php file reports that the cookie is not set. I am newbie, please correct me if the process I am following is wrong.
I am adding index.php that verifies if the user is logged in:
<?php
if(!isset($_COOKIE["username"]))
echo '<a id="login_button">login</a> <div id="login_box_pane"><form action=validate.php method="post">Username: <input type="text"/> Password:<input type="password"/><input type="submit"/></form></div>';
else
echo "<a>".$_COOKIE["username"]."</a>";
?>
When you set your cookie on your page it should be like this:
<?php //login page
session_start()
$username = $_POST['username'];
$password = $_POST['password'];
/*
Check authentication with database values
*/
//if login successful set whatever session vars you want and create cookie
$_SESSION['username'] = $username;
setcookie($username, $password, time()+3600);
?>
Prior to this you will have check the users credentials and log them in or deny them. Once logged in you set the session variables. Then to create the cookie you use the code above.
$user = mysql_real_escape_string($_POST['user']);
$pass = mysql_real_escape_string($_POST['pass']);
$sql = "SELECT * FROM users WHERE username='$user' AND password='$pass'";
$result = mysql_query($sql);
That will take care of your sql injection vulnerabilities and also get you the correct account only if both the username and password are correct
Now you can use your conditions to set the cookies and sessions