Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
58 views38 pages

Redirect Loop Fix

The document addresses a redirect loop issue in a PHP login system, which occurs when a user is redirected back to the login page after logging in. It suggests adding checks on target pages to prevent infinite redirects and recommends using secure password handling with password_hash() and password_verify(). Additionally, it includes HTML and PHP code snippets for the login form and session management.

Uploaded by

sasith
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views38 pages

Redirect Loop Fix

The document addresses a redirect loop issue in a PHP login system, which occurs when a user is redirected back to the login page after logging in. It suggests adding checks on target pages to prevent infinite redirects and recommends using secure password handling with password_hash() and password_verify(). Additionally, it includes HTML and PHP code snippets for the login form and session management.

Uploaded by

sasith
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

Redirect Loop Fix

<?php
ini_set('session.cookie_httponly', 1);
ini_set('session.use_only_cookies', 1);
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') {
ini_set('session.cookie_secure', 1);
} redirected too many times
session_start();

include 'connect.php';

if (isset($_SESSION['userID'])) {
switch ($_SESSION['type']) {
case 'admin':
header('Location: ./admin/indexAdmin.php');
exit();
case 'nonadmin':
header('Location: ./user/indexNonAdmin.php');
exit();

}
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' &&


isset($_POST['login'])) {
$user = trim($_POST['username']);
$pass = $_POST['password'];

$stmt = $con->prepare("SELECT id, username, password,


type FROM users WHERE username = ?");
$stmt->bind_param("s", $user);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 1) {
$row = $result->fetch_assoc();

// ⚠ Plain password comparison — NOT SAFE


if ($pass === $row['password']) {

1/38
session_regenerate_id(true);
$_SESSION['LOGGEDIN'] = true;
$_SESSION['userID'] = $row['id'];
$_SESSION['username'] = $row['username'];
$_SESSION['type'] = $row['type'];

switch ($row['type']) {
case 'admin':
header('Location: ./admin/indexAdmin.php');
break;
case 'nonadmin':
header('Location: ./user/indexNonAdmin.php');
break;

}
exit();
}
}

$error = "Invalid username or password.";


$stmt->close();
}
$con->close();
?>

<!DOCTYPE html>
<html lang="en">

<head>
<style>
h1 {

font-family: "Jockey One", sans-serif;


margin-left: auto;
margin-right: auto;

div .headingweb {

2/38
margin-top: 100px;
}

div .loginform {
max-width: fit-content;
margin-left: auto;
margin-right: auto;
}
</style>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Login to Maintenance Job Card Web</title>
<link
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css
/bootstrap.min.css" rel="stylesheet"
integrity="sha384-
QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh
0JMhjY6hW+ALEwIH" crossorigin="anonymous">
<link rel="preconnect"
href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com"
crossorigin>
<link href="https://fonts.googleapis.com/css2?
family=Jockey+One&display=swap" rel="stylesheet">
</head>

<body>
<div class="container">
<div class="headingweb">
<center>
<div>
<img src="logo.jpg" style="height:100px;
width:200px" alt="">
</div>
<h1>ACL Welfare Society DB</h1>

</center>
</div>

<div class="loginform">
<form method="POST">

3/38
<div class="mb-3 ">
<label for="exampleInputEmail1" class="form-
label">Username</label>
<input type="text" class="form-control"
name="username" id="exampleInputEmail1"
aria-describedby="emailHelp"
placeholder="Username">

</div>
<div class="mb-3 ">
<label for="exampleInputPassword1"
class="form-label">Password</label>

<input type="password" name="password"


class="form-control" id="exampleInputPassword1"
placeholder="Password">
</div>

<button type="submit" class="btn btn-primary"


name="login">Login</button>
</form>
</div>
</div>

</body>

</html>

You're facing a "redirected too many times" issue, which is usually caused by an infinite
redirect loop. In your case, this is likely happening because of this block:

php

if (isset($_SESSION['userID'])) {
switch ($_SESSION['type']) {
case 'admin':
header('Location: ./admin/indexAdmin.php');
exit();
case 'nonadmin':
header('Location: ./user/indexNonAdmin.php');
exit();

4/38
}
}

If the redirect target page ( indexAdmin.php or indexNonAdmin.php ) also redirects back to


this login page (if session is already set), you’ll get stuck in an endless loop.

✅ Fix: Add a check on the destination page


For indexAdmin.php and indexNonAdmin.php , make sure those files don’t redirect back to
the login page if the user is already logged in.

Example fix for indexAdmin.php :

php

<?php
session_start();
if (!isset($_SESSION['userID']) || $_SESSION['type'] !== 'admin') {
header('Location: ../login.php'); // adjust path as needed
exit();
}

// your normal admin page content here


?>

✅ Optional Fix for Login Page


If you still want to keep redirecting from login if the user is already logged in, keep your
check, but ensure target pages don’t loop back.

❗️Security Warning
You're using plain text password comparison, which is unsafe:

php

5/38
if ($pass === $row['password']) {

Change it to use password_verify :

php

if (password_verify($pass, $row['password'])) {

And store passwords using password_hash when registering users:

php

$passwordHash = password_hash($pass, PASSWORD_DEFAULT);

Summary
Fix the redirect loop by checking sessions properly on both login and target pages.

Use password_hash() + password_verify() for secure authentication.

Clear your browser cookies if the loop persists during testing.

Let me know if you want me to check your indexAdmin.php or indexNonAdmin.php file too.

<?php
include '../connect.php';
include '../session.php';

if (!($_SESSION['type'] == 'user')) {
header('location:..\index.php');
}

$idu = $_GET['updateid'];

$sql = "Select * from member_info where id='$idu'";

$result = mysqli_query($con, $sql);

6/38
$row = mysqli_fetch_assoc($result);

$id = $row['id'];
$fname = $row['fname'];
$lname = $row['lname'];
$namewinitials = $row['namewinitials'];
$epfno = $row['epfno'];
$dept = $row['dept'];
$raddress = $row['raddress'];
$nic = $row['nic'];
$dob = $row['dob'];
$mobile = $row['mobile'];
$rd = $row['rd'];
$dop = $row['dop'];
$mobile = $row['mobile'];
$marital = $row['marital'];
// $gen = explode(",",$gender);
// $lang = explode(",",$datas);
// $pl = explode(",",$place);

//echo $BriefDescription;

// update operation
// if (isset($_POST['finish'])) {
// $workplace=$_SESSION['workplace'];
// $finishcomment=$_POST['finishcomment'];
// $_SESSION['FinishJob'] = true;
// if ($workplace=='Electrical')
// {
// $insert = "update jobdatasheet set
JobStatusE='Finished',FinishedCommentE='$finishcomment'
where id='$id'";
// }
// elseif($workplace=='Mechanical')
// {
// $insert = "update jobdatasheet set
JobStatusM='Finished',FinishedCommentM='$finishcomme
nt' where id='$id'";
// }

7/38
// //$insert = "update jobdatasheet set
JobStatusM='Finished' where id='$id'";

// if ($con->query($insert) == TRUE) {
// //$_SESSION['SubmitJobSucess']=true;
// //echo "Sucessfully Started Job";

// header('location:.\FinishedJobSuccesEMUser.php');

// } else {

// echo mysqli_error($con);
// //
header('location:location:..\PUser\indexPUser.php');
// }
// //$insert->close();
// }

// delete operation
if (isset($_POST['delete'])) {

$sql = "delete from member_info where id='$idu'";


$result = mysqli_query($con, $sql);
$_SESSION['DeleteJobSucess'] = true;
header('location:..\user\DeleteSuccess.php');
}

?>

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">

8/38
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Document</title>
<link
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css
/bootstrap.min.css" rel="stylesheet"
integrity="sha384-
QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh
0JMhjY6hW+ALEwIH" crossorigin="anonymous">
<link rel="preconnect"
href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com"
crossorigin>
<link href="https://fonts.googleapis.com/css2?
family=Jockey+One&display=swap" rel="stylesheet">

<link rel="stylesheet" href="..\styles\SubmitJobstyle.css">

<style>
h1 {
font-family: "Jockey One", sans-serif;
}

#inside {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
</style>
</head>

<body onload="divSelect()">
<div class="topbar">
<h1 class="topbar-text">Welcome <?php echo
$_SESSION['username'] ?> User</h1>

<a href="..\logout.php">
<h1 class="topbar-logout">Logout &nbsp</h1>
</a>
<h1 class="topbar-username"><?php echo
$_SESSION['username'] ?>&nbsp</h1>

9/38
</div>
<div class="container mt-5 ">
<h1>View EPF Record </h1>
<div class="mt-3 mb-5">
<form method="POST">
<table class="table table-striped w-50">
<tr>
<!-- Table row -->
<tr>
<td>
First Name
</td>
<td>
<?php echo $fname; ?>
</td>
</tr>
<!-- Table row -->
<tr>
<td>
Last Name
</td>
<td>
<?php echo $lname; ?>
</td>
</tr>
<!-- Table row -->
<tr>
<td>
Name with Initials
</td>
<td>
<?php echo $namewinitials; ?>
</td>
</tr>
<!-- Table row -->
<tr>
<td>
EPF No
</td>
<td>
<?php echo $epfno; ?>
</td>

10/38
</tr>
<!-- Table row -->
<tr>
<td>
Department
</td>
<td>
<?php echo $dept; ?>
</td>
</tr>
<!-- Table row -->
<tr>
<td>
Address
</td>
<td>
<?php echo $raddress; ?>
</td>
</tr>
<!-- Table row -->
<tr>
<td>
NIC
</td>
<td>
<?php echo $nic; ?>
</td>
</tr>
<!-- Table row -->
<tr>
<td>
Date of Birth
</td>
<td>
<?php echo $dob; ?>
</td>
</tr>
<!-- Table row -->
<tr>
<td>
Marital Status
</td>

11/38
<td>
<?php echo $marital; ?>
</td>
</tr>
<!-- Table row -->
<tr>
<td>
Recruitment Date
</td>
<td>
<?php echo $rd; ?>
</td>
</tr>
<!-- Table row -->
<tr>
<td>
Date of Permanant
</td>
<td>
<?php echo $dop; ?>
</td>
</tr>
<!-- Table row -->
<tr>
<td>
Mobile
</td>
<td>
<?php echo $mobile; ?>
</td>
</tr>
<!-- Table row -->
<tr>
<td>
Death grant Applicants<br> according to
Welfare<br> constitution
</td>
<td>
<table class="table table-striped">
<thead>
<tr>
<th>Name</th>

12/38
<th>Relation</th>
</tr>
</thead>
<tbody>
<?php
$sql_applicants = "SELECT
applicant_name, relation FROM applicants WHERE
member_id = '$idu'";
$result_applicants = mysqli_query($con,
$sql_applicants);

while ($row_app =
mysqli_fetch_assoc($result_applicants)) {
$name =
htmlspecialchars($row_app['applicant_name']);
$relation =
htmlspecialchars($row_app['relation']);
echo "<tr><td>$name</td>
<td>$relation</td></tr>";
}
?>
</tbody>
</table>
</td>
</tr>

</table>

<!-- <button type="submit" class="btn btn-success


mt-3" name="finish"
onclick="return confirm('Are you sure?')">Finish
& send for Approval</button> -->
<!-- <button type="submit" class="btn btn-warning
mt-3" name="delete"
onclick="return confirm('Are you
sure?')">Transfer</button> -->

<button type="button" class="btn btn-info mt-3


mx-2"><a href="..\admin\BrowseEPFNo.php" style="text-

13/38
decoration:none;color:black">Back to Search</a></button>
<button type="back" class="btn btn-danger mt-3
mx-2" name="back"><a href="..\admin\indexAdmin.php"
style="text-decoration:none;color:white">Back to Main</a>
</button>
</form>
</div>
</div>

</body>
</body> add exiting grants for above diffrent table like
below code <?php
include '../connect.php';
include '../session.php';

if (!($_SESSION['type'] == 'admin')) {
header('location:../index.php');
exit;
}

$idu = $_GET['updateid'];

// Fetch member info


$sql = "SELECT * FROM member_info WHERE id='$idu'";
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($result);

$id = $row['id'];
$fname = $row['fname'];
$lname = $row['lname'];
$namewinitials = $row['namewinitials'];
$epfno = $row['epfno'];
$dept = $row['dept'];
$raddress = $row['raddress'];
$nic = $row['nic'];
$dob = $row['dob'];
$mobile = $row['mobile'];
$rd = $row['rd'];
$dop = $row['dop'];

14/38
$marital = $row['marital'];

//✅ Check if Self → Death or Retirement already granted


$blockGrant = false;
$check_termination_query = "SELECT * FROM grants g
INNER JOIN applicants a ON g.applicant_id =
a.id
WHERE g.member_id = '$idu'
AND a.relation = 'Self'
AND (g.grant_type = 'Death' OR
g.grant_type = 'Retirement')";
$result_termination_check = mysqli_query($con,
$check_termination_query);
if (mysqli_num_rows($result_termination_check) > 0) {
$blockGrant = true;
}

// Handle form submission


if (isset($_POST['submit']) && !$blockGrant) {
$applicat_id = $_POST['applicant'];
$grant_type = $_POST['grant_type'];
$grant_date = $_POST['grant_date'];

$check_query = "SELECT * FROM grants WHERE


member_id = $idu AND applicant_id = $applicat_id AND
grant_type = '$grant_type'";
$check_result = mysqli_query($con, $check_query);

if (mysqli_num_rows($check_result) > 0) {
echo "<script>alert('Grant has already been added for
this applicant and type.');</script>";
} else {
$sql_insert_grants = "INSERT INTO grants
(member_id, applicant_id, grant_type, grant_date)
VALUES ($idu, $applicat_id, '$grant_type',
'$grant_date')";
$insert_grants = mysqli_query($con,
$sql_insert_grants);

if ($insert_grants) {
echo "<script>alert('Grant successfully added');
window.location.href='../admin/indexAdmin.php';</script>";

15/38
exit;
} else {
echo "Error inserting grant: " . mysqli_error($con);
}
}
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add New Grant</title>
<link
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css
/bootstrap.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?
family=Jockey+One&display=swap" rel="stylesheet">
<link rel="stylesheet" href="../styles/SubmitJobstyle.css">
<style> h1 { font-family: "Jockey One", sans-serif; }
</style>
</head>

<body>
<div class="topbar">
<h1 class="topbar-text">Welcome <?php echo
$_SESSION['username'] ?> </h1>
<a href="../logout.php"><h1 class="topbar-
logout">Logout &nbsp</h1></a>
<h1 class="topbar-username"><?php echo
$_SESSION['username'] ?>&nbsp</h1>
</div>

<div class="container mt-5">

<h3>Existing Grants</h3>
<table class="table table-bordered table-striped mt-3 w-
75">
<thead class="table-dark">
<tr>
<th>#</th>
<th>Applicant Name</th>

16/38
<th>Relation</th>
<th>Grant Type</th>
<th>Grant Date</th>
</tr>
</thead>
<tbody>
<?php
$sql_history = "SELECT g.id, a.applicant_name,
a.relation, g.grant_type, g.grant_date
FROM grants g
INNER JOIN applicants a ON g.applicant_id =
a.id
WHERE g.member_id = '$idu'
ORDER BY g.grant_date DESC";
$result_history = mysqli_query($con, $sql_history);
$counter = 1;

if (mysqli_num_rows($result_history) > 0) {
while ($row = mysqli_fetch_assoc($result_history)) {
echo "<tr>
<td>{$counter}</td>
<td>{$row['applicant_name']}</td>
<td>{$row['relation']}</td>
<td>{$row['grant_type']}</td>
<td>{$row['grant_date']}</td>
</tr>";
$counter++;
}
} else {
echo "<tr><td colspan='5' class='text-center text-
muted'>No grants added yet.</td></tr>";
}
?>
</tbody>
</table>

<a href="../admin/indexAdmin.php" class="btn btn-


danger mt-3">Back to Main</a>
</div>

<div class="container mt-5">


<h1>Add New Grant</h1>

17/38
<?php if ($blockGrant): ?>
<div class="alert alert-danger mt-4">
⚠️ This member is marked as
<strong>terminated</strong> (Self → Death or Retirement).
No further grants are allowed to the member or
their family.
</div>
<?php else: ?>
<form method="POST" onsubmit="return
validateForm();">
<table class="table table-striped w-50">
<tr><td>First Name</td><td><?php echo $fname; ?>
</td></tr>
<tr><td>Last Name</td><td><?php echo $lname; ?>
</td></tr>
<tr><td>Name with Initials</td><td><?php echo
$namewinitials; ?></td></tr>
<tr><td>EPF No</td><td><?php echo $epfno; ?></td>
</tr>
<tr><td>Department</td><td><?php echo $dept; ?>
</td></tr>
<tr><td>Address</td><td><?php echo $raddress; ?>
</td></tr>
<tr><td>NIC</td><td><?php echo $nic; ?></td></tr>
<tr><td>Date of Birth</td><td><?php echo $dob; ?>
</td></tr>
<tr><td>Marital Status</td><td><?php echo
$marital; ?></td></tr>
<tr><td>Recruitment Date</td><td><?php echo $rd;
?></td></tr>
<tr><td>Date of Permanent</td><td><?php echo
$dop; ?></td></tr>
<tr><td>Mobile</td><td><?php echo $mobile; ?>
</td></tr>

<tr>
<td>Grant to be Applied</td>
<td>
<select name="applicant"
id="applicantDropdown" class="form-control my-2"
onchange="updateGrantType()">
<option value="">-- Select Applicant --

18/38
</option>
<?php
$sql_applicants = "SELECT id, applicant_name,
relation FROM applicants WHERE member_id = '$idu'";
$result_applicants = mysqli_query($con,
$sql_applicants);
while ($row =
mysqli_fetch_assoc($result_applicants)) {
echo "<option value='{$row['id']}' data-
relation='{$row['relation']}'>{$row['applicant_name']} -
{$row['relation']}</option>";
}
?>
</select>

<select name="grant_type"
id="grantTypeDropdown" class="form-control">
<option value="">-- Select Grant Type --
</option>
</select>

<input type="date" name="grant_date"


id="grant_date" class="form-control my-2">
</td>
</tr>
</table>

<button type="submit" name="submit" class="btn btn-


success mx-2" onclick="return confirm('Are you
sure?')">Add Grant</button>
<a href="../admin/BrowseEPFNo.php" class="btn btn-
info mx-2">Back to Search</a>
<a href="../admin/indexAdmin.php" class="btn btn-
danger mx-2">Back to Main</a>
</form>
<?php endif; ?>
</div>

<script>
function updateGrantType() {
const applicantDropdown =
document.getElementById("applicantDropdown");

19/38
const grantTypeDropdown =
document.getElementById("grantTypeDropdown");
const selectedOption =
applicantDropdown.options[applicantDropdown.selectedIn
dex];
const relation = selectedOption.getAttribute("data-
relation");

grantTypeDropdown.innerHTML = "<option value=''>--


Select Grant Type --</option>";

if (relation === "Self") {


grantTypeDropdown.innerHTML += "<option
value='Death'>Death</option>";
grantTypeDropdown.innerHTML += "<option
value='Retirement'>Retirement</option>";
grantTypeDropdown.innerHTML += "<option
value='Marriage'>Marriage</option>";
} else if (relation === "Son" || relation === "Daughter")
{
grantTypeDropdown.innerHTML += "<option
value='Birth'>Birth</option>";
grantTypeDropdown.innerHTML += "<option
value='Deathb6'>Death before age 6 months</option>";
grantTypeDropdown.innerHTML += "<option
value='Deatha6'>Death after age 6 months</option>";
} else {
grantTypeDropdown.innerHTML += "<option
value='Death'>Death</option>";
}
}

function validateForm() {
const applicantDropdown =
document.getElementById("applicantDropdown");
const grantTypeDropdown =
document.getElementById("grantTypeDropdown");
const grantDate =
document.getElementById("grant_date");

if (applicantDropdown.value === "") {


alert("Please select an applicant.");

20/38
return false;
}

if (grantTypeDropdown.value === "") {


alert("Please select a grant type.");
return false;
}

if (grantDate.value === "") {


alert("Please select a grant date.");
return false;
}

return true;
}
</script>
</body>
</html>

To add the "Existing Grants" section from your admin view into the user view page, you
simply need to copy and adapt that section into the user page (the first code you shared).

Here’s how to insert it correctly:

✅ Replace this part in your user page:


Right after this block (line 254):

php

<tr>
<td>
Death grant Applicants<br> according to Welfare<br> constitution
</td>
<td>
<table class="table table-striped">
...
</table>
</td>
</tr>

21/38
✅ Add the following block after that, to show Existing Grants:
php

<tr>
<td>
Existing Grants
</td>
<td>
<table class="table table-bordered table-striped">
<thead class="table-dark">
<tr>
<th>#</th>
<th>Applicant Name</th>
<th>Relation</th>
<th>Grant Type</th>
<th>Grant Date</th>
</tr>
</thead>
<tbody>
<?php
$sql_grants = "SELECT g.id, a.applicant_name, a.relation, g.grant_type, g.grant_date
FROM grants g
INNER JOIN applicants a ON g.applicant_id = a.id
WHERE g.member_id = '$idu'
ORDER BY g.grant_date DESC";
$result_grants = mysqli_query($con, $sql_grants);
$counter = 1;

if (mysqli_num_rows($result_grants) > 0) {
while ($row = mysqli_fetch_assoc($result_grants)) {
echo "<tr>
<td>{$counter}</td>
<td>{$row['applicant_name']}</td>
<td>{$row['relation']}</td>
<td>{$row['grant_type']}</td>
<td>{$row['grant_date']}</td>
</tr>";
$counter++;
}
} else {
echo "<tr><td colspan='5' class='text-center text-muted'>No grants added yet.</td></tr>";
}

22/38
?>
</tbody>
</table>
</td>
</tr>

🔐 Important Note:
You're currently not escaping or sanitizing your inputs/outputs properly. For a safer system:

Escape all output using htmlspecialchars($value)

Avoid directly injecting $_GET['updateid'] into SQL → use prepared statements to


prevent SQL injection.

Let me know if you'd like me to refactor this entire page securely with best practices.

2/2

give me full code

Here is the full updated user view page with Existing Grants table added, properly styled
and integrated:

php

<?php
include '../connect.php';
include '../session.php';

if (!($_SESSION['type'] == 'user')) {
header('location:..\index.php');
exit;
}

$idu = $_GET['updateid'];

$sql = "SELECT * FROM member_info WHERE id='$idu'";


$result = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($result);

23/38
$fname = $row['fname'];
$lname = $row['lname'];
$namewinitials = $row['namewinitials'];
$epfno = $row['epfno'];
$dept = $row['dept'];
$raddress = $row['raddress'];
$nic = $row['nic'];
$dob = $row['dob'];
$mobile = $row['mobile'];
$rd = $row['rd'];
$dop = $row['dop'];
$marital = $row['marital'];

if (isset($_POST['delete'])) {
$sql = "DELETE FROM member_info WHERE id='$idu'";
mysqli_query($con, $sql);
$_SESSION['DeleteJobSucess'] = true;
header('location:..\user\DeleteSuccess.php');
exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>View EPF Record</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Jockey+One&display=swap" rel="stylesheet">
<link rel="stylesheet" href="../styles/SubmitJobstyle.css">
<style>
h1 { font-family: "Jockey One", sans-serif; }
#inside { border: 1px solid #dddddd; text-align: left; padding: 8px; }
</style>
</head>

<body>
<div class="topbar">
<h1 class="topbar-text">Welcome <?php echo $_SESSION['username'] ?> User</h1>
<a href="..\logout.php"><h1 class="topbar-logout">Logout &nbsp</h1></a>
<h1 class="topbar-username"><?php echo $_SESSION['username'] ?>&nbsp</h1>

24/38
</div>

<div class="container mt-5">


<h1>View EPF Record</h1>
<form method="POST">
<table class="table table-striped w-75">
<tr><td>First Name</td><td><?php echo htmlspecialchars($fname); ?></td></tr>
<tr><td>Last Name</td><td><?php echo htmlspecialchars($lname); ?></td></tr>
<tr><td>Name with Initials</td><td><?php echo htmlspecialchars($namewinitials); ?></td>
</tr>
<tr><td>EPF No</td><td><?php echo htmlspecialchars($epfno); ?></td></tr>
<tr><td>Department</td><td><?php echo htmlspecialchars($dept); ?></td></tr>
<tr><td>Address</td><td><?php echo htmlspecialchars($raddress); ?></td></tr>
<tr><td>NIC</td><td><?php echo htmlspecialchars($nic); ?></td></tr>
<tr><td>Date of Birth</td><td><?php echo htmlspecialchars($dob); ?></td></tr>
<tr><td>Marital Status</td><td><?php echo htmlspecialchars($marital); ?></td></tr>
<tr><td>Recruitment Date</td><td><?php echo htmlspecialchars($rd); ?></td></tr>
<tr><td>Date of Permanent</td><td><?php echo htmlspecialchars($dop); ?></td></tr>
<tr><td>Mobile</td><td><?php echo htmlspecialchars($mobile); ?></td></tr>

<tr>
<td>Death Grant Applicants<br>according to Welfare Constitution</td>
<td>
<table class="table table-bordered">
<thead>
<tr><th>Name</th><th>Relation</th></tr>
</thead>
<tbody>
<?php
$sql_applicants = "SELECT applicant_name, relation FROM applicants WHERE
member_id = '$idu'";
$result_app = mysqli_query($con, $sql_applicants);
while ($app = mysqli_fetch_assoc($result_app)) {
echo "<tr><td>".htmlspecialchars($app['applicant_name'])."</td>
<td>".htmlspecialchars($app['relation'])."</td></tr>";
}
?>
</tbody>
</table>
</td>
</tr>

25/38
<tr>
<td>Existing Grants</td>
<td>
<table class="table table-bordered table-striped">
<thead class="table-dark">
<tr>
<th>#</th>
<th>Applicant Name</th>
<th>Relation</th>
<th>Grant Type</th>
<th>Grant Date</th>
</tr>
</thead>
<tbody>
<?php
$sql_grants = "SELECT g.id, a.applicant_name, a.relation, g.grant_type, g.grant_date
FROM grants g
INNER JOIN applicants a ON g.applicant_id = a.id
WHERE g.member_id = '$idu'
ORDER BY g.grant_date DESC";
$result_grants = mysqli_query($con, $sql_grants);
$counter = 1;

if (mysqli_num_rows($result_grants) > 0) {
while ($grant = mysqli_fetch_assoc($result_grants)) {
echo "<tr>
<td>{$counter}</td>
<td>".htmlspecialchars($grant['applicant_name'])."</td>
<td>".htmlspecialchars($grant['relation'])."</td>
<td>".htmlspecialchars($grant['grant_type'])."</td>
<td>".htmlspecialchars($grant['grant_date'])."</td>
</tr>";
$counter++;
}
} else {
echo "<tr><td colspan='5' class='text-center text-muted'>No grants added yet.</td>
</tr>";
}
?>
</tbody>
</table>
</td>

26/38
</tr>
</table>

<div class="mt-4">
<a href="..\admin\BrowseEPFNo.php" class="btn btn-info mx-2">Back to Search</a>
<a href="..\admin\indexAdmin.php" class="btn btn-danger mx-2">Back to Main</a>
</div>
</form>
</div>
</body>
</html>

✅ Summary of Improvements:
Grants section is added.

All dynamic content is HTML-escaped for security.

Clear layout and Bootstrap styling preserved.

Let me know if you want to allow grant adding from the user side (with form), or if this page
is only for viewing.

show that boottrap part ⚠️ This member is marked as


<strong>terminated</strong> (Self → Death or Retirement).
No further grants are allowed to the member or
their family.

Here's how you can display the termination warning message using Bootstrap styling in
your user view page, just like the admin version:

✅ Add this block right after you fetch $idu and before the main
content:
php

27/38
<?php
// Check if Self → Death or Retirement already granted
$blockGrant = false;
$check_termination_query = "SELECT * FROM grants g
INNER JOIN applicants a ON g.applicant_id = a.id
WHERE g.member_id = '$idu'
AND a.relation = 'Self'
AND (g.grant_type = 'Death' OR g.grant_type = 'Retirement')";
$result_termination_check = mysqli_query($con, $check_termination_query);
if (mysqli_num_rows($result_termination_check) > 0) {
$blockGrant = true;
}
?>

✅ Then, inside your main HTML (for example, just below <h1>View EPF
Record</h1> ):

php

<?php if ($blockGrant): ?>


<div class="alert alert-danger mt-4">
⚠️ This member is marked as <strong>terminated</strong> (Self → Death or Retirement).
No further grants are allowed to the member or their family.
</div>
<?php endif; ?>

✅ Output Example:
It will show like this:

<div class="alert alert-danger mt-4"> ⚠️ This member is marked as


<strong>terminated</strong> (Self → Death or Retirement). No further grants are allowed to
the member or their family. </div>

28/38
Let me know if you want to hide the grant table as well when this message appears.

giveme full code

Here's the full updated code of the user view page with the following additions:

✅ Full user info display


✅ Applicant list
✅ Existing grants table
✅ Termination warning message (if Self → Death or Retirement is granted)

✅ Full Code:
php

<?php
include '../connect.php';
include '../session.php';

if (!($_SESSION['type'] == 'user')) {
header('location:..\index.php');
exit;
}

$idu = $_GET['updateid'];

// Fetch member info


$sql = "SELECT * FROM member_info WHERE id='$idu'";
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($result);

$fname = $row['fname'];
$lname = $row['lname'];
$namewinitials = $row['namewinitials'];
$epfno = $row['epfno'];
$dept = $row['dept'];
$raddress = $row['raddress'];

29/38
$nic = $row['nic'];
$dob = $row['dob'];
$mobile = $row['mobile'];
$rd = $row['rd'];
$dop = $row['dop'];
$marital = $row['marital'];

// Check if Self → Death or Retirement grant exists


$blockGrant = false;
$check_termination_query = "SELECT * FROM grants g
INNER JOIN applicants a ON g.applicant_id = a.id
WHERE g.member_id = '$idu'
AND a.relation = 'Self'
AND (g.grant_type = 'Death' OR g.grant_type = 'Retirement')";
$result_termination_check = mysqli_query($con, $check_termination_query);
if (mysqli_num_rows($result_termination_check) > 0) {
$blockGrant = true;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>View EPF Record</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Jockey+One&display=swap" rel="stylesheet">
<link rel="stylesheet" href="../styles/SubmitJobstyle.css">
<style>
h1 { font-family: "Jockey One", sans-serif; }
</style>
</head>

<body>
<div class="topbar">
<h1 class="topbar-text">Welcome <?php echo $_SESSION['username'] ?> User</h1>
<a href="../logout.php"><h1 class="topbar-logout">Logout &nbsp</h1></a>
<h1 class="topbar-username"><?php echo $_SESSION['username'] ?>&nbsp</h1>
</div>

<div class="container mt-5">

30/38
<h1>View EPF Record</h1>

<?php if ($blockGrant): ?>


<div class="alert alert-danger mt-4">
⚠️ This member is marked as <strong>terminated</strong> (Self → Death or Retirement).
No further grants are allowed to the member or their family.
</div>
<?php endif; ?>

<form method="POST">
<table class="table table-striped w-75">
<tr><td>First Name</td><td><?php echo htmlspecialchars($fname); ?></td></tr>
<tr><td>Last Name</td><td><?php echo htmlspecialchars($lname); ?></td></tr>
<tr><td>Name with Initials</td><td><?php echo htmlspecialchars($namewinitials); ?></td>
</tr>
<tr><td>EPF No</td><td><?php echo htmlspecialchars($epfno); ?></td></tr>
<tr><td>Department</td><td><?php echo htmlspecialchars($dept); ?></td></tr>
<tr><td>Address</td><td><?php echo htmlspecialchars($raddress); ?></td></tr>
<tr><td>NIC</td><td><?php echo htmlspecialchars($nic); ?></td></tr>
<tr><td>Date of Birth</td><td><?php echo htmlspecialchars($dob); ?></td></tr>
<tr><td>Marital Status</td><td><?php echo htmlspecialchars($marital); ?></td></tr>
<tr><td>Recruitment Date</td><td><?php echo htmlspecialchars($rd); ?></td></tr>
<tr><td>Date of Permanent</td><td><?php echo htmlspecialchars($dop); ?></td></tr>
<tr><td>Mobile</td><td><?php echo htmlspecialchars($mobile); ?></td></tr>

<tr>
<td>Death Grant Applicants<br>according to Welfare Constitution</td>
<td>
<table class="table table-bordered">
<thead><tr><th>Name</th><th>Relation</th></tr></thead>
<tbody>
<?php
$sql_applicants = "SELECT applicant_name, relation FROM applicants WHERE member_id
= '$idu'";
$result_app = mysqli_query($con, $sql_applicants);
while ($app = mysqli_fetch_assoc($result_app)) {
echo "<tr><td>".htmlspecialchars($app['applicant_name'])."</td>
<td>".htmlspecialchars($app['relation'])."</td></tr>";
}
?>
</tbody>
</table>

31/38
</td>
</tr>

<tr>
<td>Existing Grants</td>
<td>
<table class="table table-bordered table-striped">
<thead class="table-dark">
<tr>
<th>#</th>
<th>Applicant Name</th>
<th>Relation</th>
<th>Grant Type</th>
<th>Grant Date</th>
</tr>
</thead>
<tbody>
<?php
$sql_grants = "SELECT g.id, a.applicant_name, a.relation, g.grant_type, g.grant_date
FROM grants g
INNER JOIN applicants a ON g.applicant_id = a.id
WHERE g.member_id = '$idu'
ORDER BY g.grant_date DESC";
$result_grants = mysqli_query($con, $sql_grants);
$counter = 1;

if (mysqli_num_rows($result_grants) > 0) {
while ($grant = mysqli_fetch_assoc($result_grants)) {
echo "<tr>
<td>{$counter}</td>
<td>".htmlspecialchars($grant['applicant_name'])."</td>
<td>".htmlspecialchars($grant['relation'])."</td>
<td>".htmlspecialchars($grant['grant_type'])."</td>
<td>".htmlspecialchars($grant['grant_date'])."</td>
</tr>";
$counter++;
}
} else {
echo "<tr><td colspan='5' class='text-center text-muted'>No grants added yet.</td>
</tr>";
}
?>

32/38
</tbody>
</table>
</td>
</tr>
</table>

<div class="mt-4">
<a href="../admin/BrowseEPFNo.php" class="btn btn-info mx-2">Back to Search</a>
<a href="../admin/indexAdmin.php" class="btn btn-danger mx-2">Back to Main</a>
</div>
</form>
</div>
</body>
</html>

Let me know if you also want to:

✅ Hide the grant table entirely when terminated


✅ Add export/print features
✅ Enable users to request grants (if allowed)
Happy to help!

how to trace activities of users of web site

To trace user activities on your website, especially in a PHP-based system like yours, you
can implement a logging system that records key actions (login, logout, data edits, views,
deletions, etc.) in a dedicated activity_log table.

✅ Step 1: Create activity_log Table

Run this SQL in your database:

sql

33/38
CREATE TABLE activity_log (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
username VARCHAR(100),
activity TEXT,
ip_address VARCHAR(45),
user_agent TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

✅ Step 2: Create a Logging Function in PHP


Make a reusable function (e.g. in log_activity.php ):

php

<?php
function logActivity($con, $userId, $username, $activity) {
$ip = $_SERVER['REMOTE_ADDR'];
$userAgent = $_SERVER['HTTP_USER_AGENT'];
$stmt = $con->prepare("INSERT INTO activity_log (user_id, username, activity, ip_address,
user_agent) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param("issss", $userId, $username, $activity, $ip, $userAgent);
$stmt->execute();
$stmt->close();
}
?>

✅ Step 3: Use the Logger in Your Pages


In any page (after session_start() and DB connection), include and use like this:

php

include 'log_activity.php';

// Example: when viewing member record

34/38
logActivity($con, $_SESSION['userID'], $_SESSION['username'], "Viewed EPF record of member ID
$idu");

Other examples:

Login success: logActivity(..., "Logged in")

Grant added: logActivity(..., "Added grant for applicant ID $applicat_id")

Record deleted: logActivity(..., "Deleted member record ID $idu")

✅ Step 4: Admin View Logs (Optional)


You can create a page view_logs.php to let admins see the logs:

php

<?php
include '../connect.php';
$result = mysqli_query($con, "SELECT * FROM activity_log ORDER BY created_at DESC");
?>

<table class="table table-striped">


<thead>
<tr><th>User</th><th>Activity</th><th>IP</th><th>Device</th><th>Time</th></tr>
</thead>
<tbody>
<?php while($log = mysqli_fetch_assoc($result)): ?>
<tr>
<td><?php echo $log['username']; ?></td>
<td><?php echo $log['activity']; ?></td>
<td><?php echo $log['ip_address']; ?></td>
<td><?php echo substr($log['user_agent'], 0, 30); ?></td>
<td><?php echo $log['created_at']; ?></td>
</tr>
<?php endwhile; ?>
</tbody>
</table>

35/38
🔒 Tips:
Only allow admins to view the logs.

Consider archiving logs after a certain period to keep the database light.

If needed, log more details like URLs or query params.

Would you like me to generate the full log_activity.php file or help you integrate it into
your current project?

can we set activity table delete old values atomaticxally

Yes, you can automatically delete old activity log entries using one of these two common
methods:

✅ Option 1: MySQL Event Scheduler (fully automatic)


This is the best way if you want MySQL to handle it on its own — no PHP needed.

🔧 Step 1: Enable the MySQL Event Scheduler


Run this SQL once:

sql

SET GLOBAL event_scheduler = ON;

To keep it always enabled, add this to your MySQL config ( my.cnf or my.ini ):

ini

event_scheduler=ON

36/38
🗑️ Step 2: Create an Event to Delete Logs Older Than 90 Days (for
example)
sql

CREATE EVENT IF NOT EXISTS delete_old_logs


ON SCHEDULE EVERY 1 DAY
DO
DELETE FROM activity_log
WHERE created_at < NOW() - INTERVAL 90 DAY;

You can change 90 DAY to whatever you want: 30 DAY , 6 MONTH , etc.

✅ Option 2: PHP Cleanup Script (manual or cron job)


Create a simple PHP script (e.g. cleanup_logs.php ):

php

<?php
include 'connect.php';

$sql = "DELETE FROM activity_log WHERE created_at < NOW() - INTERVAL 90 DAY";
if (mysqli_query($con, $sql)) {
echo "Old logs cleaned.";
} else {
echo "Error: " . mysqli_error($con);
}
?>

Then:

Run it manually

Or set a cron job on your server to run it daily/weekly

✅ Bonus: Add TTL-like Behavior (Optional)


37/38
If using InnoDB (which supports triggers/events), the event scheduler is better. MySQL
doesn’t support automatic TTL like MongoDB, but these approaches achieve the same result.

Would you like me to:

✅ Generate a ready file for the event?


.sql

✅ Help set up a cron job on your server?


✅ Add soft-delete ( is_deleted column) instead of permanent delete?

Let me know what fits your system best.

38/38

You might also like