getting processed value back in same page in php - php

I want that when I press login button I get the response back in the same page e.g. if user name doesn't exist or is duplicate it should show the error message on the same page, one more thing this data goes to another page and after some database action it returns the value, I got the value in the page where I use that database query, but how to get it back to the very first page from where I actually submitted it
this is the scenario login->function selector->controller(database query page)
what I need to do is to get value from controller to login after a successful query generation here is a glimpse of code
<form method="post" action="selector.php?type=login" id="login" id="loginForm">
<div class="row">
<div class="offset1 span1">
<div class="lbel"><label class="control-label" for ="loginName">Username/Email</label></div>
<div class="lbl_inpuCnt"><input type="text" class="input-xlarge" id="loginName" name="loginName" maxlength="50"/></div>
<div id="usernameError" style="font-size: 10px; color: red;"> </div>
<div class="lbel"><label class="control-label" for="loginPassword">Password</label></div>
<div class="controls">
<input type="password" class="input-xlarge" id="loginPassword" name="loginPassword" maxlength="50"/>
</div>
<div id="passwordError" style="font-size: 10px; color: red;"> </div><br/>
</div>
</div>
<div style="margin-left: 55px;">
<input class="btn" style="width: 80px;" type="reset" name="reset" value="Reset" onclick="clearFields()"/>
<input class="btn" style="width: 80px;" type="submit" name="submit" value="Login" onclick="return validateForm();"/>
</div>
</form>
then comes the selector page
<?php
include_once 'classes/controller.php';
$controller = new controller();
switch ($_GET['type']) {
case 'signup':
$registerStatus = $controller->register($_POST);
$_POST['username'] = $registerStatus;
break;
case 'login':{
$result= $controller->login($_POST);
echo $result; //here i get the value from next page after process, i need it back to login page to show error there!
}
break;
case 'uploadSongs':
$controller->uploadSongs();
break;
case "delete":
echo "Function Called";
break;
}
?>
and this is the controller function in controller.php
public function login($request = array()) {
$login = $request['loginName'];
$password = ($request['loginPassword']);
$query = "select * from user where (user_name = '" . $login . "' OR email = '" . $login . "') AND (password = '" . $password . "')";
$user = $this->model->select($query);
if (is_array($user) && isset($user[0]['user_id'])) {
$_SESSION['uid'] = $user[0]['user_id'];
echo $_SESSION['name'] = $user[0]['first_name'];
$this->redirect("userArea.php");
} else {
echo "-1";
return $login;
}
exit;
}

Login page can submit to itself, and on a successful login, you redirect to member area. On a failed login, you simply display a message.

Related

Facing Problem with PHP post request method

I want to update my data in SQL database but i am facing issues like as you can see i already defined the request method as POST but when i gonna check it, it doesn't work like:
if (
isset($_POST["form"])
) {
...
}
else{ echo "form's method is not set as POST"}
this condition get false and print "form's method is not set as POST".
This is my form HTML
<form name="form" method="post" action="courses.php">
<div class=" mb-3">
<label for="c_name_u" class="form-label">Course Name</label>
<input type="text" class="form-control" name="c_name_u" id="c_name_u" require>
</div>
<div class=" mb-3">
<label for="credit_hours_u" class="form-label">Credite Hours</label>
<input type="text" class="form-control" name="credit_hours_u" id="credit_hours_u" require>
</div>
<a style="text-decoration: none; color: white;" href="courses.php?edit_task=<?php echo $course_id ?>">
<button type="submit" class="btn btn-primary btn-md">
Update Course
</button>
</a>
</form>
and my PHP code is:
<?php
if (isset($_GET['edit_task'])) {
if (
isset($_POST["form"])
) {
$c_name_u = $_POST["c_name_u"];
$credit_hours_u = $_POST["credit_hours_u"];
$course_id = $_GET['edit_task'];
$query = "UPDATE `courses` SET `Course_name` = '$c_name_u', `Credit_hours` = '$credit_hours_u' WHERE `courses`.`Course_id` =" . $course_id;
$update_db = $conn->query($query);
if (!$update_db) {
echo " data is not saved";
}
}
}
?>

Setting up a logout link properly

Currently working a little Sign-Up/Login system with PHP. Here is the situation:
I have this first page named "signup.php" for signing up and logging in. Once you submit your form, you are redirected to a second page called "diary.php". Once you click the submit button, a session is created respectively with your id within the "users" database. Without the diary.php, there's a logout link.
If you signed up or logged in and you are now viewing diary.php, you cannot view the signup.php page unless you press logout. Once you press logout, you are redirected to the signup.php page, but with a logout variable in the $_GET array.
<a href='signup.php?logout=1'>Logout</a>
I'm using this logout variable to check the moment there is a "logout" key exists in $_GET array, it destroys the session and redirects me back to the signup.php page.
Now here is the problem. Say I signed up for a new account, then logged out. Once I log out there's going to be a "logout" key within the GET, right? (to destroy session). If I try to sign up for another account, it actually is going to sign up me (on the database), but it automatically logs out for me since I had the logout key in my link and also because there was no session (I have in my code few lines that automatically take you back to signup.php if there is no session).
I hope that was enough to make it clear for you all. I'm going to leave the code for my two pages for you to examine. Thank you!
signup.php
session_start();
$conn = mysqli_connect("localhost","root","","diary");
$error = '';
$success = '';
if (array_key_exists("submit",$_POST)) {
if (!$_POST['email']) {
$error.= "Email field is missing.<br>";
}
if (!$_POST["password"]) {
$error .= "Password field is missing.<br>";
}
if ($error != '') {
$error = "Fill in the missing field(s):<br>".$error;
}
else if ($_POST["submit"] == "Sign up") {
$email = $_POST["email"];
$query = "SELECT * FROM users WHERE email = '$email';";
$result = mysqli_query($conn,$query);
if (mysqli_num_rows($result) != 0) {
$error .= "This account already exists!";
} else {
$email = $_POST["email"];
$password = $_POST["password"];
$query1 = "INSERT INTO users (email,password) VALUES ('$email','$password');";
mysqli_query($conn,$query1);
$success.= "Successfully signed up!";
$query = "SELECT id FROM users WHERE email = '$email';";
$row = mysqli_fetch_array(mysqli_query($conn,$query));
$id=$row["id"];
$_SESSION["id"] = $id;
header("Location: diary.php");
if (!isset($_POST["signUpRemember"])) {
} else {
setcookie("id",$id,time() + 60*60*24*30);
}
}
} else if ($_POST["submit"] == "Login") {
$email = $_POST["email"];
$password = $_POST["password"];
$query = "SELECT * FROM users WHERE email = '$email';";
if (mysqli_num_rows(mysqli_query($conn,$query)) == 0) {
$error.= "This account does not exist, sign up for a new account!";
} else {
$query = "SELECT password FROM users WHERE email = '$email';";
$rows = mysqli_fetch_array(mysqli_query($conn,$query));
if ($password != $rows["password"]) {
$error.= "You have inserted the wrong password for this account. Please, try again!";
} else {
$query = "SELECT id FROM users WHERE email = '$email';";
$rows = mysqli_fetch_array(mysqli_query($conn,$query));
$_SESSION["id"] = $rows["id"];
if (!isset($_POST["signUpRemember"])) {
} else {
setcookie("id",$rows["id"],time() + 60*60*24*30);
}
header("Location :diary.php");
}
}
}
}
if (array_key_exists("logout",$_GET)) {
unset($_SESSION["id"]);
setcookie("id","",time() - 60*600);
}
if (array_key_exists("id",$_SESSION)) {
header("Location: diary.php");
}
?>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js" integrity="sha384-o+RDsa0aLu++PJvFqy8fFScvbHFLtbvScb8AjopnFD+iEQ7wo/CG0xlczd+2O/em" crossorigin="anonymous"></script>
<title>Secret Diary</title>
<style>
body {
margin:0;
height: 0;
}
#error {
background-color: red;
}
body {
background-image: url("img/bg.jpg");
background-color: #cccccc;
}
#containerLogin {
margin: auto;
width: 30%;
padding: 10px;
margin-top: 5%;
}
#containerSignup {
margin: auto;
width: 30%;
padding: 10px;
margin-top: 5%;
}
.switchBtt {
margin-top: 5%;
width: 70%;
}
.display-4 {
font-weight: 300;
}
</style>
</head>
<body>
<div id="error"><?php if ($error != "") { echo $error; } else { echo "<script>$( '#error' ).css('background-color', 'green');</script>"; echo $success;} ?></div>
<div id="containerLogin">
<center><h1 class="display-4 text-muted "><font color="#6D3E6C">Secret Diary</font></h1>
<br>
<h5 class=" text-muted "><font color="#DFD2CA">Welcome back!</font></h5>
<br>
<form method="post" name="signup">
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" name="email" aria-describedby="emailHelp" placeholder="Enter email">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" name="password" placeholder="Password">
</div>
<div class="form-group form-check ">
<input type="checkbox" class="form-check-input" value="checked" name="signUpRemember">
<label class="form-check-label" for="signUpRemember">Keep me signed in</label>
</div>
<input class="btn btn-primary" type="submit" value="Login" name="submit">
</form>
<div class="btn btn-secondary switchBtt">Switch to sign-up panel ↹ </div>
</center>
</div>
<div id="containerSignup">
<center><h1 class="display-4 text-muted "><font color="#6D3E6C">Secret Diary</font></h1>
<br>
<h5 class="text-muted "><font color="#DFD2CA">Sign up today, for free!</font></h5>
<br>
<form method="post" name="signup">
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" name="email" aria-describedby="emailHelp" placeholder="Enter email">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" name="password" placeholder="Password">
</div>
<div class="form-group form-check ">s
<input type="checkbox" class="form-check-input" value="checked "name="LoginRemember">
<label class="form-check-label" for="LoginRemember">Keep me signed in</label>
</div>
<input class="btn btn-primary" type="submit" value="Sign up" name="submit">
</form>
<div class="btn btn-secondary switchBtt">Switch to login panel ↹ </div>
</center>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
</body>
<script>
$("#containerLogin").hide();
$(".switchBtt").click (function () {
$("#containerLogin").toggle();
$("#containerSignup").toggle();
});
</script>
</html>
diary.php
session_start();
if (array_key_exists("id",$_SESSION)) {
echo "<p>Logged In! <a href='signup.php?logout=1'>Logout</a></p>";
echo "<br>";
echo $_SESSION["id"]."<br>";
} else {
header("Location: signup.php");
}
?>
You generally shouldn't be using GET query strings to change state in your application for pretty much this exact reason.
GET requests are not supposed to have any side effects and browsers will try to take advantage of this to speed up page loads by either pre-requesting pages before a user clicks on them or by caching a page and not actually requesting it from the server. Either of these cases will result in unexpected behavior. Also, if someone bookmarks the page with ?logout=1 on it they'll (probably accidentally) log themselves out any time they return to the page.
It'd be better to use the POST verb for this. You can easily do with with an HTML <form> tag and a submit button:
<form action="signup.php" method="POST" id="logout_form">
<input type="hidden" name="logout" value="1" />
<input type="submit" value="Logout" />
</form>
In your PHP you can detect if someone has hit the button by doing the following:
if(isset($_POST['logout'])) {
//log user out
}
Michael's answer is a good one (and accepted!), but at the moment where I work is going through an accessibility audit, so I have that on my mind. Screen readers, people who use high contrast custom style sheets, etc. can't deal with a form button as easily as plain text.
Also I've had issues in (old) PHP clearing sessions with session_destroy, so I loop through the session variables and unset them.
Log out
And then logout.php:
<?php
session_start();
foreach($_SESSION as $sk=>$sv){
unset($_SESSION[$sk]);
}
header("location: /");
?>

PHP Header Exceptions

I have a seperate navigator.php included on top of every page that I have for public.And it has a login form.If users have an account,they can login and be sent to the current page that they are at.
I pass the current URL adress to a hidden input as it's value.And post it to giris.php(login).Then redirecting the user with Header.
But when it comes to register.php(when no sessions were set);Im trying to login there and it still sends me back to the register.php.But SESSION is being set.Thats where I need an exception and want to send user to the index.php through register.php.
navigator.php
<div id="top">
<ul class="topnav" id="myTopnav">
<li>Anasayfa</li>
<li>İletişim</li>
<li>Hakkımızda</li>
<?php
if (isset($_SESSION["giris"]))
{
echo '<li>Panel</li>
<li>Çıkış Yap</li>';
}
else
{
$url= $_SERVER["REQUEST_URI"];
echo '<li>Kayıt Ol</li>
<li id="log">
<form method="post" action="giris.php"><div id="login">
<input type="hidden" name="location" value="'.$url.'">
<input type="text" name="username" placeholder="Kullanıcı Adı" class="loginField" required>
<input type="password" name="password" placeholder="Şifre" class="loginField" required>
<input type="submit" name="login" value="Giriş" id="logBut">
</form>
</li>';
}
?>
<li class="icon">
☰</li>
</ul>
</div>
<div id="banner">
<div id="title">
<h1>Topluluk Bloğu</h1>
<br/>
<h5>Community Blog</h5>
<br/>
<?php if(isset($_SESSION["giris"])){echo '<p id="username">Hoşgeldin '.$_SESSION["kullanici"].'</p>'; }?>
</div>
</div>
giris.php
<?php
session_start();
ob_start();
include 'func/constr.php';
if(isset($_POST["login"]))
{
$kullanici = $_POST['username'];
$password = $_POST['password'];
$URL = $_POST["location"];
$query = mysqli_query($connect,"SELECT * FROM kullanicilar where kullanici_adi='$kullanici' and sifre='$password'");
$count = mysqli_num_rows($query);
if ($count == 1)
{
$_SESSION["giris"] = true;
$_SESSION["kullanici"] = $kullanici;
$_SESSION["sifre"] = $password;
header("Location:$URL");
}
else
{
$invalid = "Kullanıcı adı ya da şifre yanlış";
$_SESSION["invalid"] = $invalid;
header("Location:index.php");
}
}
ob_end_flush();
?>
try this but not tested, if your other code is ok and redirect problem then
header("Location:$URL");
to
header('Location: ' . $URL);

php - how to have a remember me on login [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Hi guys im having a big problem on my project i wan to have a remember me on my log in but when i try it using this code below its not working there are no error messages came out. please help me badly needed thanks in advance. here is my html code for login.
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
mysql_connect("localhost", "root", "");
mysql_select_db("vrooms");
$result = mysql_query("SELECT * FROM registration where username = '$username' and password = '$password'")
or die("Failed to query database" .mysql_error());
$row = mysql_fetch_array($result);
if($username != $username){
header("location: home/homepage.php");
echo'<script>
alert("Not Allowed to Login With a Different Account!");
</script>';
$username = $_POST['username'];
}
if($row['username'] == 'admin_jake' && $row['password'] == $_POST['password']){
$_SESSION['type'] = 'admin';
}
if($row['username'] == $_POST['username'] && $row['password'] == $_POST['password'] && $_SESSION['type'] != 'admin'){
$_SESSION['type'] = 'user';
$_SESSION['username'] = $username;
header("location: home/homepage.php");
}
else if($row['username'] != $_POST['username'] && $row['password'] != $_POST['password']){
$_SESSION['message'] = "Incorrect Username or Password";
header("location: loginpage.php");
}
else if($_SESSION['type'] == 'admin' && $_SESSION['type'] != 'user'){
$_SESSION['admin'] = $username;
header("location: admin/adminpage.php");
}
if(isset($_REQUEST['remember']))
$escapedRemember = myqli_real_escape_string($conn, $_REQUEST['remember']);
$cookie_time = 60 * 60 * 24 * 30;
$cookie_time_Onset = $cookie_time + time();
if(isset($escapedRemember)){
setcookie("username", $username, $cookie_time_Onset);
setcookie("escapedPW", $password, $cookie_time_Onset);
}
else{
$cookie_time_fromOffset = time() - $cookie_time;
setcookie("username", '', $cookie_time_fromOffset);
setcookie("password", '', $cookie_time_fromOffset);
}
?>
<?php
session_start();
include_once("CORE/dbconfig.php");
if(isset($_SESSION['type'])){
if ($_SESSION['type'] == 'user') {
header("location: home/homepage.php");
}
else if ($_SESSION['type'] == 'admin') {
header("location: admin/adminpage.php");
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Car Hub - Don't dream, ride it!</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="CSS FILES/login_chstyle.css">
</head>
<body>
<br>
<?php
if(isset($_SESSION['message'])){
echo '<div class = "msg">';
echo '<p>' .$_SESSION['message']. '</p>';
unset($_SESSION['message']);
echo '</div>';
}
?>
<div class="header">
<img src="images/CarHubLogos.png" style="margin-top: 10px; height: 50px">
<!-- ___________________________________________________________________________For Log In Syntax_______________________________________________________________ -->
<div id="buttonsize"><button onclick="document.getElementById('id01').style.display='block'" style="width:auto;">Sign In</button></div>
<div id="id01" class="modal">
<span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal" style="margin-top: 50px">×</span>
<form class="modal-content animate" action="login.php" method="POST">
<div class="container">
<label><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="username" id="username" value="<?php if(isset($_COOKIE['username'])) echo $_COOKIE['username']; ?>" required>
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="password" id="password" value="<?php if(isset($_COOKIE['password'])) echo $_COOKIE['password']; ?>" required>
<input type ="checkbox" id="remember" name="remember" <?php if(isset($_COOKIE['username'])){ echo"checked = 'checked'";}?> value="1">
<label>Remember Me</label>
<button class="colorgr" name="login" type="submit">Login</button>
<button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelbtn">Cancel</button>
</div>
</form>
</div>
<!-- ___________________________________________________________________________For Log In Syntax_______________________________________________________________ -->
<!--____________________________________________________________________________SCRIPT START ___________________________________________________________________ -->
<script>
// Get the modal for Log In
var modal = document.getElementById('id01');
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
// Get the modal for sign up
var modal = document.getElementById('id02');
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
<!--____________________________________________________________________________SCRIPT END ____________________________________________________________________ -->
<!--____________________________________________________________________________Sign Up ____________________________________________________________________ -->
<div id="buttonResize">
<button onclick="document.getElementById('id02').style.display='block'" style="width:auto;">Sign Up</button>
</div>
<div id="id02" class="modal">
<span onclick="document.getElementById('id02').style.display='none'" class="close" title="Close Modal" style="margin-top: 50px">×</span>
<form name="myForm" class="modal-content animate" action="signup.php" method="post">
<div class="container">
<label><b>Last Name</b></label><br>
<input type="text" placeholder="Enter Last Name" id="customer_lname" name="customer_lname" pattern="[a-zA-Z ]+" title="Must not contain a special character and numbers. e.g. !##$%^&*0-9" required>
<br>
<label><b>First Name</b></label><br>
<input type="text" placeholder="Enter First Name" id="customer_fname" name="customer_fname" pattern="[a-zA-Z ]+" title="Must not contain a special character and numbers. e.g. !##$%^&*0-9" required>
<br>
<label><b>Contact Number </b></label><br>
<input type="tel" placeholder="Enter Contact Number" id="contact_number" name="contact_number" pattern="^\d{4}-\d{3}-\d{4}$" title="XXXX-XXX-XXXX" style = "width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
box-sizing: border-box;" required>
<br>
<label><b>Email</b></label><br>
<input type="email" placeholder="Enter Email" id="email_address" name="email_address" style = "width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
box-sizing: border-box;" required>
<br>
<label><b>Username</b></label><br>
<input type="text" placeholder="Enter Username" id="username" name="username" pattern="^[a-z0-9_-]{4,16}$"
title="Must contain at least 4-16 characters and must not have some special character. e.g !##$%^&*" required >
<br>
<label><b>Password</b></label><br>
<input type="password" placeholder="Enter Password" id="password" name="password" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" title="Must contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters" onchange="form.c_password.pattern = this.value;" required >
<br>
<label><b>Repeat Password</b></label><br>
<input type="password" placeholder="Repeat Password" id="c_password" name="c_password" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" title="Password Must Match!" required>
<p>By creating an account you agree to our Terms & Privacy.</p>
<div class="clearfix">
<button type="button" onclick="document.getElementById('id02').style.display='none'" class="cancelbtn">Cancel</button>
<button class="colorgr" type="submit" name="submit_cus" class="signupbtn">Sign Up</button>
</div>
</div>
</form>
</div>
<!--____________________________________________________________________________Sign Up ____________________________________________________________________ -->
</div>
<br>
<hr>
<br>
<ul>
<li>Home</li>
<li>Vehicles</li>
<li>About</li>
<li>FAQ</li>
</ul>
<div id="bodywall">
<br>
<h1 class="gety">Ride a<br>car today</h1>
<p class="stylo1">Sign up for free</p>
<br><br><br><br><br><br><br><br><br><br>
</div>
<div class="footer"><img src="images/CarHubLogos.png" style="height: 100%"></div>
</body>
</html>
<script>
window.onload = function () {
if (typeof history.pushState === "function") {
history.pushState("jibberish", null, null);
window.onpopstate = function () {
history.pushState('newjibberish', null, null);
};
} else {
var ignoreHashChange = true;
window.onhashchange = function () {
if (!ignoreHashChange) {
ignoreHashChange = true;
window.location.hash = Math.random();
} else {
ignoreHashChange = false;
}
};
}
}
</script>
First of all, you will need to keep a cookie on the client-side called hash (a randomized string), whenever a user logs in.
Along with this cookie, you must create a row in a table (sessions) within your database with the value of the hash, and the corresponding logged in user id.
For example: If user 4 logs in; it will generate a hash with the value 1234, this value will then be stored within the database table along with that users id (4).
Whenever a user visits the website, you need to check if the cookie value has been set, and if it has, check if the value matches any within the database. Assuming it finds one, grab the user id that matches with the corresponding value, and log that specific user in.
Make sure, once you've logged them in, you generate a new hash and delete the old hash from your sessions table.
Same thing goes for when the user logs out; delete the hash from the client-side and the database table, every time (for security purposes).
Hopefully, this gives you an idea of what you need to do to achieve this.
If you want a more in depth explanation on how to do this, I highly suggest reading these:
The definitive guide to form-based website authentication
What is the best way to implement “remember me” for a website?
SIDENOTE: I've noticed you're still using the deprecated mysql_* extension. Please discontinue the use of mysql_*, it is no longer secure or safe to use, and there are much better alternatives. I would suggest mysqli_* or PDO.
you have to use session_start() at the top of all your html sites, otherwise you loose reference to the session and to all its stored variables.

Registration Form that Submits to Database and Sends a Confirmation Email to the User with Their Info - 2 Actions, 1 Button

I thought the solution would be easy to find, but I cannot find it. I want my registration form to submit to the database and send the form data to the user's email, as a confirmation email, at the same time and using the same submit button. It seems logical that the form would have two actions, but I'm finding no example of such a thing. Perhaps some PHP code on the registration page that will recognize the successful submission and send the data to a php file that will process an email at the same time the data is being inserted into the database table??
register.php, the PHP above the HTML
<?php
session_start();
if (!isset($_SESSION['usr_id']) && empty($_SESSION['usr_id']) ) {
} else {
header('Location: mustlogout.php'); #redirect URL
}
?>
<?php
include_once 'db.php';
//set validation error flag as false
$error = false;
//check if form is submitted
if (isset($_POST['signup'])) {
$name = mysqli_real_escape_string($con, $_POST['name']);
$user_name = mysqli_real_escape_string($con, $_POST['user_name']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$password = mysqli_real_escape_string($con, $_POST['password']);
$cpassword = mysqli_real_escape_string($con, $_POST['cpassword']);
$name = stripslashes($name);
$user_name = stripslashes($user_name);
$email = stripslashes($email);
$password = stripslashes($password);
$cpassword = stripslashes($cpassword);
if (!preg_match("/^[a-zA-Z ]+$/",$name)) { /* name can contain only alpha characters and space */
$error = true;
$name_error = "Name must contain only letters";
}
if (!preg_match("/^[a-zA-Z-0-9 ]+$/",$user_name)) { /* letters and numbers */
$error = true;
$user_name_error = "User name can contain only letters and numbers";
}
if(!filter_var($email,FILTER_VALIDATE_EMAIL)) { /* will accept only email addresses */
$error = true;
$email_error = "Please Enter Valid Email ID";
}
if(strlen($password) <6 ) { /* must be 6 or more characters */
$error = true;
$password_error = "Password must be minimum of 6 characters";
}
if($password != $cpassword) { /* must match the first password entry */
$error = true;
$cpassword_error = "Password and Confirm Password doesn't match";
}
if (!$error) {
if(mysqli_query($con, "INSERT INTO forumusers(name,user_name,email,password) VALUES('" . $name . "', '" . $user_name . "', '" . $email . "', '" . md5($password) . "')")) {
$successmsg = "Successfully Registered! <a href='login.php'>Click here to Login</a>"; /* if register is successful */
} else {
$errormsg = "Error in registering...Please try again later!"; /* if register is not successful */
}
}
}
?>
<!doctype html>
<html><!-- InstanceBegin template="/Templates/index.dwt" codeOutsideHTMLIsLocked="false" -->
<head>
register.php, the form in the HTML
<!-- InstanceBeginEditable name="EditRegion3" -->
<div class="title-bar"><n6>Forum Registration</n6></div>
<div class="main-content">
<div class="form-reg" style="margin-bottom: 4em;"><!-- Begin div to contain form -->
<table width="50%" style="padding-left: 20px;">
<form role="form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="signupform">
<fieldset>
<tr>
<td>
<div style="margin-top: 0px; margin-bottom: 5px;">
<label for="name" class="formfield-names">Name</label>
<input type="text" name="name" placeholder="Enter Your Full Name" required value="<?php if($error) echo $name; ?>" class="form-control" />
<span class="text-danger"><?php if (isset($name_error)) echo $name_error; ?></span>
</div>
</td>
</tr>
<tr>
<td>
<div style="margin-top: 0px; margin-bottom: 5px;">
<label for="name" class="formfield-names">User Name</label>
<input type="text" name="user_name" minlength="5" maxlength="15" placeholder="5 to 15 Letters/Numbers" required value="<?php if($error) echo $user_name; ?>" class="form-control" />
<span class="text-danger"><?php if (isset($user_name_error)) echo $user_name_error; ?></span>
</div>
</td>
</tr>
<tr>
<td>
<div style="margin-top: 10px; margin-bottom: 5px;">
<label for="name" class="formfield-names">Email</label>
<input type="text" name="email" placeholder="Enter a Valid Email" required value="<?php if($error) echo $email; ?>" class="form-control" />
<span class="text-danger"><?php if (isset($email_error)) echo $email_error; ?></span>
</div>
</td>
</tr>
<tr>
<td>
<div style="margin-top: 10px; margin-bottom: 5px;">
<label for="name" class="formfield-names">Password</label>
<input type="password" name="password" minlength="6" maxlength="16" placeholder="6 to 16 Chracters" required class="form-control" />
<span class="text-danger"><?php if (isset($password_error)) echo $password_error; ?></span>
</div>
</td>
</tr>
<tr>
<td>
<div style="margin-top: 10px; margin-bottom: 5px;">
<label for="name" class="formfield-names">Confirm Password</label>
<input type="password" name="cpassword" placeholder="Confirm Password" required class="form-control" />
<span class="text-danger"><?php if (isset($cpassword_error)) echo $cpassword_error; ?></span>
</div>
</td>
</tr>
<tr>
<td>
<div style="margin-top: 10px; margin-bottom: 5px;">
<input type="submit" name="signup" value="Register" class="button" />
</div>
</fieldset>
</form>
</td>
</tr>
<tr><td><div style="margin-top: 10px; margin-bottom: 5px;" class="formfield-names">Already Registered? Login Here</div></td></tr>
</table>
<span class="formfield-names"><?php if (isset($successmsg)) { echo $successmsg; } ?></span>
<span class="formfield-names"><?php if (isset($errormsg)) { echo $errormsg; } ?></span>
</div><!-- End div to contain form -->
</div>
<!-- InstanceEndEditable -->
I found alot of "form with two buttons" and various "how to submit a form to a database" and "how to send email with a form" and displaying various confirmation messages and the one I found with the 2 actions appears to be incomplete. Help would be greatly appreciated.
It is quite a simple question, you should try thinking out the process before coding it.
some code ....
if(mysqli_query($con, "INSERT INTO forumusers(name,user_name,email,password) VALUES('" . $name . "', '" . $user_name . "', '" . $email . "', '" . md5($password) . "')")) {
$successmsg = "Successfully Registered! <a href='login.php'>Click here to Login</a>"; /* if register is successful */
// add email here.
}
some code ....
It seems logical that the form would have two actions
No. The action attribute determines the URL to which the data will be sent. HTML is not designed to send data to multiple places (because it is geared up to display one page at a time).
If you want to do more than one thing with the data, you just need to make the program at that URL do more than one thing.
Your existing PHP already does two things:
Inserts data into a database
Outputs an HTML page back to the browser
You just need to insert the code to send the email into the same program.
Perhaps some PHP code on the registration page that will recognize the successful submission and send the data to a php file that will process an email at the same time the data is being inserted into the database table
If you want to divide your code up into smaller, logically grouped, chunks: You can use includes, functions and classes.

Categories