首页 > 技术文章 > 代码练习之 登陆 PHP会话控制 session cookie

perseverancevictory 2015-02-05 01:09 原文

log.html

<html>
    <head><title>Home Page</title></head>
    <body>
        <form action="login.php" method="post">
            <input type="text" name="name">
            <input type="submit" value="Log in">
            </form>
    </body>
</html>

login.php

<?php
session_start();
if (isset($_POST['name'])) {
    $name=$_POST['name'];
    $connect=@new mysqli('localhost','root','123','mytestdb');
    if (mysqli_connect_errno()) {
        echo "Connection to database failed:".mysqli_connect_errno();
        exit;
        # code...
    }
    $query="select*from users where name='$name'";

    $result=$connect->query($query);
    if ($result->num_rows) {
        $_SESSION['name']=$name;
        # code...
    }

    $connect->close();
    # code...
}
if (isset($_SESSION['name'])) {
    echo "You are logged in as ".$_SESSION['name']."<br/>";
    echo "<a href='logout.php'>Log out</a>"."<br/>";
    # code...
}else{
    if (isset($name)) {
        echo "Could not log in"."<br/>";
        # code...
    }else{
        echo "You are not logged in"."<br/>";
    }
}

logout.php

<?php
session_start();
unset($_SESSION['name']);
session_destroy();

if (empty($_SESSION['name'])) {
    echo "You have log out!";
    # code...
}

 

推荐阅读