I am trying to learn php and I am trying to login with this user;
When user1 logs in and a new window user2 logs in, when I refresh the user1 page, the user1 information disappears and the user2 information comes.
There is no such problem with the videos I watch on the internet.
Is there a way to do this without using javascript session storage?
$mail = strip_tags(trim($_POST['mail']));
$pass= strip_tags(trim($_POST['pass'])) ;
$control = $db->prepare("SELECT * FROM users WHERE BINARY usermail = :mail and userpass = :pass");
$control->execute(array(
"mail" => $mail,
"pass" => $pass
));
if($control->rowCount()){
$user = $control->fetch(PDO::FETCH_ASSOC);
$_SESSION['user'] = $user;
header("location:usercontrol");
}else{
$error['login'] = "...";
}
you need to check is the is set session is set using the super $_SESSION global variable like so
if (isset($_SESSION['user'])) {
echo '<script type="text/JavaScript">
sessionStorage.clear()</script>';
} else {
session_start();
// your code
}
Related
I'm attempted to create a login authentication system using PHP. So far I've managed to query the DB to check if a username/password given by the user matches any rows in the DB. However I have a column in the DB named "isadmin" which stores a boolean value. I want to implement a check if true/false. Depending on the result depends on which php file is loaded (included).
EDIT: I have two php files, both containing the same HTML displaying the index page of a website. However, one php file is for regular users, the other is for admin users which will contain added features. When a user enters their username and password, I want a check for the user level of that login, Once the check is done it should show the appropriate php page.
$stmt = $pdo->prepare('SELECT * FROM Reg_User WHERE username = :username AND password = :password');
$details = [
'username' => $_POST['username'],
'password' => sha1($_POST['password'])
];
unset($_POST['submit']);
$stmt->execute($details);
if ($stmt->rowCount() > 0) {
$user = $stmt->fetch();
$_SESSION['loggedin'] = $user['user_id'];
echo 'Logged in as ' . $_POST['username'];
include 'index.php';
}
else {
echo 'Sorry, your username and password could not be found Please <a href="login.html">try again
or register!</a>';
}
A simple if/else statement will do it.
if ($user["isadmin"]) {
echo "Logged in as an admin.";
#you can include your related php page here.
} else {
echo "Logged in as an user.";
#you can include your related php page here.
}
There's no sanitizing of user input in your code, this is a must in a login system, try this after your login form.
info: I don't use PDO, $con is the MYSQLI connection.
<?php
// Handle log in
if (isset($_POST['login'])) {
$username = $_POST['username'];
$password = $_POST['password'];
// Sanitize username input
$username = strip_tags($username);
$username = trim($username);
$username = mysqli_real_escape_string($con, $username);
$username = urldecode($username);
// Sanitize password input
$password = strip_tags($password);
$password = trim($password);
$password = mysqli_real_escape_string($con, $password);
$password = urldecode($password);
}
?>
Your site should be set to https only, if it is ignore this link: htaccess redirect to https://www and you should be providing either a secure session cookie or a secure persistent cookie for users who are able to log in successfully. The code underneath this paragraph should be at the very top of your page before any html. This example is for time related persistent https secure cookie set to 1 day after which it will expire. You could use a session cookie but I find this annoys people if they frequent your site quite often, they don't want to have to log in again the same day if they close and reopen a browser or tab.
<?php
// All this code goes right at the top of your page before anything else!
function addcookie() {
global $condition;
if ($condition == "green") {
global $nameofcookie;
setrawcookie('loggedin', $nameofcookie, strtotime('+1 day'), '/', '', isset($_SERVER["HTTPS"]), true);
echo "<script>window.location.replace('https://example.com/mypage');</script>";
}
}
?>
The above code is will set a secure cookie using a function because you only want it firing after a successful login. The name of the cookie really should be random and unique, something based on microtime would work well. Make sure it's not anything important which could identify the user!IMPORTANT: the name of the cookie for reference should be created at the time of account creation and added to the users table so you can identify users and represent their login details.
Standard security measures should also include a separate table of the ip, time, date and username of who logged in. If your site is busy the table will fill quickly so you could set a cron job to clean old records to keep the size down, in that case you will need to add a column for datetime to identify the age of records.
Handling the login...
<?php
$condition = "red";
if (isset($_POST['login'])) {
$select_login = "select * from Reg_User where username='$username' and password='$password'";
$connect_login = mysqli_query($con, $select_login);
$rows_login = mysqli_num_rows($connect_login);
if ($rows_login == 0) {
// code here to handle failed logins, I would record them and use a 3 strike method
}
// Handle successful logins, add cookie
else {
while ($row_login=mysqli_fetch_array($connect_login)) {
// Retrieve cookie name here from table
$nameofcookie=$row_login['cookie'];
$condition = "green"; // This allows you to add the cookie
addcookie();
}
}
}
?>
Retrieving the cookie to authenticate users...
<?php
if (isset($_COOKIE['loggedin'])) {
$cookie = $_COOKIE['loggedin'];
$select_authenticated_user = "select * from Reg_User where cookie='$cookie'";
$connect_authenticated_user = mysqli_query($con, $select_authenticated_user);
while ($row_authenticated_user=mysqli_fetch_array($connect_authenticated_user)) {
// Retrieve values here from table
$logged_in_user=$row_authenticated_user['username'];
$logged_in_admin=$row_authenticated_user['isadmin'];
// Resolve admin status
if ($logged_in_admin == TRUE) {
$type = "admin";
} else {
$type = "member";
}
}
// Echo statement for logged in user with admin or not status, you could change the echo to a variable name if you want to use this in a specific place on your page.
echo "Welcome $logged_in_user<br/>
Type: $type
";
}
?>
Here's a link for obtaining IP's: How to get the client IP address in PHP
Developing Hybrid App I know it is possible to use php session. Anyone know how it works? I would like to display all the info of the user logged-in on their home page like, fullname, contact no., address, etc.
The login: (login.html) This is the code with ajax:
function handleData(responseData) {
var response = JSON.parse(responseData);
var access = response.user_access;
if (access == "real") {
alert("Welcome");
location.href = "home.html"; //should redirect and auto display all the info.
} else {
alert("Your username and password didn\'t match.");
}
}
So the login page send request to the server to log-in.
Now the server side(PHP) code.
if(isset($_POST['input_email']) && isset($_POST['input_password'])){
$post = $_POST;
array_walk_recursive($post, 'clean');
//SQL query here- check if email/password match
$using = 'real';
}
if($user['user_status'] == 'active'){
$_SESSION['user_id'] = $user['user_id'];
$_SESSION['user_email'] = $user['user_email'];
$_SESSION['user_fullname'] = $user['user_fullname'];
}else{
$using = 'notmatch';
}
Declare variable for session:
$user_fullname = $_SESSION['user_fullname'];
$user_id = $_SESSION['user_id'];
$user_email = $_SESSION['user_email'];
$result_array = array( user_id => $user_id, user_fullname => $user_fullname, user_email => $user_email, user_access => $loggedinusing);
echo json_encode($result_array);
}
Login was working well and redirected to the home page when login credentials are right. My home.html for now don't have any code. I need for now is to display the user info in home page with PHP session. I don't know where to start.
I do a lot of work using PHP frameworks but I am now building a simple login system from scratch and I am stumped. I am using PDO for my database queries. I have a simple login form which points to the same page using $_SERVER['PHP_SELF']. Then I have this code...
<?php
//LOG IN
if($_POST['login_submit']){
$username = $_POST['username'];
$password = $_POST['password'];
//Query
$database->query("SELECT * FROM users WHERE username = :username AND password = :password");
$database->bind(':username',$username);
$database->bind(':password',$password);
$rows = $database->resultset();
$count = count($rows);
if($count > 0){
session_start();
//Assign session variables
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
$_SESSION['logged_in'] = 1;
} else {
$login_msg[] = 'Sorry, that login does not work';
}
}
When I login, its fine. It starts the session. But as soon as I go to another page the session is broken. I suspect maybe cause the session_start() is in the if($_POST['login_submit']) condition. But I could sware Ive done it like this before. Any help would be awesome..thanks!
The first line of your code...
if($_POST['login_submit']){
Only, if you submit your login form, the session is started.
And, on all other pages, you have to call session_start() ...
Another attempt at designing a user membership. Got to log in successfully, finds the data in the database. But in my index file, after logging in, it should check if I'm logged in and display links to my account instead of register and login. Here's the code:
<?php
session_start(); // Must start session first thing
// See if they are a logged in member by checking Session data
$toplinks = "";
if (isset($_SESSION['id'])) {
// Put stored session variables into local php variable
$userid = $_SESSION['id'];
$username = $_SESSION['username'];
$toplinks = '' . $username . ' •
Account •
Log Out';
} else {
$toplinks = 'Register • Login';
}
?>
And here is the login form code, where I think the problem is because it's not storing my session id:
<?php
if ($_POST['email']) {
//Connect to the database through our include
include_once "connect_to_mysql.php";
$email = stripslashes($_POST['email']);
$email = strip_tags($email);
$email = mysql_real_escape_string($email);
$password = preg_replace("[^A-Za-z0-9]", "", $_POST['password']);
// filter everything but numbers and letters
$password = md5($password);
// Make query and then register all database data that -
// cannot be changed by member into SESSION variables.
// Data that you want member to be able to change -
// should never be set into a SESSION variable.
$sql = mysql_query("SELECT * FROM users WHERE email='$email' AND password=
'$password'AND emailactivated='1'");
$login_check = mysql_num_rows($sql);
if($login_check > 0){
while($row = mysql_fetch_assoc($sql)){
// Get member ID into a session variable
$userid = $row["id"];
$_SESSION['id'] = $userid;
// Get member username into a session variable
$username = $row["username"];
$_SESSION['username'] = $username;
// Update last_log_date field for this member now
mysql_query("UPDATE users SET lastlogin=now() WHERE id='$userid'");
// Print success message here if all went well then exit the script
header("location: member_profile.php?id=$userid");
exit();
} // close while
} else {
// Print login failure message to the user and link them back to your login page
print '<br /><br /><font color="#FF0000">No match in our records, try again
</font> <br/>
<br />Click here to go back to the login page.';
exit();
}
}// close if post
?>
Once again I'm following someone's tutorial and trying to implement it to my website and this would be perfect if it worked. Please advice why the $toplinks aren't being set after logging in.
I think the problem is, that you have to include the session_start() in every file where you want to use your session. Otherwise its working in the file like a normal array but not global. In your form i can't see that you start your session.
Edit: You need this only if you have 2 files. When you have only one file and include the other page its working when you include in once on top.
If you want to log out, then you should create a logout file, and include
session_destroy();
probably add also a href to get redirection link by doing something like:
header('location:index.php'); // will return you to index as soon as you logout.
I am creating a user login system similar to a client intranat. And when I try to access the main page I get a redirect loop in FF.
I am checking to see if a user is logged in with this:
if(($_SERVER['PHP_SELF'] != '/webmaster/index.php') && ($_SESSION['loggedin'] != '1234')){
header("Location: ".$domain."index.php?l=no");
exit();
}
Below is my process-login.php -> which is the file that handles client login:
<?php
ob_start();
session_start();
ini_set('display_errors', 1);
error_reporting(E_ALL | E_NOTICE);
include ("config.inc.php");
include ("jsonEncode.php");
// username and password sent from form
$username = '';
$password = '';
$username = mysql_real_escape_string($_GET['username']);
$password = mysql_real_escape_string($_GET['password']);
$sql = "SELECT * FROM clients WHERE username='$username' AND password='$password' LIMIT 1";
//echo $sql;
$result = mysql_query($sql);
$data = mysql_fetch_array($result);
$count = mysql_num_rows($result);
if($count==1){
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
$_SESSION['client_id'] = $data['c_id'];
$_SESSION['loggedin'] = "1234";
/*
echo $_SESSION['client_id'];
echo $_SESSION['password'];
echo $_SESSION['username'];
*/
echo $_SESSION['loggedin'];
// valid
$var = array('valid' => 1, 'username' => $username, 'password' => $password);
print php_json_encode($var);
}else{
// invalid
$var = array('valid' => 0, 'username' => $username, 'password' => $password);
print php_json_encode($var);
}
?>
The main index.php page has two forms one for clients and one for webmastsers, and if you are a client you are redirected to: clients/, and if you're a webmaster you're redirected to: webmaster/.
I have checked my login scripts and it is returning the right information and logging it in, but it keeps looping.
The form is submitted via ajax then returns JSON with a value of 1 being valid or 0 invalid to see if the user can continue.
If the form is submitted through AJAX are you sure that the session cookie is set accordingly? I know that Firefox will send cookie information together with asynchronous requests but are you confident that it will work the other way around?
if (($_SERVER['PHP_SELF'] != '/webmaster/index.php') &&
($_SESSION['loggedin'] != '1234')) { // I don't like this!
header("Location: ".$domain."index.php?l=no");
exit();
}
The $_SESSION['loggedin'] value would be != '1234' most of the time and this would be the case initially, you should check whether the value is undefined as well and act accordingly. What guarantees do you have right now that if the user requests index.php that $_SESSION['loggedin'] is not != '1234' if this is a new session? Otherwise you'll have a redirection loop which can be caused if the AJAX response doesn't set a session cookie accordingly, assuming you use session cookies to track user session?