2011-03-12 7 views
2

Lynda.com에서 PHP 2 비디오를 배우면서 강사가 동영상에서 수행하는 단계 중 하나를 수행하는 것을 간과 한 것 같습니다. 관련 동영상을 여기 http://www.youtube.com/watch?v=fFKgAa7RAjo에 업로드했지만 문제를 설명합니다. 비디오 6시 40 분에 우리 애플리케이션에 로그인 한 후, 두 개의 링크가있는 public/admin/index.php에 도착합니다. 하나의 링크는 그를 "view log file"으로 하여금 그를 public/admin/logfile.php로 데려 갈 수 있도록 허용하고 다른 링크는 그를 로그 아웃시킬 수있게합니다. 그는이 링크를 만드는 방법을 우리에게 말하지 않습니다. 나는 분명히 로그 파일을PHP 로그 아웃

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

을 볼 수있는 링크를 만들 수 있지만 분명히 몇 가지 PHP를 포함하기 때문에 나는 나를 기록합니다 링크를 만드는 방법을 알고하지 않습니다.

다음은 login.php 파일, index.php 파일 (로그인 한 후 index.php로 리디렉션 됨) 및 functions.php 파일입니다. 이걸 어떻게 내가 로그 아웃 할 수 있는지 아십니까?

은 Functions.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 

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'); ?> 

업데이트

Initialize.php

0,123,516 Index.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 

//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"); 

?> 

User.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(); 

?> 
+0

'initialize.php' 및/또는'User' 클래스가 정의되어있는 곳이라면 도움이 될 것입니다. – NullUserException

+0

@NullUserException 감사합니다. initialize.php, user.php (사용자 클래스 정의) 및 session.php를 추가했습니다. – Leahcim

답변

3
<?php 
    session_start(); 
    session_destroy(); 
?> 

. 정말 원시적 인 로그 아웃이지만 작동해야합니다. 그런 다음 "index.php"또는 원하는 페이지로 리디렉션하십시오.

+0

대단히 고마워요. 나는 완전 초보자 야. login.php로 리디렉션되는 링크에 로그 아웃 할 수있는 방법이 있습니까? – Leahcim

+0

헤더 추가 ("login.php"); 세션을 파괴하면 redirect_to ("login.php") 같은 리디렉션 기능이있는 것처럼 보입니다. 그러면 Alex

+0

고맙습니다.하지만 로그 아웃하기 위해 클릭 한 index.php (로그인 한 후 도착하는 위치)의 링크 모양은 어떻게됩니까? index.php의 링크를 클릭하여 logout.php 파일에서 코드를 실행하는 방법은 무엇입니까? – Leahcim