Skip to content

Instantly share code, notes, and snippets.

@tranchausky
Last active April 21, 2025 09:20
Show Gist options
  • Save tranchausky/71360caeaee3adddf691a85b1f5ba9e6 to your computer and use it in GitHub Desktop.
Save tranchausky/71360caeaee3adddf691a85b1f5ba9e6 to your computer and use it in GitHub Desktop.
login logout php basic
<?php
session_start();
//$php_main = 'admin.php';
$host = $_SERVER['HTTP_HOST'];
$scriptName = $_SERVER['SCRIPT_NAME'];
$atinput_linkUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http");
$atinput_linkUrl .= "://$host".$scriptName;
//http://localhost:81/test/login-basic/main.php
//var_dump($atinput_linkUrl);
if ($_SERVER["REQUEST_METHOD"] == "GET" && isset($_GET['logout'])) {
session_start();
session_destroy();
header("Location: $atinput_linkUrl");
exit;
}
// Check login
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_SESSION['last_attempt']) && time() - $_SESSION['last_attempt'] < 1) {
$remaining = 60 - (time() - $_SESSION['last_attempt']);
$error = "Please wait $remaining seconds before trying again.";
} else {
$input_password = $_POST['password'];
$_SESSION['last_attempt'] = time(); // Record time of this attempt
$correct_password = "secret123"; // Change this to your real password
if ($input_password === $correct_password) {
unset($_SESSION['last_attempt']); // clear timer on success
$_SESSION['logged_in'] = true;
header("Location: $atinput_linkUrl");
exit;
} else {
$error = "Wrong password!";
}
}
}
if (isset($_SESSION['logged_in']) && $_SESSION['logged_in'] === true) {
echo '<div class="logout"><a href="'.$atinput_linkUrl.'?logout=1">Logout</a></div>';
return;
}else{
?>
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h2>Login</h2>
<?php if (!empty($error)) echo "<p style='color:red;'>$error</p>"; ?>
<form method="post">
<label for="password">Enter Password:</label>
<input type="password" name="password" id="password" required>
<button type="submit">Login</button>
</form>
</body>
</html>
<?php }?>
<?php
die;
?>
<?php
include_once __DIR__.'/for_login.php';
?>
All content after login here;
@tranchausky
Copy link
Author

tranchausky commented Apr 5, 2025

can use password has for run

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $input_password = $_POST['password'];
    //$correct_password = "secret123"; // Change this to your real password
    

//echo password_hash("secret123", PASSWORD_DEFAULT); //get stored_hash

    //if ($input_password === $correct_password) {
    $stored_hash = '$2y$10$ZgvbvFLdyDwxy5aBwU8EoOLmeufHvZKMWXd2222IJXIf1lWky';
    if (password_verify($input_password, $stored_hash)) {
        $_SESSION['logged_in'] = true;
        header("Location: $php_main");
        exit;
    } else {
        $error = "Wrong password!";
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment