简体   繁体   English

如何使用PHP创建会话?

[英]How to create sessions using PHP?

I am developing an application on android, which has a web server and a MySQL database. 我正在使用具有Web服务器和MySQL数据库的android开发应用程序。

The database contains the user names and the passwords. 该数据库包含用户名和密码。

I would like to implement the login procedure and establish a session between the android device and the web server using PHP. 我想实现登录过程并使用PHP在android设备和Web服务器之间建立会话。

Thanks in advance... 提前致谢...

From your question it seems like you just want to know how to do this in php, android or not. 从您的问题看来,您似乎只想知道如何在php,android中做到这一点。 You need to have users and passwords (hashed) stored in your DB, for instance when the user registers an account with you. 您需要将用户名和密码(哈希)存储在数据库中,例如,当用户向您注册帐户时。

session_start(); //Start the session.  Call on every page that will have the login.
$login = $_POST['login'];
$pass = $_POST['pass'];  //Get login and password the user has sent.

if (is_valid_user($login, $pass)) {
   //If user is valid, pass them along to the next page.
   $_SESSION['logged_in_user'] = $login; //Keep track of the username in the session
}
else echo "Not a valid login";

Okay... so for the login action you could have something like... 好吧...所以对于登录操作,您可能会遇到类似...

session_start();

if(isLoginCorrect())
{
    $_SESSION['logged_in'] = true;
}

Where isLoginCorrect is a function which verifies the username and password are correct. 其中isLoginCorrect是用于验证用户名和密码正确的函数。 Then you can have some logic in your template files with stuff like this... 然后,您可以在模板文件中包含一些类似这样的逻辑...

<?php if($_SESSION['logged_in']): ?>
    You are logged in
<?php else: ?>
    You aren't logged in
<?php endif; ?>

Then to logout you can use, session_destroy() or unset($_SESSION['logged_in']); 然后可以注销,使用session_destroy()或unset($ _ SESSION ['logged_in']);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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