I have a user login/registration system on my simple site everything works great but I would like to have a function that sends a generic email to the user when the logout button is clicked. probably saying something like please send us an email regarding your findings on our site.
the site is an entertainment agency that books out Carnival equipment, registration and login is purely for users to view prices should they be interested in the actual product.
i have no idea where or how to implement anything like this.
my understanding is i must create a query to the databases requesting email from email column and if user email address exist proceed with the email sending (if they are at the point of logout then that means email address is available in database) then once it is sent log user out and redirect to a page. i just dont know how to do the query exactly.
any advice would be much appreciated
ps, I don't know what documentation you would need to see in order to see what i have done?
this is my logout page:
<?php
require_once 'db.php';
session_start();
if (isset($_SESSION['username']) && !empty($_SESSION['username'])):
if (isset($_GET['action']) && !empty($_GET['action'])) {
$action = $_GET['action'];
if ($action == "logout") {
$stmt = $pdo->prepare("SELECT email FROM users WHERE email = ? ");
$stmt->execute([$_SESSION['username']]);
$email = $stmt->fetchColumn();
$message = "Hellow you just used our website....";
if (mail($email, "Feedback", $message)) {
// the email is sent now log the user out.
session_destroy();
header("location:login_page.php");
exit();
}
}
}
endif;
?>
You can follow the following steps to accomplish that
Step 1:
When the user logs in, save his Email ID in the session. I.e When the login ios successful you must be sending some "Success" response and redirecting to the user page.So, before doing that, if the login is successful create a session and store the Email Id in it.
login.php
<?php
session_start();
//Some database actions...
if($login == "success"){ // Just an example
$_SESSION["email"] = $EMAIL // This is the user Email Address.
}
?>
Step 2:
When the user logs out, he must be redirected to the logout page where you destroy all the sessions.You'll have to call the trigger mail function in that function.
In logout.php
<?php
session_start();
$EMAIL = $_SESSION["email"] // Get the previously saved email in login process.
triggerMail($EMAIL);
session_unset();
session_destroy();
header("location:home.php");
exit();
function triggerMail($email){
//Your email logic.. return either true or false.
}
?>
When the user successful log's in if they are using their email address to login then store that email address on a session. Then on logout before destroying the session send the email to the email stored in the session.
Then have a logout link like this :
Logout
then you can verify the action on that logoutpage if user wanna logout.
<?php
session_start();
if (isset($_SESSION['currentUser']) && !empty($_SESSION['currentUser'])):
if (isset($_GET['action']) && !empty($_GET['action'])) {
$action = $_GET['action'];
if ($action == "logout") {
$message = "Hellow you just used our website.... what ever you want to write";
if (mail($_SESSION['currentUser'], "Feedback", $message)) {
// the email is sent now log the user out.
session_destroy();
header("location:loginPage.php");
exit();
}
}
}
endif;
?>
NB : $_SESSION['currentUser'] is the session you created when the
user was logging and stored their email.
Well if you not using email address as username for login then then you can query the email address before user log's out. then send email then logout.
<?php
session_start();
if (isset($_SESSION['currentUser']) && !empty($_SESSION['currentUser'])):
if (isset($_GET['action']) && !empty($_GET['action'])) {
$action = $_GET['action'];
if ($action == "logout") {
$stmt = $dbh->prepare("SELECT email FROM users WHERE userID = ? ");
$stmt->execute([$_SESSION['currentUser']]);
$email = $stmt->fetchColumn();
$message = "Hellow you just used our website....";
if (mail($email, "Feedback", $message)) {
// the email is sent now log the user out.
session_destroy();
header("location:loginPage.php");
exit();
}
}
}
endif;
?>
I' m not quit sure which API you are using MYSQLI or PDO as you did not specify much on your question, the above uses PDO.
Related
I tried implementing a system wherein the user enters his username and phone number, when the form is submitted, it checks the database to verify the number and username based on it's existence. An SMS is sent to that number. He gets a popup to enter the OTP code.
However on entering the OTP code I get an error of redirecting loops. I'll just explain the flow of the files below:
INDEX.PHP -> LOGIN.PHP -> OTP.PHP -> CHECK_OTP.PHP -> HOME.PHP
Those are the files being used. It reaches the otp page and when you enter, it does authenticate successfully but it goes into a loop. I will post the code to see what is wrong with the OTP authentication code.
session_start(); // Starting Session
$error=''; // Variable To Store Error Message
if (isset($_POST['verify'])) {
if (empty($_POST['otp'])) {
$error = "OTP is invalid";
}
else
{
// Post OTP
$otp=$_POST['otp'];
}
$otp = stripslashes($otp);
$otp = pg_escape_string($otp);
$check = "select * from otp where otp = '$otp'";
$ret_check = $dbConnection->executeQuery($check);
$ret_num = $dbConnection->numRows($ret_check);
$cust_code = '';
while($row = $dbConnection->fetchRow($ret_check)){
$cust_code = $row[0];
}
$cust_code;
if($ret_num != 1){
$error = "Wrong OTP entered";
header("Location: otp-home.php");
}
else {
echo $_SESSION['login_user'] = $cust_code;
header("Location: home.php");
}
I hope this is enough. If anything else is required. Please let me know. Any help will be greatly appreciated. Thank you
I am trying to display the error at the end if the use doesn't enter the correct combination of their log in. However, the error message is not showing when I enter the wrong password or email. Any suggestions
<?php
include ("connect.php");
if (isset($_POST["user_login"]) && (isset($_POST["user_pass"]))){
// formatting field via reg replace to ensure email and password only conisists of letters and numbers preg_replace('#[^A-Za-z0-9]#i','',
$login_user = $_POST["user_login"];
$login_password = $_POST["user_pass"];
// password is encryted in DB (MD5) therefore user inputted password will not match encryted password in DB - we have to assign new var
$decrypted_password = md5($login_password);
// Query which finds user (if valid) from DB - Achieving authentication via username and password
$user_query = mysqli_query($connect, "SELECT * FROM users WHERE email = '$login_user' AND password = '$decrypted_password' AND closed = 'no' LIMIT 1");
$check_user = mysqli_num_rows($user_query); // checking to see if there is infact a user which those credentials in the DB
if ($check_user==1){
while ($row = mysqli_fetch_array($user_query)){
$id = $row['user_id'];
$user_type = $row['account'];
}
$_SESSION["user_login"] = $login_user;
// check the user type and redirect according to it
if($user_type == "Student"){
$student_page = "profile_student.php";
header( "Location:{$student_page}" );
} elseif ($user_type == "Landlord"){
$landlord_page = "landlord_profile.php";
header( "Location:{$landlord_page}" );
} elseif ($user_type == "Administrator"){
$admin_page = "admin_profile.php";
header( "Location:{$admin_page}" );
}else {
$refresh_page = "sign_up.php";
header( "Location:{$refresh_page}" ); // refresh page
echo "You have entered an incorrect email or password. Please try again.";
}
}
}
?>
you redirect user if input data is wrong and only after that you try to echo message, thats not how that works. read about headers in php_manual. probably the best way here, is to store error message in session and after redirect check if session error message exists
else {
$refresh_page = "sign_up.php";
$_SESSION['error'] = "your error message"
header( "Location:{$refresh_page}" ); // refresh page
}
in sign_up.php file check if error message exists in session
if(isset($_SESSION["error"])){
echo $_SESSION["error"];
unset($_SESSION["error"]);
}
maybe you should correct this code a little bit))
use unset cause' after you show the message it should be removed from session, in other case if you fail for example 5 times, it will show 5 messages)) also make sure that session is started session_start() hope it helps:)
You only display the error when $user_type doesn't match any of your expected types.
You need a second else after your if ($check_user==1){ block to handle the case where a user with that email or password doesn't exist.
What I've attempted to do is make it so that when you log in to the website it will reference the type of account that is in the database and depending on the type it will set the session variable then it will link you to the appropriate page which will work with that session login. The issue I'm having is that no matter what it just sends me to back to the login page which should only occur for the else condition which is for when a user type is not detected. I'm using Oracle APEX database and I'm not sure why this is happening so any help at all would be greatly appreciated.
<?php
//include connection to titan
include 'oci_connect.php';
session_start();
$query_str = "SELECT type_of_Account FROM User_Account WHERE user_name = '".$_POST["Username"]."' AND PASSWORD = ('".$_POST["Password"]."')";
$stid =oci_parse($connection, $query_str);
oci_execute($stid);
$type =$info['type_of_Account'];
if($type == "Customer")
{
$_SESSION['type']=1;
//redirect to user page where it will be found through matching the user id and only display their details, can only be accessed if logged in
echo '<script>window.location="user.php"</script>';
}
elseif($type == "Trader")
{
$_SESSION['type']=2;
//redirect to traders page where it will display the traders details and only theirs, only accessed if logged in with specific account type
echo '<script>window.location="trader.php"</script>';
}
elseif($type == "Admin")
{
$_SESSION['type']=3;
//redirect to admin page where they can view and edit all details, only one account type acceptable
echo '<script>window.location="admin.php"</script>';
}
else {
//Return to login page as login details are invalid
echo '<script>window.location="login.html"</script>';
}
?>
This is my user page which is meant to be session 1:
<?php
session_start();
if($_SESSION['type']!=1){
echo '<script>window.location="login.html"</script>';
}
?>
This is my traders page which is meant to be session 2:
<?php
session_start();
if($_SESSION['type']!=2){
echo '<script>window.location="login.html"</script>';
}
?>
This is my admin page which is meant to be session 3:
<?php
session_start();
if($_SESSION['type']!=3){
echo '<script>window.location="login.html"</script>';
}
?>
I have tried a session.php script which runs at the head of each page in my website to verify that the user has logged in before they can browse the site. However, now the process_login script won't load the secure landing page and it just reloads to the login page. I believe that my secure session is not being set correctly. Can someone further explain how this works to me?
This is the script, process_login, which executed when a user clicks login:
<?php
// Initialize session
session_start();
// Require database connection settings
require('config.inc');
// Retrieve email and password from database
$email = mysql_real_escape_string($_POST['email']);
$password = mysql_real_escape_string(md5($_POST['password']));
$query = "SELECT * FROM $table WHERE email='$email' AND password='$password' LIMIT 1";
$result = mysql_query($query);
// Check email and password match
if(mysql_num_rows($result)) {
// Set email session variable
$_SESSION['email'] = $_POST['email'];
// Jump to secured page
header('Location: home.php');
}
else {
// Jump to login page
header('Location: index.php');
}
?>
and this is the session.php script which is in the head of each page that requires a user to be logged in:
<?php
if (isset($_SESSION['email']) == 0) {
// Redirect to login page
header('Location: index.php');
}
?>
You need to include the code
session_start();
in the your file session.php to access your session variables
Or you should make sure that session auto start is enabled on your php configuration.
I already have an advanced user login/register system on my website (colemansystems.psm2.co.uk). However, I would like to have a email sent to new users for verification of their email address. If they have not clicked the link they will not be able to access their account. I am semi-experienced with PHP and MySQL, so please explain in depth.
The code I'm using for the verify.php file (the link the user click on with a GET (for example, verify.php?d=51773199320))
$secret = $_GET['d'];
$result = mysql_query("SELECT valid FROM users WHERE secret=$secret");
while ($row = mysql_fetch_array($result))
{
$valid = $row['valid'];
}
if ($valid == "") {
echo"There seems to be a problem with the verification code.<br><br><br><br><br>";
}
elseif ($valid == "1")
{
echo"Your account is already verified.<br><br><br><br><br>";
}
else
{
mysql_query("UPDATE users SET valid = '1' WHERE secret=$secret");
echo "Thank you, your account is now verified and you are free to use the exclusive features!<br><br><br><br><br><br>";
}
Is this secure?
The easiest way is not to register unverified users at all.
Ask them for an email address and send email with a link that contains this address sealed with a hash. Upon receiving this link you can start the registration process.
Something like this
$secret = "35onoi2=-7#%g03kl";
$email = urlencode($_POST['email']);
$hash = MD5($_POST['email'].$secret);
$link = "http://example.com/register.php?email=$email&hash=$hash";
And in your register.php add 2 hidden fields to the registration form - email and hash, storing their received values from GET.
Finally, process registration and check,
if (md5($_POST['email'].$secret) == $_POST['hash']) {
//Continue registration.
}
Easiest for whom - user, coder, computer?
What are you optimizing - the quantity of keypresses, the size of the code, the user experience?
The easiest to code is probably unsafe.
You should check the email address for correctness before sending a letter to it.
after registration create a hashed string and save it to the temporary user table send that hashed string to the user email address using this code
if(isset($_POST['register']))
{
$email_id=$_POST['email'];
$pass=$_POST['password'];
$code=substr(md5(mt_rand()),0,15);
mysql_connect('localhost','root','');
mysql_select_db('sample');
$insert=mysql_query("insert into verify values('','$email','$pass','$code')");
$db_id=mysql_insert_id();
$message = "Your Activation Code is ".$code."";
$to=$email;
$subject="Activation Code For Talkerscode.com";
$from = 'your email';
$body='Your Activation Code is '.$code.' Please Click On This link Verify.php?id='.$db_id.'&code='.$code.'to activate your account.';
$headers = "From:".$from;
mail($to,$subject,$body,$headers);
echo "An Activation Code Is Sent To You Check You Emails";
}
and after that create a verify page and then
if(isset($_GET['id']) && isset($_GET['code']))
{
$id=$_GET['id'];
$code=$_GET['id'];
mysql_connect('localhost','root','');
mysql_select_db('sample');
$select=mysql_query("select email,password from verify where id='$id' and code='$code'");
if(mysql_num_rows($select)==1)
{
while($row=mysql_fetch_array($select))
{
$email=$row['email'];
$password=$row['password'];
}
$insert_user=mysql_query("insert into verified_user values('','$email','$password')");
$delete=mysql_query("delete from verify where id='$id' and code='$code'");
}
}
if you have any problem here is a complete tutorial http://talkerscode.com/webtricks/account-verification-system-through-email-using-php.php