【问题标题】:PHP logging outPHP 注销
【发布时间】:2011-03-12 00:31:23
【问题描述】:

我正在观看 Lynda.com 学习 PHP 2 的视频,但遇到了一个问题,因为讲师似乎忽略了告诉我们他在视频中执行的步骤之一。我已经在http://www.youtube.com/watch?v=fFKgAa7RAjo 上传了相关视频,但也会描述这个问题。在视频的 6:40,登录到我们的应用程序后,他到达了 public/admin/index.php,其中有两个链接。一个链接允许他“查看日志文件”,这会将他带到 public/admin/logfile.php,另一个链接允许他注销。他没有告诉我们如何建立这些链接。我显然可以创建一个链接来查看日志文件

 <a href="logfile.php">View Logfile</a>

但我不知道如何制作可以让我退出的链接,因为这显然会涉及一些 PHP。

我在login.php 文件、index.php 文件(登录后重定向到index.php)和functions.php 文件下面包含了。你知道我将如何退出吗?

这是 login.php 文件

<?php

require_once("../../includes/initialize.php");

if($session->is_logged_in()){
    redirect_to("index.php");
}

//Remember to give your form's submit tag a name="submit" attribute
if (isset($_POST['submit'])) {//Form has been submitted.

$username = trim($_POST['username']);
$password = trim($_POST['password']);

//Check database to see if username/password exist

$found_user = User::authenticate($username, $password);

if ($found_user) {
    $session->login($found_user);
    log_action('Login', "{$found_user->username} logged in.");
    redirect_to("index.php");
} else {
    //username/password combo was not found in the database
    $message = "Username/password combination incorrect.";
} 
} else {//Form has not been submitted.
    $username = "";
    $password = "";
    }
?>

<?php include_layout_template('admin_header.php'); ?>

        <h2>Staff Login</h2>
        <?php echo output_message($message); ?>

        <form action="login.php" method="post">
            <table>
                <tr>
                    <td>Username:</td>
                    <td>
                        <input type="text" name="username" maxlength="30" value="<?php
                        echo htmlentities($username); ?>" />
                    </td>
                </tr>
                <tr>
                    <td>Password:</td>
                    <td>
                        <input type="password" name="password" maxlength="30" value="<?php
                        echo htmlentities($password); ?>" />
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <input type="submit" name="submit" value="login" />
                    </td>
                </tr>
            </table>
        </form>
        </div>
        <?php include_layout_template('admin_footer.php'); ?>

函数.php

<?php

function strip_zeros_from_date( $marked_string=""){
//first remove the marked zeros
$no_zeros = str_replace('*0', '', $marked_string);
//then remove any remaining marks
$cleaned_string = str_replace('*', '', $no_zeros);
return $cleaned_string;

}

function redirect_to( $location= NULL) {
    if($location != NULL) {
    header("Location: {$location}");
    exit;
    }

}

function output_message($message=""){
if (!empty($message)) {
return "<p class=\"message\">{$message}</p>";
} else {
    return "";
    }
}

function __autoload($class_name) {
  $class_name = strtolower($class_name);
  $path = LIB_PATH.DS."{$class_name}.php";
  if(file_exists($path)){
  require_once($path);
  } else {
  die("The file {$class_name}.php could not be found.");
  }
}

function include_layout_template($template=""){
include(SITE_ROOT.DS.'public'.DS.'layouts'.DS.$template);
}

function log_action($action, $message=""){
$logfile = SITE_ROOT.DS.'logs'.DS.'log.txt';
$new = file_exists($logfile) ? false : true;
if($handle = fopen($logfile, 'a')) { //apppend
$timestamp = strftime("%Y-%m-%d %H:%M:%S", time());
$content = "{$timestamp} | {$action}: {$message}\n";
fwrite($handle,$content);
fclose($handle);
if($new) {chmod($logfile, 0755); }
} else {
 echo "Could not open log file for writing.";
}
}

?>

索引.php

<?php

require_once('../../includes/initialize.php');

if (!$session->is_logged_in()) { redirect_to("login.php"); }
?>

<?php include_layout_template('admin_header.php'); ?>

        <h2>Menu</h2>

        </div>


<?php include_layout_template('admin_footer.php'); ?>

更新

初始化.php

<?php

//Directory_separator is a PHP pre-defined constant
// (\ for windows, / for Unix)

defined('DS') ? null : define('DS', DIRECTORY_SEPARATOR);

defined('SITE_ROOT') ? null : 
 define('SITE_ROOT', DS.'hsphere'.DS.'local'.DS.'home'.DS.'c263430'.DS.'quoralist.com');
// define('SITE_ROOT', realpath(dirname(__FILE__).'/../'));

 //echo SITE_ROOT."<br/>";

 defined('LIB_PATH') ? null : define('LIB_PATH', SITE_ROOT.DS.'includes');
// die(LIB_PATH);

 //echo LIB_PATH."<br/>";

require_once(LIB_PATH.DS."config.php");
require_once(LIB_PATH.DS."functions.php");
require_once(LIB_PATH.DS."session.php");
require_once(LIB_PATH.DS."database.php");
require_once(LIB_PATH.DS."database_object.php");
require_once(LIB_PATH.DS."user.php");

//echo("You die here");

?>

用户.php

<?php

require_once(LIB_PATH.DS.'database.php');

class User extends DatabaseObject{

protected static $table_name="users";
public $id;
public $username;
public $password;
public $first_name;
public $last_name;

public function full_name() {
if(isset($this->first_name) && isset($this->last_name)) {
return $this->first_name . " " . $this->last_name;
} else {
  return "";
}
}

public static function authenticate($username="",$password="") {
global $database;
$username = $database->escape_value($username);
$password = $database->escape_value($password);
$sql = "SELECT * FROM users ";
$sql .= "WHERE username = '{$username}' ";
$sql .= "AND password = '{$password}' ";
$sql .= "LIMIT 1";
$result_array = self::find_by_sql($sql);
return !empty($result_array) ? array_shift($result_array) : false; 

}

//common database methods

public static function find_all(){
return self::find_by_sql("SELECT * FROM ".self::$table_name);

}

public static function find_by_id($id=0) {
global $database;
$result_array = self::find_by_sql("SELECT * FROM ".self::$table_name." WHERE id={$id} LIMIT 1");
return !empty($result_array) ? array_shift($result_array) : false; 
}

public static function find_by_sql($sql=""){
global $database;
$result_set = $database->query($sql);
$object_array = array();
while ($row = $database->fetch_array($result_set)) {
$object_array[] = self::instantiate($row);
}
return $object_array;
}




private static function instantiate($record){

$object = new self;
//$object->id = $record['id'];
//$object->username = $record['username'];
//$object->password = $record['password'];
//$object->first_name = $record['first_name'];
//$object->last_name = $record['last_name'];

foreach($record as $attribute=>$value) {
if($object->has_attribute($attribute)) {
$object->$attribute = $value;
}
}
return $object;
}

private function has_attribute($attribute) {
$object_vars = get_object_vars($this);
return array_key_exists($attribute, $object_vars);
}

}




?>

Session.php

<?php


class Session {

    private $logged_in=false;
    public $user_id;

    function __construct() {
    session_start();
    $this->check_login();
    if($this->logged_in){
    //actions to take right away if user is logged in
    } else {
    //actions to take right away if user is not logged in
    }
    }

    public function is_logged_in() {
    return $this->logged_in;
    }

    public function login($user) {
    //database should find user based on username/password
    if($user){
    $this->user_id = $_SESSION['user_id'] = $user->id;
    $this->logged_in = true;
    }
    }

    public function logout(){
    unset($_SESSION['user_id']);
    unset($this->user_id);
    $this->logged_in = false;
    }

    private function check_login(){
    if(isset($_SESSION['user_id'])){
    $this->user_id = $_SESSION['user_id'];
    $this->logged_in = true;
    } else {
     unset($this->user_id);
     $this->logged_in = false;
    }
    }
}

$session = new Session();

?>

【问题讨论】:

  • 拥有initialize.php 和/或定义User 类的位置会有所帮助
  • @NullUserException 谢谢。我添加了 initialize.php 、 user.php (定义用户类)和 session.php

标签: php


【解决方案1】:
 <?php
    session_start();
    session_destroy();
 ?>

这应该销毁存储在会话中的所有变量。这确实是原始的注销,但它应该可以工作。完成后,只需重定向到“index.php”或您想要的任何页面。

【讨论】:

  • 非常感谢。我是一个完全的新手。有没有办法可以将该注销放入将重定向到 login.php 的链接中?
  • 只需添加 header("login.php");销毁会话后。好像你有一个方便的重定向功能,所以redirect_to(“login.php”)。所以你会有一个 logout.php 页面,它是
  • 谢谢,但是我会点击注销的 index.php(我登录后到达的位置)上的链接是什么样的?如何通过点击index.php上的链接让logout.php文件中的代码运行?
  • 与您建立任何链接的方式相同。 注销
  • @Alex Logout index.php 上的这个链接可以运行 logout.php 吗?
猜你喜欢
  • 1970-01-01
  • 2018-01-29
  • 2012-05-23
  • 2014-11-16
  • 2012-08-25
  • 2014-02-14
  • 2011-05-31
  • 2017-06-03
  • 2013-07-29
相关资源
最近更新 更多