From what I understood it may be,
session_start();
!isset($_SESSION['loggedin']))
and maybe few other lines
After the user registers successfully, I want him to be redirected to home.php
Could you please show me an exact snippet?
register.php
<?php
include 'main.php';
// Now we check if the data was submitted, isset() function will check if the data exists.
if (!isset($_POST['username'], $_POST['password'], $_POST['cpassword'], $_POST['email'])) {
// Could not get the data that should have been sent.
exit('<div >Please complete the registration form!</div>');
}
// Make sure the submitted registration values are not empty.
if (empty($_POST['username']) || empty($_POST['password']) || empty($_POST['email'])) {
// One or more values are empty.
exit('<div >Please complete the registration form!</div>');
}
// Check to see if the email is valid.
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
exit('<div >Email is not valid!</div>');
}
// Username must contain only characters and numbers.
if (!preg_match('/^[a-zA-Z0-9] $/', $_POST['username'])) {
exit('<div >Username is not valid!</div>');
}
// Password must be between 5 and 20 characters long.
if (strlen($_POST['password']) > 20 || strlen($_POST['password']) < 5) {
exit('<div >Password must be between 5 and 20 characters long!</div>');
}
// Check if both the password and confirm password fields match
if ($_POST['cpassword'] != $_POST['password']) {
exit('<div >Passwords do not match!</div>');
}
// Check if the account with that username already exists
$stmt = $pdo->prepare('SELECT id, password FROM accounts WHERE username = ? OR email = ?');
$stmt->execute([ $_POST['username'], $_POST['email'] ]);
$account = $stmt->fetch(PDO::FETCH_ASSOC);
// Store the result so we can check if the account exists in the database.
if ($account) {
// Username already exists
echo '<div >Username and/or email exists!</div>';
} else {
// Username doesn't exist, insert new account
$stmt = $pdo->prepare('INSERT INTO accounts (username, password, email, activation_code) VALUES (?, ?, ?, ?)');
// We do not want to expose passwords in our database, so hash the password and use password_verify when a user logs in.
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$uniqid = account_activation ? uniqid() : 'activated';
$stmt->execute([ $_POST['username'], $password, $_POST['email'], $uniqid ]);
if (account_activation) {
// Account activation required, send the user the activation email with the "send_activation_email" function from the "main.php" file
send_activation_email($_POST['email'], $uniqid);
echo 'Please check your email to activate your account!';
} else {
echo '<div >You have successfully registered, you can now login!</div>';
}
}
?>
main.php
<?php
// The main file contains the database connection, session initializing, and functions, other PHP files will depend on this file.
// Include thee configuration file
include_once 'config.php';
// We need to use sessions, so you should always start sessions using the below code.
session_start();
// No need to edit below
try {
$pdo = new PDO('mysql:host=' . db_host . ';dbname=' . db_name . ';charset=' . db_charset, db_user, db_pass);
} catch (PDOException $exception) {
// If there is an error with the connection, stop the script and display the error.
exit('Failed to connect to database!');
}
// The below function will check if the user is logged-in and also check the remember me cookie
function check_loggedin($pdo, $redirect_file = 'index.php') {
// Check for remember me cookie variable and loggedin session variable
if (isset($_COOKIE['rememberme']) && !empty($_COOKIE['rememberme']) && !isset($_SESSION['loggedin'])) {
// If the remember me cookie matches one in the database then we can update the session variables.
$stmt = $pdo->prepare('SELECT * FROM accounts WHERE rememberme = ?');
$stmt->execute([ $_COOKIE['rememberme'] ]);
$account = $stmt->fetch(PDO::FETCH_ASSOC);
if ($account) {
// Found a match, update the session variables and keep the user logged-in
session_regenerate_id();
$_SESSION['loggedin'] = TRUE;
$_SESSION['name'] = $account['username'];
$_SESSION['id'] = $account['id'];
$_SESSION['role'] = $account['role'];
} else {
// If the user is not remembered redirect to the login page.
header('Location: ' . $redirect_file);
exit;
}
} else if (!isset($_SESSION['loggedin'])) {
// If the user is not logged in redirect to the login page.
header('Location: ' . $redirect_file);
exit;
}
}
// Send activation email function
function send_activation_email($email, $code) {
$subject = 'Account Activation Required';
$headers = 'From: ' . mail_from . "\r\n" . 'Reply-To: ' . mail_from . "\r\n" . 'Return-Path: ' . mail_from . "\r\n" . 'X-Mailer: PHP/' . phpversion() . "\r\n" . 'MIME-Version: 1.0' . "\r\n" . 'Content-Type: text/html; charset=UTF-8' . "\r\n";
$activate_link = activation_link . '?email=' . $email . '&code=' . $code;
$email_template = str_replace('%link%', $activate_link, file_get_contents('activation-email-template.html'));
mail($email, $subject, $email_template, $headers);
}
?>
CodePudding user response:
To perform auto login after registration you need to follow these steps:
- Make sure you start the session. As I can see, you are already starting the session in main.php which is then included in register.php
- After successful registration you need to populate the session variables in exactly the same way as you would do after successful login. You can receive the auto-generated ID by calling
lastInsertId()
method. The username comes from the form. The role is the default one, so you can hardcode it or read from database.// Username doesn't exist, insert new account $stmt = $pdo->prepare('INSERT INTO accounts (username, password, email, activation_code) VALUES (?, ?, ?, ?)'); // We do not want to expose passwords in our database, so hash the password and use password_verify when a user logs in. $password = password_hash($_POST['password'], PASSWORD_DEFAULT); $uniqid = account_activation ? uniqid() : 'activated'; $stmt->execute([ $_POST['username'], $password, $_POST['email'], $uniqid ]); // Login in the user session_regenerate_id(); $_SESSION['loggedin'] = TRUE; $_SESSION['name'] = $_POST['username']; $_SESSION['id'] = $pdo->->lastInsertId(); $_SESSION['role'] = 'the default role'; if (account_activation) { // Account activation required, send the user the activation email with the "send_activation_email" function from the "main.php" file send_activation_email($_POST['email'], $uniqid); echo 'Please check your email to activate your account!'; } else { header('Location: home.php'); exit; }
- In the above example, I added
header('Location: home.php');
after successful registration. Adjust it according to your needs. Once the session variables are populated, you can redirect the user to the home page where the check forisset($_SESSION['id'])
should take place. This will tell you whether the user is logged in or not.
I am not sure what is the purpose of $_SESSION['loggedin']
as it seems to be true in all cases. Maybe you can remove it from your code.