My error is always said "invalid username and password",
please any one can help?
i want to fix some errors"'please help
i want to do this like in this link please see" this is a program i like to do
http://alumnisys.hostei.com/
please any one can solve this problem""
the error is is in variable sysntax""
code below is i like to fix
heres my other code""
connect.php
login.php
index.php
admin.php
staff.php
student.php
|
Username:
Password:
S u b m i t
This is a sample program of 3 accounts use this as your guide to your case study.
The pdf files is in the admin page login first before download:)
note: you need to debug the codes :)
note: the database is in the student page.
Admin Account
username: admin
password: admin
Staff Account
username staff
password staff
student account
username pedro
password pedropedro
Connect.php
<?php
$db = mysql_connect('localhost', 'root', '');
mysql_select_db('psu1', $db);
?>
Index.php
<?php
session_start();
$pg='hm';
if($_SESSION['usertype']=='admin'){
header('location: admin.php');
}elseif($_SESSION['usertype']=='staff'){
header('location: staff.php');
}elseif($_SESSION['usertype']=='alumni'){
header('location: alumnu.php');
}else{
}
$msg='';
if(isset($_POST['do'])){
$uname = $_POST['username'];
$upass = $_POST['password'];
if(($uname=='') && ($upass=='')){
$msg = 'frmError';
$m = 'Dont leave blanks...';
}else{
include('connect.php');
$sql="SELECT * FROM alumni_login WHERE userrname='".$uname."' AND password='".md5($upass)."'";
$result=mysql_query($sql);
$rc = mysql_num_rows($result);
if($rc==0){
$msg = 'frmError';
$m = 'Invalid Username or Password';
}else{
$row = mysql_fetch_assoc($result);
$ip=$_SERVER['REMOTE_ADDR'];
$sql2="INSERT INTO login_infos VALUES(".$row['userid'].",
'".$row['username']."', '".date('Y-m-d H:i:s')."', '$ip')";
$result2=mysql_query($sql2);
if($result2){
$_SESSION['username'] = $row['username'];
$_SESSION['useraydi'] = $row['userid'];
$_SESSION['usertype'] = $row['usertype'];
if($row['usertype']=='admin'){
header('location: admin.php');
}elseif($row['usertype']=='staff'){
header('location: staff.php');
}elseif($row['usertype']=='alumni'){
header('location: student.php');
}
}
}
}
}
?>
<head>
<title>index</title>
<meta http-equiv="Content-Type" content="text/html; charset=Windows-1251" />
<link rel="stylesheet" href="css/main.css" type="text/css" />
<style type="text/css">
<!--
.style1 {font-size: 10px}
.style2 {
font-size: 11px;
font-weight: bold;
}
</style>
</head>
<body>
<?php include('login.php'); ?>
</div>
</body>
</html>
Admin.php
<?php
session_start();
$pg='hm';
if($_SESSION['usertype']!='admin'){
header('location: index.php');
}
?>
<head>
<title>Admin-Main Page</title>
</head>
<body>
<li style="background: none;">Welcome ADMIN</li>
<h3>Welcome System Administration.</h3>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<li><a href="logout.php"><img src="menu/logout.png"
/></a></li>
</body>
</html>
Staff.php
<?php
session_start();
$pg='st';
if($_SESSION['usertype']!='staff'){
header('location: index.php');
}
include('connect.php');
$sql = "SELECT * FROM alumni_login WHERE userid='".$_SESSION['useraydi']."'";
$result = mysql_query($sql);
$rc=#mysql_num_rows($result);
if($rc>0){
$row=mysql_fetch_assoc($result);
$neym=$row['username'];
}
?>
<html><title>staff page</title>
</head>
<body>
<li style="background: none;">Welcome STAFF</li>
<h3>Staff Main Page</h3>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<li><a href="logout.php"><img src="menu/logout.png"
/></a></li>
</div>
</body>
</html>
Student.php
<?php
session_start();
if($_SESSION['usertype']!='student'){
header('location: index.php');
}
$pg='hm';
include('../student_for_demo correct codes/connect.php');
$sql = "SELECT * FROM alumni_info WHERE userid='".$_SESSION['useraydi']."'";
$result = mysql_query($sql);
$rc=#mysql_num_rows($result);
if($rc>0){
$row=mysql_fetch_assoc($result);
$neym=$row['firstname'];
if($row['myphoto']!='')
if(file_exists($uploads.$row['myphoto']))
$imgphoto = $uploads.$row['myphoto'];
else
$imgphoto = $uploads.'nopic.gif';
else
$imgphoto = $uploads.'nopic.gif';
}
?>
<html>
<head>
<title>student page</title>
<td id="content" valign="top"><h2>Welcome, <?php echo $neym;?></h2>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<li><a href="../student_for_demo correct codes/logout.php"><img src="../student_for_demo
correct codes/menu/logout.png" /></a></li>
</div>
</body>
</html>
Inc.login.php
<form method="post" id="loginform" action="index.php">
<div align="center"><strong><font color="#003300" size="2"><span class="<?php echo $msg;
?>"><font color="#EDF5FE">|</font><?php echo $m; ?></span></font></strong></div>
<table width="222"><tr height="30">
<td align="right"><strong>Username:</strong></td>
<td><input name="username" type="text"></td>
</tr><tr>
<td align="right"><strong>Password:</strong></td>
<td><input name="password" type="password"></td>
</tr></table>
<br />
<input type="image" align="center" src="images/login.png" name="do" value="S u b m i t" />
</form>
Logout.php
<?php
session_start();
session_destroy();
header("location: index.php");
?>
I have check, In your query there is spelling mistake
New Query
$sql="SELECT * FROM alumni_login WHERE username='".$uname."' AND password='".md5($upass)."'";
You have used userrname it should be username
Related
I am trying to insert form data to my profile table when I click the add button, but whenever I test my code below it just reloads my add.php page and clears the form instead of adding it to my table.
add.php code:
<?php
//connection to the database
$pdo = require_once 'pdo.php';
session_start();
//if user is not logged in redirect back to index.php with an error message
if(!isset($_SESSION['user_id'])){
die("ACCESS DENIED");
return;
}
//if the user requested cancel go back to index.php
if(isset($_POST['cancel'])){
header('Location: index.php');
return;
}
//handling incoming data
$uid = $_SESSION['user_id'];
if (isset($_POST['first_name']) && isset($_POST['last_name']) &&
isset($_POST['email']) && isset($_POST['headline']) && isset($_POST['summary'])){
if (strlen($_POST['first_name']) == 0 || strlen($_POST['last_name']) == 0 ||
strlen($_POST['email']) || strlen($_POST['headline']) == 0 || strlen($_POST['summary']) == 0){
$_SESSION['error'] = "All fields are required";
header("Location: add.php");
return;
}
if(strpos($_POST['email'], '#') === false){
$_SESSION['error'] = "Email address must contain #";
header("Location: add.php");
return;
}
$stmt = $pdo->prepare('INSERT INTO profile
(user_id, first_name, last_name, email, headline, summary)
VALUES ( :uid, :fn, :ln, :em, :he, :su)');
$stmt->execute(array(
':uid' => $uid,
':fn' => $_POST['first_name'],
':ln' => $_POST['last_name'],
':em' => $_POST['email'],
':he' => $_POST['headline'],
':su' => $_POST['summary'])
);
$_SESSION['success'] = "profile added";
header("location: index.php");
return;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Mandla'ke Makondo's Profile Add</title>
<!-- bootstrap.php - this is HTML -->
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7"
crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css"
integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r"
crossorigin="anonymous">
</head>
<body>
<div class="container">
<h1>Adding Profile for UMSI</h1>
<form method="post" action="index.php">
<p>First Name:
<input type="text" name="first_name" size="60"/></p>
<p>Last Name:
<input type="text" name="last_name" size="60"/></p>
<p>Email:
<input type="text" name="email" size="30"/></p>
<p>Headline:<br/>
<input type="text" name="headline" size="80"/></p>
<p>Summary:<br/>
<textarea name="summary" rows="8" cols="80"></textarea>
<p>
<input type="submit" name="add" value="Add">
<input type="submit" name="cancel" value="Cancel">
</p>
</form>
</div>
</body>
</html>
here I created my connection to the database using pdo connection and also require my config.php file for database sign in credentials
here is my pdo.php code:
<?php
require_once 'config.php';
//setting DSN
$dsn = "mysql:host=$host;dbname=$dbname;charset=UTF8";
//creating a PDO instance
try{
$pdo = new PDO($dsn, $user, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if($pdo){
echo "database connected Successfully";
return;
}
}catch(PDOException $e){
echo $e->getMessage();
}
?>
my database sign in credentials are in this file, the username, password and dbname are not necessarily correct, I only changed them for the sake of asking.
here is my config.php code:
<?php
//my variables
$host = 'localhost';
$user = 'myusername';
$password = 'mypass';
$dbname = 'mydb';
?>
my index.php code has a static display for the profile entries, I wanted to be able to add the profiles first so I can make it dynamically display the profiles but here is my index.php code:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>Mandla'ke Makondo's Resume Registry</title>
<!-- bootstrap.php - this is HTML -->
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7"
crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css"
integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r"
crossorigin="anonymous">
</head>
<body>
<div class="container">
<h1>Mandla'ke Makondo's Resume Registry</h1>
<p>
<?php
if(isset($_SESSION['user_id'])){
echo " <a href='logout.php'>Logout</a>";
}
if(!isset($_SESSION['user_id'])){
echo "<a href='login.php'>Please log in</a>";
}
?>
</p>
<?php
if(isset($_SESSION['user_id'])){
echo"<table border = '1'>
<tr><th>Name</th><th>Headline</th><th>Action</th><tr><tr><td>
<a href='view.php?profile_id=5634'>srghrsh yteu yt uuu</a></td><td>
eyetu e5u5</td><td><a href = 'edit.php'>Edit</a> <a href = 'delete.php'>Delete</a></td></tr>
</table>";
echo "<a href='add.php'>Add New Entry</a>";
}
if(!isset($_SESSION['user_id'])){
echo "<table border='1'>
<tr><th>Name</th><th>Headline</th>
<tr>
<tr><td>
<a href='view.php?profile_id=5634'>srghrsh yteu yt uuu</a></td><td>
eyetu e5u5</td></tr>
</table>";
}
?>
</div>
</body>
enter code here
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>Mandla'ke Makondo's Resume Registry</title>
<!-- bootstrap.php - this is HTML -->
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7"
crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css"
integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r"
crossorigin="anonymous">
</head>
<body>
<div class="container">
<h1>Mandla'ke Makondo's Resume Registry</h1>
<p>
<?php
if(isset($_SESSION['user_id'])){
echo " <a href='logout.php'>Logout</a>";
}
if(!isset($_SESSION['user_id'])){
echo "<a href='login.php'>Please log in</a>";
}
?>
</p>
<?php
if(isset($_SESSION['user_id'])){
echo"<table border = '1'>
<tr><th>Name</th><th>Headline</th><th>Action</th><tr><tr><td>
<a href='view.php?profile_id=5634'>srghrsh yteu yt uuu</a></td><td>
eyetu e5u5</td><td><a href = 'edit.php'>Edit</a> <a href = 'delete.php'>Delete</a></td></tr>
</table>";
echo "<a href='add.php'>Add New Entry</a>";
}
if(!isset($_SESSION['user_id'])){
echo "<table border='1'>
<tr><th>Name</th><th>Headline</th>
<tr>
<tr><td>
<a href='view.php?profile_id=5634'>srghrsh yteu yt uuu</a></td><td>
eyetu e5u5</td></tr>
</table>";
}
?>
</div>
</body>
I want to store data (id, profile_image, caption) from another table
(I just download the code for uploading images)
The problem is when I am about to save the data, processForm.php always give me a zero value for Session ID which is my current ID is "1".
I'm a newbie here.
(login.php)
<?php
// Initialize the session
session_start();
// Check if the user is already logged in, if yes then redirect him to
welcome page
if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){
header("location: welcome.php");
exit;
}
// Include config file
require_once "config.php";
// Define variables and initialize with empty values
$username = $password = "";
$username_err = $password_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Check if username is empty
if(empty(trim($_POST["username"]))){
$username_err = "Please enter username.";
} else{
$username = trim($_POST["username"]);
}
// Check if password is empty
if(empty(trim($_POST["password"]))){
$password_err = "Please enter your password.";
} else{
$password = trim($_POST["password"]);
}
// Validate credentials
if(empty($username_err) && empty($password_err)){
// Prepare a select statement
$sql = "SELECT id, username, password FROM users WHERE username = ?";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_username);
// Set parameters
$param_username = $username;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Store result
mysqli_stmt_store_result($stmt);
// Check if username exists, if yes then verify password
if(mysqli_stmt_num_rows($stmt) == 1){
// Bind result variables
mysqli_stmt_bind_result($stmt, $id, $username, $hashed_password);
if(mysqli_stmt_fetch($stmt)){
if(password_verify($password, $hashed_password)){
// Password is correct, so start a new session
session_start();
// Store data in session variables
$_SESSION["loggedin"] = true;
$_SESSION["id"] = $id;
$_SESSION["username"] = $username;
// Redirect user to welcome page
header("location: welcome.php");
} else{
// Display an error message if password is not valid
$password_err = "The password you entered was not valid.";
}
}
} else{
// Display an error message if username doesn't exist
$username_err = "No account found with that username.";
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
}
// Close connection
mysqli_close($link);
}
?>
<!DOCTYPE html>
<html lang="en">
<link rel="stylesheet" type="text/css" href="style.css">
<link rel="icon" href="logo2.png" type="image">
<head>
<title>Fox - Log In | Sign Up</title>
<meta charset="windows-1252">
</head>
<body>
<div class="header" id="myHeader" >
<img src="logo.png" alt="Fox Logo" width="5%" height="20%">
<div class="tooltip">
<img src="text.png" alt="Fox text" width="50%" height="15%" usemap="#foxlogo">
<span class="tooltiptext">Go To Fox Home</span>
</div>
<map name="foxlogo">
<area shape="rect" coords="0,0,133,126" href="login.php">
</map>
</div>
<div class="container">
<img class="img" src="bg2.jpg">
</div>
<div class="signup"><br><br><br><br><br>
<h1 style="text-align:center; font-size:12;">Log In</h1><br>
<form style="margin-left:25px; margin-top: -20px;" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>">
<p style="font-size: 14px; color: white;margin-left: 0px;width: 980px;">Username</p>
<input placeholder="Enter Username" type="text" name="username" class="form-control" value="<?php echo $username; ?>">
<br><span class="help-block"><?php echo $username_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>">
<p style="font-size: 14px; color: white;margin-left: 0px;width: 980px;">Password</p>
<input placeholder="Enter Password" type="password" name="password" class="form-control" >
<span class="help-block"><?php echo $password_err; ?></span>
</div>
<div class="form-group">
<input style="margin-top:20px;" type="submit" class="button" value="Login">
</div>
<p2>Sign up now</p2>
</form>
</div>
<div>
<img class="user" src="user.png">
</div>
<a type="link2" style="margin:30px; text-decoration: none;" href="#">Terms & Policies</a>
<a type="link2" style="text-decoration: none;" href="#">Help</a>
</div>
</body>
</html>
(welcome.php)
<?php
require_once "config.php";
// Initialize the session
session_start();
// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login.php");
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<link rel="stylesheet" type="text/css" href="home.css">
<link rel="icon" href="logo2.png" type="image">
<head>
<meta charset="UTF-8">
<title>Fox | Home</title>
<style type="text/css">
body{ font: 14px sans-serif; text-align: center; }
</style>
</head>
<body>
<br>
<a style="margin-left:90%;position: relative;" href="logout.php" name="signout" class="btn btn-danger">Sign Out</a>
<div style="margin-right:96%"class="tooltip">
<img style="margin-right: 96%;margin-top:0%;" src="logo.png" alt="Fox Logo" width="100%" usemap="#foxlogo">
<span class="tooltiptext">Go To Fox Home</span>
</div>
<map name="foxlogo">
<area shape="rect" coords="0,0,133,126" href="welcome.php">
</map>
<hr>
<div class="profile">
<div class="page-header">
<h1><b><?php echo htmlspecialchars($_SESSION["username"]); ?></b></h1>
<div class="container">
<img name="profile" class="image" src="images/placeholder.png" id="profileDisplay" style="display: block;width: 45%;margin: 10px auto;border-radius:50%;"><br>
<input type="file" name="profileImage" id="profileImage" style="display: none;">
<div class="overlay">
<div class="text"><br>
Update Profile<br><br><br>
View profile
</div>
</div>
<?php
$con = mysqli_connect("localhost","root","","demo");
$q = mysqli_query($con,"SELECT * FROM users WHERE id ='{$_SESSION["id"]}'");
while($row = mysqli_fetch_assoc($q)){
echo $row['created_at'];
}
?>
</div>
<p>
Reset Your Password<br><br><br>
</p>
</div>
</body>
</html>
(config.php)
<?php
/* Database credentials. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'demo');
/* Attempt to connect to MySQL database */
$link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
?>
(updateprofile.php)
I try to echo my current id(1) in this form and it is fine. but in saving id in XAMPP php my admin gives me ZERO. processForm gives me zero value for my SESSION ID
picture1:I try to echo my ID and its fine
Picture2:After I upload a picture. it gives me a zero value for ID
<?php
require_once "config.php";
include 'processForm.php';
// Initialize the session
session_start();
// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login.php");
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<link rel="stylesheet" type="text/css" href="home.css">
<link rel="icon" href="logo2.png" type="image">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<head>
<meta charset="UTF-8">
<title>Fox | Home</title>
<style type="text/css">
body, html{ font: 14px sans-serif; text-align: center;height: 100%; width: 100%; }
</style>
</head>
<body>
<div style="margin-left:90%"class="tooltip">
<span class="tooltiptext">Go To Fox Home</span>
</div>
<map name="foxlogo">
<area shape="rect" coords="0,0,133,126" href="welcome.php">
</map>
</div>
<img style="margin-right: 90%; margin-top:2%;" src="logo.png" alt="Fox Logo" width="5%" usemap="#foxlogo">
<a style="margin-left:90%; margin-top:-5%; position: relative;" href="logout.php" name="signout" class="btn btn-danger">Sign Out</a>
<hr>
<div style="margin-left: 35%"class="container">
<div class="row">
<div class="col-4 offset-m-d4 form-div">
<form enctype="multipart/form-data" action="index.php" method="post" >
<h3 class="text-center">Upload Profile</h3>
<?php //echo htmlspecialchars($_SESSION["username"]);
echo " My id is {$_SESSION["id"]}"; ?>
<div class="form-group text-center">
<img src="images/placeholder.png" id="profileDisplay" onclick="triggerClick()" style="display: block;width: 60%;margin: 10px auto;border-radius:50%;">
<input type="file" name="profileImage" onchange="displayImage(this)" id="profileImage" style="display: none;">
</div>
<div clas="form-group">
<label for="caption">Caption</label>
<textarea name="caption" id="caption" class="form-control"></textarea>
</div>
<div class="form-group">
<br>
<button type="submit" name="save-user" class="btn btn-primary btn-block">Upload</button>
</div>
</form>
</div>
</div>
</div>
<br><br><br><br>
<script src="scripts.js"></script>
</body>
</body>
</html>
(processForm.php)
<?php
require_once "config.php";
//connect db
$conn = mysqli_connect('localhost','root','','demo');
if(isset($_POST['save-user'])){
$caption = $_POST['caption'];
$profileImageName =time() . '_' . $_FILES['profileImage']['name'];
$target = 'images/' . $profileImageName;
if(move_uploaded_file($_FILES['profileImage']['tmp_name'], $target)){
//* */
$sql = "INSERT INTO photos (id,profile_image,caption) VALUES ('{$_SESSION['id']}','$profileImageName','$caption')";
if (mysqli_query($conn, $sql)){
$msg="Image uploaded and saved to database";
$css_class = "alert-success";
}else{
$msg="Database error: Failed to save user";
$css_class = "alert-danger";
}
//
$msg="Image uploaded";
$css_class = "alert-success";
header("location: welcome.php");
}else{
$msg="Failed to upload";
$css_class = "alert-danger";
header("location: updateprofile.php");
}
}
you can add the output of the $_SESSION variable with a var_dump(); After the loggin and another one in the same moment of the saved of the photo in mysql , and compare??? I think that your (processForm.php) is missing at the beginning too ... session_start ();
I designed a validation form which takes the input and checks against the MySQL entry to login and create a session and it works just perfect. But when I try to destroy the session and logout, it doesn't work. Here are the three relevant pages.
Note - the signin.inc.php, signout.inc.php, nav.php, home.php, etc are all inside the "include" folder. Only index.php is outside.
Index.php ->
<?php session_start(); ?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>DigiVault</title>
<link rel="stylesheet" type="text/css" href="css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="css/clean.css">
<link rel="stylesheet" type="text/css" href="css/home.css">
<link rel="stylesheet" type="text/css" href="css/index.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.css" />
</head>
<body>
<header>
<div class="main-brand">
<?php
if(isset($_SESSION['u_id'])){
echo "
<label for='menuToggle' class='menu-icon'>☰</label>
";
}
?>
<h2> DigiV<span style="color:#ccc"><i class="fa fa-lock" aria-hidden="true"></i></span>ult</h2>
</div>
</header>
<?php
if(!isset($_SESSION['u_id'])){
echo "
<nav id='index-nav'>
<ul>
<li id='about-us'>About Us</li>
<li id='get-started'>Get Started</li>
</ul>
</nav>
";
}else {
include_once 'include/nav.php';
}
?>
<div class="main-wrapper">
<?php
if(!isset($_SESSION['u_id'])){
include_once 'include/home.php';
} else{
include_once 'include/user.php';
}
?>
</div>
</body>
</html>
Home.php ->
<div class="signin-container">
<p class="form-header" style="color:white">Login</p>
<form id="signin-form" action="include/signin.inc.php" method="POST">
<input type="text" name="uid" placeholder="Username/Email">
<input type="password" name="pwd" placeholder="Password">
<button type="submit" class="form-button" name="submit-signin">Sign In!</button>
<span id="to-register" style="padding-top:1.13em">Are you new?</span>
</form>
</div>
Nav.php ->
<nav class="user-nav animated bounceInLeft">
<ul>
<li>HOME</li>
<li>ABOUT</li>
<li>FORM</li>
<li>GALLERY</li>
<li>BLOG</li>
<li>
<?php
if(isset($_SESSION['u_id'])){
echo "
<form action='signout.inc.php' method='post'>
<button type='button' name='submit-signout'>Logout</button>
</form>
";
}
?>
</li>
</ul>
</nav>
signin.inc.php ->
<?php
session_start();
if(isset($_POST['submit-signin'])){
include_once 'dbh.inc.php';
$uid= mysqli_real_escape_string($conn,$_POST['uid']);
$pwd= mysqli_real_escape_string($conn,$_POST['pwd']);
if(empty($uid) || empty($pwd)){
header("Location: ../index.php?signin=error");
exit();
}else {
$sql= "SELECT * FROM users where user_uid='$uid' OR user_email='$uid'";
$result = mysqli_query($conn,$sql);
$resultcheck = mysqli_num_rows($result);
if($resultcheck < 1){
header("Location: ../index.php?signin=error");
exit();
} else {
if($row = mysqli_fetch_assoc($result)){
$hashedPwdCheck = password_verify($pwd, $row['user_pwd']);
if($hashedPwdCheck == false){
header("Location: ../index.php?signin=error");
exit();
}
elseif($hashedPwdCheck == true) {
$_SESSION['u_id'] = $row['user_id'];
$_SESSION['u_first'] = $row['user_first'];
$_SESSION['u_last'] = $row['user_last'];
$_SESSION['u_email'] = $row['user_email'];
$_SESSION['u_uid'] = $row['user_uid'];
header("Location: ../index.php");
exit();
}
}
}
}
}else {
header("Location: ../index.php?signin=error");
exit();
}
signout.inc.php ->
<?php
if(isset($_POST['submit-signout'])){
session_start();
session_unset();
session_destroy();
header("Location: ../index.php");
exit();
}
Note - The problem lies with signing out, the validation and signing in works perfectly but I put them just in case if there's a bug somewhere.
<button type='button' name='submit-signout'>Logout</button> need to be <button type='submit' name='submit-signout'>Logout</button>, otherwise it won't submit the form
My reports.php page keeps redirecting me back to the login page even though i have supposedly logged into the website. I am not quite sure what i might be doing wrong here.
reports page:
<?php require_once('dbadmin.php');?>
<?php
session_start();
$user = $_SESSION['users'];
if(!isset($users)){
header("Location:admin_login.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>e</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
</head>
<body>
<header><img src="images/eastersealsclevelogo.png" alt="Easter Seals Logo" width="445" height="300"</img> </header>
<nav>
<ul>
<li>Home</li>
<li>Run Sign-Up</li>
<li>Refer-a-Friend</li>
<li>Admin Login</li>
<li>Reports</li>
</ul>
</nav>
<h1>Reports</h1>
<table border="1" style="width:100%">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Address</th>
<th>City</th>
<th>State</th>
<th>Distance</th>
</tr>
<?php
include('dbuser.php');
$select = "SELECT `fname`, `lname`, `email`, `distance` FROM runner ORDER BY `lname`";
$result = mysql_query($connect, $select) or die ('Oops! '.mysql_error($connect));
if($rowcnt==0){
echo "<tr><td colspan=3>There are currently no results.</td</tr>";}
while($row = mysql_fetch_assoc($result)) {
echo '<tr><td>'.$row['fname'].'</td>';
echo '<td>'.$row['lname'].'</td>';
echo '<td>'.$row['email'].'</td>';
echo '<td>'.$row['distance'].'</td></tr>';
}
?> </table>
<footer></footer>
</body>
</html>
adminlogin page:
<?php require_once('dbadmin.php');?>
<?php
session_start();
if(isset($_POST['adminlogin'])) {
$username = trim($_POST['user']);
$password = trim($_POST['password']);
include('dbadmin.php');
$sql = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
$result = mysql_query($sql) or die("Invalid query: ".mysql_error());
if(mysql_num_rows($result)==0) {
$confirm = '<h2 style="color:red;">Invalid Credentials!</h2>';
} else {
$_SESSION['user'] = $username;
$confirm = '<h2> Login Successful</h2>';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>My Gaming Products Site</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
</head>
<body>
<header><img src="images/eastersealsclevelogo.png" alt="Easter Seals Logo" width="445" height="300"/> </header>
<nav>
<ul>
<li>Home</li>
<li>Run Sign-Up</li>
<li>Refer-a-Friend</li>
<li>Admin Login</li>
<li>Reports</li>
</ul>
</nav>
<h1>Enter Your Login Information</h1>
<?php if(isset($confirm)) echo $confirm; ?>
<form method="post" name="adminlogin" id="adminlogin" title="adminlogin" action="admin_login.php">
<p>User: <br> <input type="text" name="user"></p>
<p>Password: <br><input type="password" name="password"></p>
<p><input type="submit" name="adminlogin" id="adminlogin" value="Login"></p>
</form>
</p>
<footer>| WDD420</footer>
</body>
</body>
</html>
I think it might be something with my reports page but i am not sure if it has anything to do with the login page either.
Try to make your script a bit more readable, I suggest with a function:
<?php
function is_loggedin()
{
return (!empty($_SESSION['users']));
}
session_start();
if(!is_loggedin()){
header("Location:admin_login.php");
exit;
}
?>
By doing $user = $_SESSION['users'] then checking if $user is set, that will always be true because you set it. You will want to check empty().
In your adminlogin.php page the session variable is $_SESSION['user']. But in reports.php page it checks for $_SESSION['users']. Change that to $_SESSION['user'] and change the variable name to $user from $users.
session_start();
$user = $_SESSION['user'];
if(!isset($user)){
header("Location:admin_login.php");
}
Try checking users by this :
session_start();
if(!isset($_SESSION['users']) && empty($_SESSION['users'])){
header("Location:admin_login.php");
}
try this for check the variable is set or not :
session_start();
if(isset($_SESSION['users']) && !empty($_SESSION['users'])) {
print_r($_SESSION['users']);
}
Try this to also to check => var_dump($_SESSION['users']);
Put session_start(); at the first line of your php page.
Note : Also keep in mind, you need to call session_start(); on each and every page if you are making use of session variables.
I'm trying to create a mobile site and I'm using sessions to get the users username. When I view the mobile site on my desktop it works fine and I can get the username of the user from page to page. But when I view the same site on my mobile browser the session doesn't carry over from page to page.
Here is my login page:
<?php
//allow sessions to be passed so we can see if the user is logged in
session_start();
ob_start();
//connect to the database so we can check, edit, or insert data to our users table
$con = mysql_connect(***info to connect to database) or die(mysql_error());
$db = mysql_select_db('dbname', $con) or die(mysql_error());
//include out functions file giving us access to the protect() function made earlier
include "./functions.php";
$userid = $_SESSION['uid'];
$lookupusername = mysql_query("SELECT * FROM users WHERE ID='$userid'");
$row = mysql_fetch_assoc($lookupusername);
$username = $row['username'];
$usercountry = $row['country'];
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="apple-mobile-web-app-capable" content="yes" />
<title>15:11 Project Mobile</title>
<link rel="stylesheet" href="css/jquery.mobile-1.3.0.css" />
<link href="//netdna.bootstrapcdn.com/font-awesome/3.2.0/css/font-awesome.css" rel="stylesheet">
<script src="js/jquery-1.8.3.js"></script>
<script src="js/jquery.mobile-1.3.0.js"></script>
</head>
<body>
<!-- BEGIN LOGIN PAGE -->
<div data-role="page" id="login" style="background: #c66200;">
<div data-role="header">
</div>
<div data-role="content">
<center>
<div class="ui-grid-b">
<img src="images/logo_white.png">
</div>
</center>
<?
//check if the login session does no exist
if(strcmp($_SESSION['uid'],'') == 1){
//if it doesn't display an error message
header('Location: feed.php');
}
else {
//If the user has submitted the form
if($_POST['submit']){
//protect the posted value then store them to variables
$username = protect($_POST['username']);
$thepassword = md5($_POST['password']);
$password = protect($thepassword);
//Check if the username or password boxes were not filled in
if(!$username || !$password){
//if not display an error message
echo "<center>You need to fill in a <b>Username</b> and a <b>Password</b>!</center>";
}else{
//if the were continue checking
//select all rows from the table where the username matches the one entered by the user
$res = mysql_query("SELECT * FROM `users` WHERE `username` = '".$username."'");
$num = mysql_num_rows($res);
//check if there was not a match
if($num == 0){
//if not display an error message
echo "<center>The <b>Username</b> you supplied does not exist!</center>";
}else{
//if there was a match continue checking
//select all rows where the username and password match the ones submitted by the user
$res = mysql_query("SELECT * FROM `users` WHERE `username` = '".$username."' AND `password` = '".$password."'");
$num = mysql_num_rows($res);
//check if there was not a match
if($num == 0){
//if not display error message
echo "<center>The <b>Password</b> you supplied does not match the one for that username!</center>";
}else{
//if there was continue checking
//split all fields fom the correct row into an associative array
$row = mysql_fetch_assoc($res);
//check to see if the user has not activated their account yet
if($row['active'] != 1){
//if not display error message
echo "<center>You have not yet <b>Activated</b> your account!</center>";
}else{
//if they have log them in
//set the login session storing there id - we use this to see if they are logged in or not
$_SESSION['uid'] = $row['id'];
//show message
echo "<center>You have successfully logged in!</center>";
//update the online field to 50 seconds into the future
$time = date('U')+50;
mysql_query("UPDATE `users` SET `online` = '".$time."' WHERE `id` = '".$_SESSION['uid']."'");
//redirect them to the usersonline page
$loginpage="#feed";
header("Location: feed.php" . $loginpage);
exit();
}
}
}
}
}
}
?>
<center>
<form action="index.php#feed" method="post" data-ajax="false">
<div style="width: 75%; border-top: 1px solid #ffffff; margin-top: 20px; padding-top: 20px; border-bottom: 1px solid #ffffff; margin-bottom: 20px; padding-bottom: 20px;">
<div class="ui-hide-label">
<label for="username">Username:</label>
<input type="text" name="username" id="username" value="" placeholder="username" data-mini="true" style="color: #c66200;"/><br>
<label for="password">password:</label>
<input type="password" name="password" id="password" value="" placeholder="password" data-mini="true" style="color: #c66200;"/><br>
</div>
<div style="width: 40%;">
<input type="submit" data-role="button" name="submit" value="Login" data-mini="true" style="color: #c66200 !important;"/>
</div>
</div>
</center>
<?
ob_end_flush();
?>
</div>
<div data-role="footer">
</div>
</div>
<!-- END LOGIN PAGE -->
</body>
</html>
Here is what I have for my feed.php page which the login page routes to. I can get the users info on this page. Whenever I click a link to go to the "browseresults" page the information doesn't carry over.
<?php
//allow sessions to be passed so we can see if the user is logged in
session_start();
ob_start();
//connect to the database so we can check, edit, or insert data to our users table
$con = mysql_connect(***db info***) or die(mysql_error());
$db = mysql_select_db('dbname', $con) or die(mysql_error());
//include out functions file giving us access to the protect() function made earlier
include "./functions.php";
$userid = $_SESSION['uid'];
$lookupusername = mysql_query("SELECT * FROM users WHERE ID='$userid'");
$row = mysql_fetch_assoc($lookupusername);
$username = $row['username'];
$usercountry = $row['country'];
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="apple-mobile-web-app-capable" content="yes" />
<title>15:11 Project Mobile</title>
<link rel="stylesheet" href="css/jquery.mobile-1.3.0.css" />
<link href="font-awesome/css/font-awesome.css" rel="stylesheet">
<script src="js/jquery-1.8.3.js"></script>
<script src="js/jquery.mobile-1.3.0.js"></script>
</head>
<body>
<!-- BEGIN PAGE 3 -->
<div data-role="page" id="browse">
<div data-role="panel" id="settingspanel" data-position="left" data-display="overlay">
<ul data-role="controlgroup">
<li>Page Two</li>
<li>Page Three</li>
<li>Page Four</li>
<li>Logout</li>
</ul>
</div>
<div data-role="header" data-position="fixed" data-theme="c" data-tap-toggle="false" data-id="foo1" style="padding-top: 5px; border-bottom: 1px solid #eccfb3; padding-bottom: 5px;">
<center><img src="images/logo_app_white.png" width="30px"></center>
</div>
<div data-role="content">
<?php
$fquery = "SELECT state, city, count(city) as num FROM needs WHERE country='$usercountry' AND status='posted' GROUP BY state, city ORDER BY state, city";
if ($result = mysql_query($fquery)) {
$num_rows = mysql_num_rows($result);
echo "<table>";
$i = 1;
$cols = 2;
$prev = "";
while ($frows = mysql_fetch_array($result)) {
$fcity = $frows['city'];
$fstate = $frows['state'];
$fcitycount = $frows['num']; // num is holding your count by city
if ($fstate != $prev) {
echo "<tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr><th align='left'>$fstate</th></tr><tr>";
}
echo "<td><a href='browseresults.php?city=$fcity&state=$fstate'>$fcity, $fstate ($fcitycount)</a> </td>";
echo ($i < $num_rows) ? ((($i % $cols) == 0) ? '</tr>' : '') : '';
$i++;
$prev = $fstate;
}
echo "</table>";
}
?>
</div>
<div data-role="footer" data-position="fixed" data-theme="c" data-tap-toggle="false" data-id="foo1" style="border-top: 1px solid #eccfb3; padding-top: 5px;">
<div data-role="navbar" style="background: #ce8339;">
<ul>
<li>My Feed</li>
<li>Submit</li>
<li>Browse</li>
<li>Projects</li>
</ul>
</div><!-- /navbar -->
</div>
</div>
<!-- END PAGE 3 -->
</body>
</html>
And here is the browseresults.php page which is the page that is not getting the session data.
<?php
//allow sessions to be passed so we can see if the user is logged in
session_start();
ob_start();
//connect to the database so we can check, edit, or insert data to our users table
$con = mysql_connect(***dbinfo***) or die(mysql_error());
$db = mysql_select_db(dbname, $con) or die(mysql_error());
//include out functions file giving us access to the protect() function made earlier
include "./functions.php";
$userid = $_SESSION['uid'];
$lookupusername = mysql_query("SELECT * FROM users WHERE ID='$userid'");
$row = mysql_fetch_assoc($lookupusername);
$username = $row['username'];
$usercountry = $row['country'];
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="apple-mobile-web-app-capable" content="yes" />
<title>15:11 Project Mobile</title>
<link rel="stylesheet" href="css/jquery.mobile-1.3.0.css" />
<link href="font-awesome/css/font-awesome.css" rel="stylesheet">
<script src="js/jquery-1.8.3.js"></script>
<script src="js/jquery.mobile-1.3.0.js"></script>
</head>
<body>
<!-- BEGIN PAGE 1 -->
<?
echo "$username";
?>
<!-- END PAGE 1 -->
</body>
</html>
no username is outputted. Can anyone help explain why and help me get this sorted out please?