2015-11-20 85 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的文件和變化應該已經生效。