Создание простого простого имени пользователя / пароля в php

Я хочу сделать один логин только для одного пользователя без сохранения в базе данных, но я не могу заставить его работать.

Мой код: login.php

<html> <head> <title>Login</title> </head> <h3>Add entry</h3> <p> Add another Article</p> <form action="trylog.php" method = "post"> <label for="username">Username</label> <input type="username" id="usename" name="username"><br /><br /> <label for="password">Password:</label> <input type="text" id="password" name="password"><br /><br /> <button type = "submit">Login</button> </form> </html> 

trylog.php

 <html> <title>Login</title> <body> <?php $usr = "admin"; $psw = "password"; $username = '$_POST[username]'; $password = '$_POST[password]'; //$usr == $username && $psw == $password session_start(); if ($_SESSION['login']==true || ($_POST['username']=="admin" && $_POST['password']=="password")) { echo "password accepted"; $_SESSION['login']=true; else { echo "incorrect login"; } ?> <form name="input" action="adminportal.php" method="get"> <input type="submit" value="Home"> </form> </body> </html> 

Ваш код может выглядеть по-другому:

 <?php session_start(); $errorMsg = ""; $validUser = $_SESSION["login"] === true; if(isset($_POST["sub"])) { $validUser = $_POST["username"] == "admin" && $_POST["password"] == "password"; if(!$validUser) $errorMsg = "Invalid username or password."; else $_SESSION["login"] = true; } if($validUser) { header("Location: /login-success.php"); die(); } ?> <!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html;charset=utf-8" /> <title>Login</title> </head> <body> <form name="input" action="" method="post"> <label for="username">Username:</label><input type="text" value="<?= $_POST["username"] ?>" id="username" name="username" /> <label for="password">Password:</label><input type="password" value="" id="password" name="password" /> <div class="error"><?= $errorMsg ?></div> <input type="submit" value="Home" name="sub" /> </form> </body> </html> 

Теперь, когда страница перенаправляется на основе header('LOCATION:wherever.php) , поместите session_start() вверху страницы и проверьте, чтобы $_SESSION['login'] === true . Помните, что == будет true, если $_SESSION['login'] == 1 . Конечно, это плохая идея по соображениям безопасности, но мой пример может научить вас другому способу использования PHP.

Во-первых, вам нужно поставить session_start(); перед любым выходом в браузер, обычно в верхней части страницы. Посмотрите руководство.

Во-вторых, это не повлияет на ваши результаты, но эти строки нигде не используются и должны быть удалены:

 $usr = "admin"; $psw = "password"; $username = '$_POST[username]'; $password = '$_POST[password]'; 

… и последние две строки там не сработают, вам нужно поставить кавычки в квадратные скобки:

 $username = $_POST['username']; 

Если вы поставили session_start() в верхней части страницы (т.е. перед <html> т. Д.), Это должно работать нормально.

Вот простой скрипт php для входа в систему и страница, доступ к которой возможен только при входе в систему.

login.php

 <?php session_start(); echo isset($_SESSION['login']); if(isset($_SESSION['login'])) { header('LOCATION:index.php'); die(); } ?> <!DOCTYPE html> <html> <head> <meta http-equiv='content-type' content='text/html;charset=utf-8' /> <title>Login</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> </head> <body> <div class="container"> <h3 class="text-center">Login</h3> <?php if(isset($_POST['submit'])){ $username = $_POST['username']; $password = $_POST['password']; if($username === 'admin' && $password === 'password'){ $_SESSION['login'] = true; header('LOCATION:admin.php'); die(); } { echo "<div class='alert alert-danger'>Username and Password do not match.</div>"; } } ?> <form action="" method="post"> <div class="form-group"> <label for="username">Username:</label> <input type="text" class="form-control" id="username" name="username" required> </div> <div class="form-group"> <label for="pwd">Password:</label> <input type="password" class="form-control" id="pwd" name="password" required> </div> <button type="submit" name="submit" class="btn btn-default">Login</button> </form> </div> </body> </html> 

admin.php (только зарегистрированные пользователи могут получить к нему доступ)

 <?php session_start(); if(!isset($_SESSION['login'])) { header('LOCATION:login.php'); die(); } ?> <html> <head> <title>Admin Page</title> </head> <body> This is admin page view able only by logged in users. </body> </html> 

Ваш код может выглядеть по-другому:

 <?php session_start(); $username = $password = $userError = $passError = ''; if(isset($_POST['sub'])){ $username = $_POST['username']; $password = $_POST['password']; if($username === 'admin' && $password === 'password'){ $_SESSION['login'] = true; header('LOCATION:wherever.php'); die(); } if($username !== 'admin')$userError = 'Invalid Username'; if($password !== 'password')$passError = 'Invalid Password'; } ?> <!DOCTYPE html> <html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'> <head> <meta http-equiv='content-type' content='text/html;charset=utf-8' /> <title>Login</title> <style type='text.css'> @import common.css; </style> </head> <body> <form name='input' action='<?php echo $_SERVER['PHP_SELF'];?>' method='post'> <label for='username'></label><input type='text' value='<?php echo $username;?>' id='username' name='username' /> <div class='error'><?php echo $userError;?></div> <label for='password'></label><input type='password' value='<?php echo $password;?>' id='password' name='password' /> <div class='error'><?php echo $passError;?></div> <input type='submit' value='Home' name='sub' /> </form> <script type='text/javascript' src='common.js'></script> </body> </html> 
 <?php session_start(); mysql_connect('localhost','root',''); mysql_select_db('database name goes here'); $error_msg=NULL; //log out code if(isset($_REQUEST['logout'])){ unset($_SESSION['user']); unset($_SESSION['username']); unset($_SESSION['id']); unset($_SESSION['role']); session_destroy(); } // if(!empty($_POST['submit'])){ if(empty($_POST['username'])) $error_msg='please enter username'; if(empty($_POST['password'])) $error_msg='please enter password'; if(empty($error_msg)){ $sql="SELECT*FROM users WHERE username='%s' AND password='%s'"; $sql=sprintf($sql,$_POST['username'],md5($_POST['password'])); $records=mysql_query($sql) or die(mysql_error()); if($record_new=mysql_fetch_array($records)){ $_SESSION['user']=$record_new; $_SESSION['id']=$record_new['id']; $_SESSION['username']=$record_new['username']; $_SESSION['role']=$record_new['role']; header('location:index.php'); $error_msg='welcome'; exit(); }else{ $error_msg='invalid details'; } } } ?> // replace the location with whatever page u want the user to visit when he/she log in из <?php session_start(); mysql_connect('localhost','root',''); mysql_select_db('database name goes here'); $error_msg=NULL; //log out code if(isset($_REQUEST['logout'])){ unset($_SESSION['user']); unset($_SESSION['username']); unset($_SESSION['id']); unset($_SESSION['role']); session_destroy(); } // if(!empty($_POST['submit'])){ if(empty($_POST['username'])) $error_msg='please enter username'; if(empty($_POST['password'])) $error_msg='please enter password'; if(empty($error_msg)){ $sql="SELECT*FROM users WHERE username='%s' AND password='%s'"; $sql=sprintf($sql,$_POST['username'],md5($_POST['password'])); $records=mysql_query($sql) or die(mysql_error()); if($record_new=mysql_fetch_array($records)){ $_SESSION['user']=$record_new; $_SESSION['id']=$record_new['id']; $_SESSION['username']=$record_new['username']; $_SESSION['role']=$record_new['role']; header('location:index.php'); $error_msg='welcome'; exit(); }else{ $error_msg='invalid details'; } } } ?> // replace the location with whatever page u want the user to visit when he/she log in с <?php session_start(); mysql_connect('localhost','root',''); mysql_select_db('database name goes here'); $error_msg=NULL; //log out code if(isset($_REQUEST['logout'])){ unset($_SESSION['user']); unset($_SESSION['username']); unset($_SESSION['id']); unset($_SESSION['role']); session_destroy(); } // if(!empty($_POST['submit'])){ if(empty($_POST['username'])) $error_msg='please enter username'; if(empty($_POST['password'])) $error_msg='please enter password'; if(empty($error_msg)){ $sql="SELECT*FROM users WHERE username='%s' AND password='%s'"; $sql=sprintf($sql,$_POST['username'],md5($_POST['password'])); $records=mysql_query($sql) or die(mysql_error()); if($record_new=mysql_fetch_array($records)){ $_SESSION['user']=$record_new; $_SESSION['id']=$record_new['id']; $_SESSION['username']=$record_new['username']; $_SESSION['role']=$record_new['role']; header('location:index.php'); $error_msg='welcome'; exit(); }else{ $error_msg='invalid details'; } } } ?> // replace the location with whatever page u want the user to visit when he/she log in с <?php session_start(); mysql_connect('localhost','root',''); mysql_select_db('database name goes here'); $error_msg=NULL; //log out code if(isset($_REQUEST['logout'])){ unset($_SESSION['user']); unset($_SESSION['username']); unset($_SESSION['id']); unset($_SESSION['role']); session_destroy(); } // if(!empty($_POST['submit'])){ if(empty($_POST['username'])) $error_msg='please enter username'; if(empty($_POST['password'])) $error_msg='please enter password'; if(empty($error_msg)){ $sql="SELECT*FROM users WHERE username='%s' AND password='%s'"; $sql=sprintf($sql,$_POST['username'],md5($_POST['password'])); $records=mysql_query($sql) or die(mysql_error()); if($record_new=mysql_fetch_array($records)){ $_SESSION['user']=$record_new; $_SESSION['id']=$record_new['id']; $_SESSION['username']=$record_new['username']; $_SESSION['role']=$record_new['role']; header('location:index.php'); $error_msg='welcome'; exit(); }else{ $error_msg='invalid details'; } } } ?> // replace the location with whatever page u want the user to visit when he/she log in с <?php session_start(); mysql_connect('localhost','root',''); mysql_select_db('database name goes here'); $error_msg=NULL; //log out code if(isset($_REQUEST['logout'])){ unset($_SESSION['user']); unset($_SESSION['username']); unset($_SESSION['id']); unset($_SESSION['role']); session_destroy(); } // if(!empty($_POST['submit'])){ if(empty($_POST['username'])) $error_msg='please enter username'; if(empty($_POST['password'])) $error_msg='please enter password'; if(empty($error_msg)){ $sql="SELECT*FROM users WHERE username='%s' AND password='%s'"; $sql=sprintf($sql,$_POST['username'],md5($_POST['password'])); $records=mysql_query($sql) or die(mysql_error()); if($record_new=mysql_fetch_array($records)){ $_SESSION['user']=$record_new; $_SESSION['id']=$record_new['id']; $_SESSION['username']=$record_new['username']; $_SESSION['role']=$record_new['role']; header('location:index.php'); $error_msg='welcome'; exit(); }else{ $error_msg='invalid details'; } } } ?> // replace the location with whatever page u want the user to visit when he/she log in с <?php session_start(); mysql_connect('localhost','root',''); mysql_select_db('database name goes here'); $error_msg=NULL; //log out code if(isset($_REQUEST['logout'])){ unset($_SESSION['user']); unset($_SESSION['username']); unset($_SESSION['id']); unset($_SESSION['role']); session_destroy(); } // if(!empty($_POST['submit'])){ if(empty($_POST['username'])) $error_msg='please enter username'; if(empty($_POST['password'])) $error_msg='please enter password'; if(empty($error_msg)){ $sql="SELECT*FROM users WHERE username='%s' AND password='%s'"; $sql=sprintf($sql,$_POST['username'],md5($_POST['password'])); $records=mysql_query($sql) or die(mysql_error()); if($record_new=mysql_fetch_array($records)){ $_SESSION['user']=$record_new; $_SESSION['id']=$record_new['id']; $_SESSION['username']=$record_new['username']; $_SESSION['role']=$record_new['role']; header('location:index.php'); $error_msg='welcome'; exit(); }else{ $error_msg='invalid details'; } } } ?> // replace the location with whatever page u want the user to visit when he/she log in