2012-03-20 207 views
0

我必須創建一個簡單的站點,您可以登錄和退出,如果用戶登錄,他們會看到一些他們不能訪問的功能。我對網絡開發不太擅長,但是我已經設法把這些東西結合起來,這似乎已經奏效了。我決定在登錄和註銷時不想將用戶重定向到另一個頁面,所以這使我更難理解。PHP會話登錄和註銷

我只是想知道我是否會以正確的方式開始並銷燬會話,如果任何人都可以給我任何指示,讓它更好,如果這甚至是可能的。

<?php 


if(isset($_POST['logout'])) { 
    session_destroy(); 
    } 
} 
    session_start(); 
if(!isset($_SESSION['username'])) { 
    if (!empty($_POST['username']) && !empty($_POST['password'])) { 
     $result = mysql_query("SELECT * FROM users WHERE username ='$_POST['username']' AND password = '$_POST['password']'"); 
     if(mysql_num_rows($result)) 
      $_SESSION['username'] = $_POST['username']; 
     } 
     else { 
      echo ""; 
     } 
    } 
} 
?> 
     <?php if(!isset($_SESSION['username'])) { 
       echo '<div id = "account"> 
         <form name="input" action="index.php" method="post"> 
          Username:<input type="text" name="username" /> Password:<input type="password" name="password" /> 
          <input type="submit" value="GO!" /> 
         </form> 
      } 
      else { 
        echo "Signed in" 
        <form name='logout' action='index.php' method='post'> 
        <input type='submit'value='Reset' name='logout'/> 
        "; 
      } ?> 
      <?php 
      $test = mysql_query("SELECT * FROM posts ORDER BY post_id DESC"); 
      if($test) { 
       while($row = mysql_fetch_array($test)) { 
        echo '<div class="posts">'; 
         echo "$row[post]"; 
        echo '</div>'; 
       } 
      } 
+1

將session_start()添加到PHP代碼的最頂部! 。順便說一句,你爲什麼要加兩次? – 2012-03-20 18:17:25

+0

試試這個http://www.w3schools.com/php/php_sessions.asp – 2012-03-20 18:18:02

+0

對不起,加兩次? – W0lf7 2012-03-20 18:21:44

回答

1

我工作了你的代碼並做了很多改變。我試着添加很多評論,以便更容易理解。希望沒有語法錯誤,但我實際上無法進行測試,因爲我沒有MySQL數據庫等。

這是你的主要代碼:

<?php 
//When you are developing and testing, set the error level as high as possible. 
//This will help you find problems early. A well written program will have no errors and warnings, ever. 
error_reporting(E_ALL | E_STRICT); 

//Starting the session should be one of the first things your code does, and should only be done once. 
session_start(); 

require 'config.php'; 

if(isset($_POST['logout'])) 
{ 
    //I don't think there is any reason to check if username is set. If you are logging out, just destroy. 
    session_destroy(); 

    //Also unset the session username since session_destroy() does not affect existing globals. 
    unset($_SESSION['username']); 
} 
//I changed this to elseif, because there should not be a condition where you are logging out and checking for a login. 
elseif(!isset($_SESSION['username'])) 
{ 
    //You should not assume that variables are set, because accessing them if they are not set 
    //will cause a warning. I've added isset(). 
    if(isset($_POST['username']) && !empty($_POST['username']) && isset($_POST['password']) && !empty($_POST['password'])) 
    { 
     //You absolutely MUST escape your strings or you are at risk of SQL injection. 
     //Use mysql_real_escape_string() for this. 
     $username = mysql_real_escape_string($_POST['username']); 
     $password = mysql_real_escape_string($_POST['password']); 
     $result = mysql_query("SELECT * FROM members WHERE username ='$username' AND password = '$password'"); 

     //You should probably check that the value === 1 here. 
     //I'm assuming it should always be 1 or 0. 
     if(0 === mysql_num_rows($result)) 
     { 
      $_SESSION['username'] = $username; 
     } 
     else { 
      echo "Fail :("; 
     } 
    } 
    //If you put an else statement here, you could print an error for if the username was not specified. 
} 

//You should not have SQL queries in your template, so I moved this here. 
//Notice that I'm just setting $posts to the data. It's best to just pass 
//the data, and format it in the template. 
$result = mysql_query("SELECT * FROM posts ORDER BY post_id DESC"); 
if($result) 
{ 
    $posts = array(); 

    while($row = mysql_fetch_array($result)) 
    { 
     $posts[] = $row['post']; 
    } 
} 
else 
{ 
    $posts = false; 
} 

//Try to separate code logic from templates. 
//Your program is small, so it's not that important, but I would do it anyway. 
require 'template.php'; 
?> 

這是你的模板代碼,它應該在一個名爲的template.php新文件:

<div id = "container"> 
    <h1>#HookyGear Bay</h1> 
    <div id = "login"> 
     <?php if(!isset($_SESSION['username'])) { 
       echo '<div id = "accountBox"> 
         <form name="input" action="index.php" method="post"> 
          Username:<input type="text" name="username" /> Password:<input type="password" name="password" /> 
          <input type="submit" value="Sign In" /> 
         </form> 
       </div>'; 
      } 
      else { 
        echo "<div id='accountBox'>You Are logged in as ".$_SESSION['username']." 
        <form name='logout' action='index.php' method='post'> 
        <input type='submit'value='Reset' name='logout'/> 
        </div> "; 
      } ?> 
    </div> 

     <div id = "content"> 
      <?php 

      if(false !== $posts) 
      { 
       foreach($posts as $post) 
       { 
        echo '<div class="blogPosts">'.$post.'</div>'; 
       } 
      } 
      else { ?> 
       <div class="blogPosts"><?php echo "no blog posts"; ?></div> 
      <?php 
      } 
      ?> 

      <div style="clear:both;"></div> 
     </div> 
</div> 
+0

謝謝,這似乎工作正常,但是當我點擊註銷按鈕,實際上需要兩次點擊註銷。 – W0lf7 2012-03-20 18:56:58

+0

更正它執行會話銷燬,但重置按鈕仍然存在,它只是不顯示它應該什麼,因爲它需要另一個頁面重新加載。有沒有辦法解決? – W0lf7 2012-03-20 19:10:02

+0

是的,我對註銷代碼做了輕微修改。我忘記清除$ _SESSION ['用戶名']。 – 2012-03-20 19:11:21

0

可能不是檢查$ _ POST ['logout']每次頁面加載時,您都可以將用戶重定向到不同的註銷特定頁面。

0

您可以嘗試撥打session。就像我

這將檢查您是否連接到你的數據庫中,我將其命名爲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 
} 

?> 

希望這有助於