i am new to php and i am trying to make a register and log in page.
When I register as a new user it works fine and comes up in the database.However, when it comes to logging in there seems to be a problem that i tried everything.
what i want to do is when a user logs in, it redirect them to the home page, and if the log in information was wrong then it would show an error message.
Here is the php code that is in the log in file:
<?php
session_start();
if( isset($_SESSION['users_id']) ){
header("Location: /");
}
require 'database.php';
if(!empty($_POST['email']) && !empty($_POST['password'])):
$records = $conn->prepare('SELECT id,email,password FROM users WHERE email = :email');
$records->bindParam(':email', $_POST['email']);
$records->execute();
$results = $records->fetch(PDO::FETCH_ASSOC);
$message = '';
if(count($results) > 0 && password_verify($_POST['password'], $results['password']) )
{
$_SESSION['users_id'] = $results['id'];
header("Location: php.dev/index.php", true, 301); exit();
}
else {
$message = 'Sorry, thoes credentials do not match';
}
endif;
?>
the header("Location:....) this doesn't seem to work. i'm really stuck here any help ?
Here is the html code:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Login</title>
<link href="Style/phpstyle.css" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet">
</head>
<body>
<div class="header">
TIPBUCKET
</div>
<?php if(!empty($message)): ?>
<p><?= $message ?></p>
<?php endif; ?>
<h1>Login</h1>
<span> or Register here</span>
<form action="login.php" method="POST">
<input type="text" placeholder="enter your email" name="email">
<input type="password" placeholder="Password" name="password">
<input type="submit">
</form>
</body>
</html>
Thank you in advance to any replies :)
You have a typo in your header:
header("Location: php.dev/index.php", ture, 301);
should be
header("Location: php.dev/index.php", true, 301);
Related
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.
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'])){
...
So, I am kinda new to php and mysql, but I have found a login form and adapted it to my needs as I dont have the knowledge to make one my self yet. I added a firstname and surname column into the database and the register form adds the values into the database fine.
Now I want to be able to display the firstname and surname onto a restricted page, the reason why I need this is because I want it to say: Welcome Jo Blogs. Below is the register form.
<?php
session_start();
if( isset($_SESSION['user_id']) ){
header("Location: /");
}
require 'database.php';
$message = '';
if(!empty($_POST['email']) && !empty($_POST['password']) && !empty($_POST['firstname']) && !empty($_POST['surname'])):
// Enter the new user in the database
$sql = "INSERT INTO users (email, password, firstname, surname) VALUES (:email, :password, :firstname, :surname)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':email', $_POST['email']);
$stmt->bindParam(':password', password_hash($_POST['password'], PASSWORD_BCRYPT));
$stmt->bindParam(':firstname', $_POST['firstname']);
$stmt->bindParam(':surname', $_POST['surname']);
if( $stmt->execute() ):
$message = 'Successfully created new user';
else:
$message = 'Sorry there must have been an issue creating your account';
endif;
endif;
?>
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
<?php include '../header.php'; ?>
</head>
<body>
<?php if(!empty($message)): ?>
<p><?= $message ?></p>
<?php endif; ?>
<h1>Register</h1>
<span>or login here</span>
<form action="register.php" method="POST">
<input type="text" placeholder="Enter your email" name="email">
<input type="password" placeholder="and password" name="password">
<input type="password" placeholder="confirm password" name="confirm_password">
<input type="text" placeholder="Enter your first name" name="firstname">
<input type="text" placeholder="Enter your surname" name="surname">
<input type="submit">
</form>
</body>
</html>
And below here is the login form as im not really sure what you guys need to help me :)
<?php
session_start();
if( isset($_SESSION['user_id']) ){
header("Location: /");
}
require 'database.php';
if(!empty($_POST['email']) && !empty($_POST['password'])):
$records = $conn->prepare('SELECT id,email,password FROM users WHERE email = :email');
$records->bindParam(':email', $_POST['email']);
$records->execute();
$results = $records->fetch(PDO::FETCH_ASSOC);
$message = '';
if(count($results) > 0 && password_verify($_POST['password'], $results['password']) ){
$_SESSION['user_id'] = $results['id'];
header("Location: /");
} else {
$message = 'Sorry, those credentials do not match';
}
endif;
?>
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<?php include '../header.php'; ?>
</head>
<body>
<?php if(!empty($message)): ?>
<p><?= $message ?></p>
<?php endif; ?>
<h1>Login</h1>
<span>or register here</span>
<form action="login.php" method="POST">
<input type="text" placeholder="Enter your email" name="email">
<input type="password" placeholder="and password" name="password">
<input type="submit">
</form>
</body>
</html>
Also while I am here, I am currently using javascript to redirect to the homepage once you log out as i couldn't find any information on how to do it with php
Restricted.php:
<!DOCTYPE html>
<html>
<head>
<title>Restricted Area</title>
<link rel="stylesheet" type="text/css" href="../assets/css/style.css">
<link href='http://fonts.googleapis.com/css?family=Comfortaa' rel='stylesheet' type='text/css'>
<?php
include '../header.php';
?>
</head>
<body>
<?php
session_start();
if(isset($_SESSION['user_id'])) { ?>
<h1>Restriced Area</h1>
<h2>You have sucessfully logged in with your credentials</h2>
<?php
} else { ?>
<script type="text/javascript">
window.location = "login.php";
</script>
<?php
exit;
}
?>
</body>
</html>
Just let me know if you guys need any more information/code.
Thanks.
As Qirel suggested...
Restricted.php should resemble this:
<?php
session_start();
if (!isset($_SESSION['user_id'])) {
header("Location: /login.php"); // no need to query
}
require('database.php'); // assumed to declare $conn=new PDO(...);
$loggedin = $conn->prepare('SELECT firstname,surname FROM users WHERE id=?');
$loggedin->execute([$_SESSION['user_id']]);
$results = $loggedin->fetch(PDO::FETCH_ASSOC);
if (!$results) {
header("Location: /login.php"); // unsuccessful query
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Restricted Area</title>
<link rel="stylesheet" type="text/css" href="../assets/css/style.css">
<link href='http://fonts.googleapis.com/css?family=Comfortaa' rel='stylesheet' type='text/css'>
<?php include '../header.php'; ?>
</head>
<body>
<h1>Restriced Area</h1>
<h2>You have successfully logged in with your credentials</h2>
<?php echo "Welcome {$results['firstname']} {$results['surname']}"; ?>
</body>
</html>
Edit:
This statement borders on too serious but I would like to mention, especially to inexperienced php coders, that SESSION data can be hijacked (this is outlined in Pro PHP Security: From Application Security Principles to the Implementation of XSS Defense - Chapter 7: Preventing Session Hijacking) and so it can be suggested to never store any personal information in $_SESSION. This would most critically include credit card numbers, government issued ids, and passwords; but would also extend into less assuming data like usernames, emails, phone numbers, etc which would allow a hacker to impersonate/compromise a legitimate user.
The internet is still very much in its "Wild West" era, and nothing is 100% safe. ...and Internet Security is a rabbit hole / money pit. Every coder should devote some time to understanding known threats and preventing them, but just how far to go with this will differ from person to person.
Maybe this??
In the first snippet after successfully adding a new user..
if( $stmt->execute() ):
$message = 'Successfully created new user';
$_SESSION['firstname'] = $_POST['firstname'];
$_SESSION['surname'] = $_POST['surname'];
# redirect to login or you could just
# have the logged in at this point and..
# redirect to restricted.php..
header("Location: /login.php");
else:
$message = 'Sorry there must have been an issue creating your account';
endif;
Then set up restricted.php like so:
<?php
session_start();
if (!isset($_SESSION['user_id'])) {
header("Location: /login.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Restricted Area</title>
<link rel="stylesheet" type="text/css" href="../assets/css/style.css">
<link href='http://fonts.googleapis.com/css?family=Comfortaa' rel='stylesheet' type='text/css'>
<?php include '../header.php'; ?>
</head>
<body>
<h1>Welcome <?php echo $_SESSION['firstname']; ?> <?php echo $_SESSION['surname']; ?></h1>
<h2>You have sucessfully logged in with your credentials</h2>
</body>
</html>
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>