I have two files: a login file and a view file.
In the login.php file I start a session like this: “$_SESSION["who"] = $_POST["who"];”
When I press the login button, it redirects me to the view.php file. The view.php checks the session to see if the user's name is set and if the user's name is not present, the view.php must stop immediately using the PHP die() function.
My problem is that regardless if I put the user name or not, always uses the die() function.
This is my code for each file.
The login.php file:
session_start();
if ( isset($_POST['cancel'] ) ) {
// Redirect the browser to game.php
header("Location: index.php");
return;
}
$salt = 'XyZzy12*_';
$stored_hash = '1a52e17fa899cf40fb04cfc42e6352f1'; // Pw is php123
$failure = false; // If we have no POST data
// Check to see if we have some POST data, if we do process it
if ( isset($_POST['who']) && isset($_POST['pass']) ) {
unset($_SESSION["who"]);
if ( strlen($_POST['who']) < 1 || strlen($_POST['pass']) < 1 ) {
$_SESSION["error"] = "User name and password are required";
header( 'Location: login.php' ) ;
return;
} else {
if (strpos($_POST['who'], '#') == false) {
$_SESSION["error"] = "Email must have an at-sign #";
header( 'Location: login.php' ) ;
return;
} else {
$check = hash('md5', $salt.$_POST['pass']);
if ( $check == $stored_hash ) {
$_SESSION["who"] = $_POST["who"];
header( 'Location: view.php' ) ;
return;
} else {
$_SESSION["error"] = "Incorrect password";
header( 'Location: login.php' ) ;
return;
}
}
}
}
// Fall through into the View
?>
<!DOCTYPE html>
<html>
<head>
<?php require_once "bootstrap.php"; ?>
<title>123</title>
</head>
<body>
<div class="container">
<h1>Please Log In</h1>
<?php
if ( isset($_SESSION["error"]) ) {
echo('<p style="color:red">'.htmlentities($_SESSION['error'])."</p>\n");
unset($_SESSION["error"]);
}
?>
<form method="POST">
<label for="who">Email</label>
<input type="text" name="who" id="who"><br/>
<label for="id_123">Password</label>
<input type="text" name="pass" id="id_1723"><br/>
<input type="submit" value="Log In">
<input type="submit" name="cancel" value="Cancel">
</form>
<p>
For a password hint, view source and find a password hint
in the HTML comments.
<!-- Hint: The password is php (all lower case) followed by 123. -->
</p>
</div>
</body>
The view.php file:
<?php
if ( ! isset($_SESSION['who']) ) {
die('Not logged in');
}
require_once "pdo.php";
?>
<!DOCTYPE html>
<html>
<head>
<title>123</title>
<?php require_once "bootstrap.php"; ?>
</head>
<body>
<div class="container">
<h1>Tracking Autos for <?php ?> </h1>
<h2>Automobiles</h2>
<p>Add New | Logout</p>
</div>
</body>
</html>
You forgot to put session_start(); at the beginning of the view.php.
<?php
session_start();
if ( ! isset($_SESSION['who']) ) {
die('Not logged in');
}
require_once "pdo.php";
?>
<!DOCTYPE html>
<html>
<head>
<title>123</title>
<?php require_once "bootstrap.php"; ?>
</head>
<body>
<div class="container">
<h1>Tracking Autos for <?php ?> </h1>
<h2>Automobiles</h2>
<p>Add New | Logout</p>
</div>
</body>
</html>
Related
I'm making a web page using php code, where the index.php code changes after the user successfully log in.
The user starts at index.php before loging in, gets directed to login.php then redirected back to index.php. The index.php have a completely different code after and before loging in. I want to know what is the correct approach to make to the page to modify it, because I'm trying if statements and they don't seem to work.
index page
<?php
require_once "pdo.php";
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>Index Page</title>
</head>
<body>
<div class="container">
<h2>Welcome to the Automobiles Database</h2>
<?php
if ( isset($_SESSION['error']) ) {
echo '<p style="color:red">'.$_SESSION['error']."</p>\n";
unset($_SESSION['error']);
}
if ( isset($_SESSION['success']) ) {
echo '<p style="color:green">'.$_SESSION['success']."</p>\n";
unset($_SESSION['success']);
}
if(!isset($_POST['email']) || !isset($_POST['pass']))//this code should work if the
//user is not loged in
{
echo '<p>Please log in</p>' ;
echo '<p>Attempt to add data without logging in</p>' ;
}
if(isset($_POST['email']) && isset($_POST['pass']))//this code should work if the user
//is loged in
{
if(isset($_POST['make']) && isset($_POST['year']) && isset($_POST['model']) &&
isset($_POST['mileage']))//this code should work if the user entered data
{
echo('<table border="1">'."\n");
$stmt = $pdo->query("SELECT * autos");
while ( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) {
echo "<tr><td>";
echo(htmlentities($row['make']));
echo("</td><td>");
echo(htmlentities($row['model']));
echo("</td><td>");
echo(htmlentities($row['year']));
echo("</td><td>");
echo(htmlentities($row['mileage']));
echo("</td><td>");
echo('Edit / ');
echo('Delete');
echo("</td></tr>\n");
}
}
else if(!isset($_POST['make']) || !isset($_POST['year']) || !isset($_POST['model']) ||
!isset($_POST['mileage']))//this code should work if the user didn't enter data
{
echo "<p>no rows found</p>";
}
echo '<p>Add New Entery</p>';
echo '<p>Logout</p>';
}
?>
login page
<?php
require_once "pdo.php";
session_start();
if ( isset($_POST['cancel'] ) ) {
header("Location: login.php?name=".urlcode($_POST['email']));
return;
}
$salt = "XyZzy12*_";
$stored_hash = "1a52e17fa899cf40fb04cfc42e6352f1"; // Pw is php 123
$failure = false; // If we have no POST data
// Check to see if we have some POST data, if we do process it
if ( isset($_POST['email']) && isset($_POST['pass']) ) {
if ( strlen($_POST['email']) < 1 || strlen($_POST['pass']) < 1 ) {
$_SESSION['error'] = "User name and password are required";
header("Location: login.php");
return;
}
else if (!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) {
$_SESSION['error'] = "Email must have an at-sign (#)";
header("Location: login.php");
return;
}
else {
$check = hash('md5', $salt.$_POST['pass']);
if ( $check == $stored_hash ) {
error_log("Login success ".$_POST['email']);
$_SESSION['name'] = $_POST['email'];
header("Location: index.php");
return;
} else {
error_log("Login fail ".$_POST['email']." $check");
$_SESSION['error'] = "Incorrect password";
header("Location: login.php");
return;
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7"
crossorigin="anonymous">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css"
integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r"
crossorigin="anonymous">
<link rel="stylesheet"
href="https://code.jquery.com/ui/1.12.1/themes/ui-lightness/jquery-ui.css">
<script
src="https://code.jquery.com/jquery-3.2.1.js"
integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
crossorigin="anonymous"></script>
<script
src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"
integrity="sha256-T0Vest3yCU7pafRw9r+settMBX6JkKN06dqBnpQ8d30="
crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<h1>Please Log In</h1>
<?php
if ( isset($_SESSION['error']) ) {
echo('<p style="color: red;">'.htmlentities($_SESSION['error'])."</p>\n");
unset($_SESSION['error']);
}
?>
<form method="POST" action="login.php">
User Name <input type="text" name="email"><br/>
Password <input type="text" name="pass"><br/>
<input type="submit" value="Log In">
Cancel</p>
</form>
<p>
For a password hint, view source and find a password hint
in the HTML comments.
<!-- Hint: The password is the three character name of the
programming language used in this class (all lower case)
followed by 123. -->
</p>
</div>
</body>
</html>
You should make 3 pages instead.
In index ,check user is logged.
If logged, redirect to home page.
If not logged, call die() and redirect to login page.
i'm trying to learn about session_start() but when i run the file, it only show what is inside the
if (isset($_SESSION['username'])&& isset($_SESSION['password'])==$password) {
?>
log out
<?php } ?>
and not showing else{...} and even after i click log out, it won't print anything in else statement and only print inside the if statement. I use another file to do the log out proses but i don't know the right code for session_destroy()
here's the logout.php code below:
<?php
session_start();
session_destroy();
header("location: home.php");
?>
here's the full code:
<?php
session_start();
include("DB/db.php");
$_SESSION['username']=$username;
$_SESSION['password']=$password;
$_SESSION['is_log_in'] = true;
?><!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="css/css.css">
</head>
<body>
<div id="blank"></div>
<div id="panel">
<nav id="bar">
<div id="submen">
<form id="sir">
<input type="Search" name="search" placeholder="Search.." id="search">
</form>
Walpaper
Art
Photos
Image
<?php
if (isset($_SESSION['username'])&& isset($_SESSION['password'])==$password) {?>
<?php echo $username?>
log out
</div>
</nav>
</div>
</table>
<?php } else {
?>
login
register
</div>
</nav>
</div>
</table>
<?php } ?>
</body>
</html>
UPDATE for log in script
<?php
session_start();
include("DB/db.php");
if ($_GET['log']=='out'){
session_destroy();
}
if ($_POST['user']){
$sql = "Select password from user where username = '".$_POST['user']."' ";
$result = mysqli_query($koneksi, $sql);
if (mysqli_num_rows($result)){
$row = mysqli_fetch_assoc($result);
if ($row['password'] == md5($_POST['pass'])) {
$_SESSION['login'] = TRUE;
$_SESSION['username'] = $user;
$_SESSION['password'] = $pass;
}else{
$pesan = "Username and password mismatch";
}
}else{
$pesan = "please register";
}
}
?><!DOCTYPE html>
<html>
<head>
<title>Log in</title>
</head>
<body>
<?php
if ($_SESSION['login']) {
echo "text";
}else{
?>
<h1>Login</h1>
<form method="post" action="rahasia.php">
Username: <input type="text" name="user">
Password: <input type="password" name="pass">
<input type="submit" name="" value="Login">
</form>
<form method="post" action="register.php">
<input type="submit" name="register" value="register">
</form>
<?php
}
echo $pesan;
?>
</body>
</html>
where have i gone wrong
Your $_SESSION vars are always set, and $password always equals $_SESSION['password'].
$_SESSION['username']=$username; // null, plus notice in error_log
$_SESSION['password']=$password; // null, plus notice in error_log
Unless those two vars are set in include("DB/db.php");, in which case that is bad practice. Can you paste db.php to see what is happening inside?
UPDATE.
Okay so the vars are being set. This now means:
$_SESSION['username']=$username; // a
$_SESSION['password']=$password; // 123456789
Therefore they will still match. You need to refactor these lines to function properly. Are you sure the mysql credentials is what you want for your logged in user
?
i am new to php and i am trying to make a register and log in page.
When I register as a new user it works fine and comes up in the database.However, when it comes to logging in there seems to be a problem that i tried everything.
what i want to do is when a user logs in, it redirect them to the home page, and if the log in information was wrong then it would show an error message.
Here is the php code that is in the log in file:
<?php
session_start();
if( isset($_SESSION['users_id']) ){
header("Location: /");
}
require 'database.php';
if(!empty($_POST['email']) && !empty($_POST['password'])):
$records = $conn->prepare('SELECT id,email,password FROM users WHERE email = :email');
$records->bindParam(':email', $_POST['email']);
$records->execute();
$results = $records->fetch(PDO::FETCH_ASSOC);
$message = '';
if(count($results) > 0 && password_verify($_POST['password'], $results['password']) )
{
$_SESSION['users_id'] = $results['id'];
header("Location: php.dev/index.php", true, 301); exit();
}
else {
$message = 'Sorry, thoes credentials do not match';
}
endif;
?>
the header("Location:....) this doesn't seem to work. i'm really stuck here any help ?
Here is the html code:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Login</title>
<link href="Style/phpstyle.css" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet">
</head>
<body>
<div class="header">
TIPBUCKET
</div>
<?php if(!empty($message)): ?>
<p><?= $message ?></p>
<?php endif; ?>
<h1>Login</h1>
<span> or Register here</span>
<form action="login.php" method="POST">
<input type="text" placeholder="enter your email" name="email">
<input type="password" placeholder="Password" name="password">
<input type="submit">
</form>
</body>
</html>
Thank you in advance to any replies :)
You have a typo in your header:
header("Location: php.dev/index.php", ture, 301);
should be
header("Location: php.dev/index.php", true, 301);
I am working on a simple login form with sessions..Here is my index.php code
<?php
ob_start();
session_start();
?>
<?
// error_reporting(E_ALL);
// ini_set("display_errors", 1);
?>
<html lang = "en">
<head> </head>
<body>
<h2>Enter Username and Password</h2>
<div class = "container form-signin">
<?php
$msg = '';
if (isset($_POST['login']) && !empty($_POST['username']) && !empty($_POST['password']))
{
if ($_POST['username'] == '1' && $_POST['password'] == '1' )
{
$_SESSION['valid'] = true;
$_SESSION['timeout'] = time();
header('Location: /test/login.php');
}
else $msg = 'not working';
}
?>
</div> <!-- /container -->
</div>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="post" >
<?php echo $msg; ?>
<input type="text" name="username">
<input type="password" name="password" >
<input type="submit" name="login">
</form>
</body>
</html>
When someone write the right password, he will go to this page
localhost:8080/test/login.php
but, if someone try to open "localhost:8080/test/login.php" directly, he will go to this page "localhost:8080/test/index.php".
this is my login.php code
<?php
session_start();
if ($_POST['username'] == '1' && $_POST['password'] == '1' )
{
$_SESSION['valid'] = true;
$_SESSION['timeout'] = time();
header('Location: /test/login.php');
}
else{
header('Location: /test/index.php/');
}
?>
test 1
Youve made several small mistakes (see comments), but the big mistake you make is that the session is never checked. Use this at login.php :
<?php
session_start();
if(!isset($_SESSION["valid"])){
header("location: index.php");
die();
}
?>
This checks if the session is set, and if not redirects back to index php
I have a log-in script for user login. The user information is stored in the MYSQL database. When i login for first time, it stores the information in the session and display the welcome message. But when i log-out and try to log-in again, the session array display empty although it is logged in.
Here are my codes:
reservation.php
<?php
session_start();
require_once("./includes/config_db.php");
$error1=array();
if(isset($_POST['submit'])){
if (preg_match ('%^[A-Za-z0-9]{4,8}$%', stripslashes(trim($_POST['user_id'])))) {
$e = escape_data($_POST['user_id']);
} else {
$e = FALSE;
$error1['user_id']="UserID Required!";
}
if (preg_match ('%^[A-Za-z0-9]{8,}$%', stripslashes(trim($_POST['password'])))) {
$p = escape_data($_POST['password']);
} else {
$p = FALSE;
$error1['password']="Password Required!";
}
if($e && $p){
$query="SELECT * FROM users WHERE(user_id='$e' AND password=SHA('$p')) AND active='NULL'";
$results=mysql_query($query);
if(mysql_affected_rows() == 1){
$row=mysql_fetch_array($results, MYSQL_NUM);
mysql_free_result($results);
$_SESSION['name']=$row[0];
$_SESSION['department']=$row[1];
$_SESSION['email']=$row[2];
$_SESSION['user_id']=$row[4];
$_SESSION['phone']=$row[5];
$_SESSION['pre']=$row[8];
//create second token
$tokenid=rand(10000,9999999);
$query2="UPDATE r_users SET token='$tokenid' WHERE user_id='$_SESSION[user_id]'";
$result2=mysql_query($query2);
$_SESSION['tokenid']=$tokenid;
session_regenerate_id();
mysql_close();
header("Location:local.php");
exit();
}else
{
$error1['active']="Either your Account is inactive or Email/Password is incorrect";
mysql_close();
}
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Reservation System</title>
<!--Link to external files-->
<link rel="stylesheet" type="text/css" href="css/reservation.css"></link>
</head>
<body class="body">
<div id="mainHeader">
<?php include('includes/ers_header.php'); ?>
</div>
<div id="content">
</div>
<div id="navigation">
<?php include('includes/ers_nav.php');?>
<h3>Member Login</h3>
<form id="login" action="reservation.php" method="post">
<?php if(!empty($error1['active'])) echo '<p><font color="red">'.$error1['active'].'</font></p>'; ?>
<label for="userid">User ID:</label>
<input type="text" name="user_id" <?php if (!empty($error1['user_id'])){ echo 'value="'.htmlentities($_POST['user_id']).'"';} ?> autofocus />
<?php if (!empty($error1['user_id'])){ echo '<p><font color="red">'.$error1['user_id'].'</font></p>';} ?>
<label for="password">Password:</label>
<input type="password" name="password" />
<?php if (!empty($error1['password'])){ echo '<p><font color="red">'.$error1['password'].'</font></p>';} ?>
<button class="submit" name="submit" type="submit">Login</button>
</form
</div>
</body>
</html>
ers_header.php:
<h1>XXXXXXXXXX</h1>
<h2>YYYYYYYYYYY</h2>
<h2>ZZZZZZZZZZZZ</h2>
<?php
require_once("./includes/config_db.php");
if(isset($_SESSION['name'])){
$sql="SELECT token FROM users WHERE(user_id='$_SESSION[user_id]')";
$result=mysql_query($sql);
if (mysql_affected_rows() == 1) { // A match was made.
$row = mysql_fetch_array ($result, MYSQL_NUM);
mysql_free_result($result);
mysql_close(); // Close the database connection.
if($_SESSION['tokenid'] == $row[0]){
echo '<p>Welcome';
echo " {$_SESSION['name']}";
$loggedin=1;
}else{
$loggedin=0;
}
}
}
if(isset($_SESSION['user_id']) AND (substr($_SERVER['PHP_SELF'] AND $loggedin,-10)!='logout.php')){
echo' Logout';
echo'</p>';
}
?>
logout.php
<?php
session_start();
require_once("./includes/config_db.php");
if ( !isset( $_SESSION['name'] ) ) {
header("Location: reservation.php");
exit();
} else {
$_SESSION = array(); // Destroy the variables.
session_destroy(); // Destroy the session itself.
setcookie( session_name(), ", time()-300, '/', ", 0 ); // Destroy the cookie.
header("Location:reservation.php");
}
I don't know what is the problem. I have tried a lot but couldn't find it out. Please can anyone figure out my mistake.
You really should only need to unset the $_SESSION array, not destroy the session and cookie data, try removing those lines, but also:
mysql_affected_rows should be mysql_num_rows
also this line of code is incorrect:
$query2="UPDATE r_users SET token='$tokenid' WHERE user_id='$_SESSION[user_id]'";
$_SESSION[user_id] should be $_SESSION["user_id"] and you should wrap it in {}. PHP probably gives warnings about this.
and this line of code is strange:
if(isset($_SESSION['user_id']) AND (substr($_SERVER['PHP_SELF'] AND $loggedin,-10)!='logout.php')
is the $loggedin,-10 really supposed to be in substr?