简体   繁体   中英

Use cookie in a PHP login page

I'm create a form to login with PHP (and, obviously, MySQL). This is the PHP code:

<?php
$host = 'localhost';
$db_user = 'root';
$db_password = '';
$db_name = 'learningsql';

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

if (strlen($username) < 1 || strlen($password) < 1){
    echo "Username or password incorrect";
} else {
    $username = trim(filter_var($_POST['username'], FILTER_SANITIZE_STRING));
    $password = trim(filter_var($_POST['password'], FILTER_SANITIZE_STRING));
    $hash = hash("sha512",$username. $password);
    $connection = mysqli_connect($host, $db_user, $db_password);
    $db = mysqli_select_db($connection, $db_name);
    $result = mysqli_query("SELECT * FROM utenti WHERE username = '$username' AND password = '$hash'");
    if(mysqli_num_rows($result)==0{
        die("Username or password incorrect");
    } else{
        $_SESSION['loggedin']=1;
        $user = mysqli_fetch_array($result);
        header("location:loggato.php");

    }
}
?>

The .html page with form contains PHP code for session:

<?php
session_start();
if(isset($_SESSION['loggedin']))
    header('location:loggato.html');
?>

But, I have a problem. I use at the moment the login's sessions, but I wanna use cookie. How? Thanks for the answers.

The PHP session stores a cookie to enable the session. With the function session_start() you start the session (duhh) and the session will set a cookie called PHPSESSID. Check it in your browser with some dev tool.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM