Unable to use $_SESSION in an other file (PHP) - php

Hello good afternoon, I'm having the trouble of not being able to use add a $_POST value to my $_SESSION variable so that I can use it later in my profile file.
I can give it other values like "hello" outside the if and it echoes hello in levraiprofilewesh.php.
I've tried making $_SESSION a super global variable and global but it didn't work.
I've been stuck on it for a few hours :(.
I don't need to upload the website on the web, it's just for local use, so there's no need for privacy feedback although it has helped me for the future.
login.php code:
<?php
session_start();
include("db_connect.php");
if(isset($_POST['login_button'])) {
$user_email = trim($_POST['user_email']);
$user_password = trim($_POST['password']);
$_SESSION['password'] = $user_password;
$usql = "SELECT * FROM users WHERE Email='$user_email' && Password='$user_password'";
$uresult = mysqli_query($db, $usql) or die("database error:". mysqli_error($db));
$urow = mysqli_fetch_assoc($uresult);
//while($row = mysqli_fetch_array($uresult))
//$STPMARCHEFRERE = $row['Firstname'];
//$SESSION = $row['Firstname'];
if($urow['Password']==$user_password){
setcookie("userid",$user_password,time()+(60*60*24*7));
setcookie("useremail",$user_email,time()+(60*60*24*7));
//$GLOBALS['SESSION'] = $user_password;
$time=time();
$queryz = "UPDATE Users
Set Online='Online',
Time='$time'
WHERE Password='$user_password' ";
$db->query($queryz) or die('Errorr, query failed to upload');
echo "ok";
} else {
echo "email or password does not exist."; // wrong details
}
}
?>
levraiprofilewesh.php code:
<?php
session_start();
include("login.php");
$connection = mysqli_connect('localhost', 'root','','phpchart');
if(isset($_SESSION['password'])) {
$username = $_SESSION['password'];
$query = "SELECT *
FROM users
WHERE Password = '%$username%'";
$select_user_profile_query = mysqli_query($connection, $query);
while($row = mysqli_fetch_array($select_user_profile_query)) {
$post_tamere = $row['Firstname'];
$post_tondaron = $row['Sirname'];
$post_tasoeur = $row['Phone'];
$post_tonneveu = $row['Institution'];
$post_julia = $row['Email'];
}
}
?>
<?php
if(isset($_POST['edit_user'])) {
$user_firstname = $_POST['user_firstname'];
$user_lastname = $_POST['user_lastname'];
$user_role = $_POST['user_role'];
//$post_image = $_FILES['image']['name'];
//$post_image_temp = $_FILES['image']['tmp_name'];
$username = $_POST['username'];
$user_email = $_POST['user_email'];
$user_password = $_POST['user_password'];
//$post_date = date('d-m-y');
//move_uploaded_file($post_image_temp, "./images/$post_image" );
$query = "SELECT randSalt FROM users";
$select_randsalt_query = mysqli_query($connection, $query);
if(!$select_randsalt_query) {
die("Query Failed" . mysqli_error($connection));
}
$row = mysqli_fetch_array($select_randsalt_query);
$salt = $row['randSalt'];
$hashed_password = crypt($user_password, $salt);
$query = "UPDATE users SET ";
$query .="user_firstname = '{$user_firstname}', ";
$query .="user_lastname = '{$user_lastname}', ";
$query .="user_role = '{$user_role}', ";
$query .="username = '{$username}', ";
$query .="user_email = '{$user_email}', ";
$query .="user_password = '{$hashed_password}' ";
$query .= "WHERE username = '{$username}' ";
$edit_user_query = mysqli_query($connection,$query);
confirmQuery($edit_user_query);
}
?>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<title>Hello, world!</title>
</head>
<div id="wrapper">
<!-- Navigation -->
<div id="page-wrapper">
<div class="container-fluid">
<!-- Page Heading -->
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Welcome to Profile
<small>Author</small>
</h1>
<form action="" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="title">Firstname</label>
<input type="text" value="<?php echo $post_tamere; ?>" class="form-control" name="user_firstname">
</div>
<div class="form-group">
<label for="post_status">Lastname</label>
<input type="text" value="<?php echo $post_tondaron; ?>" class="form-control" name="user_lastname">
</div>
<div class="form-group">
<select name="user_role" id="">
<option value="subscriber"><?php echo $user_role; ?></option>
<?php
if($user_role == 'admin') {
echo "<option value='subscriber'>subscriber</option>";
} else {
echo "<option value='admin'>admin</option>";
}
?>
</select>
</div>
<!--<div class="form-group">
<label for="post_image">Post Image</label>
<input type="file" name="image">
</div>-->
<div class="form-group">
<label for="post_tags">Phone</label>
<input type="text" value="<?php echo $post_tasoeur; ?>" class="form-control" name="username">
</div>
<div class="form-group">
<label for="post_content">Email</label>
<input type="email" value="<?php echo $post_tonneveu; ?>" class="form-control" name="user_email">
</div>
<div class="form-group">
<label for="post_content">Password</label>
<input type="password" value="<?php echo $post_julia; ?>" class="form-control" name="user_password">
</div>
<h1><?php echo $_SESSION['superhero']; ?></h1>
<div class="form-group">
<input class="btn btn-primary" type="submit" name="edit_user" value="Update Profile">
</div>
</form>
</div>
</div>
<!-- /.row -->
</div>
<!-- /.container-fluid -->
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script>

Related

getting Invalid Email or Password in my localhost website

i'm using php 7.2.31 .. i'v already imported my DB file in phpmyAdmin
when i'm trying to login in admin website page (or the others 2 users ) it's getting this message :-
(Invalid Email or Password )
the email address and password already in the database and it's correct .. ! !
here's my login-in code :-
<?php session_start();?>
<link rel="stylesheet" href="popup_style.css">
<!DOCTYPE html>
<html lang="en">
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<head>
<title>Admin Panel</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="description" content="#">
<meta name="keywords" content="Admin , Responsive">
<meta name="author" content="Nikhil Bhalerao +919423979339.">
<link href="https://fonts.googleapis.com/css?family=Open+Sans:400,600,800" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="files/bower_components/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="files/assets/icon/themify-icons/themify-icons.css">
<link rel="stylesheet" type="text/css" href="files/assets/icon/icofont/css/icofont.css">
<link rel="stylesheet" type="text/css" href="files/assets/css/style.css">
</head>
<body class="fix-menu">
<?php
include('connect.php');
extract($_POST);
if(isset($_POST['btn_login']))
{
$passw = hash('sha256', $_POST['password']);
function createSalt()
{
return '2123293dsj2hu2nikhiljdsd';
}
$salt = createSalt();
$pass = hash('sha256', $salt . $passw);
//echo $pass;
if($_POST['user'] == 'admin'){
$sql = "SELECT * FROM admin WHERE loginid='" .$email . "' and password = '". $pass."'";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($result);
//print_r($row);
$_SESSION["adminid"] = $row['id'];
$_SESSION["id"] = $row['id'];
$_SESSION["username"] = $row['username'];
$_SESSION["password"] = $row['password'];
$_SESSION["email"] = $row['loginid'];
$_SESSION["fname"] = $row['fname'];
$_SESSION["lname"] = $row['lname'];
$_SESSION['image'] = $row['image'];
$_SESSION['user'] = $_POST['user'];
}else if($_POST['user'] == 'doctor'){
$sql = "SELECT * FROM doctor WHERE loginid='" .$email . "' and password = '". $pass."'";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($result);
//print_r($row);
$_SESSION["doctorid"] = $row['doctorid'];
$_SESSION["id"] = $row['doctorid'];
$_SESSION["password"] = $row['password'];
$_SESSION["email"] = $row['loginid'];
$_SESSION["fname"] = $row['doctorname'];
$_SESSION['user'] = $_POST['user'];
}else if($_POST['user'] == 'patient'){
$sql = "SELECT * FROM patient WHERE loginid='" .$email . "' and password = '". $pass."'";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($result);
//print_r($row);
$_SESSION["patientid"] = $row['patientid'];
$_SESSION["id"] = $row['patientid'];
$_SESSION["password"] = $row['password'];
$_SESSION["email"] = $row['loginid'];
$_SESSION["fname"] = $row['patientname'];
$_SESSION['user'] = $_POST['user'];
}
//print_r($row);
$count=mysqli_num_rows($result);
if($count==1 && isset($_SESSION["email"]) && isset($_SESSION["password"])) {
{
?>
<div class="popup popup--icon -success js_success-popup popup--visible">
<div class="popup__background"></div>
<div class="popup__content">
<h3 class="popup__content__title">
Success
</h3>
<p>Login Successfully</p>
<p>
<!-- <button class="button button--success" data-for="js_success-popup"></button> -->
<?php echo "<script>setTimeout(\"location.href = 'index.php';\",1500);</script>"; ?>
</p>
</div>
</div>
<!-- <script>
window.location="index.php";
</script> -->
<?php
}
}
else {?>
<div class="popup popup--icon -error js_error-popup popup--visible">
<div class="popup__background"></div>
<div class="popup__content">
<h3 class="popup__content__title">
Error
</h3>
<p>Invalid Email or Password</p>
<p>
<button class="button button--error" data-for="js_error-popup">Close</button>
</p>
</div>
</div>
<?php
}
}
?>
<?php
$que="select * from manage_website";
$query=$conn->query($que);
while($row=mysqli_fetch_array($query))
{
//print_r($row);
extract($row);
$business_name = $row['business_name'];
$business_email = $row['business_email'];
$business_web = $row['business_web'];
$portal_addr = $row['portal_addr'];
$addr = $row['addr'];
$curr_sym = $row['curr_sym'];
$curr_position = $row['curr_position'];
$front_end_en = $row['front_end_en'];
$date_format = $row['date_format'];
$def_tax = $row['def_tax'];
$logo = $row['logo'];
}
?>
<section class="login-block">
<div class="container-fluid">
<div class="row">
<div class="col-sm-12">
<div class="auth-box card" >
<div class="text-center">
<image class="profile-img" src="uploadImage/Logo/<?php echo $logo; ?>" style="width: 60%"></image>
</div>
<div class="card-block" >
<div class="row m-b-20">
<div class="col-md-12">
<h5 class="text-center txt-primary">Sign In</h5>
</div>
</div>
<form method="POST" >
<div class="form-group form-primary">
<select name="user" class="form-control" required="">
<option value="">-- Select One --</option>
<option value="admin">Admin</option>
<option value="doctor">Doctor</option>
<option value="patient">Patient</option>
</select>
<span class="form-bar"></span>
</div>
<div class="form-group form-primary">
<input type="email" name="email" class="form-control" required="" placeholder="Email">
<span class="form-bar"></span>
</div>
<div class="form-group form-primary">
<input type="password" name="password" class="form-control" required="" placeholder="Password">
<span class="form-bar"></span>
</div>
<div class="row m-t-25 text-left">
<div class="col-12">
<div class="forgot-phone text-right f-right">
Forgot Password?
</div>
</div>
</div>
<div class="row m-t-30">
<div class="col-md-12">
<button type="submit" name="btn_login" class="btn btn-primary btn-md btn-block waves-effect text-center m-b-20">LOGIN</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<script type="text/javascript" src="files/bower_components/jquery/js/jquery.min.js"></script>
<script type="text/javascript" src="files/bower_components/jquery-ui/js/jquery-ui.min.js"></script>
<script type="text/javascript" src="files/bower_components/popper.js/js/popper.min.js"></script>
<script type="text/javascript" src="files/bower_components/bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript" src="files/bower_components/jquery-slimscroll/js/jquery.slimscroll.js"></script>
<script type="text/javascript" src="files/bower_components/modernizr/js/modernizr.js"></script>
<script type="text/javascript" src="files/bower_components/modernizr/js/css-scrollbars.js"></script>
<script type="text/javascript" src="files/bower_components/i18next/js/i18next.min.js"></script>
<script type="text/javascript" src="files/bower_components/i18next-xhr-backend/js/i18nextXHRBackend.min.js"></script>
<script type="text/javascript" src="files/bower_components/i18next-browser-languagedetector/js/i18nextBrowserLanguageDetector.min.js"></script>
<script type="text/javascript" src="files/bower_components/jquery-i18next/js/jquery-i18next.min.js"></script>
<script type="text/javascript" src="files/assets/js/common-pages.js"></script>
</body>
<!-- for any PHP, Codeignitor or Laravel work contact me at mayuri.infospace#gmail.com -->
</html>
and the check-login file :-
<?php
session_start();
if((isset($_SESSION["email"]) && isset($_SESSION["password"]))){
$myemail = $_SESSION['email'];
}else {
header("location:login.php");
}
?>
thanks !
You are getting
invalid Email and password because the variable $email which you are using in your query has no email from the form. After this line:
$pass = hash('sha256', $salt . $passw);
Add this line:
$email = $_POST['email'];
This will solve your problem. But there are many other other problems in your code like it is open to SQL injection. You can use prepare statements.
PHP Prepared Statements. Always validate the data coming from users.
Do not store password as a plain text. See here password-encryption-storing-password-in-session
If you want to get only one record from a database always use LIMIT 1 in your code.

Problem in if and {endif} and {endwhile} in my first Project?

This problem in php I need solution in this day
Please for my homework
Can you help me in my homework please because I'm not working but I'm reading in my university Please can you solve this problem.
Can you explain to my this problem or can connection to my desktop to solution this problem or can send explain .
This code
index.php:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
</head>
<body>
<?php require_once 'process.php'?>
<?php
if(isset ($_SESSION['message']));?>
<div class="alert alert-<?=$_SESSION['msg_type']?>">
<?php
echo $_SESSION['message'];
unset($_SESSION['message']);
// and this problem !
<?php endif ?>
?>
<div class="contener">
<?php
$mysqli = new mysqli('localhost', 'root', 'rootroot','crudcrud') or die(mysqli_error($mysqli));
$result = $mysqli->query("SELECT * FORM data") or die($mysqli->error);
?>
<div class="row justify-content-center">
<table class="table">
<thead>
<tr>
<th>usernames</th>
<th>Passowrds</th>
<th colspan="2">Action</th>
<tr>
</thead>
</div>
<?php while ($row = $result->fetch_assoc()): ?>
<tr>
<td><?php echo $row ['username'];?></td>
<td><?php echo $row ['password'];?></td>
<td>
<a href="index.php?edit=<?php echo $row ['id']; ?>"
class="btn btn-info">edit</a>
<a hraf="process.php?delete=<?php echo $row ['id']; ?>"
class="btn btn-danger">
</td>
</tr>
//this problem !
<?php endwhile; ?>
</table>
<?php
function pre_r( $arry ){
echo'<pre>';
print_r($array);
echo'</pre>';
}
?>
<div class="col-lg-6 m-auto">
<form action="process.php" method="post">
<input type="hidden" name="id" value=" <?php echo $id ?> "
<br><br><div class="card">
<div class="card-header bg-dark">
<h1 class="text-white text-center"> Insert Operation </h1>
</div><br>
<label> Username: </label>
<input type="text" name="username" class="form-control" value=" <?php echo $username; ?> " placeholder="Enter Your Username"> <br>
<label> Password: </label>
<input type="text" name="password" class="form-control" value=" <?php echo $password; ?> " placeholder="Password"> <br>
<?php
if ($update == true)
?>
<button class="btn btn-info" type="submit" name="update"> update </button>
<?php else: ?>
<button class="btn btn-success" type="submit" name="save"> Submit </button>
// and this problem !
<?php endif; ?>
</div>
</form>
</div>
</div>
</body>
</html>
code
process.php
=======================================================
<?php
session_start();
$mysqli = new mysqli('localhost', 'root', 'rootroot','crudcrud') or
die(mysqli_error($mysqli));
$id = 0;
$update = false;
$username = '';
$password = '';
if (isset ($_POST['save'])){
$usernames = $_POST['username'];
$passwords = $_POST['password'];
$mysqli->query("INSERT INTO data (username, password) VALUES('$username', '$password')") or
die($mysqli->error);
$_SESSION['message'] = "Record has been saved!";
$_SESSION['msg_type'] = "success!";
header('loocation: index.php');
}
if (isset ($_GET['delete'])){
$id = $_GET['delete'];
$mysqli->query("DELETE FROM data WHERE id=$id") or
die($mysqli->error());
SESSION['message'] = "Record has been deleted!";
SESSION['msg_type'] = "denger!";
header('loocation: index.php');
}
if (isset ($_GET['edit'])){
$id = $_GET['edit'];
$update = true;
$result = $mysqli->query("DELETE FROM data WHERE id=$id") or
die($mysqli->error());
if (count($result)==1){
$row = $result->fetch_array();
$username = $row['username'];
$password = $row['password'];
}
}
if (isset($_POST['update'])){
$id = $_POST['id'];
$username = $_POST['username'];
$password = $_POST['password'];
$mysqli->query("UPDATE data SET username='$username', password='$password' WHERE id=$id") or
die($mysqli->error);
$_SESSION['message'] = "Record has been Update!";
$_SESSION['msg_type'] = "warning!";
header('loocation: index.php');
}
This piece is completely wrong:
if(isset ($_SESSION['message']));?> //<-- : not ;
<div class="alert alert-<?=$_SESSION['msg_type']?>">
<?php
echo $_SESSION['message'];
unset($_SESSION['message']);
//<-- no closing tag
<?php endif ?> //<-- missing ;
Should be:
if(isset ($_SESSION['message'])):?>
<div class="alert alert-<?=$_SESSION['msg_type']?>">
<?php
echo $_SESSION['message'];
unset($_SESSION['message']);
endif; ?>
It get's pretty ugly when you use a lot of PHP and HTML in the same file, it might be time to look at using a template engine.

Update query is not updating data in PHP mysqli (procedural)

I am facing issues with id='$id'
SELECT Query is working fine but update query is not working
if I put any id number instead of $id it updates the data but when I use $id it just does nothing.
<?php
$db = mysqli_connect("localhost", "root", "", "aashir");
$id = $_GET['id'];
$query = "SELECT * FROM students WHERE id='$id' ";
$result = mysqli_query($db, $query);
while ($row = mysqli_fetch_array($result)) {
$key = $row['id'];
$name = $row['student_name'];
$fname = $row['father_name'];
$program = $row['student_program'];
}
if (isset($_POST['submit'])) {
$s_name = $_POST['s_name'];
$s_fname = $_POST['s_fname'];
$s_program = $_POST['s_program'];
$query2 = "UPDATE students SET student_name = '$s_name', father_name = '$s_fname', student_program = '$s_program' WHERE id='$id' ";
mysqli_query($db, $query2);
header("Location:show.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Edit Student</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
</head>
<body>
<div class="container mt-5">
<form method="POST" action="edit.php" class="col-lg-6 offset-lg-3">
<h2 class="text-center">Edit a Student</h2>
<div class="form-group">
<input type="text" name="s_name" class="form-control" value="<?php echo $name; ?>">
</div>
<div class="form-group">
<input type="text" name="s_fname" class="form-control" value="<?php echo $fname; ?>">
</div>
<div class="form-group">
<input type="text" name="s_program" class="form-control" value="<?php echo $program; ?>">
</div>
<div class="form-group">
<input type="submit" name="submit" class="btn btn-success" value="Update">
</div>
</form>
</div>
</body>
</html>
you have two options to fix your issue (without talking about SQL injection, already quoted in the comments and to be addressed since it is a huge security risk for your application)
Change the form action to pass the id to the page while processing the form:
action="edit.php?id=<?php echo $id; ?>"
or better add an hidden input with the id:
<input type="hidden" name="id" value="<?php echo $id; ?>">
and then:
if (isset($_POST['submit'])) {
$s_name = $_POST['s_name'];
$s_fname = $_POST['s_fname'];
$s_program = $_POST['s_program'];
$id = $_POST['id'];
in this case the action can remain the same.
Posting the form you are reloading the page and not passing the id anymore via url as at the first load
You're performing the UPDATE using a POST request, yet you're looking for $id as a GET parameter. This way, $id will always be undefined, and thus the query fails.
You can try overloading the form action URL, like so:
<form method="POST" action="edit.php?id=<?php echo $_GET['id']; ?>" class="col-lg-6 offset-lg-3">

Unable to retrieve data from DB and using $_SESSION variable

I've been working on a project that has to do with renting houses. Visitors can register or log-in, and only logged-in users can Add a house for rental. Each user has his own profile showing his username, email and accommodations he has uploaded for rental.
My problem is that I cannot retrieve the email of the logged in user. Also, on my MySQL DB I'm using a foreign key in my accom(modation) table, which references the primary key(USER-ID) of the users. The key fails to match the USER-ID.
Any advice would be really helpful. Thank you a lot in advance.
Posting some of the code below:
register.php
<?php include('server.php') ?>
<? php
if (isset($_SESSION['username'])) {
$_SESSION['msg'] = "You're now logged in.";
unset($_SESSION["register.php"];
header('Location: user_index.php');
}
?>
<!DOCTYPE html>
<html>
<link href="https://fonts.googleapis.com/css?family=Eater" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="mystyle.css">
<body>
<p id="pagetitle">Booking Planet </p>
<div class="navbar" id="topnav">
<button onclick="document.getElementById('id01').style.display='block'"
style="width:auto;">Login</button>
<button onclick="document.getElementById('id02').style.display='block'"
style="width:auto;">Register</button>
HOME
</div>
<?php
$db = mysqli_connect('localhost', 'root', '', 'registration');
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($db,"SELECT * FROM accom");
echo "<p> </p>";
echo "<div class='acclist'> Explore some fairytale destinations.. </div>";
echo "<ul>";
while($row = mysqli_fetch_array($result))
{
$image=$row['image'];
$target = "images/".basename($image);
echo "<img src='" . $target . "' width=800 height=500/>";
echo "<li id='title'><b>" . $row['title'] . "</b></li>";
echo "<li> Description: <i>" . $row['description'] . "</i></li>";
echo "<li> Address: <i>". $row['address'] . "</i></li>";
echo "<li> Available from: <i>" . $row['checkin'] . "</i></li>";
echo "<li> Available until: <i>" . $row['checkout'] . "</i></li>";
?><button onclick="document.getElementById('id01').style.display='block'"
type='button' class='bookbtn'>Log-in to book now!</button>
<?php
echo "<li><img src='sepline.png' width=1500 height=75> </li>";}
echo "</ul>";
mysqli_close($db);
?>
</div>
<div id="id01" class="modal">
<? php include('errors.php'); ?>
<form action="" method="post" class="modal-content animate" name="login" >
<div class="logocontainer"> Booking Planet
</div>
<h3> Account Log-in. </h3>
<div class="container">
<? php echo $errors; ?>
<label><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="username" required>
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="password"
required>
<button type="submit" name="login_user">Login</button>
</div>
<div class="container">
<button type="button" class="cancelbtn" id="cncl1">Cancel</button>
</div>
</form>
</div>
<!-- REGISTRATION -->
<div id="id02" class="modal">
<form action="" method="post" class="modal-content animate" name="register"
>
<div class="logocontainer"> Booking Planet
</div>
<h3> Create an account. </h3>
<div class="container">
<label><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="username" required>
<label><b>Name</b></label>
<input type="text" placeholder="Enter your Name!" name="name" required>
<label><b>Surname</b></label>
<input type="text" placeholder="Enter your Surname!" name="surname" required>
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="password" required>
<label><b>Email</b></label>
<input type="email" placeholder="Enter Email" name="email" required>
<div class="avatar"><label>Select your avatar: </label>
<input type="file" name="avatar" accept="image/*" required />
<button type="submit" name="reg_user">Register</button>
</div>
<div class="container">
<button type="button" class="cancelbtn" id="cncl2">Cancel</button>
</div>
</form>
</div>
<script src="myscripts.js"></script>
</body>
</html>
user_index.php: is pretty much similar to register.php, it's where people who have registered or logged-in are redirected. I'm posting the beginning of the code.
<?php include('server.php'); ?>
<?phpinclude('auth.php');
session_start();
if ($_SESSION['username']<1) {
session_destroy();
unset($_SESSION['username']);
header("Location: register.php");
}
$db = mysqli_connect('localhost', 'root', '', 'registration');
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($db,"SELECT email FROM users WHERE
username='$_SESSION['username']'");
$row = mysqli_fetch_array($result);
$_SESSION['email'] = $result;
$username = $_SESSION['username'];
$_SESSION['id']=$id;
header("Location: server.php");
?>
server.php: contains the validation for registration and logging-in. Also, links to the DB. I will be skipping the validation parts.
<?php
session_start();
$email=$_SESSION['email'];
// initializing variables
$errors = array();
// connect to the database
$db = mysqli_connect('localhost', 'root', '', 'registration');
//...validationon code
//once no errors, register user
if (count($errors) == 0) {
$password = md5($password);//encrypt the password before saving in the
database
$query = "INSERT INTO users (username, email, password, name, surname)
VALUES('$username', '$email', '$password', '$name', '$surname')";
mysqli_query($db, $query);
$_SESSION['username'] = $username;
$_SESSION['email'] = $email;
$_SESSION['success'] = "You are now logged in";
header('Location: user_index.php');
}
}
// LOGIN USER
$msg = '';
if (isset($_POST['login_user'])) {
$username = mysqli_real_escape_string($db, $_POST['username']);
$password = mysqli_real_escape_string($db, $_POST['password']);
if (empty($username)) {
array_push($errors, "Username is required");
}
if (empty($password)) {
array_push($errors, "Password is required");
}
if (count($errors) == 0) {
$password = md5($password);
$query = "SELECT * FROM users WHERE username='$username' AND
password='$password'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
session_start();
$_SESSION['email']=$row['email'];
$_SESSION['username'] = $username;
$_SESSION['email'] = $email;
$_SESSION['id']= $id;
$_SESSION['success'] = "You are now logged in";
header('Location: user_index.php');
}else {
echo $msg;
}
}
}
auth.php
<?php
session_start();
if(!isset($_SESSION["username"])){
echo $errors; }
?>
For any additional information you might need, please feel free to ask anything.
I am genuinely sorry for the block of text and code.

php $_SESSION['id'] is causing errors

index.php :
<?php
session_start();
require 'res/connection.php';
if($_SESSION['id'] !== null){
header("Location: profile.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Welcome to the members section, Login or Register</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="js/fadein.js"></script>
<link rel="stylesheet" type="tex/css" href="css/master.css"/>
<link rel="stylesheet" type="tex/css" href="css/form.css"/>
</head>
<body>
<div class="container loginbdy">
<div class="row">
<div class="col-lg-12 loginform">
<form action="" method="post" class="form">
<h2>Log In :</h2>
<label name="username-label">Username :</label>
<input class="form-control" type="text" placeholder="Your username" name="username" id="username" maxlength="120"/>
<label name="password-label">Password :</label>
<input class="form-control" type="password" placeholder="Your password" name="password" id="password" maxlength="35"/></br>
<input type="submit" class="btn btn-default" value="Log In" name="submit" /></br>
<p>Not a member yet ? <a href="register.php" ><i><b>register</b></i></a></p>
</form>
</div>
<div class="col-lg-3 errorlogin">
<?php
if(isset($_POST['submit'])){
$username = mysqli_real_escape_string($con, $_POST['username']);
$password = mysqli_real_escape_string($con, $_POST['password']);
if(empty($username)){
echo '
<div class="alert alert-danger">
<strong>Error!</strong> username is empty.
</div>
';
}elseif(empty($password)){
echo '
<div class="alert alert-danger">
<strong>Error!</strong> password is empty.
</div>
';
}else{
$result = mysqli_query($con,"SELECT * FROM `users` WHERE `username` = '$username'");
$row_cnt = mysqli_num_rows($result);
if($row_cnt === 0){
echo '
<div class="alert alert-danger">
<strong>Error!</strong> The username you tried to login with doesn\'t exist, would you like to register it ?
</div>
';
}else{
$row = mysqli_fetch_array($result);
$userpassword = $row['password'];
$salt = $row['salt'];
$id = $row['user_id'];
$hashedpassword = crypt($password,$salt);
if($hashedpassword === $userpassword){
$_SESSION['id'] = $id;
echo "
<div class=\"alert alert-success\">
<strong>Session has been set</strong> you are now logged in! your user id is "; echo $_SESSION['id']; echo '
</div>
';
$user_id = mysqli_query($con, "SELECT * FROM `users` WHERE `username` = '$username'");
$row = mysqli_fetch_array($user_id);
$id = $row['user_id'];
$firstname = $row['first name'];
$lastname = $row['last name'];
$semail = $row['email'];
$susername = $row['username'];
$spaid = $row['paid'];
$sdate = $row['date_created'];
$sconfirmed = $row['confirmed'];
$_SESSION['id'] = $id;
$_SESSION['fname'] = $firstname;
$_SESSION['lname'] = $lastname;
$_SESSION['email'] = $semail;
$_SESSION['username'] = $susername;
$_SESSION['paid'] = $spaid;
$_SESSION['date'] = $sdate;
$_SESSION['confirmed'] = $sconfirmed;
header('Location: profile.php');
}else{
echo '
<div class="alert alert-danger">
<strong>Error!</strong> The username or password you entered is incorrect!
</div>
';
}
}
}
}
?>
</div>
</div>
</div>
</body>
</html>
register.php :
<?php
session_start();
require 'res/connection.php';
if($_SESSION['id'] !== null){
header("Location: profile.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Welcome to the members section, Login or Register</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="tex/css" href="css/master.css"/>
<link rel="stylesheet" type="tex/css" href="css/form.css"/>
</head>
<body background="res/background.jpg">
<div class="container">
<div class="row">
<div class="col-lg-9 registerform">
<?php
?>
<form action="" method="post" class="form">
<h2>Register :</h2>
<label name="lname-label">First Name :</label>
<input class="form-control" type="text" placeholder="Your First Name" name="fname" id="fname" maxlength="100" tabindex="1" autofocus />
<label name="lname-label">Last Name :</label>
<input class="form-control" type="text" placeholder="Your Last Name" name="lname" id="lname" maxlength="100" tabindex="2" />
<label name="username-label">Username :</label>
<input class="form-control" type="text" placeholder="Your desired Username" name="username" id="username" maxlength="24" tabindex="3" />
<label name="email-label">Email :</label>
<input class="form-control" type="email" placeholder="Your Email address" name="email" id="email" maxlength="120" tabindex="4" />
<label name="password-label">Password :</label>
<input class="form-control" type="password" placeholder="Your desired password" name="password" id="password" maxlength="35" tabindex="5" />
<label name="repassword-label">re enter Password :</label>
<input class="form-control" type="password" placeholder="Your password again" name="repassword" id="repassword" maxlength="35" tabindex="6" />
<label name="type-label">i am here to :</label></br>
<select name="type" class="form-control" tabindex="7" >
<option>develop websites</option>
<option>hire a developer</option>
</select>
</br>
<input type="submit" class="btn btn-default" value="Register" name="submit" /></br>
<p>already a member ? <a href="index.php" ><i><b>Log In</b></i></a></p>
</form>
</div>
<div class="col-lg-3 errorlog">
<?php
/* if submit button is clicked start the registration */
if(isset($_POST['submit'])){
/* get all the values from the textboxes */
$fname = mysqli_real_escape_string($con,$_POST['fname']);
$lname = mysqli_real_escape_string($con,$_POST['lname']);
$username = mysqli_real_escape_string($con,$_POST['username']);
$email = mysqli_real_escape_string($con,$_POST['email']);
$password = mysqli_real_escape_string($con,$_POST['password']);
$password_verification = mysqli_real_escape_string($con,$_POST['repassword']);
$type = mysqli_real_escape_string($con,$_POST['type']);
$paid = false;
/* form validation */
if(empty($fname)){
echo '
<div class="alert alert-danger">
<strong>Error!</strong> first name is empty.
</div>
';
}else if(empty($lname)){
echo '
<div class="alert alert-danger">
<strong>Error!</strong> Last name is empty.
</div>
';
}else if(empty($username)){
echo '
<div class="alert alert-danger">
<strong>Error!</strong> Username is empty.
</div>
';
}else if(0 === preg_match("/.+#.+\..+/",$email)){
echo '
<div class="alert alert-danger">
<strong>Error!</strong> The email you entered is invalid.
</div>
';
}else if(0 === preg_match("/.{6,}/",$password)){
echo '
<div class="alert alert-danger">
<strong>Error!</strong> Passwords has to be atleast 6 characters long.
</div>
';
}else if($password !== $password_verification){
echo '
<div class="alert alert-danger">
<strong>Error!</strong> The passwords you entered do not match.
</div>
';
}else if(empty($type)){
echo '
<div class="alert alert-danger">
<strong>Error!</strong> You can be eithere a developer or a host
</div>
';
}else{
$query = "SELECT * FROM users WHERE username = '$username'";
$equery = "SELECT * FROM users WHERE email = '$email'";
if($result = mysqli_query($con,$query)){
$row_cnt = mysqli_num_rows($result);
if($row_cnt > 0){
echo '
<div class="alert alert-danger">
<strong>Error!</strong> This username is already taken!
</div>
';
}else if ($eresult = mysqli_query($con,$equery)){
$erow_cnt = mysqli_num_rows($eresult);
if($erow_cnt > 0){
echo '
<div class="alert alert-danger">
<strong>Error!</strong> This email is already registered!
</div>
';
}else{
$salt = rand(100 , 999) . rand(100 , 999) . rand(1000 , 9999);
$hashedpassword = crypt($password,$salt);
if($type === "develop websites"){
$type="developer";
}else if($type === "hire a developer"){
$type="owner";
}else{
echo'
<div class="alert alert-danger">
<strong>Error!</strong> you can only be an owner or a developer
</div>
';
}
$date = date("m/d/Y h:i:sa");
$confirm = false;
$confirmation_code = rand(100,999) . "-" . rand(100,999);
$insertion = mysqli_query($con,"INSERT INTO `users` (`first name`, `last name`, `email`, `password`, `username`, `salt`, `type`, `paid`, `date_created`, `confirmed`,`confirmation_code`) VALUES ('$fname','$lname','$email','$hashedpassword','$username','$salt','$type','0','$date','$confirm','$confirmation_code')");
if($insertion){
echo "
<div class=\"alert alert-success\">
<strong>Success</strong> your account has been successfully created!
</div>
";
$user_id = mysqli_query($con, "SELECT * FROM `users` WHERE `username` = '$username'");
$row = mysqli_fetch_array($user_id);
$id = $row['user_id'];
$firstname = $row['first name'];
$lastname = $row['last name'];
$semail = $row['email'];
$susername = $row['username'];
$spaid = $row['paid'];
$sdate = $row['date_created'];
$sconfirmed = $row['confirmed'];
$sconfirmation_code = $row['confirmation_code'];
$_SESSION['id'] = $id;
$_SESSION['fname'] = $firstname;
$_SESSION['lname'] = $lastname;
$_SESSION['email'] = $semail;
$_SESSION['username'] = $susername;
$_SESSION['paid'] = $spaid;
$_SESSION['date'] = $sdate;
$_SESSION['confirmed'] = $sconfirmed;
$_SESSION['confirmation_code'] = $sconfirmation_code;
if($user_id){
echo "
<div class=\"alert alert-success\">
<strong>Session has been set</strong> you are now logged in!
</div>
";
echo"<script>
setTimeout(function () {
window.location.href = 'profile.php';},8000);
</script>";
echo "
<div class=\"alert alert-info\">
<strong>Thank you!</strong> in 8 seconds you will be redirected to your new profile
</div>
";
}else{
echo "
<div class=\"alert alert-danger\">
<strong>Failed</strong> your account has been created, but we were unable to log you in, you will have to do this manually here
</div>";
}
}else{
echo "
<div class=\"alert alert-danger\">
<strong>Failed</strong> your account has not been created, something went wrong
</div>";
}
}
}
}
}
}
?>
</div>
</div>
</div>
</body>
</html>
now the thing is that once u go to login or register it checks if you have a session ongoing by checking this :
if($_SESSION['id'] !== null){
header("Location: profile.php");
}
but it is returning an error saying :
Notice: Undefined index: id
i understand that the error is because the session is not set so the variable $_SESSION['id'] is not set which is causing this error, what i would like to know is if there is another way around this that does not include the use of cookies, because i am storing user info, and cookies are not safe in that case
i tried using session_id(), but whenever you start a session the session_id() is automatically set. so it will always redirect to profile.php even if your not logged in
ps : i know my php is not very neat and tidy, i am still new at php, so any comments about improving it will be much appreciated
Try isset :-
if(isset($_SESSION['id'])){
header("Location: profile.php");
}else{
echo 'session is not set';die;
}
Use isset!
if (isset($_SESSION['id'])) {
// ..
}
Isset checks if the var/index is defined, so this would work perfectly for you.
Keep in mind, there's an difference between isset and !empty. isset only checks, if the var is defined, !empty does some more test, like $var !== false, $var !== array(), $var !== '0', $var !== 0, etc..
This probably doesn't matter in your case(except, you have an allowed id=0), but is always good to know.
<?php
Session_start();
if(isset($_SESSION['id'])
Do what you wanna do
?>
You can use isset() to see if id is set or no.
if(isset($_SESSION['id'])){
header("location: profile.php");
}
In php isset() is used to check that id is set or not.

Categories