Ok, So on my main login php page I have this:
<?php
session_start();
require 'connect.php';
if(mysqli_connect_errno()) {
echo 'Failed to Connect to MySQL' . mysqli_connect_errno();
}
if(isset($_POST['submit'])) {
//Variables
$user = $_POST['username'];
$pass = md5 ($_POST['password']);
//prevent MySQL Inject
$user = stripslashes($user);
$pass = stripslashes($pass);
$query = mysqli_query($con, "SELECT * FROM tech WHERE username = '$user' and password = '$pass'") or die("Can not query the DB");
$count = mysqli_num_rows($query);
if($count == 1) {
$_SESSION['username'] = $user;
$url = 'home.php';
echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.$url.'">';
} else {
echo 'Username and Password do not match! Try Again';
$url = 'carelogin.php';
echo '<META HTTP-EQUIV=Refresh CONTENT="2; URL='.$url.'">';
session_destroy();
}
}
?>
And then, On every page at the very top I have this.
<?php
session_start();
require_once 'connect.php';
if(!isset($_SESSION['username'])) {
echo "<h1>You are not an authorised user</h1>";
$url = 'carelogin.php';
echo '<META HTTP-EQUIV=Refresh CONTENT="1; URL='.$url.'">';
} else {
}
?>
After about 30 seconds or so from not touching my mouse on any of those pages if I click REFRESH or if I go forward or backwards, It keeps logging me out. I don't understand. I have all the sessions set but within just 30 seconds I get logged out.
Someone please modify my code to allow me to stay logged in until I click log out Thank you guys!
I think you will find that people will suggest a framework for this sort of thing, however, if you are going to attempt a login, you will probably want to split your script out more thoroughly to accommodate both cleaner and more expandable code. Also, make sure to use ini_set("display_errors",1); error_reporting(E_ALL); above session_start() to be alerted on any errors/warnings happening on the page when testing the site (turn off error reporting in live environment).
Here is a bit of more complex code than what you have, but it should protect you from injection. Note all the folders for each of the files should be in relation to the domain root. Also note, you need to store all your passwords in your database using the password_hash() function. You can use some of this, all of this, none of this, but if you do use it, make sure to look through the PHP manual to understand what all this is doing:
/core.processor/classes/class.DatabaseConfig.php
// This is your database. Fill out the credentials in the connect() method
// I use PDO because I think personally it's easier to use
class DatabaseConfig
{
private static $singleton;
public function __construct()
{
if(empty(self::$singleton))
self::$singleton = $this->connect();
return self::$singleton;
}
// This is the method that creates the database connection
public function connect($host = "localhost", $username = "username", $password = "password", $database = "database")
{
// Create connection options
// 1) Make PDO Exception errors, 2) Do real binding 3) By default prefer fetching associative arrays
$opts = array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC);
$conn = new PDO('mysql:host='.$host.';dbname='.$database, $username, $password,$opts);
// Send back the database connection. You can use a "utf-8" character setting here as well...
return $conn;
}
}
/core.processor/classes/class.QueryEngine.php
// This is a simple query engine. It allows for binding (or not binding)
class QueryEngine
{
private $results;
private static $singleton;
public function __construct()
{
if(empty(self::$singleton))
self::$singleton = $this;
return self::$singleton;
}
// This method sends queries to your database
public function query($sql = false,$bind = false)
{
$this->results = 0;
// Create database connection
$db = new DatabaseConfig();
// Attempt to connect and fetch data
try {
// Bind or not bind, provided there is a bind array
// This is important to look up!
if(!empty($bind)) {
$query = $db ->connect()
->prepare($sql);
$query->execute($bind);
}
else {
$query = $db ->connect()
->query($sql);
}
$this->results = $query;
}
catch (PDOException $e)
{
die($e->getMessage());
}
return $this;
}
// This method will fetch an the associative array if used with select statement
public function fetch()
{
while($row = $this->results->fetch())
$result[] = $row;
return (!empty($result))? $result : 0;
}
}
/core.processor/classes/class.HeaderProcessor.php
// This class deals with functions that should happen before the page outputs to the browswer
class HeaderProcessor
{
private static $userData;
// This method just sits and waits for actions to happen
// This method should expand with whatever you plan to do in the future
public static function eventListener($array = array())
{
if(isset($array['action'])) {
if($array['action'] == 'login') {
if(self::getLogin($array['username'],$array['password'])) {
if(self::setSession(self::$userData)) {
$_SESSION['password'] = NULL;
}
header("Location: home.php");
exit;
}
}
elseif($array['action'] == 'logout') {
session_destroy();
header("Location: loggedout.php");
exit;
}
}
}
// Process login
private static function getLogin($user,$pass)
{
$query = new QueryEngine();
$getUser = $query ->query("SELECT * FROM `users` WHERE `username` = :0",array($user))
->fetch();
if($getUser == 0)
return false;
self::$userData = $getUser[0];
// Verify the password hash (this is why you need to store your passwords differently in your db
return password_verify($pass,$getUser[0]['password']);
}
// Assign session variables
private static function setSession($userData)
{
$_SESSION = array_filter(array_merge($userData,$_SESSION));
return true;
}
// This can set options for your site, I just threw in timezone
// as well as the class autoloader
public static function initApp($settings = false)
{
$timezone = (!empty($settings['timezone']))? $settings['timezone'] : 'America/Los_Angeles';
include_once(FUNCTIONS_DIR."/function.autoLoader.php");
date_default_timezone_set($timezone);
}
}
/core.processor/functions/function.autoLoader.php
// This function will auto load your classes so you don't have to always
// include files. You could make a similar function to autoload functions
function autoLoader($class)
{
if(class_exists($class))
return true;
if(is_file($include = CLASS_DIR.'/class.'.$class.'.php'))
include_once($include);
}
/config.php
/*** This config is located in the root folder and goes on every page ***/
// Start session
session_start();
// Define common places
define("ROOT_DIR",__DIR__);
define("CLASS_DIR",ROOT_DIR.'/core.processor/classes');
define("FUNCTIONS_DIR",ROOT_DIR.'/core.processor/functions');
// Require the page initializer class
require_once(CLASS_DIR."/class.HeaderProcessor.php");
// Initialize the autoloader for classes
// Load timezone
// You can put any other preset in this method
HeaderProcessor::initApp();
// Here is where you put in events like login, logout, etc...
HeaderProcessor::eventListener($_POST);
// Use this function to help load up classes
spl_autoload_register('autoLoader');
/login.php
<?php
// add in the config file
require(__DIR__."/config.php");
?><!DOCTYPE html>
<html>
<meta charset="UTF-8">
<title>My Login</title>
<head>
</head>
<body>
<form id="loginForm" method="post" action="">
<input name="username" type="text" />
<input name="password" type="password" />
<input name="action" type="hidden" value="login" />
<input type="submit" value="LOGIN" />
</form>
</body>
</html>
Please increase session timeout with this:
// server should keep session data for AT LEAST 1 hour
ini_set('session.gc_maxlifetime', 3600);
// each client should remember their session id for EXACTLY 1 hour
session_set_cookie_params(3600);
session_start(); // ready to go!
First you need to find out what your php settings are:
create an info.php file at the root of your project with the following lines:
<?php
phpinfo();
Load the page on your browser and locate the following variable:
session.gc_maxlifetime
It is likely that your sessions have been set to expire after a very short period of time (the default is about 24 mins but the value displayed is in seconds - 1440). In your case, this value might be equal to 30
To change it to your preferred length of time, you need to change your php settings as follows(ensure you have the right permissions to make write changes on your server):
Locate your php.ini settings file. It is likely located in the following location on your linux server:
/etc/php/7.0/apache2/php.ini
You should open this file with your editor of choice, e.g. nano on your command line as follows:
sudo nano /etc/php/7.0/apache2/php.ini
Locate the following variable:
session.gc_maxlifetime
Change the corresponding value to a longer time span such as 1 day which you can calculate as follows: 1day * 24hrs * 60mins * 60secs = 86400secs
Set it up as follows:
session.gc_maxlifetime = 86400
Save the file and restart apache as follows from your command line:
sudo service apache2 restart
Reload your info.php file and the changes should have taken effect.
EDIT: I remove my first Suggestion
Or try my code
Here it will check if you are connected to your database I name it connect.inc.php
<?php
if(!mysql_connect('localhost', 'root', '')|| !mysql_select_db('byp_db'))
{
die(mysql_error());
}
?>
Next I created my core.inc.php where it will check if you are already in session you will use the loggedin() method in that
<?php
error_reporting(E_ALL ^ E_NOTICE);
ob_start();
session_start();
$current_file = $_SERVER['SCRIPT_NAME'];
$http_referer = $_SERVER['HTTP_REFERER'];
function loggedin() {
if(isset($_SESSION['user_p_info_id'])&&!empty($_SESSION['user_p_info_id'])) {
return true;
}else {
return false;
}
}
function getuserfield($field){
$query = "SELECT `$field` FROM `user_p_info` where `user_p_info_id`='".$_SESSION['user_p_info_id']."'";
if($query_run = mysql_query($query)){
if($query_result = mysql_result($query_run, 0, $field)){
return $query_result;
}
}
}
?>
Next is you will create your log-in form
<?php
require 'connections/connect.inc.php';
require 'connections/core.inc.php';
if(isset($_POST['uname']) && isset($_POST['password'])){
$uname = $_POST['uname'];
$pword = $_POST['password'];
//echo $uname;
//echo $pword;
if(!empty($uname)&&!empty($pword)){
$query_login = "SELECT * FROM user_a_info where username = '$uname' and password = '$pword'";
//echo $query_login;
$query_result = mysql_query($query_login);
$num_rows = mysql_num_rows($query_result);
if($num_rows == 0){
?>
<script type="text/javascript">
alert("Invalid Data !");
</script>
<?php
}else{
//echo "validated";
$user_p_info_id = mysql_result($query_result, 0, 'user_p_info_id');
$_SESSION['user_p_info_id']=$user_p_info_id;
header('Location: index.php');
}
}
}
?>
<form action="login.php" method="POST">
<p> USERNAME : <input type="text" name="uname" /> </p>
<p> PASSWORD : <input type="password" name="password" /> </p>
<p> <input type="submit" value="LOGIN" /> </p>
</form>
And then your log-out function will look like this
<?php
require 'core.inc.php';
session_destroy();
header('Location: ../index.php');
?>
Just take note that if you want to check whether you are in session or not just put this condition
<?php
require 'connections/connect.inc.php';
require 'connections/core.inc.php';
if(loggedin()) {
// Do something
}
?>
Hope this helps
Related
<?php
ini_set('display_errors', '1');
require_once 'core/init.php';
if(logged_in() === TRUE) {
header('location: dashboard.php');
}
if($_POST) {
$username = $_POST['username'];
$password = $_POST['password'];
if($username == "") {
echo "Username Field is Required <br />";
}
if($password == "") {
echo "Password Field is Required <br />";
}
if($username && $password) {
if(userExists($username) == TRUE) {
$login = login($username, $password);
if($login) {
$userdata = userdata($username);
$_SESSION['id'] = $userdata['id'];
header('location: dashboard.php');
exit();
} else {
echo "Incorrect username/password combination";
}
} else{
echo "Username does not exists";
}
}
} // /if
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles1.css">
<script type="text/javascript" src="jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="scripts.js"></script>
<title>Login</title>
</head>
<body class="container">
<div class = "login-box">
<img src = "image/person1.png" class = "avatar">
<h1 id = "login-header">Login</h1>
<form id=registration_form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST">
<div>
<label for="username">Username</label>
<input type="text" name="username" id="form_username" autocomplete="off" placeholder="Username" />
<span id="username_error"></span>
</div>
<br />
<div>
<label for="password">Password</label>
<input type="password" name="password" id="form_password" autocomplete="off" placeholder="Password" />
<span id="password_error"></span>
</div>
<br />
<div>
<input type="submit" name="btnLogin" value = "Login">
</div>
Not yet a member? Register
</form>
</body>
</html>
Can somebody help me regarding to my PHP. I'm very new in PHP. My website must have a multi-login user. But I try to do it and I failed. I don't received any error. But the problem is when I press the login button nothing happen. If the user_type is equal to admin I want to link it to adminPanel.php and if user_type is equal to user I want to link it to userPanel.php. Can somebody fix my code below. I really appreciate it.
function login($username, $password) {
global $connect;
$userdata = userdata($username);
if($userdata) {
$makePassword = makePassword($password, $userdata['salt']);
$sql = "SELECT * FROM tbl_user WHERE username = '$username' AND password = '$makePassword'";
$query = $connect->query($sql);
if($query->num_rows == 1) {
$logged_in_user = mysqli_fetch_assoc($query);
if ($logged_in_user['user_type'] == 'admin') {
$_SESSION['user'] = $logged_in_user;
header('location: adminPanel.php');
}else{
$_SESSION['user'] = $logged_in_user;
header('location: userPanel.php');
}
}
}
$connect->close();
// close the database connection
}
Forword
I feel generous tonight...
This may not fix your issue. As I said in the comments, there are many things that can be wrong. Without more information on what is happening, how you do things there is no way to tell.
These are things that are important (things to check)
how you submit the post (the form)
fields could be named wrong, form could be setup wrong etc.
the form action could simply be wrong
the form method could simply be wrong
how you handle that submission
variables could be sent to login() incorrectly, login($password,$username) instead of login($username,$password)
vairables could simply be translated wrong, for example you could have $_POST['user'] insead of $_POST['username']
you could be doing validation checks on input, which may or may not remove data, could be wrong.
how you handle starting the session
you can't use session until you start it
what if any output you have when handling the submission
output before header location will prevent the redirect
header location does not exit the current code scope, stuff after it can run so you should call exit after doing a redirect.
how you connect to the DB
you may have DB error
what if any errors you get, what error reporting do you have
you could have errors your not reporting for any of the above, and many things I didn't mention.
You probably shouldn't roll you own login system until you have a better handle on the security implications ( and other things).
Password/Security
The makePassword function is not included (in your code), but in any case you should use the built in (PHP5.4+) password function. It's much more secure and saves a lot of work:
function makePassword($plaintext){
return password_hash($plaintext, PASSWORD_DEFAULT);
}
This will return a 60 char long hash, but it's recommended to use VARCHAR(255).
It will look something like this in the DB:
//$2y = BCRYPT (default), $10 Cost or iterations (default), that's all I can remember.
$2y$10$.vGA1O9wmRjrwAVXD98HNOgsNpDczlqm3Jq7KnEd1rVAGv3Fykk1a
Then for login (MySqli):
//session_start(); //make sure this is called
function login($username, $password, \mysqli $connect) //use type hinting
{
//can fail because of syntax errors, missing privileges
$stmt = $connect->prepare('SELECT * FROM tbl_user WHERE username = ?') OR die($connect->error);
//can fail because of incorrect number of arguments, invalid types
$stmt->bind_param("s", $username) OR die($stmt->error);
//can fail for various reasons
$stmt->execute() OR die($stmt->error);
$result = $stmt->get_result();
if($result->num_rows == 1) {
$user = $result->fetch_assoc($query);
if(password_verify($password, $user['password'])){
$_SESSION['user'] = $user;
header('location: '.$user['user_type'].'Panel.php');
exit;
}else{
//password error
}
}else{
//username error
}
}
Personally I only use PDO these days. It's been several years sense I used MySqli (so forgive me if I got anything wrong here).
For PDO, this is how I connect with it:
$dsn = 'mysql:dbname=database;host=localhost';
$user = 'user';
$pass = 'pass';
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
];
try{
$PDO = new PDO($dsn, $user, $pass, $options);
}catch(PDOException $e){
//only show end user error codes
die("Error[{$e->getCode()}] connection to DB");
}
The options turn on, Exception error reporting and set the default fetch mode to fetch associative array. With those settings the same thing as above can be done like this:
//session_start(); //make sure this is called
function login($username, $password, \PDO $Pdo) //use type hinting
{
try{
$stmt = $Pdo->prepare('SELECT * FROM tbl_user WHERE username = :username');
$stmt->execute([':username' => $username]);
if($stmt->rowCount()){
$user = $stmt->fetch();
if(password_verify($password, $user['password'])){
$_SESSION['user'] = $user;
header('location: '.$user['user_type'].'Panel.php');
exit;
}else{
//password error, return an error, or throw an exception etc.
}
}else{
//username error
}
}catch(PDOException $e){
//only show end user error codes
die("Database Error[{$e->getCode()}]");
}
}
If you notice it takes around 5 calls to MySqi, and PDO takes only 3 calls. Besides that MySqi is dealing with 3 objects (mysqli, mysqli_stmt, mysqli_result), PDO deals with only 2 (PDO, PDOStatment). Error reporting is also much cleaner.
A few other notes.
use password_hash($plaintext, algo) to create hashes
use password_verify($plaintext, $hash) to check passwords (note plaintext)
use prepared statements
Do not lookup by password, it's not a secure way of verifing 2 hashes are the same (casing, encoding etc...)
use session_start() before using $_SESSION
Do not output anything (not even a single space) before using header
call exit; after using header as it doesn't exit the script it's called in, so it can run code beneath it and produce unexpected results
avoid using global it can be hard to debug your code, instead use dependency injection (pass in the DB connection)
use DRY principals (Dont Repeat Yourself)
And there is probably a bunch of stuff I am forgetting.
UPDATE
Based on the code you added, the part that handles the form submission can be done like this:
<?php
error_reporting(E_ALL); //unclear
ini_set('display_errors', '1');
require_once 'core/init.php';
if(true === logged_in()) { //put constant values on the left
header('location: dashboard.php');
}
if('POST' == $_SERVER['REQUEST_METHOD']){ //put constant values on the left
//ternary condition (shorthand if then)
$username = empty($_POST['username']) ? false : $_POST['username'];
$password = empty($_POST['password']) ? false : $_POST['password'];
//PHP7+ null coalescing can be used instead of above
//$username = $_POST['username'] ?? false;
if(!$username) {
echo "Username Field is Required <br />";
}
if(!$password) {
echo "Password Field is Required <br />";
}
if($username && $password) {
login($username, $password);
//don't forget the connection, if you use the functions without
//it as a global, (which I refuse to use). I once spent a week
//tracking down changes to a global variable in some code I was fixing, never again.
// global $connect;
// login($username, $password, $connect);
}
}
You don't need to do redirects after calling login it's already doing them. You don't need to check if the user exists because you are already checking when fetching there saved password. If you need to know that information there you can either throw exceptions (to much to cover) or you can have the login function return them. In the case that the login is successfule the code will exit before the errors can return.
Summery
My best guess, barring any errors (and assuming the session is started) is that this is happening
form submission, to self
call to login()
everything works, call to header('location: adminPanel.php'); (with no exit)
code returns to the form page (because no exit)
call to header('location: dashboard.php'); And exit();
But that is just a guess, because when yo say "when I press the login button nothing happen" that can mean many things.
One of these days I will put a tutorial for something like this on my website, but it will be more comprehensive.
Anyway, hope it helps you.
I am new to PHP and can't find answers as to why the following code doesn't work. This should be easy, but I can't figure this out. This code produces no errors, and the SQL statement is correct in the phpAdmin SQL console. I've searched web & StackOverflow, but can't find a good answer. What's wrong?
ALL users (whether in the db or not) get ignored and stuck on login page.
<?php
session_start();
//create function to check login form for admin or other type of user.
//Redirect the admin user to the welcome page.
function login()
{
//strip login and password using in-build htmlspecialchars function
$value1 = htmlspecialchars($_POST['login']);
$value2 = htmlspecialchars($_POST['password']);
//set variables for the db connection
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb";
$loggedin = '';
//Create new connection to db
$conn = new mysqli($servername, $username, $password, $dbname);
//Check connection and handle any error
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
header('Locatin: login.php');
}
else {
//check if super admin user exists in db
$sql = "SELECT count(*) FROM admins WHERE AdminLevel = 1";
$result = mysqli_query($conn,$sql);
//check to see if query returns any rows
if(mysql_num_rows(($result) > 0) {
include 'welcome.php';
}
//check if the password and username match
if(($username === $value1) && ($password === $value2)) {
$_SESSION['loggedin'] = TRUE;
echo "Hello ".$value1.", you are logged in!<br>";
}
//send user error message if login/username and password wrong
else {
echo "Incorrect username or password<br>";
include 'login.php';
}
//close the db connection
$conn->close();
}
?>
Login Form:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Admin Login</title>
<script>
//function to check the form
function chkForm()
{
//determine the number of elements in the user login form
var intFormLen = document.forms[0].elements.length;
//loop through the form fields to see that a value has been input
for (var i = 0; i < intFormLen; i++) {
if (document.forms[0].elements[i].value == "") {
//send user an error message if login field empty
document.getElementById(document.forms[0].elements[i].name).innerHTML="Required Field";
document.forms[0].elements[i].focus();
return false;
}
}
//clear the form fields
function clearWarn(fieldName)
{
document.getElementById(fieldName).innerHTML = "";
return true;
}
return;
}
</script>
</head>
<body>
<h2>Admin Login</h2>
<div class="phpEcho">
<div class="formLayout">
<form action="#" method="post" onsubmit="return chkForm();">
<label for="login">Login:</label>
<input type="text"name="login" onchange="return clearWarn('fieldName')">
<div id="login" style="color:red"></div><br>
<label for="password">Password:</label>
<input type="password" name="password" onchange="return clearWarn('fieldName')">
<div id="password" style="color:red"></div><br><br>
<input type="submit" name="cmdSubmit" value="Log in">
</form>
</div>
</div>
</body>
</html>
You set your form action="#" and don't submit it in JavaScript.
As noted by Jason, chkForm() will never return true, which would also prevent the form from submitting.
This script has a lot of issues that should be addressed. I will go over a couple things that may help you:
1) I would suggest using some kind of config / bootstrap file to include in your documents that contains reusable elements and start session. Require/include only once.
/config.php
define("_DS_",DIRECTORY_SEPARATOR);
define("DBUSER",'root');
define("DBPASS",'');
define("DBHOST",'localhost');
define("DBDATABASE",'mydb');
// Start session
session_start();
2) You will want to separate out your functions, importantly your database connection, whether by class or by function. You want to keep tasks separate so it's easy to reuse.
Here is an example (I am going to use PDO because I am more familiar with it but principle is the same):
/functions/connection.php
function connection()
{
// This is just a really basic connection, one could expand on this
return new PDO('mysql:host='.DBHOST.';dbname='.DBDATABASE, DBUSER, DBPASS);
}
/functions/login.php
/*
** #param $username [string] by making this a param, you can manually log in users outside of POST
** #param $password [string] same as username
** #param $conn [resource] You will want to inject your connection into this
** in order to use it. Don't make the connection
** inside. May as well reuse resources already active
** #return [bool] If you return TRUE or FALSE, that will tell your script
** whether the login succeeded or failed for notification
*/
function login($username,$password,$conn)
{
// Don't worry about stripping down the username/pass, just bind
// the username and match the password
// You need to select from your user table (or whatever table
// you are storing your usernames for your site)
$query = $conn->prepare("select * from `users` where `username` = :0");
$query->execute(array(':0'=>$username));
$result = $query->fetch(PDO::FETCH_ASSOC);
if(empty($result))
return false;
// You will want to use password_hash to save passwords
if(!password_verify($password,$result['password']))
return false;
// I use htmlspecialchars here so I don't forget when echoing to page
// but you can do it at the time you echo to browser
$_SESSION['first_name'] = htmlspecialchars($result['first_name']);
//etc....
return true;
}
To use:
/index.php
// Include our soon-to-be-used files
require_once(__DIR__._DS_.'config.php');
require_once(__DIR__._DS_.'functions'. _DS_.'connection.php');
require_once(__DIR__._DS_.'functions'. _DS_.'login.php');
// Set connection
$con = connection();
// See if a post has been made
if(isset($_POST['login'])) {
$loggedin = login($_POST['login'],$_POST['password'],$con);
}
// If the login attempt made
if(isset($loggedin)) {
// If successful
if($loggedin) {
header('Location: welcome.php');
exit;
}
else
// If failed, you can note in a variable an echo in the html section
$error = 'Login failed';
}
For the client-side validation, I would suggest jQuery Validate, it's easy and works very well.
I have a class named User which has a function named logout(). I create an instance of this class in index.php and i pass it's value to $_SESSION[usr] before i call memberspage.php . In memberspage.php i have a link named logout which when clicked i want the logout() function to run and also send the user to index.php. For this purpose i've done something like this.
Log out
I know that -> causes the problem but i don't know how to fix it. thnx for your time.
The following code worked for me
Log out
but there is a problem. If i go to the page(memberspage.php) where the above code is and i press the back arrow (not logout link) the logOut() function will still be used(the session is destroyed and i will have to log in again to access memberpage.php) . I don't get it because i thought that the only way to call the logOut() function was to click on Log out link.
If $_SESSION[usr]->logout() is working for you as you said in your comment. I don't know how.
But here is just for calling a php function inside anchor tag.It's totally depend on your function response.
<?php
function usr(){
return "abc";
}
?>
Log out
First i suggest that you change your use of session you can create a page for example session.php where all your session is place, it can also be the re directory page of your login page.
like this one named login.php
create in your form make action redirect to session.php
i also suggest that all your php codes of login are inside the session.php then make this one.
<?php
session_start();
$host = "localhost";
$uname = "root";
$pass = "";
$db = "mydb;
//database connection
$conn = mysqli_connect($host, $uname, $pass, $db);
mysqli_select_db($conn, $db);
if(!$conn){
die("Connection failed: " . mysqli_connect_error());
}
if(isset($_POST['username'])){
$username = $_POST['username'];
$password = $_POST['password'];
$username = stripslashes($username);
$password = stripslashes($password);
//$username = mysqli_real_escape_string($username);
//$password = mysqli_real_escape_string($password);
$sql = "SELECT * FROM table WHERE username = '" .$username. "' AND password = '".$password."' LIMIT 1";
$res = mysqli_query($conn, $sql);
if(mysqli_num_rows($res) > 0){
if($data = mysqli_fetch_assoc($res))
{
$_SESSION['type'] = $data['type'];
if(isset($_SESSION["login_user"]))
{
if($data['type'] == 'admin'){
header('location: admin.php');
}
else if($data['type'] == 'customer'){
header('location: customerhome.php');
}//header('location: uservalidation.php');
}
}
}
else{
//header('location: #');
echo '<script>';
echo 'alert("Invalid no?")';
echo '</script>';
header('location: logind.php');
}
}
?>
then create another page which is logout.php
put this code inside:
<?php
session_start();
header('location: index.php');
session_destroy();
?>
then save put the a link your page for logout.php
Add file logout.php and put into them your logout implementation:
<?php
header('Content-Type: application/json');
$_SESSION[usr]->logout();
echo json_encode(['message' => 'ok']);
And call this file with AJAX:
<script>
function logout() {
$.ajax({
url: '/logout.php'
}).then(function (res) {
window.location.href = '/';
});
}
</script>
Log out
my site is working (sort off). When i check if there sessions are there, they echo out a message which works BUT when i check session storage in chrome, the sessions are not coming up, which is strange. I have also tried to set a cookie but that is not coming up either. So what am i doing wrong. So the sessions are working but not getting stored, and the cookies are not getting stored either
this is part of login class
public function __construct(DB $pdo)
{
$this->pdo = $pdo->pdo;
if(isset($_GET['logout'])){
$_SESSION = array();
session_destroy();
}
}
public function checklogin()
{
if(isset($_SESSION['user_sess']) && $_SESSION['logged_in'] === true){
return true;
} else {
return false;
}
}
public function loginwithdata($email, $password)
{
$query = $this->pdo->prepare('SELECT * FROM `users` WHERE `email` = ?');
$query->bindValue(1, $email);
try{
$query->execute();
$data = $query->fetch();
$salt = $data['salt'];
$user_key = $data['user_key'];
$hashed_pass = sha1(md5($salt.$password));
if($this->verify($hashed_pass, $email) === true){
$_SESSION['user_sess'] = $user_key;
$_SESSION['logged_in'] = true;
setcookie('key', '12345678910', 1209600, '/');
return true;
} else {
return false;
}
} catch(PDOException $e) {
die($e->getMessage());
}
}
here is the ajax_login.php
require '../core/init.php';
if(isset($_POST))
{
$email = $_POST['email'];
$password = $_POST['password'];
if(!empty($email) && (!empty($password))){
$try = $login->loginwithdata($email, $password);
if($try){
//login successful
echo 'success';
} else {
echo 'login failed';
}
}
}
and on my index page i have
require_once 'core/init.php';
if($login->checklogin() === true){
echo "you are logged in";
} else if ($login->checklogin() === false) {
echo "you are not logged in";
}
and my init file
session_start();
error_reporting(E_ALL);
date_default_timezone_set('Europe/London');
require_once 'classes/DB.php';
require_once 'classes/Upload.php';
require_once 'classes/Login.php';
require_once 'classes/Register.php';
require_once 'classes/Site.php';
require_once 'classes/Admin.php';
require_once 'sinitize.php';
$pdo = new DB;
$upload = new Upload($pdo);
$login = new Login($pdo);
$register = new Register($pdo);
Your code looks good so far.
But wait.. dude.. Sessions generally get stored in a COOKIE (as ID). SESSION STORAGE and WEB STORAGE in chrome is something completely different and is sorta part of HTML5 rather than PHP Sessions.
You say you get the proper echoes so there is really nothing wrong with your session.
If you open the developers console and in networking tab you see the cookie sent, it's everything perfect.
If you are having problems with the session cookie itself,
please provide and check the session configuration variables from php.ini:
From console:
php -i | grep session
or use phpinfo(); in a web served script.
session.use_cookies should be On
See: http://www.php.net/manual/de/ini.list.php
Some browsers, if path is set, wants the domain too:
setcookie ( $name, $value, $expire, $path, $domain);
About $expire
It's the "absolute" time in seconds since Epoc when the cookie expire, so expire within an hour should be:
$expire = time()+3600;
see also:
http://www.php.net/setcookie
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