I am trying to store sessions in the local storage of the user when they log in, but the expiry of the session is short and it is deleted every time I route to another page, and I could not figure out what had gone wrong. Below is some snippet of my code.
connect.php
<?php
$host = "localhost";
$username = "root";
$password = "";
$database = "ezcar2";
$conn = mysqli_connect($host, $username, $password, $database);
?>
ct_home.php
<body>
<?php
include_once 'connect.php';
session_start();
if (!isset($_SESSION['username'])) {
header("Location: ct_login.php");
exit();
}
?>
</body>
Whenever I refresh the page, I would be redirected back to ct_login.php. I would like for the session to stay until the user logs out.
EDIT (ct_login.php && setting the sessions)
<?php
include_once 'connect.php';
session_start();
if(isset($_POST['btnlogin'])){
$c_username = trim($_POST['txtusername']);
$c_password = trim($_POST['txtpwd']);
$sql_query = "SELECT * FROM tblcustomer WHERE CT_USERNAME = '$c_username' AND CT_PASSWORD = '$c_password'";
$sql_role = "SELECT * FROM tblcustomer WHERE CT_USERNAME = '$c_username' AND CT_PASSWORD = '$c_password' AND CT_ROLE = 'CAR OWNER'";
$sql_status = "SELECT * FROM tblcustomer WHERE CT_USERNAME = '$c_username' AND CT_PASSWORD = '$c_password' AND CT_STATUS = 'APPROVED'";
if($result = mysqli_query($conn, $sql_query)){
$rows = mysqli_num_rows($result);
if($rows == 1) {
if ($status = mysqli_query($conn, $sql_status)) {
$row_ = mysqli_num_rows($status);
if($row_ == 1) {
if($role = mysqli_query($conn, $sql_role)){
$rows_ = mysqli_num_rows($role);
if($rows_ == 1) {
//store username & password in session variable
$rec = mysqli_fetch_row($role);
$_SESSION['username'] = $rec[7];
$_SESSION['role'] = $rec[9];
header("Location: ct_home.php");
// session_start();
} else {
$rec = mysqli_fetch_row($result);
$_SESSION['username'] = $rec[7];
$_SESSION['role'] = $rec[9];
header("Location: ct_home.php");
// session_start();
}
}
} else {
echo('<script>alert("Account request is still pending. Please wait for confirmation email.");</script>');
echo "<meta http-equiv='refresh' content='0'>";
exit();
}
}
} else {
echo('<script>alert("Invalid Credentials. Please try again!");</script>');
echo "<meta http-equiv='refresh' content='0'>";
exit();
}
}
}
?>
Edit (#1) : The database connection is used to validate user login
Please let me know what else I can provide to draw a clearer picture of the whole situation. Many thanks in advance.
I have realized why i can't actually access userdata (after i am logged) old way to find the username is $_SESSION['username']; (assuming there is a row as 'username' in MySQL database)
So as i have a test account as "good25" (reason to choose numbers was to see if Alphanumeric inputs works fine.. its just checkup by me.. nevermind)
Problem :
assuming, i have rows in a table as 'username' and all of his information.. such as 'password', 'email', 'joindate', 'type' ...
On net i found out how to snatch out username from Session
<?php session_start(); $_SESSION('username'); ?>
successful!!
i had an idea to check if session is actually registering or no??
after a log on start.php i used this code
if(isset($_SESSION['username'])) { print_r($_SESSION['username']); }
the result was "1" (while i logged in using this username "good25")
any suggestions?
index.php (lets say, index.php just holds registration + Login form + registration script.. in login form, action='condb.php')
<?php
require 'condb.php';
if (isset($_POST['btn-signup']))
{
//FetchInputs
$usern = mysqli_real_escape_string($connection,$_POST['username']);
$email = mysqli_real_escape_string($connection,$_POST['email']);
$password = mysqli_real_escape_string($connection,$_POST['password']);
$repassword = mysqli_real_escape_string($connection,$_POST['repassword']);
$usern = trim($usern);
$email = trim($email);
$password = trim($password);
$repassword = trim($repassword);
//SearchUser
$searchusr = "SELECT username FROM $user_table WHERE username='$usern'";
$usersearched = mysqli_query($connection, $searchusr);
$countuser = mysqli_num_rows($usersearched);
//SearchEmail
$searcheml = "SELECT email FROM $user_table WHERE email='$email'";
$emlsearched = mysqli_query($connection, $searcheml);
$counteml = mysqli_num_rows($emlsearched);
//RegisteringUser
if ($countuser == 0)
{
if ($counteml == 0)
{
$ctime = time();
$cday = date("Y-m-d",$ctime);
$aCode = uniqid();
$adduser = "INSERT INTO $user_table(username, email, password, realname, activationcode, verified, joindate, type, points) VALUES ('$usern','$email','$password','$name','$aCode','n','$cday','Free',$signPoints)";
if (mysqli_query($connection, $adduser))
{
?><script>alert('You have been registered');</script><?php
}
else {
?><script>alert('Couldnt Register, please contact Admin<br><?mysqli_error($connection);?>');</script><?php
}
} else {
?><script>alert('Email already exists!');</script><?php
}
} else {
?><script>alert('Username already exists!');</script><?php
}
}
?>
condb.php
$connection = mysqli_connect($db_server, $db_user, $db_pass);
mysqli_select_db($connection, $db_name);
if(!$connection) {
die ("Connection Failed: " . mysqli_connect_error);
}
if (isset($_POST['btn-login']))
{
$uname = mysqli_real_escape_string($connection,$_POST['uname']);
$upass = mysqli_real_escape_string($connection,$_POST['upass']);
//FindUser
$finduser = "SELECT * FROM $user_table WHERE username='$uname' AND password='$upass'";
$findinguser = mysqli_query($connection,$finduser);
$founduser = mysqli_num_rows($findinguser);
//ConfirmPassword
if ($founduser > 0)
{
session_start();
$_SESSION['username'] = $username;
$_SESSION['username'] = true;
if ($findinguser != false)
{
while ($fetchD = mysqli_fetch_array($findinguser, MYSQLI_ASSOC))
{
$fetchD['username'] = $usernn;
$fetchD['email'] = $email;
$fetchD['userid'] = $uid;
$fetchD['realname'] = $rlnm;
$fetchD['points'] = $pts;
$fetchD['type'] = $membertype ;
}
header("Location: start.php");
} else {
echo mysqli_error();
}
} else {
header("Location: index.php");
?><script>alert('Wrong details, please fill in correct password and email');</script><?php
}
}
I am not asking you to build a script.. just little help please? (Thank you so so so so so much, as i am a self-learner, you don't have to say everything.. just a clue is enough for me)
may be you can try this code
<?php
require_once 'require.inc.php';
//session_start();
if (isset($_POST['btn-login']))
{
$uname = mysqli_real_escape_string($_POST['uname']);
$upass = mysqli_real_escape_string($_POST['upass']);
$search = mysqli_query($connection, "SELECT username, userid, password from $user_table WHERE username='$uname' AND password='$upass'");
$match = mysqli_fetch_assoc($search);
if ($match == 1 and $match['password'] == md5($upass))
{
$_SESSION['username'] = $match['userid'];
} else {
?>
<script>alert('Password or E-mail is wrong. If you havent registered, Please Register');</script>
<?php
}
}
if (isset($_SESSION['username']) or isset($match['userid'])){
header("Location:start.php");
}
if (isset($_POST['btn-signup']))
{
$name = mysqli_real_escape_string($_POST['name']);
$usern = mysqli_real_escape_string($_POST['username']);
$email = mysqli_real_escape_string($_POST['email']);
$password = mysqli_real_escape_string($_POST['password']);
$repassword = mysqli_real_escape_string($_POST['repassword']);
$name = trim($name);
$usern = trim($usern);
$email = trim($email);
$password = trim($password);
$repassword = trim($repassword);
$query = "SELECT email FROM $user_table WHERE email='$email'";
$result = mysqli_query($connection, $query);
$count = mysqli_num_rows($result);
$querytwo = "SELECT username FROM $user_table WHERE username='$usern'";
$resulttwo = mysqli_query($connection, $querytwo);
$counttwo = mysqli_num_rows($resulttwo);
if ($count == 0 AND $counttwo == 0)
{
if ($password == $repassword) {
if (mysqli_query($connection, "INSERT INTO $user_table(username, email, password, realname) VALUES ('$usern','$email','$password','$name')"))
{
?>
<script> alert ('Successfully registered'); </script>
<?php
}
}else {
?>
<script> alert ('The Password you entered, doesnt match.. Please fill in the same password'); </script>
<?php
}
}
else {
?>
<script> alert('Username or E-mail already exist'); </script>
<?php
}
}
?>
and this is for require.inc.php
<?php
global $username;
//require 'dconn.php';
session_start();
$_SESSION["username"] = $username;
$connection = mysqli_connect("localhost","root","", "test") or die(mysqli_error());
// Check Login
if (isset($_SESSION['username']) and isset ($match['userid']))
{
$Selection = "SELECT * FROM $user_table WHERE username='$username'";
$selectQuery = mysqli_query($connection, $Selection);
if ($selectQuery != false)
{
while ($fetchD = mysqli_fetch_assoc($selectQuery))
{
$usernn = $fetchD['username'];
$email = $fetchD['email'];
$uid = $fetchD['userid'];
}
} else {
echo mysqli_error();
}
}
?>
#suggestion, create session after user login and authorized then for each page start session and take session which you created and perform SQL queries using that session variable.
for example :
$_SESSION['user_name']=$row['username'];
for each page:
session_start();
$user_name=$_SESSION['user_name'];
SQL query
mysqli_query($con,"SELECT * FROM users where column_name='$user_name'");
I think you need to include dconn.php file in all files where you want to perform the mysql operation. If you have included it only in require.inc.php then you you it in all your other files.
I would like to have a page in which a user, when logged in, can edit their username/password/email, but am having difficulty in understanding any way in which to do this easily; I am new to PHP and SQL. I know this version of SQL is deprecated, but I am not building this for security, so I am not concerned with SQL injection attacks at the moment.
This is my login code currently.
<?PHP
$uname = "";
$pword = "";
$errorMessage = "";
$num_rows = 0;
//==========================================
// ESCAPE DANGEROUS SQL CHARACTERS
//==========================================
function quote_smart($value, $handle) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
if (!is_numeric($value)) {
$value = "'" . mysql_real_escape_string($value, $handle) . "'";
}
return $value;
}
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$uname = $_POST['username'];
$pword = $_POST['password'];
$uname = htmlspecialchars($uname);
$pword = htmlspecialchars($pword);
//==========================================
// CONNECT TO THE LOCAL DATABASE
//==========================================
$user_name = "root";
$pass_word = "";
$database = "login";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $pass_word);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$uname = quote_smart($uname, $db_handle);
$pword = quote_smart($pword, $db_handle);
$SQL = "SELECT * FROM login WHERE L1 = $uname AND L2 = $pword";
$result = mysql_query($SQL);
$num_rows = mysql_num_rows($result);
//====================================================
// CHECK TO SEE IF THE $result VARIABLE IS TRUE
//====================================================
if ($result) {
if ($num_rows > 0) {
session_start();
$_SESSION['login'] = "1";
header ("Location: Logged.php");
}
else {
echo "<script> alert('Invalid Login')</script>";
}
}
else {
echo "<script> alert('Invalid Login')</script>";
}
mysql_close($db_handle);
}
}
?>
This will then take you to a page called logged.php, which will contain forms for the user to enter in the new username, password, and email they want to use, but I don't know how to make it able to actually edit a database entry and, secondly, to edit the correct entry.
The database columns currently are ID, L1, L2 and Email. What am I doing incorrectly?
so I have my site which i am coding, in my login.php, this is the source:
<?php
include "out_config.php";
session_start();
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
if(!$username) {
header("Location: ../index?errormsg=nousername");
}
if(!$password) {
header("Location: ../index?errormsg=nopassword");
}
$sql = "SELECT * FROM users WHERE username='$username' and password='$password'";
if($rankcheck == "Administrator" || $rankcheck == "Client") {
$check = 1;
}
else {
$check = 0;
}
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$result = mysql_query($sql);
$count = mysql_num_rows($result);
if($count==1 && $check == 1) {
$_SESSION['username'] = $username;
header("Location: ../home");
}
else {
header("location: ../index?errormsg=invalidlogin");
}
}
?>
1st: I know MySQL is depreciated but I want to use MySQL because my Host Supports MySQL more than MySQLi/PDO.
2nd: You can see my $rankcheck won't work. My rank check lines are included in out_config.php, the source for it is:
<?php
<Removed Details>
$connect = mysql_connect($host, $username, $password);
$selectdb = mysql_select_db($db);
$IP = getenv('REMOTE_ADDR');
$sql2 = mysql_query("SELECT `rank` FROM `users` where username='$user'");
if(isset($_SESSION['username'])) {
$user = $_SESSION['username'];
$rankcheck = mysql_result($sql2,0);
}
?>
So you can see, it looks all fine. :P
Now, the problem is that I am trying to allow access to this area only to people who are ranked 'Administrator' and 'Client' so it won't work. My Database structure is:
http://i.stack.imgur.com/AAzr9.png
It does not grant access to User and Awaiting usergroup members. But it does not even let Administrator's and Clients. ( I am sure there is no Password Encryption yet ).
If you could help me, it would be really helpful!
in the moment you are including your "out_config.php" $username and $password is not set
change to this:
<?php
session_start();
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
include "out_config.php";
if(!$username) {
header("Location: ../index?errormsg=nousername");
}
if(!$password) {
header("Location: ../index?errormsg=nopassword");
}
$sql = "SELECT * FROM users WHERE username='$username' and password='$password'";
if($rankcheck == "Administrator" || $rankcheck == "Client") {
$check = 1;
}
else {
$check = 0;
}
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$result = mysql_query($sql);
$count = mysql_num_rows($result);
if($count==1 && $check == 1) {
$_SESSION['username'] = $username;
header("Location: ../home");
}
else {
header("location: ../index?errormsg=invalidlogin");
}
}
?>
Sorry I am new to php so please be patient with me. I am creating a user interface and when I register it says I have registered but it doesn't store the data into the database. Also every time I register at the moment it comes up with error "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'testing101''' at line 1." Can someone please help me!
<?PHP
$uname = "";
$pword = "";
$errorMessage = "";
$num_rows = 0;
function quote_smart($value, $handle) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
if (!is_numeric($value)) {
$value = "'" . mysql_real_escape_string($value, $handle) . "'";
}
return $value;
}
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$uname = $_POST['username'];
$pword = $_POST['password'];
$uname = htmlspecialchars($uname);
$pword = htmlspecialchars($pword);
$uLength = strlen($uname);
$pLength = strlen($pword);
if ($uLength >= 10 && $uLength <= 20) {
$errorMessage = "";
}
else {
$errorMessage = $errorMessage . "Username must be between 10 and 20 characters" . "<BR>";
}
if ($pLength >= 8 && $pLength <= 16) {
$errorMessage = "";
}
else {
$errorMessage = $errorMessage . "Password must be between 8 and 16 characters" . "<BR>";
}
if ($errorMessage == "") {
$user_name = "root";
$pass_word = "";
$database = "user authentication";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $pass_word);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$uname = quote_smart($uname, $db_handle);
$pword = quote_smart($pword, $db_handle);
$SQL = "SELECT * FROM login WHERE USERNAME = '".$uname."'";
$result = mysql_query($SQL)or die(mysql_error());
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
$errorMessage = "Username already taken";
}
else {
$SQL = "INSERT INTO login (USERNAME, PASSWORD) VALUES ('{$uname}', MD5('{$pword}'))";
$result = mysql_query($SQL);
mysql_close($db_handle);
//=================================================================================
// START THE SESSION AND PUT SOMETHING INTO THE SESSION VARIABLE CALLED login
// SEND USER TO A DIFFERENT PAGE AFTER SIGN UP
//=================================================================================
session_start();
$_SESSION['login'] = "1";
header ("Location: page1.php");
}
}
else {
$errorMessage = "Database Not Found";
}
}
}
?>
<html>
<head>
<title>Basic Login Script</title>
</head>
<body>
<FORM NAME ="form1" METHOD ="POST" ACTION ="signup.php">
Username: <INPUT TYPE = 'TEXT' Name ='username' value="<?PHP print $uname;?>" maxlength="20">
Password: <INPUT TYPE = 'TEXT' Name ='password' value="<?PHP print $pword;?>" maxlength="16">
<P>
<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Register">
</FORM>
<P>
<?PHP print $errorMessage;?>
</body>
</html>
You're double-quoting your text:
1 set of quotes gets added in your smart_quote() function.
1 set of quotes gets added in your actual query, so you're producting:
INSERT .... VALUES (''$uname'', ''$password'');
If you had proper error handling your query calls, you'd have seen this:
$result = mysql_query($sql) or die(mysql_error());
^^^^^^^^^^^^^^^^^^^^^^