For login im using a session_start(), for desktop its works fine, but on mobile, it doesnt work. When I make a session_id() with variable, for example, session_id('login') its works on mobile, but break other sessions on other computers. But when session_id() is generated automatically, it doesn't work on mobile. What should I do?
My session_start code on index.php
session_start();
if (isset($_SESSION['username'])){
session_id();
}
Whole code for login.php file
<?php
require('config.php');
$usernameOK = false; $passwordOK = false;
if (isset($_POST['username']) and isset($_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
$UserQuery = "SELECT username FROM `members` WHERE username='$username'";
$userTestResult = mysqli_query($connection, $UserQuery);
$usernameTEST = mysqli_num_rows($userTestResult);
if($usernameTEST == 1){$usernameOK = true;}
$PasswordQuery = "SELECT password FROM `members` WHERE username='$username'";
$result = mysqli_query($connection,$PasswordQuery);
$row = mysqli_fetch_row($result);
if (password_verify($password, $row[0])){$passwordOK = true;}
if($usernameOK == true && $passwordOK == true){
$_SESSION['username'] = $username;
}else{
$error_message = "Incorrect login data";
}
}
if (isset($_SESSION['username'])){
header("Location: ../");
exit;
}else{?>
<form class="login-form" method="POST">
<?php if(isset($error_message)){ ?><div class="mini-mes error"> <?php echo $error_message; ?> </div><?php } ?>
<span class="placeholder">username</span>
<input type="text" name="username" placeholder="username" required>
<span class="placeholder">password</span>
<input type="password" name="password" id="inputPassword" placeholder="password" required>
<button type="submit">Login</button>
<a class="form-link" href="register.php">Register</a>
</form>
<?php } ?>
Not really sure what your code does, because I dont see anything regarding setting the username or anything of that sort. What your code does is, it starts the session and checks if username variable in session is set, and if YES, it calls session_id.
Can you use this to check if the session is created properly?
session_start();
if (session_status() !== PHP_SESSION_NONE)
{
echo session_id();
}
Starts a session and shows you the session ID if the session_status is not PHP_SESSION_NONE
You don't need to do a session_id() to start a session, session_start() is enough.
I've tested the following on Safari on iPhone 6 (just add the db query part back if you want):
testa.php
<?php
//require('config.php');
session_start();
echo "Session ID: ".session_id()." <br>\n";
$usernameOK = false;
$passwordOK = false;
if (isset($_POST['username']) and isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$usernameOK = true;
$passwordOK = true;
if ($usernameOK == true && $passwordOK == true) {
$_SESSION['username'] = $username;
} else {
$error_message = "Incorrect login data";
}
}
if (isset($_SESSION['username'])) {
header("Location: ../");
exit;
} else {
?>
<form class="login-form" method="POST">
<?php if (isset($error_message)) { ?>
<div class="mini-mes error"> <?php echo $error_message; ?> </div><?php } ?>
<span class="placeholder">username</span>
<input type="text" name="username" placeholder="username" required>
<span class="placeholder">password</span>
<input type="password" name="password" id="inputPassword" placeholder="password" required>
<button type="submit">Login</button>
<a class="form-link" href="register.php">Register</a>
</form>
<?php } ?>
testb.php
<?php
session_start();
echo "Session ID: ".session_id()." <br>\n";
echo "Data stored in session: {$_SESSION['username']}<br>\n";
Clear data/cookies on your mobile browser (or just go into incognito mode). This will make sure you "start from scratch".
Open testa.php on your mobile browser. Take note of the session id shown. Enter your login details and tap Submit. The next page may show blank.
Open testb.php. Again, take note of the session id shown. It should be equal to the session id shown in test1.php. If they are different then it is possible your mobile browser is configured not to accept cookies.
I've personally tested this on Safari on iPhone 6 and I was able to get the username data from session.
PS. A friendly reminder: don't forget to escape the data you use in queries (i.e. $username and $password). Use mysqli_real_escape_string, or use prepared statements. For security.
Maybe you are experiencing some conflict issues:
My session_start code
if (isset($_SESSION['username'])){
session_id();
} else if (!isset($_SESSION)){
session_start();
}
Whole code for login.php file
<?php
require('config.php');
$usernameOK = false; $passwordOK = false;
if (isset($_POST['username']) and isset($_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
$UserQuery = "SELECT username FROM `members` WHERE username='$username'";
$userTestResult = mysqli_query($connection, $UserQuery);
$usernameTEST = mysqli_num_rows($userTestResult);
if($usernameTEST == 1){$usernameOK = true;}
$PasswordQuery = "SELECT password FROM `members` WHERE username='$username'";
$result = mysqli_query($connection,$PasswordQuery);
$row = mysqli_fetch_row($result);
if($usernameOK == true && password_verify($password, $row[0])){
if (isset($_SESSION)){
$_SESSION['username'] = $username;
} else{
session_start();
$_SESSION['username'] = $username;
}
}else{
$error_message = "Incorrect login data";
}
}
if (isset($_SESSION['username'])){
header("Location: ../");
exit;
}else{?>
<form class="login-form" method="POST">
<?php if(isset($error_message)){ ?><div class="mini-mes error"> <?php echo $error_message; ?> </div><?php } ?>
<span class="placeholder">username</span>
<input type="text" name="username" placeholder="username" required>
<span class="placeholder">password</span>
<input type="password" name="password" id="inputPassword" placeholder="password" required>
<button type="submit">Login</button>
<a class="form-link" href="register.php">Register</a>
</form>
<?php } ?>
In the index.php on the first line I have -> REMOVE THAT, PUT FIRST ROUTINE OF SESSION CHECKING
if (!isset($_SESSION)){
session_start();
}
EDIT: I noted that you're using header function to redirect to the index page. It's important avoid such redirects unless you're sending user out of your system, because some environments doesn't work well with them. I suggest to change your routine to user POST/GET http routines instead:
Inside validateSession.php
outside validateSession, NOTHING about sessions rules, concentrate everything there
index.php/head.php/some code that always starting in every page start only that:
<?php
include_once('validateSessions.php');
?>
Your form:
<form class="login-form" action="index.php" method="POST">
<?php if(isset($error_message)){ ?><div class="mini-mes error"> <?php echo $error_message; ?> </div><?php } ?>
<span class="placeholder">username</span>
<input type="text" name="username" placeholder="username" required>
<span class="placeholder">password</span>
<input type="password" name="password" id="inputPassword" placeholder="password" required>
<button type="submit">Login</button>
<a class="form-link" href="register.php">Register</a>
</form>
EDIT: I reviewed your routine, pay attention on validateSessions.php, I was forgetting to load session_start() in every routine that called the file. Put validateSessions inside your include directory.
UPDATE: Even my code helping the OP, the main problem was the SESSION configuration into php.ini file with session.save_path, causing issues about session routines. The php.ini fix solved the problem, the code I expect that helped OP to think about some routines towards Session stuff.
Probably your session is not set. Depending on the PHP version you use, check your session.
For versions of PHP >= 5.4.0
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
For versions of PHP < 5.4.0
if(session_id() == '') {
session_start();
}
Cookies definitely work on mobile browsers.
I have simplified the code and the session is started when all checks are passed.
<?php
require('config.php');
if (isset($_POST['username']) and isset($_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
$UserQuery = "SELECT password FROM `members` WHERE username='$username'";
$result = mysqli_query($connection, $UserQuery);
$usernameTEST = mysqli_num_rows($result);
if($usernameTEST == 1){
$row = mysqli_fetch_row($result);
if(password_verify($password, $row[0])) {
session_start();
$_SESSION['username'] = $username;
header("Location: ../");
exit();
}
}
$error_message = "Incorrect login data";
}
<form class="login-form" method="POST">
<?php if(isset($error_message)){ ?><div class="mini-mes error"> <?php echo $error_message; ?> </div><?php } ?>
<span class="placeholder">username</span>
<input type="text" name="username" placeholder="username" required>
<span class="placeholder">password</span>
<input type="password" name="password" id="inputPassword" placeholder="password" required>
<button type="submit">Login</button>
<a class="form-link" href="register.php">Register</a>
</form>
Simplified the code to make it easier to understand.Ignoring checks for username and password etc. You're basically trying to set a session variable. That happens in login.php. Code for that is.
<?php
$username = "Umesh";
if (isset($_SESSION))
{
$_SESSION['username'] = $username;
}
else
{
session_start();
$_SESSION['username'] = $username;
}
print_r($_SESSION);
?>
In index.php you're trying to check the session status. The code is below.
if (isset($_SESSION['username'])){
session_id();
} else if (!isset($_SESSION)){
session_start();
}
print_r($_SESSION);
The above works for me on every browser and device. I even tested chrome on iphone. It seems to work fine. Please check this and see if it works. If not, we will have to check your webserver to see, what the issue is, with session objects on that system.
I verified that print_r ($_SESSION) was same in both cases.
Why you use session_id(). session I am always use this login system. I have no problem Desktop or Mobile session.
PHP code
<?php
session_start();
include 'connect.php';
if(isset($_POST['submit']))
{
$username = htmlspecialchars($_POST["uname"], ENT_QUOTES, "ISO-8859-1");
$username = stripslashes($username);
$password = htmlspecialchars($_POST["pass"], ENT_QUOTES, "ISO-8859-1");
$password = stripslashes($password);
$sql="SELECT * FROM member WHERE username= '$username' AND password='$password' AND status='1' ";
$result=mysql_db_query($dbname,$sql);
$row=mysql_fetch_row($result);
$num=mysql_num_rows($result);
$msg= "<h3 style='padding:0px;margin:0px;font-size:16px;background:#fff;padding:8px;'><font color='red'><center>Incorrect login data</center></font></h3>";
if($num>0)
{
$_SESSION['id'] =$row[0];
$_SESSION['fullName'] =$row[1];
$_SESSION['username'] =$row[2];
$_SESSION['password'] =$row[3];
$_SESSION['email'] =$row[4];
$_SESSION['userType'] =$row[5];
$_SESSION['status'] =$row[6];
header('location:index.php');
}
}
?>
My HTML Form
<form method="post">
<p><?php if (isset($_POST['submit'])) { echo $msg; } ?> </p>
<div>
<input type="text" name="uname" class="form-control" placeholder="Username..." required="" />
</div>
<div>
<input type="password" name="pass" class="form-control" placeholder="Password..." required="" />
<p align="right">Forgot it?</a></p>
</div>
<div>
<button class="btn btn-success submit" type="submit" name="submit"> Login <i class="fa fa-sign-in"></i></button>
</div>
</form>
Remove session_start(); in index.php
and Add this in your config.php
if (session_status() == PHP_SESSION_NONE)
{
session_start();
}
Going by your last comment I guess it is due to the query string you are using. Basically using password as a column name sometimes breaks the query as password is also a mysql keyword.
Also, regarding your session you can refer to session_id() vs session_regenerate_id() for further details regarding the functions. Session_id('login') basically sets the session id to login which works on your mobile device as this creates the session with the specific static id. However, you can try using session_regenerate_id(true) to see if it helps.
Also i tried executing the code by putting static value as username as follows
login.php
<?php
$username = "deadlock";
if (isset($_SESSION))
{
$_SESSION['username'] = $username;
}
else
{
session_start();
$_SESSION['username'] = $username;
}
print_r($_SESSION);
index.php
<?php
if (isset($_SESSION['username'])){
session_regenerate_id(true);
} else if (!isset($_SESSION)){
session_start();
}
print_r(session_id());
I started using index.php directly using the phone which printed the output as array() with no values.turned out that the Login.php file is not executed.after I explicitly executed Login.php the index.php printed the session array. Can you make sure that the login php file is properly executed.
Regards
Check that session_start() is placed before any browser output. I have found that Chrome on Desktop can be a lot more forgiving then other browsers as well as Mobile Chrome
This problem is generated with Chrome "Lite Mode" to reduce data load throw the Phone. If you use secret navigation so the lite mode is automatically disable an page work correctly. You have to disable "Lite Mode" on Chrome.
This is the final solution.
My problem was on server-side the session.save_path not definied to my server. Thanks a lot to all, who helped me :)
I created a simple login form. When I enter the correct username and password, it is always displaying the access denied message.
verify.php:
<?php
session_start();
$conn = mysqli_connect('localhost','root','') or die(mysqli_error());
mysqli_select_db($conn,'maindata') or die(mysqli_error($conn));
$uname=$_POST['username'];
$pass=$_POST['password'];
$password = md5($pass);
$result = mysqli_query($conn,"select * from users where username='$uname' and password='$password'")
or die("Could not execute the select query.");
$row = mysqli_fetch_assoc($result);
if(is_array($row) && !empty($row))
{
$validuser = $row['username'];
$_SESSION['valid'] = $validuser;
}
else
{
echo "<center></h1>Access Denied</h1></center>"."<br />";
echo "<center></h6>Please wait while you are redirected in 3 seconds</h6></center>"."<br />";
header('Refresh: 3; url=login.html');
}
if(isset($_SESSION['valid']))
{
header("Location:index.html");
}
login.html:
<?php
session_start();
if(isset($_SESSION['valid'])){
header("Location:index.html");
}
else
{
header("location:login.html");
}
?>
<form method="post" action="verify.php" class="login" class="contact_form">
<p>
<label for="login">Email:</label>
<input type="text" name="username" placeholder = "Enter Username Here...">
</p>
<p>
<label for="password">Password:</label>
<input type="password" name="password" placeholder = "*******">
</p>
<p class="login-submit">
<button type="submit" class="login-button">Login</button>
</p>
<p class="forgot-password">Forgot your password?</p>
</form>
You'r code loops it self, Login.html checks if a user is logged in ( which they arrent because they cant login ) and redirects them from Login.html to Login.html meaning that you never enter your php code. You should not check if the user is already logged in when trying to access the login page.
Also you should consider making a file to check if the user is logged in, it could be something like this:
checkloggedin.php
<?php
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
if($_SESSION['loggedin'] == false)
{
die(header("Location: ./index.php"));
}
?>
When you need to check if a user is logged in you can just start your pages off with:
<?php
include"checkloggedin.php"
?>
I am beginner in using php cookies and I am trying to make a simple login and logout form using cookies. everything was good but when I press logout link I can't logout. and to logout I have to delete the cookies from the browser.
log_in page
<?php
session_start();
if (isset($_COOKIE["Email"])){
header("location: home.php");
}
?>
<form method="post" action="log_in.php">
<font size="6">Sign In</font>
Email Address: </b></font><input type="text" name="Email" id="email" />
password: <input type="password" name="password" id="password" />
<input type="checkbox" name="rememberMe" value="1" id="check"/> Remember Me
<input type="submit" name="Login" id="sign" value="sign in" >
<?php
include 'db.php';
if(isset($_POST['Login'])){
$user_email = $_POST['Email'];
$password = $_POST['password'];
$check_user = "SELECT * FROM user where user_email = '$user_email' AND user_pass = '$password'";
$run = mysql_query($check_user );
if (mysql_num_rows($run) > 0){
$_SESSION['Email']= $user_email;
$_SESSION['start'] = time();
if(isset($_POST['rememberMe'])){
$expire=time()+120;
setcookie("Email", "Email", $expire);
}
else{
$expire=time()+30;
setcookie("Email", "Email", $expire);
}
echo "<script>window.open('home.php','_self')</script>";
}
else {
echo "<script>alert('email or password incorrect!')</script>";
}}
?>
home page
<?php
if (isset($_COOKIE["Email"])){
echo "Welcome " . $_COOKIE["Email"] . "!<br>";
echo 'logout';
}
else{
$now = time(); // Checking the time now when home page starts.
if ($now > $expire) {
session_destroy();
header("location: log_in.php");
}}
logout page
<?php
session_start();
unset($_SESSION['Email']);
session_destroy();
header("Location: log_in.php");
if(isset($_SESSION['Email'])):
setcookie($_SESSION['Email'],'',time()-7000000,'/');
endif;
?>
Your home page (code) doesn't have session_start(); least not in what you posted; it's required when using session_destroy(); it doesn't work on its own.
Give this a go:
Sidenote: $expire is undefined for home page code, so you will need to use the same or similar method as you used for the other pages.
<?php
if (isset($_COOKIE["Email"])){
echo "Welcome " . $_COOKIE["Email"] . "!<br>";
echo 'logout';
}
else{
$now = time(); // Checking the time now when home page starts.
if ($now > $expire) { // $expire is undefined
session_start(); // <= required
session_destroy(); // <= does not work on its own
header("location: log_in.php");
}
}
If you're looking to completely destroy the session, you can just use session_destroy()
<?php
session_start();
session_destroy();
?>
Or if you are just looking to unset the Email, you can use
<?php
session_start();
if(isset($_SESSION['Email']))
unset($_SESSION['Email']);
?>
So this is the code for page index.php: the $_SESSION["username"] variable seems to be not setted and I dunno why becuase in the login page I am using the isset control and the login is successful if I'm entering the right values;it is not if I am entering wrong username and password. I know I should "code" the password with md5 but right now that is not my problem :(
As you can see I'm redirecting to the index page after the login. From the index page I'm redirecting to the "home.php" page if the user already logged in. The problem is that after been doing the login,it keeps showing the login form and it is not redirecting me to home.php..
<?php session_start();
require_once "dbConn.php"; dbconnect();
if(isset($_SESSION["username"])){
echo $_SESSION["username"]; // TEST it never enters THERE!!!
echo'<p>Trasferimento alla home page</p>';
header("Refresh: 2; URL = home.php");
}
else{
echo'<div id=\"container\">';
echo'
<div id=\"content\">
<h2> You need to login :</h2>
<br/>
<form id="form1" name="form1" method="post" action="login.php">
<input type="text" name="username" id="username" />
<input type="password" name="password" id="password" />
<input type="submit" name="accedi" id="accedi" value="Accedi" />
</form>
<br/>
</div>';
include 'Footer.php';
echo'</div>';
}?>
And this is the login.php page:
<?php
require_once "dbConn.php"; dbconnect();
if(isset($_POST['username']) && isset($_POST['password'])) {
$username=mysql_real_escape_string($_POST['username']);
$pwd = mysql_real_escape_string($_POST['password']);
$query = mysql_query("SELECT * FROM user WHERE username='$username' AND password ='$pwd';");
if(mysql_num_rows($query) == 1){
$sessione =mysql_fetch_array($query);
$_SESSION["username"] = $sessione["username"];
echo $_SESSION["username"]; //TEST - it prints what I want: my username
$_SESSION["logged"] = true;
echo'Login effettuato con successo!';
header("Refresh: 2; URL = index.php");
}
else if((mysql_num_rows($query) == 0)){
echo'Utente non registrato o password errata';
header("Refresh: 2; URL = index.php");
}
}
?>
Thx all ;)
You forgot to call session_start() on your login page
<?php
require_once "dbConn.php"; dbconnect();
should be
<?php
session_start()
require_once "dbConn.php"; dbconnect();
after playing around with the script from all the help you people have given me I have come over another problem, when i click login on the login form it says: The page isn't redirecting properly Firefox has detected that the server is redirecting the request for this address in a way that will never complete.
Now i do admit i am no script pro but this is the only script i can find on how to use a phpbb forum database on a external site. so my question is whats wrong with all the .php file i am about to show you and how can i repair them?
login.php
<?php
//ob
ob_start();
//session
session_start();
if (isset($_SESSION['username']))
{
header("Location: main.php");
exit();
}
//connect
$error = 'Zaoby Database ERROR! connection failture!';
mysql_connect('localhost','root','') or die ($error);
mysql_select_db('phpbbtest') or die($error);
//include functions.php php script
require 'forums/includes/functions.php';
if (isset($_POST['login']))
{
//get form data
$username = addslashes(strip_tags(strtolower($_POST['username'])));
$password = addslashes(strip_tags($_POST['password']));
if (!$username||!$password)
echo "please enter a username and password<p />";
else
{
//find username
$find = mysql_query("SELECT * FROM phpbb_users WHERE username_clean='$username'");
if (mysql_num_rows($find)==0)
echo "username not found<p />";
else
{
while ($find_row = mysql_fetch_assoc($find))
{
// grab password hash for user
$password_hash = $find_row['user_password'];
}
$check = phpbb_check_hash($password, $password_hash);
if ($check==FALSE)
echo "Incorrect password<p />";
else if ($check==TRUE)
{
$_SESSION['username']=$username;
header("Location: main.php");
exit();
}
}
}
}
?>
<form action="login.php" method="POST">
Username:<br />
<input type="text" name="username"><p />
Password:<br />
<input type="password" name="password"><p />
<input type="submit" name="login" value="Log in">
</form>
main.php
<?php
//ob
ob_start();
//session
session_start();
$session_username = $_SESSION['username'];
if (!isset($_session_username))
{
header("Location: login.php");
exit();
}
else
{
echo "hello, ".$_session_username." <a href='logout.php'>Log out</a>";
}
ob_end_flush();
?>
logout.php
<?php
session_start();
session_destroy();
header("Location: login.php")
?>
P.S someone in my last question about this put something about using MySQLi instead of mysql_query and that i should put a ob_end_flush somewhere?
Try to use ob_start(); just after the
e.g. <?php ob_start();