I tried getting the CRUD app to work from Tutorial Republic. I can create rows, but can’t read, update, or delete them.
I uploaded index, create, read, update, delete, config, and error.php. It loads index.php fine but when I try to update, read, or delete, all I get is a blank page. Please help. Here’s the code.
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', 'user');
define('DB_PASSWORD', 'secret');
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());
}
?>
read.php
<?php
// Check existence of id parameter before processing further
if(isset($_GET["id"]) && !empty(trim($_GET["id"]))){
// Include config file
require_once "config.php";
// Prepare a select statement
$sql = "SELECT * FROM employees WHERE id = ?";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "i", $param_id);
// Set parameters
$param_id = trim($_GET["id"]);
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
$result = mysqli_stmt_get_result($stmt);
if(mysqli_num_rows($result) == 1){
/* Fetch result row as an associative array. Since the result set
contains only one row, we don't need to use while loop */
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
// Retrieve individual field value
$name = $row["name"];
$address = $row["address"];
$salary = $row["salary"];
} else{
// URL doesn't contain valid id parameter. Redirect to error page
header("location: error.php");
exit();
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
// Close connection
mysqli_close($link);
} else{
// URL doesn't contain id parameter. Redirect to error page
header("location: error.php");
exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>View Record</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<style>
.wrapper{
width: 600px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<h1 class="mt-5 mb-3">View Record</h1>
<div class="form-group">
<label>Name</label>
<p><b><?php echo $row["name"]; ?></b></p>
</div>
<div class="form-group">
<label>Address</label>
<p><b><?php echo $row["address"]; ?></b></p>
</div>
<div class="form-group">
<label>Salary</label>
<p><b><?php echo $row["salary"]; ?></b></p>
</div>
<p>Back</p>
</div>
</div>
</div>
</div>
</body>
</html>
update.php
<?php
// Include config file
require_once "config.php";
// Define variables and initialize with empty values
$name = $address = $salary = "";
$name_err = $address_err = $salary_err = "";
// Processing form data when form is submitted
if(isset($_POST["id"]) && !empty($_POST["id"])){
// Get hidden input value
$id = $_POST["id"];
// Validate name
$input_name = trim($_POST["name"]);
if(empty($input_name)){
$name_err = "Please enter a name.";
} elseif(!filter_var($input_name, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[a-zA-Z\s]+$/")))){
$name_err = "Please enter a valid name.";
} else{
$name = $input_name;
}
// Validate address address
$input_address = trim($_POST["address"]);
if(empty($input_address)){
$address_err = "Please enter an address.";
} else{
$address = $input_address;
}
// Validate salary
$input_salary = trim($_POST["salary"]);
if(empty($input_salary)){
$salary_err = "Please enter the salary amount.";
} elseif(!ctype_digit($input_salary)){
$salary_err = "Please enter a positive integer value.";
} else{
$salary = $input_salary;
}
// Check input errors before inserting in database
if(empty($name_err) && empty($address_err) && empty($salary_err)){
// Prepare an update statement
$sql = "UPDATE employees SET name=?, address=?, salary=? WHERE id=?";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "sssi", $param_name, $param_address, $param_salary, $param_id);
// Set parameters
$param_name = $name;
$param_address = $address;
$param_salary = $salary;
$param_id = $id;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Records updated successfully. Redirect to landing page
header("location: index.php");
exit();
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
}
// Close connection
mysqli_close($link);
} else{
// Check existence of id parameter before processing further
if(isset($_GET["id"]) && !empty(trim($_GET["id"]))){
// Get URL parameter
$id = trim($_GET["id"]);
// Prepare a select statement
$sql = "SELECT * FROM employees WHERE id = ?";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "i", $param_id);
// Set parameters
$param_id = $id;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
$result = mysqli_stmt_get_result($stmt);
if(mysqli_num_rows($result) == 1){
/* Fetch result row as an associative array. Since the result set
contains only one row, we don't need to use while loop */
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
// Retrieve individual field value
$name = $row["name"];
$address = $row["address"];
$salary = $row["salary"];
} else{
// URL doesn't contain valid id. Redirect to error page
header("location: error.php");
exit();
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
// Close connection
mysqli_close($link);
} else{
// URL doesn't contain id parameter. Redirect to error page
header("location: error.php");
exit();
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Update Record</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<style>
.wrapper{
width: 600px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<h2 class="mt-5">Update Record</h2>
<p>Please edit the input values and submit to update the employee record.</p>
<form action="<?php echo htmlspecialchars(basename($_SERVER['REQUEST_URI'])); ?>" method="post">
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control <?php echo (!empty($name_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $name; ?>">
<span class="invalid-feedback"><?php echo $name_err;?></span>
</div>
<div class="form-group">
<label>Address</label>
<textarea name="address" class="form-control <?php echo (!empty($address_err)) ? 'is-invalid' : ''; ?>"><?php echo $address; ?></textarea>
<span class="invalid-feedback"><?php echo $address_err;?></span>
</div>
<div class="form-group">
<label>Salary</label>
<input type="text" name="salary" class="form-control <?php echo (!empty($salary_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $salary; ?>">
<span class="invalid-feedback"><?php echo $salary_err;?></span>
</div>
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<input type="submit" class="btn btn-primary" value="Submit">
Cancel
</form>
</div>
</div>
</div>
</div>
</body>
</html>
delete.php
<?php
// Process delete operation after confirmation
if(isset($_POST["id"]) && !empty($_POST["id"])){
// Include config file
require_once "config.php";
// Prepare a delete statement
$sql = "DELETE FROM employees WHERE id = ?";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "i", $param_id);
// Set parameters
$param_id = trim($_POST["id"]);
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Records deleted successfully. Redirect to landing page
header("location: index.php");
exit();
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
// Close connection
mysqli_close($link);
} else{
// Check existence of id parameter
if(empty(trim($_GET["id"]))){
// URL doesn't contain id parameter. Redirect to error page
header("location: error.php");
exit();
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Delete Record</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<style>
.wrapper{
width: 600px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<h2 class="mt-5 mb-3">Delete Record</h2>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="alert alert-danger">
<input type="hidden" name="id" value="<?php echo trim($_GET["id"]); ?>"/>
<p>Are you sure you want to delete this employee record?</p>
<p>
<input type="submit" value="Yes" class="btn btn-danger">
No
</p>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
error.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Error</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<style>
.wrapper{
width: 600px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<h2 class="mt-5 mb-3">Invalid Request</h2>
<div class="alert alert-danger">Sorry, you've made an invalid request. Please go back and try again.</div>
</div>
</div>
</div>
</div>
</body>
</html>
Related
So I have a custom Login page on Wordpress that connects to my users database and checks if all the information is correct. This is the login.php:
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<title>Login</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<?php
require('db.php');
// If form submitted, insert values into the database.
if (isset($_POST['email'])){
// removes backslashes
$email = stripslashes($_REQUEST['email']);
//escapes special characters in a string
$email = mysqli_real_escape_string($conn,$email);
$password = stripslashes($_REQUEST['password']);
$password = mysqli_real_escape_string($conn,$password);
//Checking is user existing in the database or not
$query = "SELECT * FROM `users` WHERE email='$email'
and password='".md5($password)."'";
$result = mysqli_query($conn,$query) or die(mysql_error());
$rows = mysqli_num_rows($result);
if($rows==1){
$_SESSION['email'] = $email;
// Redirect user to index.php
header("Location: index.php");
}else{
echo "<div class='form'>
<h3>Email/password is incorrect.</h3>
<br/>Click here to <a href='../login/'>Login</a></div>";
}
}else{
?>
<div class="form">
<!-- <h1>Log In</h1> -->
<form action="" method="post" name="login">
<input type="text" name="email" placeholder="Email" required />
<input type="password" name="password" placeholder="Password" required />
<br>
<input name="submit" type="submit" value="Login" />
</form>
<p>Not registered yet? <a href='../register/'>Register Here</a></p>
</div>
<?php } ?>
</body>
</html>
What I want to do is change the LOGIN button on my Wordpress header to LOGOUT (and showing the user information if it's possible) after the user is logged, and I suppose that I can do that using the $_SESSION['email'] = $email;variable.
How can I do that?
Thanks a lot!
You can use the built-in WordPress function is_user_logged_in() or is your login using also a custom table in the database and not the WordPress user table wp_user?
<?php
if ( is_user_logged_in() ) {
echo 'Login out';
} else {
echo 'Login';
}
?>
If your login system is independent of WordPress, you need to check your login function and see what session variables it creates, you might also need to start the session your self then if it is not in the function something like this then
session_start();
if (isset($_SESSION['email'])) {
/// your login button code here
} else {
/// your logout button code here
}
A function that would add it to your wordpress menu you need to style it:
add_filter('wp_nav_menu_items', 'button_login_logout', 10, 2);
function button_login_logout() {
ob_start();
if (isset($_SESSION['email'])) :
?>
<a role="button" href="logoutlink">Log Out</a>.
<?php
else :
?>
<a role="button" href="loginlink">Log In</a>
<?php
endif;
return ob_get_clean();
}
This is my code, I really don't know whats wrong does anyone else know? Currently the error that comes up is Oops! Something went wrong. Please try again later. I know that the issue is not a connection issue and is not a permissions issue. I'm really confused about what I've done wrong and have even contacted customer support multiple times and they didn't know what the issue is.
<?php
include ('config.php');
// Define variables and initialize with empty values
$username = $password = $confirm_password = "";
$username_err = $password_err = $confirm_password_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate username
if(empty(trim($_POST["username"]))){
$username_err = "Please enter a username.";
} else{
// Prepare a select statement
$sql = "SELECT username FROM users WHERE username = ?";
if($stmt = mysqli_prepare($conn, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_username);
// Set parameters
$param_username = trim($_POST["username"]);
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
/* store result */
mysqli_stmt_store_result($stmt);
if(mysqli_stmt_num_rows($stmt) == 1){
$username_err = "This username is already taken.";
} else{
$username = trim($_POST["username"]);
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
}
// Validate password
if(empty(trim($_POST["password"]))){
$password_err = "Please enter a password.";
} elseif(strlen(trim($_POST["password"])) < 6){
$password_err = "Password must have atleast 6 characters.";
} else{
$password = trim($_POST["password"]);
}
// Validate confirm password
if(empty(trim($_POST["confirm_password"]))){
$confirm_password_err = "Please confirm password.";
} else{
$confirm_password = trim($_POST["confirm_password"]);
if(empty($password_err) && ($password != $confirm_password)){
$confirm_password_err = "Password did not match.";
}
}
// Check input errors before inserting in database
if(empty($username_err) && empty($password_err) && empty($confirm_password_err)){
// Prepare an insert statement
$sql = "INSERT INTO users (username, password) VALUES (?, ?)";
if($stmt = mysqli_prepare($conn, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "ss", $param_username, $param_password);
// Set parameters
$param_username = $username;
$param_password = password_hash($password, PASSWORD_DEFAULT); // Creates a password hash
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Redirect to login page
header("location:Login.php");
} else{
echo "Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
}
// Close connection
mysqli_close($conn);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sign Up</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style type="text/css">
body{ font: 14px sans-serif; }
.wrapper{ width: 350px; padding: 20px; }
</style>
</head>
<body>
<div class="wrapper">
<h2>Sign Up</h2>
<p>Please fill this form to create an account.</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>">
<label>Username</label>
<input type="text" name="username" class="form-control" value="<?php echo $username; ?>">
<span class="help-block"><?php echo $username_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>">
<label>Password</label>
<input type="password" name="password" class="form-control" value="<?php echo $password; ?>">
<span class="help-block"><?php echo $password_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($confirm_password_err)) ? 'has-error' : ''; ?>">
<label>Confirm Password</label>
<input type="password" name="confirm_password" class="form-control" value="<?php echo $confirm_password; ?>">
<span class="help-block"><?php echo $confirm_password_err; ?></span>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Submit">
<input type="reset" class="btn btn-default" value="Reset">
</div>
<p>Already have an account? Login here.</p>
</form>
</div>
</body>
</html>
So, I am trying to retrieve data from my mysql database after a user registers or logins. The thing is that it somehow retrieves the letter "u" and that's weird, because there is no place that contains the letter "u".
This is the result I am getting as of now
https://imgur.com/t3XBrPN
index.php(where user registers or logs in)
<?php include('server.php') ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>PwettyKittyPincesa</title>
<link href="./style.css" type="text/css" rel="stylesheet" />
<script>
function start(){
closeForm();
closeRegForm();
}
function openForm() {
document.getElementById("myForm").style.display = "block";
closeRegForm();
}
function closeForm() {
document.getElementById("myForm").style.display = "none";
}
function openRegForm() {
document.getElementById("myRegForm").style.display = "block";
closeForm();
}
function closeRegForm() {
document.getElementById("myRegForm").style.display = "none";
}
</script>
</head>
<body onload="start()">
<nav>
<button class="button" type="submit" onclick="openForm()">Влез</button>
<button class="buttonReg" type="submit" onclick="openRegForm()">Регистрирай се</button>
<img src="Logo4.png" class="Logo" alt="Logo">
</nav>
<div class="form-popupRegister" id="myRegForm">
<form method="post" action="server.php" class="form-containerReg">
<h1>Регистрирация</h1>
<label for="username"><b>Име</b></label>
<input type="text" name="username" placeholder="Въведете името на лейдито" value="<?php echo $username; ?>">
<label for="email"><b>Е-майл</b></label>
<input type="email" name="email" placeholder="Въведете e-mail" value="<?php echo $email; ?>">
<label for="password_1"><b>Парола</b></label>
<input type="password" placeholder="Въведете парола" name="password_1">
<label for="password_2"><b>Повторете Парола</b></label>
<input type="password" placeholder="Въведете парола повторно" name="password_2">
<button type="submit" class="btnReg" name="reg_user">Register</button>
<button type="button" class="btn-cancelReg" onclick="closeRegForm()">Close</button>
</form>
</div>
<div class="form-popup" id="myForm">
<form method="post" action="server.php" class="form-container">
<h1>Влизане</h1>
<label for="username"><b>Име</b></label>
<input type="text" name="username" value="<?php echo $username; ?>">
<label for="password"><b>Парола</b></label>
<input type="password" name="password">
<button type="submit" class="btn" name="login_user">Login</button>
<button type="button" class="btn-cancel" onclick="closeForm()">Close</button>
</form>
</div>
</body>
</html>
index2.php(where the data should be output)
<?php include('server.php') ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>PwettyKittyPincesa</title>
<link href="./style.css" type="text/css" rel="stylesheet" />
<script>
function getUserStats(){
<?php
$queryThree = "SELECT * FROM `register` WHERE ID='$idQuery' ";
$userStats = mysqli_query($db,$queryThree);
$userStatsTwo = mysqli_fetch_assoc($userStats);
?>
}
</script>
</head>
<body onload="getUserStats()">
<div class="navWrapper">
<div class="statistics">
<div class="profilePicture" name="profilePicture">
<label class="profilePictureLabel" for="profilePicture"><b><?php echo userStatsTwo['username']; ?></b></label>
</div>
<div class="money" name="money">
<label class="rubyLabel" for="ruby"><b><?php echo userStatsTwo['money']; ?></b></label>
</div>
<div class="diamond" name="diamond">
<label class="diamondLabel" for="diamond"><b><?php echo userStatsTwo['diamonds']; ?></b></label>
</div>
<div class="ruby" name="ruby">
<label class="rubyLabel" for="ruby"><b><?php echo userStatsTwo['ruby']; ?></b></label>
</div>
<div class="level" name="level">
<label class="levelLabel" for="level"><b>Level:<?php echo userStatsTwo['level']; ?></b></label>
</div>
</div>
</div>
</body>
</html>
server.php(where the data is being processed)
<?php
session_start();
// initializing variables
$username = "";
$email = "";
$idQuery = "";
$errors = array();
// connect to the database
$db = mysqli_connect('localhost', 'id9159890_uregisterdb', 'censored', 'id9159890_registerdb');
// REGISTER USER
if (isset($_POST['reg_user'])) {
// receive all input values from the form
$username = mysqli_real_escape_string($db, $_POST['username']);
$email = mysqli_real_escape_string($db, $_POST['email']);
$password_1 = mysqli_real_escape_string($db, $_POST['password_1']);
$password_2 = mysqli_real_escape_string($db, $_POST['password_2']);
// form validation: ensure that the form is correctly filled ...
// by adding (array_push()) corresponding error unto $errors array
if (empty($username)) { array_push($errors, "Username is required"); }
if (empty($email)) { array_push($errors, "Email is required"); }
if (empty($password_1)) { array_push($errors, "Password is required"); }
if ($password_1 != $password_2) {
array_push($errors, "The two passwords do not match");
}
// first check the database to make sure
// a user does not already exist with the same username and/or email
$user_check_query = "SELECT * FROM `register` WHERE username='$username' OR email='$email' LIMIT 1";
$result = mysqli_query($db, $user_check_query);
$user = mysqli_fetch_assoc($result);
if ($user) { // if user exists
if ($user['username'] === $username) {
array_push($errors, "Username already exists");
}
if ($user['email'] === $email) {
array_push($errors, "email already exists");
}
}
// Finally, register user if there are no errors in the form
if (count($errors) == 0) {
$password = md5($password_1);//encrypt the password before saving in the database
$query = "INSERT INTO `register` (username, password, email, money, ruby, diamonds, levelpoints, level)
VALUES ('$username', '$password', '$email', '0', '0', '0', '0', '0')";
mysqli_query($db, $query);
$idQuery = "SELECT ID FROM `register` WHERE username='$username'";
mysqli_query($db, $idQuery);
$_SESSION['username'] = $username;
$_SESSION['userid'] = $idQuery;
$_SESSION['success'] = "You are now logged in";
header('location: index2.php');
}
}
// LOGIN USER
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 `register` WHERE username='$username'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
$_SESSION['username'] = $username;
$_SESSION['success'] = "You are now logged in";
header('location: index2.php');
}else {
array_push($errors, "Wrong username/password combination");
}
}
}
?>
The results that I should be getting are(from top to bottom and left to right)
Username, Level, Money, Diamond, Ruby and their values should respectively be Username, 0, 0, 0, 0.
I've tried everything and nothing changes, I've re-constructed my code twice and it still outputs only that and nothing else.
You have an issue here in your code:
$idQuery = "SELECT ID FROM `register` WHERE username='$username'";
mysqli_query($db, $idQuery);
$_SESSION['username'] = $username;
$_SESSION['userid'] = $idQuery;
As i mentioned in my comment, check what are you getting in echo "SELECT * FROM register WHERE ID='$idQuery' "; you definitely getting this kind of result:
SELECT * FROM register` WHERE ID= 'SELECT ID FROM `register` WHERE username='somename''
For sub query, remove quotes around your variable from:
"SELECT * FROM register` WHERE ID='$idQuery' ";
should be:
"SELECT * FROM register` WHERE ID = $idQuery";
Note that, this is success case, as you show your result here https://imgur.com/P64hqvI, your query is working fine..
You also need to use some protection for $idQuery if $idQuery == '' then your you can't get any result also.
As #patrick-q mentioned, use session to store username or ID instead of saving a full query.
Second, you code is wide open for SQL injection, for preventing, use PDO.
Some helpful links:
Are PDO prepared statements sufficient to prevent SQL injection?
How can I prevent SQL injection in PHP?
I am making a comment system for my blog that I am creating and currently I have two problems with it. The form appears under every post. But only works on the top post. The rest of the forms simply don't work.
The another problem I have is that I'm using ajax and the form does add the record to SQL but I still have to refresh my page for it to show. I want it to show automatically straight away after it is added.
tl:dr
Two problems:
The only form that works is the first one under the first post, the rest simply don't work
Ajax doesn't automatically show the comments, need to refresh to seem them
Code:
JQuery
function post()
{
var comment = document.getElementById("comment").value;
var name = document.getElementById("name").value;
var mail = document.getElementById("mail").value;
var post_id = document.getElementById("post_id").value;
if(comment && name && mail)
{
$.ajax
({
type: 'post',
url: 'php/comment.php',
data:
{
user_comm:comment,
user_name:name,
user_mail:mail,
post_id:post_id,
},
success: function (response)
{
document.getElementById("comments").innerHTML=response+document.getElementById("comments").innerHTML;
document.getElementById("comment").value="";
document.getElementById("name").value="";
document.getElementById("mail").value="";
}
});
}
return false;
}
Index.php
<div class="container">
<div class="row">
<div class="col-lg-8">
<?php
$result = mysql_query('SELECT * FROM `posts` ORDER BY id DESC') or die(mysql_error());
while($row = mysql_fetch_array($result)) {
$id_post = $row['id'];
$post_title = $row['post_title'];
$post_date = $row['date_created'];
$post_img = $row['post_img'];
$post_first = $row['post_first'];
$post_second = $row['post_second'];
echo " <!-- Blog Post Content Column -->
<h1> " . $row['post_title'] . " </h1><p class='lead'>
by <a href='#'>Matt</a></p> <hr>
<p><span class='glyphicon glyphicon-time'>" . $row['date_created'] . "</span></p>
<img class='img-responsive' style='width: 900px;height: 300px;' src=" . $row['post_img'] . "> <hr>
<p class='lead'>" . $row['post_first'] . "</p>
<p>" . $row['post_second'] . "</p> <hr>";
?>
<!-- Comments Form -->
<div class='well'>
<h4>Leave a Comment:</h4>
<div class="new-com-cnt">
<form method='post' onsubmit="return post();">
<input type='hidden' id='post_id'name='post_id' value='<?php echo $id_post; ?>'>
<div class='form-group'>
<input type="text" id="name" name="name-com" value="" placeholder="Your name" />
<input type="text" id="mail" name="mail-com" value="" placeholder="Your e-mail adress" />
<textarea type='text' id='comment' name='comment' class="form-control" rows='3'></textarea>
</div>
<input type="submit" value="Post Comment">
</form>
</div>
</div>
<hr>
<?php
$resultcomments = mysql_query("SELECT * FROM `comment` WHERE post_id = '$id_post' ORDER BY `date` DESC") or die(mysql_error());
while($affcom = mysql_fetch_assoc($resultcomments)){
$name = $affcom['name'];
$email = $affcom['mail'];
$comment = $affcom['comment'];
$date = $affcom['date'];
$default = "mm";
$size = 35;
$grav_url = "http://www.gravatar.com/avatar/".md5(strtolower(trim($email)))."?d=".$default."&s=".$size;
?>
<!-- Posted Comments -->
<div id='comments'class='media'>
<a class='pull-left' href='#'>
<img class='media-object' src=' <?php echo $grav_url; ?>' >
</a>
<div class='media-body'><?php echo $name; ?>
<h4 class='media-heading'>
<small><?php echo $date; ?></small>
</h4>
<?php echo $comment; ?>
</div>
</div>
<?php
}
}
?>
</div>
comment.php
include_once('../../acp/db/db.php');
$link = mysql_connect($dbhost, $dbuser, $dbpassword, $dbname);
mysql_select_db($dbname);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
if(isset($_POST['user_comm']) && isset($_POST['user_name']) && isset($_POST['user_mail']))
{
$comment=$_POST['user_comm'];
$name=$_POST['user_name'];
$mail=$_POST['user_mail'];
$post_id=$_POST['post_id'];
$insert=mysql_query("INSERT INTO comment (name,mail,comment,post_id) VALUES ('$name', '$mail', '$comment', '$post_id')");
$select=mysql_query("SELECT * FROM `comment` WHERE post_id = '$id_post' ORDER BY `date` DESC");
if($row=mysql_fetch_array($select))
{
$name=$row['name'];
$comment=$row['comment'];
$date=$row['date'];
?>
<div class='media'>
<a class='pull-left' href='#'>
<img class='media-object' src=' <?php echo $grav_url; ?>' >
</a>
<div class='media-body'><?php echo $name; ?>
<h4 class='media-heading'>
<small><?php echo $date; ?></small>
</h4>
<?php echo $comment; ?>
</div>
</div>
<?php
}
exit;
}
?>
This is the first time I am playing around with AJAX :) so be easy on me Any help will be appreciated.
I tested all your code. It's working now. I commented it overall, so search after "NB" (lat. for "Nota bene") in codes, in order to see were I made relevant changes. I'll describe here some problems with it and I'll also give you some recommendations - if I may. At last I'll insert the three corrected pages.
Problems:
One big problem was, that you were using the $id_post variable in
the SELECT sql statement (in comment.php), which does not exist
in comment.php code.
Other problem: DOM elements had same ids. The DOM elements inside
loop-forms must have unique id attributes. You must always have
unique id attributes in html elements. Give them the form
id="<early-id><post_id>" for example.
There were also other problems in more places. I commented overall,
so you'll have to read my codes.
Recommendations:
Use mysqli_ instead of mysql_ functions, because mysql
extension were completely removed from PHP >= 7.0.
Use exception handling, especially when dealing with db access.
Don't write HTML code from inside php. Alternate php with html if you
wish, but don't do echo "<div class=...></div>" for example. This
is actually very important if you use an IDE which can format your
html code. If this code is inside php, you have no chance for this
beautifying process. therefore you can miss important html-tags
without knowing it, because your IDE didn't showed you where tags are
really missing in page.
In html tags: use same name as id. Example: id=mail<?php echo
$post_id; ?>, name=mail<?php echo $post_id; ?>. Exception: radio
buttons, checkboxes and all tags which can form a group. Then, each
tag would have a unique id, but all of them would receive the same
name.
Use '' overall and "" inside them. Maintain this "standard", you'll see it's a lot better than the inverse.
Corrected pages:
Index.php:
<?php
try {
$con = mysqli_connect('<host>', '<user>', '<pass>', '<db>');
if (!$con) {
throw new Exception('Connect error: ' . mysqli_connect_errno() . ' - ' . mysqli_connect_error());
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>NB: TITLE</title>
<!-- NB: Added my scripts for testing -->
<link href="Vendor/Bootstrap-sass-3.3.7/Bootstrap.css" rel="stylesheet" type="text/css" />
<script src="Vendor/jquery-3.1.0/jquery.min.js" type="text/javascript"></script>
<script src="Vendor/Bootstrap-sass-3.3.7/assets/javascripts/bootstrap.min.js" type="text/javascript"></script>
<script type="text/javascript" src="index.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-8">
<?php
$result = mysqli_query($con, 'SELECT * FROM `posts` ORDER BY id DESC');
if (!$result) {
throw new Exception('The query could not be executed!');
}
while ($row = mysqli_fetch_array($result)) {
// NB: Unified $post_id name overall (instead of $id_post).
$post_id = $row['id'];
$post_title = $row['post_title'];
$post_date = $row['date_created'];
$post_img = $row['post_img'];
$post_first = $row['post_first'];
$post_second = $row['post_second'];
?>
<!-- Blog Post Content Column -->
<!--
NB: Extracted html code from php and added here, where it should be.
-->
<h1>
<?php echo $post_title; ?>
</h1>
<p class="lead">
by Matt
</p>
<hr/>
<p>
<span class="glyphicon glyphicon-time">
<?php echo $post_date; ?>
</span>
</p>
<img class="img-responsive" style="width: 1200px; height: 100px;" src="<?php echo $post_img; ?>">
<hr/>
<p class="lead">
<?php echo $post_first; ?>
</p>
<p>
<?php echo $post_second; ?>
</p>
<hr/>
<!-- Comments Form -->
<div class="well">
<h4>Leave a Comment:</h4>
<div class="new-com-cnt">
<form method="post" onsubmit="return post('<?php echo $post_id; ?>');">
<!--
NB: Deleted hidden input (not needed!) and was missing post_id in "id" attribute!
So: transfered post_id value to post() function as argument. See js too.
-->
<!--
NB: Added post_id to the "id" attributes. See js too.
-->
<div class="form-group">
<input type="text" id="name<?php echo $post_id; ?>" name="name-com" value="" placeholder="Your name" />
<input type="text" id="mail<?php echo $post_id; ?>" name="mail-com" value="" placeholder="Your e-mail adress" />
<textarea type="text" id="comment<?php echo $post_id; ?>" name="comment" class="form-control" rows="3"></textarea>
</div>
<input type="submit" value="Post Comment">
</form>
</div>
</div>
<hr>
<!--
NB: Added new "comments" outer-container in order to append
new comment to it and added post_id value into its "id" attribute.
See the js too.
-->
<div id="comments<?php echo $post_id; ?>" class="comments-container">
<?php
$resultComments = mysqli_query($con, 'SELECT * FROM `comment` WHERE post_id = ' . $post_id . ' ORDER BY `date` DESC');
if (!$resultComments) {
throw new Exception('The query could not be executed!');
}
while ($affcom = mysqli_fetch_assoc($resultComments)) {
$name = $affcom['name'];
$email = $affcom['mail'];
$comment = $affcom['comment'];
$date = $affcom['date'];
$default = "mm";
$size = 35;
$grav_url = "http://www.gravatar.com/avatar/" . md5(strtolower(trim($email))) . "?d=" . $default . "&s=" . $size;
?>
<!-- Posted Comments -->
<!--
NB: deleted id attribute "comments", because I added an outer
container to hold the insert results, e.g. the div
with the class "comments-container".
-->
<div class="media">
<a class="pull-left" href="#">
<img class="media-object" src="<?php echo $grav_url; ?>" >
</a>
<div class="media-body">
<?php echo $name; ?>
<h4 class="media-heading">
<small><?php echo $date; ?></small>
</h4>
<?php echo $comment; ?>
</div>
</div>
<?php
}
?>
</div>
<?php
}
?>
</div>
</div>
</div>
</body>
</html>
<?php
$closed = mysqli_close($con);
if (!$closed) {
throw new Exception('The database connection can not be closed!');
}
} catch (Exception $exception) {
// NB: Here you should just DISPLAY the error message.
echo $exception->getMessage();
// NB: And here you should LOG your whole $exception object.
// NB: Never show the whole object to the user!
// echo '<pre>' . print_r($exception, true) . '</pre>';
exit();
}
?>
comment.php:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>NB: TITLE</title>
</head>
<body>
<?php
try {
$con = mysqli_connect('<host>', '<user>', '<pass>', '<db>');
if (!$con) {
throw new Exception('Connect error: ' . mysqli_connect_errno() . ' - ' . mysqli_connect_error());
}
if (isset($_POST['user_comm']) && isset($_POST['user_name']) && isset($_POST['user_mail'])) {
$comment = $_POST['user_comm'];
$name = $_POST['user_name'];
$mail = $_POST['user_mail'];
$post_id = $_POST['post_id'];
// NB: NEW. CHANGE THIS TO YOUR wished DATE FORMAT.
// Use UNIX timestamps for dates, so that you make good date calculations.
$date = date("Y-m-d");
// NB: INSERT DATE IN DB TOO, so that you can select by date desc down under.
$insert = mysqli_query($con, "INSERT INTO comment (name,mail,comment,post_id, date) VALUES ('$name', '$mail', '$comment', '$post_id', '$date')");
if (!$insert) {
throw new Exception('The query could not be executed!');
}
// NB: Replaced $id_post with $post_id.
$select = mysqli_query($con, "SELECT * FROM `comment` WHERE post_id = '$post_id' ORDER BY `date` DESC");
if (!$select) {
throw new Exception('The query could not be executed!');
}
if ($row = mysqli_fetch_array($select)) {
$name = $row['name'];
// NB: Added email, because it wasn't provided.
$email = $row['mail'];
$comment = $row['comment'];
$date = $row['date'];
// NB: It wasn't provided, so I added the same value as in index.php.
$default = "mm";
$size = 35;
$grav_url = "http://www.gravatar.com/avatar/" . md5(strtolower(trim($email))) . "?d=" . $default . "&s=" . $size;
?>
<div class="media">
<a class='pull-left' href='#'>
<!--
NB: Where is your $grav_url value?! I added one of mine for testing.
-->
<img class='media-object' src=' <?php echo $grav_url; ?>' >
</a>
<div class='media-body'>
<?php echo $name; ?>
<h4 class='media-heading'>
<small><?php echo $date; ?></small>
</h4>
<?php echo $comment; ?>
</div>
</div>
<?php
}
// NB: Don't use exit(). Let the code flow further, because
// you maybe want to close the db connection!
// exit();
}
$closed = mysqli_close($con);
if (!$closed) {
throw new Exception('The database connection can not be closed!');
}
} catch (Exception $exception) {
// NB: Here you should just DISPLAY the error message.
echo $exception->getMessage();
// NB: And here you should LOG your whole $exception object.
// NB: Never show the whole object to the user!
// echo '<pre>' . print_r($exception, true) . '</pre>';
exit();
}
?>
</body>
</html>
Javascript file:
// NB: Added post_id as parameter. See form too.
function post(post_id) {
// NB: Added post_id value to the "id" attributes. See form too.
var comment = document.getElementById("comment" + post_id).value;
var name = document.getElementById("name" + post_id).value;
var mail = document.getElementById("mail" + post_id).value;
if (comment && name && mail) {
$.ajax({
type: 'post',
url: 'php/comment.php',
data: {
user_comm: comment,
user_name: name,
user_mail: mail,
post_id: post_id
},
success: function (response) {
// NB: Comments-post_id is now an outer container. See form.
// NB: Added post_id value to the "id" attributes. See form too.
document.getElementById("comments" + post_id).innerHTML = response + document.getElementById("comments" + post_id).innerHTML;
document.getElementById("comment" + post_id).value = "";
document.getElementById("name" + post_id).value = "";
document.getElementById("mail" + post_id).value = "";
}
});
}
return false;
}
// ******************************************************************************
// NB: Recommendation:
// ******************************************************************************
// Use jquery and ajax instead of vanilla javascript. It's no problem anymore ;-)
// Use done, fail, always instead of success, error, ....
// ******************************************************************************
//function post(post_id) {
// var comment = $('#comment' + post_id);
// var name = $('#name' + post_id);
// var mail = $('#mail' + post_id);
//
// if (comment && name && mail) {
// var ajax = $.ajax({
// method: 'POST',
// dataType: 'html',
// url: 'php/comment.php',
// data: {
// user_comm: comment.val(),
// user_name: name.val(),
// user_mail: mail.val(),
// post_id: post_id
// }
// });
// ajax.done(function (data, textStatus, jqXHR) {
// var comments = $("#comments" + post_id);
//
// // NB: I'm not sure, not tested, too tired :-) Please recherche.
// comments.html(data + comments.html());
//
// comment.val('');
// name.val('');
// mail.val('');
// });
// ajax.fail(function (jqXHR, textStatus, errorThrown) {
// // Show error in a customized messages div, for example.
// $('#flashMessage').val(textStatus + '<br />' + errorThrown);
// });
// ajax.always(function (data, textStatus, jqXHR) {
// //...
// });
// }
//
// return false;
//}
// ******************************************************************************
Good luck.
Your parent loop is generating several comments form and they all have the same id. Ids are supposed to be unique for the whole document. refer this. Perhaps this is causing other comment forms not to work except the first one.
Your second problem is not an issue. It is general behavior of how server works. When you are using ajax, it is sending data to the server which stores it in the database. Server's job is done. It cannot send the data back to the page and update the page content without refreshing the page. You can initiate another ajax call after posting to server in order to refresh the content of the page.
And though it is not related to the question. Try to be consistent with your use of single quotes and double quotes. You shouldn't randomly choose them. Decide on one and use them consistently. And yes do try to learn PDO or mysqli. I will suggest PDO.
I am having trouble with the browser back button.
When the User press Log out it have to destroy the session and cookies. I wrote the following code:
index.php
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
function disablebackbutton(){
window.history.forward();
}
disablebackbutton();
</script>
</head>
<body>
<form name="loginform" method="post" action="<?php echo __PROJECT_LINK__; ?>/php/login_exec.php">
<div class="modal-body">
<div class="form-horizontal">
<div class="form-group">
<label class="control-label">
<?php
if( isset($_SESSION['ERRMsg_ARR']) && is_array($_SESSION['ERRMsg_ARR']) && count($_SESSION['ERRMsg_ARR']) >0 ) {
echo '<ul class="err">';
foreach($_SESSION['ERRMsg_ARR'] as $msg) {
echo '<span class="label label-warning" style="margin-left: 5px;">',$msg,'</span>';
}
echo '</ul>';
unset($_SESSION['ERRMsg_ARR']);
}
?>
</label>
</div>
<div class="subnav subnav-fixed nav navbar" style="margin-top: 10px; margin-right: 10px; margin-left: 10px;">
<ul class="nav nav-pills">
<li style="margin-top: 10px;">
<span class="label label-default" style="margin-left: 22px;">Username</span>
<input type="text" id="inputUserName" name="username" placeholder="Username" style="margin-left: 5px;">
</li>
<li style="margin-top: 10px;">
<span class="label label-default" style="margin-left: 22px;">Password</span>
<input type="password" id="inputPassword" name="password" placeholder="Password" style="margin-left: 5px;">
</li>
<li style="margin-top: 10px; margin-bottom: 10px;">
</li>
</ul>
</div>
</div>
</div>
<div class="modal-footer">
<!--?php $this->btnLogLogin->Render();?-->
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Sign In</button>
</div>
</form>
</body>
</html>
login_exec.php
<?php
//Start session
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
//Include database connection details
require_once('connection.php');
//Array to store validation errors
$errmsg_arr = array();
//Validation error flag
$errflag = false;
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
if(isset($_POST['username']))
{
//Sanitize the POST values
$username = ($_POST['username']);
$password = ($_POST['password']);
//Input Validations
if($username == '') {
$errmsg_arr[] = 'Username missing';
$errflag = true;
}
if($password == '') {
$errmsg_arr[] = 'Password missing';
$errflag = true;
}
//If there are input validations, redirect back to the login form
if($errflag==true) {
$_SESSION['ERRMsg_ARR'] = $errmsg_arr;
session_write_close();
header("location:../index.php");
exit();
}
//Create query
$qry="SELECT * FROM admin WHERE user_name='$username' AND password='$password'";
$result=mysql_query($qry);
//Check whether the query was successful or not
if($result) {
if(mysql_num_rows($result)) {
while($row = mysql_fetch_array($result))
{
if($row['User_Status']=="Active"){
$expire=time()+60*60*24*30; //1month
setcookie("User_id", $row['User_id'], $expire);
$name = $row['full_name'];
$parts = explode(" ", $name);
$lastname = array_pop($parts);
$firstname = implode(" ", $parts);
$_SESSION['USER'] = $firstname;
$_SESSION['UID'] = $row['User_id'];
$_SESSION['URights'] = $row['Rights'];
header("location:../welcome.php");
}
else{
$errmsg_arr[] = 'User Status is Block. Please contact your Administrator.';
$errflag = true;
if($errflag) {
$_SESSION['ERRMsg_ARR'] = $errmsg_arr;
session_write_close();
header("location: ../index.php");
exit();
}
}
}
}
else {
//Login failed
$errmsg_arr[] = 'Username and Password not found';
$errflag = true;
if($errflag) {
$_SESSION['ERRMsg_ARR'] = $errmsg_arr;
session_write_close();
header("location: ../index.php");
exit();
}
}
}else {
die("Query failed");
}
}
?>
welcome.php
<?php include 'qcubed.inc.php'; ?>
<?php
$User_Name = $_SESSION['USER'];
?>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h1>Welcome <?php echo $User_Name; ?></h1>
<h2>Info</h2>
<h2>Sign Out</h2>
</body>
</html>
Info.php
<?php include '../../qcubed.inc.php';?>
<!DOCTYPE html>
<html lang="en">
<head>
<title><?php echo __PROJECT_TITLE__; ?> - Full Info</title>
<script type="text/javascript">
function disablebackbutton(){
window.history.forward();
}
disablebackbutton();
</script>
</head>
<?php
if(isset($_SESSION['UID']) && $_SESSION['UID'] != "")
{
//Task to do
$User_Name = $_SESSION['USER'];
?>
<body>
<h1>Info about <?php echo $User_Name; ?></h1>
<h2>Sign Out</h2>
</body>
<?php
}
else{
//redirect URL
?>
<script>
alert('You must Login first.');
window.location.href='../../index.php';
</script>";
<?php
exit();
}
?>
</html>
logout.php
<?php
//session_write_close();
session_start(); # NOTE THE SESSION START
$expire=time()-60*60*24*30; //1month
if(isset($_COOKIE['User_id'])):
setcookie('User_id', '', $expire, '/');
endif;
unset($_SESSION['UID']);
unset($_SESSION['USER']);
unset($_SESSION['URights']);
unset($_SESSION['UReg']);
$_SESSION = array();
foreach(array_keys($_SESSION) as $k) unset($_SESSION[$k]);
session_unset();
session_destroy();
header("location: ../index.php");
exit(); # NOTE THE EXIT
?>
After pressing log out from Info.php , when I press the browser back button it is showing my previous Logined user page and session username in Info.php page,
but if I use the following javascript in head section of every page it disable all the browser back button at the time of login also.
<script type="text/javascript">
function disablebackbutton(){
window.history.forward();
}
disablebackbutton();
</script>
I want to disable the browser back button only after the the time of logout.
Please help me.
That became my problem before. On my case i did not disable the back button. what i did is to check the session when the user is logged out. if there has no detected session, redirect the user to log in page or to what page you like the to redirect.. if there is a detected session redirect it to the homepage
rather than disabling the back button, you can add code to every page to see if the user is logged. If they are NOT logged in, redirect to the login page.
You could create a basic class to handle this for you and just create one on every page.
class sessionHandler
{
function __construct($special = NULL)
{
session_set_cookie_params(60 * 60 * 24 * 365); // 1 year
session_start();
// if no user num (empty session) AND this isn't the login page
if (!isset($_SESSION['userID']) && $special != 'LOGIN') {
//send to login page
header("location: login.php");
}
if ($special == 'LOGOUT') {
// This is the logout page, clear the session and
// send the user to the afterLogout page
session_destroy(); // clear session files on server
$_SESSION = Array(); // clear session variable for this session
unset($_SESSION);
// send to login page
header("location: login.php");
}
if ($special == 'LOGIN') {
// This is the login page, see if user is already logged in
// if so, just send them to the afterLogin page
// if not, validate their credentials, and store the USERID
// in the $_SESSION var
if ($this->getUserPermissions($_SESSION['userID'])) {
// send to any page you want
header("location: dashboard.php");
}
}
}
}
Now, on all your pages, put $session = new sessionHandler(); at the top (before anything else is written.
For login and logout pages you'd put:
$session = new sessionHandler('LOGIN');
$session = new sessionHandler('LOGOUT');
Not copy and paste ready, but hopefully that points you in the right direction. :-)
USE THIS CODE in login_exec.php
if($errflag==true) {
$_SESSION['ERRMsg_ARR'] = $errmsg_arr;
session_write_close();
header("location:../index.php");
exit();
}
//Create query
$qry="SELECT * FROM admin WHERE user_name='$username' AND password='$password'";
$result=mysql_query($qry);
//Check whether the query was successful or not
if($result) {
if(mysql_num_rows($result)) {
while($row = mysql_fetch_array($result))
{
if($row['User_Status']=="Active"){
$expire=time()+60*60*24*30; //1month
setcookie("User_id", $row['User_id'], $expire);
$name = $row['full_name'];
$parts = explode(" ", $name);
$lastname = array_pop($parts);
$firstname = implode(" ", $parts);
$_SESSION['USER'] = $firstname;
$_SESSION['UID'] = $row['User_id'];
$_SESSION['login']=true; //ADD THIS CODE IN login_exec.php
$_SESSION['URights'] = $row['Rights'];
header("location:../welcome.php");
}
else{
$errmsg_arr[] = 'User Status is Block. Please contact your Administrator.';
$errflag = true;
if($errflag) {
$_SESSION['ERRMsg_ARR'] = $errmsg_arr;
session_write_close();
header("location: ../index.php");
exit();
}
}
}
}
now add the code top of the info.php
session_start();
$user=$_SESSION['USER'];
if($_session['login']=true && $_session['user']= $user)
{
code of info.php
}
else
{
header(location:index.php);
}
logout.php
<?php
session_start();
unset($_SESSION['USER']);
session_destroy();
header("Location:index.php");
?>
Just add a condition at all the pages which user can access only if he is login:
if(!isset($_SESSION['UID']) || $_SESSION['UID'] == ''){
// redirect to index or login page
}
At last I solved my problem ..... :-)
I use this following code in
logout.php
<html>
<head>
<script type = "text/javascript" >
window.history.forward();
function preventBack() { window.history.forward(1); }
setTimeout("preventBack()", 0);
window.onunload = function () { null };
</script>
</head>
<body onload="preventBack();" onpageshow="if (event.persisted) preventBack();" onunload="">
Please Wait..
<?php
session_start(); # NOTE THE SESSION START
$expire=time()-60*60*24*30; //1month
if(isset($_COOKIE['User_id'])){
setcookie('User_id', '', $expire);
}
unset($_SESSION['UID']);
unset($_SESSION['USER']);
unset($_SESSION['URights']);
unset($_SESSION['UReg']);
$_SESSION = array();
foreach(array_keys($_SESSION) as $k) unset($_SESSION[$k]);
session_unset();
session_destroy();
header("Refresh: 2;url=../index.php");
?>
</body>
</html>
Now it's avoid me to use browser back button after logout and destroy the session.
Thank you all for yours valuable support...