I am having trouble writing code how to log in user automatically after registration. I am using epoch and when user passes payment it redirects him to site but he is not logged in. I already did redirection with window.location = 'www.site.com/members/?username={$member.username}'; and it redirects me to that page with correct username in URL but the user is not logged in. I just need help on how to write logic that logs in user. Any help is appreciated. Here is my code.
header.php (Here is user redirected after successful registration and here I need to write login logic. Currently I am just being redirected to login page. In elseif it would go that logic.)
<?php
session_start();
if(!isset($_SESSION["loggedin"])) {
header("Location: www.site.com/tour/login.php");
} elseif(isset($_GET["username"])) {
login_function();
}
?>
custom_functions.php (Here is my login function that logs in user on site)
function login_function() {
session_start();
require 'connection.php';
$_SESSION["username_error"] = $username_error;
$_SESSION["password_error"] = $password_error;
$v_username = $_POST['username'];
$v_password = $_POST['password'];
$username = validation($v_username);
$password = validation($v_password);
$remember = isset($_POST['remember']);
if(empty($username))
{
$_SESSION["username_error"] = "<p>Please enter your username!</p>";
header("Location: login.php");
exit();
}
if(empty($password))
{
$_SESSION["password_error"] = "<p>Please enter your password!</p>";
header("Location: login.php");
exit();
}
if($username && $password) {
$sql = "SELECT * FROM member_auth WHERE username = :username";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':username', $username);
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_ASSOC);
$cryptpass = $user['cryptpass'];
if($user === false){
$_SESSION["username_error"] = "<p>User doesn't exist</p>";
header("Location: login.php");
exit();
} elseif($user) {
$newpass = crypt($password, $cryptpass);
if($cryptpass == $newpass) {
$_SESSION['loggedin'] = TRUE;
$_SESSION['username'] = $username;
if($remember == "on") {
setcookie("remember", $username, time()+3600);
}
header('Location: login_success.php');
exit();
} else {
$_SESSION["password_error"] = "<p>Password is not correct!</p>";
header("Location: login.php");
exit();
}
}
}
}
login.php
<?php
session_start();
?>
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/login_assets/css/style.css">
<link href="https://fonts.googleapis.com/css?family=Raleway:300,400,500&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Open+Sans:400,600&display=swap" rel="stylesheet">
<link rel="stylesheet" href="/login_assets/css/media.css">
<script src="/login_assets/js/jquery.min.js"></script>
<script src="/login_assets/js/modernizr.custom.js"></script>
<!-- <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> -->
</head>
<div id="login_body">
<header class="clear hBlack">
<div class="jLogo"><img src="/login_assets/images/logo.png" alt=""></div>
</header>
<div class="logArea clear">
<form action="custom_functions.php" method="post" enctype="application/x-www-form-urlencoded">
<div class="logbox">
<div class="box clear">
<h2>Members Area</h2>
<div class="logTypes">
<input type="text" name="username" class="logtextbox" placeholder="Username or email">
<span class="text-danger"><?php if(isset($_SESSION['username_error'])){ echo $_SESSION["username_error"]; unset($_SESSION["username_error"]); } ?></span>
<input type="password" name="password" class="logtextbox" placeholder="Password"><br>
<span class="text-danger"><?php if(isset($_SESSION['password_error'])){ echo $_SESSION["password_error"]; unset($_SESSION["password_error"]); } ?></span>
<!-- <input type="text" name="captcha" class="logtextbox" placeholder="Enter the code shown below"><br>
<img style="margin: 0 auto;" src="captcha.php">
<span class="text-danger"></span> -->
<div style="text-align: center">Remember my login: <input name="remember" type="checkbox"></div>
</div>
</div>
<input type="submit" value="submit" class="logBtn" name="submit">
</div>
</form>
<div class="logtext1">
</div>
<div class="logtext2">
</div>
</div>
</div>
<footer class="clear">
</footer>
</div>
</html>
Your registration logic looks fine for me. Your header checks whether the user has logged in before, which is stored in the session variable.
if(!isset($_SESSION["loggedin"])) {
header("Location: www.site.com/tour/login.php");
} elseif(isset($_GET["username"])) {
login_function();
}
I don't understand why you call login_function again. If the Session Variable "loggedIn" is true, the user has been logged in already. Why do you want to call login function again. If you need to fetch data for that user, you need to store the user id in a session variable and use that to make the request.
If you want to login automatically after you login register and login process should be like this,
when user registration done, set the $_SESSION["loggedin"].
the login page should check if $_SESSION["loggedin"] was setted, if setted head to login success page.
You can also head to login success page when registration done, without bypass the login page.
Related
This question already has answers here:
Accessing $_COOKIE immediately after setcookie()
(9 answers)
How to validate captcha properly?
Closed 3 years ago.
I have a login form in php and remember me checkbox. I want when user enters username and password and checks that remember me checkbox to automatically be logged in for as long as he doesn't click logout button. I am trying to achieve that using cookies and sessions, altough some say that it is not safe, I don't have other options like tokens and such because I don't have access to tables and to change them. Any help is appreciated. Here is my code.
login.php
<?php
session_start();
require 'connection.php';
$username_error = "";
$password_error = "";
$captcha_error = "";
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
if(isset($_POST['submit']))
{
$v_username = $_POST['username'];
$v_password = $_POST['password'];
$v_captcha = $_POST['captcha'];
$remember = $_POST['remember'];
function validation($form_data)
{
$form_data = trim(stripcslashes(htmlspecialchars($form_data)) );
return $form_data;
}
$username = validation($v_username);
$password = validation($v_password);
$captcha = validation($v_captcha);
if(empty($username))
{
$username_error = "<p>Please enter your username!</p>";
}
if(empty($password))
{
$password_error = "<p>Please enter your password!</p>";
}
if(isset($_POST['remember'])) {
setcookie('username', $username, time()+60*60*7);
setcookie('password', $password, time()+60*60*7);
}
if ($captcha == $_SESSION['cap_code'] && !empty($captcha)) {
if(!empty($username) && !empty($password)) {
$sql = "SELECT * FROM member_auth WHERE username = :username";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':username', $username);
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_ASSOC);
$cryptpass = $user['cryptpass'];
if($user === false){
$username_error = "<p>User doesn't exist</p>";
} elseif($user) {
$newPass = crypt($password, $cryptpass);
if($cryptpass == $newPass) {
$_SESSION['loggedin'] = TRUE;
$_SESSION['username'] = $user['username'];
header('Location: login_success.php');
}else {
$password_error = "<p>Password is not correct!</p>";
}
}
}
} else {
$captcha_error = "<p>Please enter correct captcha!</p>";
}
}
}
?>
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Welcome to Love Her Feet</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="/login_assets/css/style.css">
<link href="https://fonts.googleapis.com/css?family=Raleway:300,400,500&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Open+Sans:400,600&display=swap" rel="stylesheet">
<link rel="stylesheet" href="/login_assets/css/media.css">
<script src="/login_assets/js/jquery.min.js"></script>
<script src="/login_assets/js/modernizr.custom.js"></script>
</head>
<body>
<header class="clear hBlack">
<div class="jLogo"><img src="/login_assets/images/logo.png" alt=""></div>
</header>
<div class="logArea clear">
<form action="login.php" method="post">
<div class="logbox">
<div class="box clear">
<h2>Members Area</h2>
<div class="logTypes">
<input type=text name="username" class="logtextbox" placeholder="Username">
<span class="text-danger"><?php echo $username_error; ?></span>
<input type=password name="password" class="logtextbox" placeholder="Password"><br>
<span class="text-danger"><?php echo $password_error; ?></span>
<div style="width:100%; text-align:center">
<img src="captcha.php" style="width:150px; height:30px"/><p style="margin:4px 0px 0px 0px">Reload Image</p>
</div>
<div style="width:100%">
<label>Enter Captcha:</label>
<input type="text" name="captcha" id="captcha" maxlength="6" size="6"/>
</div>
<span class="text-danger"><?php echo $captcha_error; ?></span>
<div style="text-align: center">Remember my login: <input name="remember" type=checkbox value="y"></div>
</div>
</div>
<input type="submit" name="submit" value="submit" class="logBtn">
</div>
</form>
</div>
</div>
</body>
</html>
login_success.php
<?php
session_start();
if(isset($_SESSION["loggedin"])) {
echo "Welcome, {$_SESSION["username"]} <br>";
echo "<a href='logout.php'>Logout</a>";
} else {
header("Location: login.php");
}
logout.php
<?php
session_start();
session_destroy();
header("Location: login.php");
I have a login page that regardless of what the input is (correct login or not) the page just refreshes when hitting the "login" button. I've searched on stack overflow and nothing has solved my problem yet.
Login Page Session Code
<?php
session_start();
if(isset($_SESSION['login'])) {
header('LOCATION: test-page.php'); die();
}
echo isset($_SESSION['login']);
?>
Login Page Form
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>Login</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="form-container">
<div class="image"></div>
<div class="form">
<form>
<h1>Login</h1>
<ul>
<li>
<input class="input" type="text" id="username" autocomplete="off">
<label for="username">Username</label>
<span></span>
</li>
<li>
<input class="input" type="password" id="password" autocomplete="off">
<label for="password">Password</label>
<span></span>
</li>
</ul>
<footer>
<button type="submit" class="gradient">Login</button>
</footer>
</form>
Login Page Username and Password
<?php
if(isset($_POST['submit'])){
$username = $_POST['username']; $password = $_POST['password'];
if($username === 'admin' && $password === 'password'){
$_SESSION['login'] = true; header('LOCATION: test-page.php'); die();
} elseif ($username === 'billy' && $password === 'bob') {
$_SESSION['login'] = true; header('LOCATION: test-page.php'); die();
} else {
echo "<div class='alert alert-danger'>Username and Password do not match.</div>";
}
}
?>
</div>
</div>
<script src="login.js"></script>
</body>
</html>
Page After Login Success
<?php
session_start();
if(!isset($_SESSION['login'])) {
header('LOCATION: login.php'); die(); // mlac-resources-login.php
}
?>
The login page is split up for readability but it is all one continuous block of code. The
Redirects (or any kind of header for that matter) require NO OUTPUT SENT for it to work.
Outputs include:
Echo commands
<!DOCTYPE html>
Even any whitespace could break it! (New lines or spaces)
For example:
<?php
session_start();
echo isset($_SESSION['login']); //Output
if(isset($_SESSION['login'])) {
header('LOCATION: test-page.php'); die(); //Won't work since there's already output...
}
?>
Try changing your code to:
<?php
session_start();
if(isset($_SESSION['login'])) {
header('LOCATION: test-page.php'); die(); //This should work now!
}
echo isset($_SESSION['login']); //Output goes here!
?>
A form's default method is GET and you're processing POST. Either set the method to post, or use $_GET when processing the form.
<form method="post">
...
or
if (isset($_GET['submit'])){
...
I'm having an issue with my login.php page not logging in, I can't work out why it keeps refreshing the page whenever I attempt to login. I'm using my index.php to redirect straight to my login.php not sure if this is the issue as before I change this it was working. Any ideas?
Index.php
<?php
header("Location: Login.php");
?>
Login.php
<?php
ob_clean();session_start();
if (isset($_GET['logout'])){
session_destroy();
}
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true){
header("Location: index.php");
}
$Username = $_POST['username'];
$EnteredPassword = $_POST['password'];
if (isset($_POST['submit'])){
if (is_dir("USERS/".$Username) === true){
$myFile=fopen("USERS/".$Username."/Password.txt","r") or exit("Can't open file!");
$CorrectPassword = fgets($myFile);
fclose($myFile);
if ($CorrectPassword == $EnteredPassword){
$_SESSION['loggedin'] = true;
header("Location: Home.php");
}
else {
echo '<font color="#FF0000"><p align="center">Username or Password incorrect please try again</p></font>';
}
}
else {
echo '<font color="#FF0000"><p align="center">Username or Password incorrect please try again</p></font>';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Project Archive - Login</title>
<link href="CSS/boilerplate.css" rel="stylesheet" type="text/css">
<link href="CSS/master.css" rel="stylesheet" type="text/css">
<script src="JAVASCRIPT/respond.min.js"></script>
</head>
<body link="black">
<div class="gridContainer clearfix">
<div id="headerLoginDiv">
<div id="titleLoginDiv">
<p>Project Archive</p>
</div>
</div>
<h1 align="center">Login</h1>
<h3 align="center">Welcome. Please login to continune.</h3>
<form method="post" action="index.php">
<div id="userNameLoginDiv">
<p align="center">Username:</p>
<input type="text" name="username" size="12">
</div>
<div id="userPasswordLoginDiv">
<p align="center">Password:</p>
<input type="password" name="password" size="12">
</div>
<div id="loginBtnDiv">
<input id="button" name="submit" type="submit" value="Login">
</div>
</form>
</body>
</html>
Obviously, if you go to index.php, you are asking the browser to go to login, irrespective of whether the user is logged in or not:
<?php
header("Location: Login.php"); // This blindly redirects the user to the login page.
?>
Instead of the above code, check and send the user:
<?php
// Start the session.
session_start();
// Instead check if the user is logged in and then redirect.
if (!isset($_SESSION['loggedin']))
header("Location: Login.php");
?>
Also, don't forget to start your session with session_start() at the beginning.
I'm building a CMS for a website. The problem is that after the login a blank page appears and it stays until I hit refresh. Then it loads to the correct menu page and everything else is working correctly except this little detail. Any tips to solve this? Thanks, my code is below:
<?php
session_start();
include_once('../includes/connection.php');
if(isset($_SESSION['logged_in'])) {
//display index
?>
<html>
<head>
<meta charset="UTF-8">
<title>AdminENG</title>
<link rel ="stylesheet" href="../assets/style.css"/>
</head>
<body>
<div class="container">
CMS - ENG
<ol>
<li>Add Article</li>
<li>Delete Article</li>
<li>Logout</li>
</ol>
</div>
</body>
</html>
<?php
}
else {
//display login
if(isset($_POST['username'], $_POST['password'])) {
$username = $_POST['username'];
$password = md5($_POST['password']);
if (empty($username) || empty($password)) {
$error = "All fields are required!";
}
else {
$query = $pdo->prepare("SELECT * FROM users WHERE user_name = ? AND user_password = ?");
$query->bindValue(1, $username);
$query->bindValue(2, $password);
$query->execute();
$num = $query->rowCount();
if($num == 1) {
//user entered the correct details
$_SESSION['logged_in'] = true;
header('Location: index.php');
exit();
}
else {
//user entered false details
$error = "Incorrect details!";
}
}
}
?>
<html>
<head>
<title>AdminENG</title>
<meta charset="UTF-8">
<link rel ="stylesheet" href="../assets/style.css"/>
</head>
<body>
<div class="container">
CMS
<br><br>
<?php
if (isset($error)) { ?>
<small style="color:#aa0000"><?php echo $error; ?></small>
<?php } ?>
<br><br>
<form action="index.php" method="post">
<input type ="text" name="username" placeholder="Username"/>
<input type="password" name="password" placeholder="Password"/>
<input type="submit" value="Login"/>
</form>
</div>
</body>
</html>
<?php
}
?>
Your header() redirection is probably not working. Check error log to see what the problem is. There must be absolutely no characters sent to the browser before the header() redirection, else it will fail.
My guess would be that those few spaces before <? in your script (if they are not copy/paste error) could interfere with head() redirection.
Anyway, check your error.log and see what do you have there.
You can't use Header after you execute html to the browser.
Try replace this: header('Location: index.php');
With this:
<script>window.location="index.php";</script>
I am newbie using jquery mobile with php. I have a little problem on my login form with submit button after I submited, it head to 'home.php' page but url didn't go to home.php too. (it's still /login.php) . how can i fix this?
<?php
include 'core/config.init.php'; //include all sql connect,function etc.
if(logged_in() === true)
{
header('Location: home.php');
}
if(empty($_POST) === false)
{
$check_user = true;
$check_pass = true;
$username = $_POST['username'];
$password = $_POST['password'];
if(empty($username) === true || empty($password) === true)
{
$error = 'You need to enter username and password!';
$check_user = false;
$check_pass = false;
}
else if(user_exists($username) === false )
{
$check_user = false;
}
$login = login($username, $password);
if($login === false)
{
$error = 'Username/password is incorrect!';
$check_pass = false;
}
else
{
setcookie("username", "$username", time()+1720000);
header('Location: home.php');
}
}
//print_r($error);
?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/jquery.mobile/1.1.1/jquery.mobile-1.1.1.min.css" />
<link rel="stylesheet" href="core/css/login.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.mobile/1.1.1/jquery.mobile-1.1.1.min.js"></script>
<script type="text/javascript" src="core/jquery/jquery-latest.js"></script>
<script src="core/jquery/login.js"></script>
</head>
<body>
<div data-role="page" data-theme="a">
<div id = "header-text-area">
<span id= "header-text">Login</span>
</div>
<div data-role="content" style="padding: 15px">
<form action="login.php" method="POST">
<div data-role="fieldcontain" class="ui-hide-label">
<input name="username" id="textinput1" placeholder="Username" value="test" type="text" />
</div>
<div data-role="fieldcontain" class="ui-hide-label">
<input name="password" id="textinput2" placeholder="Password" value="test" type="password" />
</div>
<div id = "submit-area">
<input type="submit" data-theme="b" value="Submit" id = "sub1"/>
</div>
</form>
</div>
</div>
</body>
You need to add data-ajax="false" to the form tag. This will submit the form to your action URL without using Ajax navigation that is built into jquery mobile. Also, you should use the full URL in the form action. (jquery mobile sometimes gets confused)
After each call to
header("Location: home.php");
you need to add a line like this:
exit();
this should solve your problem.