简体   繁体   中英

PHP - Session doesnt work on mobile

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";
  1. Clear data/cookies on your mobile browser (or just go into incognito mode). This will make sure you "start from scratch".

  2. 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.

  3. 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 (ie $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();
}

Cookie肯定适用于移动浏览器。

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

&lt;?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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM