2015-11-20 76 views
3

好了,我的主登录PHP页面我有这样的:在最高层我有这个会话保存登录我出去

<?php 
session_start(); 
require 'connect.php'; 

if(mysqli_connect_errno()) { 
    echo 'Failed to Connect to MySQL' . mysqli_connect_errno(); 
} 

if(isset($_POST['submit'])) { 
    //Variables 
    $user = $_POST['username']; 
    $pass = md5 ($_POST['password']); 

    //prevent MySQL Inject 
    $user = stripslashes($user); 
    $pass = stripslashes($pass); 

    $query = mysqli_query($con, "SELECT * FROM tech WHERE username = '$user' and password = '$pass'") or die("Can not query the DB"); 
    $count = mysqli_num_rows($query); 

    if($count == 1) { 
     $_SESSION['username'] = $user; 
     $url = 'home.php'; 
     echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.$url.'">'; 
    } else { 
     echo 'Username and Password do not match! Try Again'; 
     $url = 'carelogin.php'; 
     echo '<META HTTP-EQUIV=Refresh CONTENT="2; URL='.$url.'">'; 
     session_destroy(); 
    } 
} 
?> 

,然后在每一页上。

<?php 
session_start(); 
require_once 'connect.php'; 

if(!isset($_SESSION['username'])) { 
    echo "<h1>You are not an authorised user</h1>"; 
    $url = 'carelogin.php'; 
    echo '<META HTTP-EQUIV=Refresh CONTENT="1; URL='.$url.'">'; 
} else { 
} 
?> 

约30秒左右,从没有触及我的鼠标在任何这些页面后,如果我点击刷新或如果我去向前或向后,它让我登录了。我不明白。我有所有的会议设置,但在30秒内我退出。

有人请修改我的代码,让我保持登录,直到我点击注销谢谢你们!

+3

你的代码真的很糟糕,容易受到sql注入 –

+0

你有没有在所有的浏览器尝试..? –

+0

使用'>'?出于好奇,你从中得到什么好处? – Rasclatt

回答

-1

编辑:删除我的第一个建议

或者试试我的代码

这将检查您是否连接到你的数据库中,我将其命名为connect.inc.php

<?php 
if(!mysql_connect('localhost', 'root', '')|| !mysql_select_db('byp_db')) 
{ 
die(mysql_error()); 
} 
?> 

接下来,我创建我的core.inc.php它将检查你是否已经在session你将使用loggedin()方法在那

<?php 
error_reporting(E_ALL^E_NOTICE); 
ob_start(); 
session_start(); 
$current_file = $_SERVER['SCRIPT_NAME']; 
$http_referer = $_SERVER['HTTP_REFERER']; 

function loggedin() { 

     if(isset($_SESSION['user_p_info_id'])&&!empty($_SESSION['user_p_info_id'])) { 
    return true; 

}else { 
    return false; 
} 
} 

function getuserfield($field){ 
$query = "SELECT `$field` FROM `user_p_info` where `user_p_info_id`='".$_SESSION['user_p_info_id']."'"; 
if($query_run = mysql_query($query)){ 

    if($query_result = mysql_result($query_run, 0, $field)){ 
     return $query_result; 
    } 

} 
} 
?> 

下一个是您将创建登录表格

<?php 

require 'connections/connect.inc.php'; 
require 'connections/core.inc.php'; 

if(isset($_POST['uname']) && isset($_POST['password'])){ 

$uname = $_POST['uname']; 
$pword = $_POST['password']; 

//echo $uname; 
//echo $pword; 
if(!empty($uname)&&!empty($pword)){ 
$query_login = "SELECT * FROM user_a_info where username = '$uname' and password = '$pword'"; 
//echo $query_login; 

$query_result = mysql_query($query_login); 
$num_rows = mysql_num_rows($query_result); 
    if($num_rows == 0){ 

?> 

<script type="text/javascript"> 
alert("Invalid Data !"); 
</script> 


<?php     
    }else{ 

     //echo "validated"; 
     $user_p_info_id = mysql_result($query_result, 0, 'user_p_info_id'); 
     $_SESSION['user_p_info_id']=$user_p_info_id; 
     header('Location: index.php'); 


} 
} 
} 

?> 

<form action="login.php" method="POST"> 
<p> USERNAME : <input type="text" name="uname" /> </p> 
<p> PASSWORD : <input type="password" name="password" /> </p> 
<p> <input type="submit" value="LOGIN" /> </p> 
</form> 

然后你的日志输出功能看起来像这样

<?php 

require 'core.inc.php'; 
session_destroy(); 
header('Location: ../index.php'); 
?> 

只需要注意的是,如果你想查询不管你是在session还是没有,只要把这个条件就可以了

<?php 
require 'connections/connect.inc.php'; 
require 'connections/core.inc.php'; 

if(loggedin()) { 
// Do something 
} 

?> 

希望这有助于

+1

为什么使用'mysql_'进行演示?OP至少在'mysqli_'的正确路径,他们只是用错了,这是使用'mysql_'倒退 – Rasclatt

+0

@Rasclatt ohh对不起,我只是发布和演示简单登录与会议我没有注意到这是我的旧学校项目使用mysql – FrostyPinky

+0

@FrostyPinky我认为session_start()始终必须位于顶端,我想我错了。 – Kmiles1990123

2

请增加会话超时与此:

// server should keep session data for AT LEAST 1 hour 
ini_set('session.gc_maxlifetime', 3600); 

// each client should remember their session id for EXACTLY 1 hour 
session_set_cookie_params(3600); 

session_start(); // ready to go! 
1

我想你会发现,人们会建议对这种事情的框架,但是,如果你要尝试登录,您可能希望将脚本更彻底地分离出来,以适应更清晰和更可扩展的代码。此外,确保在测试站点时(在关闭实时环境中的错误报告时),使用ini_set("display_errors",1); error_reporting(E_ALL);以上的session_start()来警告页面上发生的任何错误/警告。

这是一个比你有更复杂的代码,但它应该保护你免受注射。请注意,每个文件的所有文件夹都应与域根相关。另请注意,您需要使用password_hash()函数将所有密码存储在数据库中。你可以使用其中的一部分,所有这些,都不是这样,但是如果你确实使用它,请确保查看PHP手册以了解所有这些功能:

/core.processor/classes/ class.DatabaseConfig。PHP

// This is your database. Fill out the credentials in the connect() method 
// I use PDO because I think personally it's easier to use 
class DatabaseConfig 
    { 
     private static $singleton; 

     public function __construct() 
      { 
       if(empty(self::$singleton)) 
        self::$singleton = $this->connect(); 

       return self::$singleton; 
      } 
     // This is the method that creates the database connection 
     public function connect($host = "localhost", $username = "username", $password = "password", $database = "database") 
      { 
       // Create connection options 
       // 1) Make PDO Exception errors, 2) Do real binding 3) By default prefer fetching associative arrays 
       $opts = array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, 
            PDO::ATTR_EMULATE_PREPARES => false, 
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC); 
       $conn = new PDO('mysql:host='.$host.';dbname='.$database, $username, $password,$opts); 
       // Send back the database connection. You can use a "utf-8" character setting here as well... 
       return $conn; 
      } 
    } 

/core.processor/classes/class.QueryEngine.php

// This is a simple query engine. It allows for binding (or not binding) 
class QueryEngine 
    { 
     private $results; 

     private static $singleton; 

     public function __construct() 
      { 
       if(empty(self::$singleton)) 
        self::$singleton = $this; 

       return self::$singleton; 
      } 
     // This method sends queries to your database 
     public function query($sql = false,$bind = false) 
      { 
       $this->results = 0; 
       // Create database connection 
       $db  = new DatabaseConfig(); 
       // Attempt to connect and fetch data 
       try { 
         // Bind or not bind, provided there is a bind array 
         // This is important to look up! 
         if(!empty($bind)) { 
           $query = $db ->connect() 
               ->prepare($sql); 
           $query->execute($bind); 
          } 
         else { 
           $query = $db ->connect() 
               ->query($sql); 
          } 

         $this->results = $query; 
        } 
       catch (PDOException $e) 
        { 
         die($e->getMessage()); 
        } 

       return $this; 
      } 
     // This method will fetch an the associative array if used with select statement 
     public function fetch() 
      { 
       while($row = $this->results->fetch()) 
        $result[] = $row; 

       return (!empty($result))? $result : 0; 
      } 
    } 

/core.processor/classes/class.HeaderProcessor.php

// This class deals with functions that should happen before the page outputs to the browswer 
class HeaderProcessor 
    { 
     private static $userData; 

     // This method just sits and waits for actions to happen 
     // This method should expand with whatever you plan to do in the future 
     public static function eventListener($array = array()) 
      {  
       if(isset($array['action'])) { 
         if($array['action'] == 'login') { 
           if(self::getLogin($array['username'],$array['password'])) { 
             if(self::setSession(self::$userData)) { 
               $_SESSION['password'] = NULL; 
              } 
             header("Location: home.php"); 
             exit; 
            } 
          } 
         elseif($array['action'] == 'logout') { 
           session_destroy(); 
           header("Location: loggedout.php"); 
           exit; 
          } 
        } 
      } 
     // Process login 
     private static function getLogin($user,$pass) 
      { 
       $query  = new QueryEngine(); 
       $getUser = $query ->query("SELECT * FROM `users` WHERE `username` = :0",array($user)) 
             ->fetch(); 

       if($getUser == 0) 
        return false; 

       self::$userData = $getUser[0]; 
       // Verify the password hash (this is why you need to store your passwords differently in your db 
       return password_verify($pass,$getUser[0]['password']); 
      } 
     // Assign session variables 
     private static function setSession($userData) 
      { 
       $_SESSION = array_filter(array_merge($userData,$_SESSION)); 

       return true;  
      } 
     // This can set options for your site, I just threw in timezone 
     // as well as the class autoloader 
     public static function initApp($settings = false) 
      { 
       $timezone = (!empty($settings['timezone']))? $settings['timezone'] : 'America/Los_Angeles'; 
       include_once(FUNCTIONS_DIR."/function.autoLoader.php"); 

       date_default_timezone_set($timezone); 
      } 
    } 

/core.processor/functions/function.autoLoader.php

// This function will auto load your classes so you don't have to always 
// include files. You could make a similar function to autoload functions 
function autoLoader($class) 
    { 
     if(class_exists($class)) 
      return true; 

     if(is_file($include = CLASS_DIR.'/class.'.$class.'.php')) 
      include_once($include); 
    } 

/config.php

/*** This config is located in the root folder and goes on every page ***/ 

// Start session 
session_start(); 
// Define common places 
define("ROOT_DIR",__DIR__); 
define("CLASS_DIR",ROOT_DIR.'/core.processor/classes'); 
define("FUNCTIONS_DIR",ROOT_DIR.'/core.processor/functions'); 
// Require the page initializer class 
require_once(CLASS_DIR."/class.HeaderProcessor.php"); 
// Initialize the autoloader for classes 
// Load timezone 
// You can put any other preset in this method 
HeaderProcessor::initApp(); 
// Here is where you put in events like login, logout, etc... 
HeaderProcessor::eventListener($_POST); 
// Use this function to help load up classes 
spl_autoload_register('autoLoader'); 

/login.php

<?php 
// add in the config file 
require(__DIR__."/config.php"); 
?><!DOCTYPE html> 
<html> 
<meta charset="UTF-8"> 
<title>My Login</title> 
<head> 
</head> 
<body> 
    <form id="loginForm" method="post" action=""> 
     <input name="username" type="text" /> 
     <input name="password" type="password" /> 
     <input name="action" type="hidden" value="login" /> 
     <input type="submit" value="LOGIN" /> 
    </form> 
</body> 
</html> 
0

首先,你需要找出你的PHP设置是什么:

创建一个info.php文件在你的p的根目录下roject有下面几行:

<?php 
phpinfo(); 

加载浏览器上的网页并找到以下变量:

session.gc_maxlifetime 

这可能是您的会话已设置的时间很短的时间后到期(默认大约24分钟,但显示的值以秒为单位 - 1440)。在您的情况下,该值可能等于30

要将其更改为您的首选时间长度,您需要按如下方式更改php设置(确保您具有在服务器上进行写入更改的权限):

找到您的php.ini设置文件。它可能位于以下位置的Linux服务器上:

/etc/php/7.0/apache2/php.ini 

你应该打开这个文件,你选择的编辑器,例如在命令行上纳米如下:

sudo nano /etc/php/7.0/apache2/php.ini 

找到以下变量:

session.gc_maxlifetime 

更改相应的值,以一个较长的时间跨度如1天,你可以计算如下:1天* 24小时* 60分钟* 60secs = 86400secs

其设置如下:

session.gc_maxlifetime = 86400 

保存文件并重新启动Apache从您的命令行,如下所示:

sudo service apache2 restart 

刷新你info.php的文件和变化应该已经生效。