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>
Related
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 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);
I have a login page with login form , it should redirect to admin page when admin loggs in. This all worked, but four days ago it redirects again to login page. When I manualy type admin after login in url, admin page can be accessed.
My login page:
<html>
<head>
<?php include 'connect.php'; ?>
<?php include 'functions.php'; ?>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, minimumscale=1.0, maximum-scale=1.0" />
<title>Login - Admin</title>
<link rel='stylesheet' href='style.css' type='text/css' />
<?php include 'header.php'; ?>
</head>
<body >
<div id="container_vanjski">
<div id="container">
<form method="post">
<br/>
<?php
if(isset($_POST['submit'])){
$username = mysqli_real_escape_string($con, $_POST['username']);
$password = md5(mysqli_real_escape_string($con, $_POST['password']));
if(empty($username) or empty($password)){
echo ' <p>Polja su prazna !</p>';
}
else {
$check_login = mysqli_query($con, "SELECT id, user_level FROM korisnici WHERE username='".$username."' AND password='".$password."'");
if(mysqli_num_rows($check_login) == 1){
$run = mysqli_fetch_array($check_login);
$user_id = $run['id'];
$user_level = $run['user_level'];
$_SESSION['user_id'] = $user_id;
header("Location: admin");
}else{
echo ' <p>Pogrešno Korisničko ime ili Lozinka!</p>';
}
}
}
?>
<br/>
<div id="log">
<label for="username">Korisničko ime:</label><input type="text" name="username" /><br />
<label for="password">Lozinka:</label><input type="password" name="password" /><br />
<br />
<input type="submit" name="submit" value="Prijava" id="button" />
</div>
</form>
</div>
<?php include 'footer.php'; ?>
</div>
</body>
</html>
On my localhost server this is working, but on web server(BLUEHOST) this stopped working four days ago.
Does anyone know why is this happening?
You can't use header after html.
Two solutions :
Header before any html code (my favorite)
buffering
<?php
ob_start( );
?>
<html>
<body>
some output
<?php
ob_end_clean( );
header( 'Location: http://www.google.com' );
exit;
?>
</body>
</html>
<?php
ob_end_flush( );
?>
Full code :
<?php
include 'connect.php';
include 'functions.php';
if(isset($_POST['submit'])){
$username = mysqli_real_escape_string($con, $_POST['username']);
$password = md5(mysqli_real_escape_string($con, $_POST['password']));
if(empty($username) or empty($password)){
$message = ' <p>Polja su prazna !</p>';
}
else {
$check_login = mysqli_query($con, "SELECT id, user_level FROM korisnici WHERE username='".$username."' AND password='".$password."'");
if(mysqli_num_rows($check_login) == 1){
$run = mysqli_fetch_array($check_login);
$user_id = $run['id'];
$user_level = $run['user_level'];
$_SESSION['user_id'] = $user_id;
header("Location: admin");
}else{
$message = ' <p>Pogrešno Korisničko ime ili Lozinka!</p>';
}
}
}
?>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, minimumscale=1.0, maximum-scale=1.0" />
<title>Login - Admin</title>
<link rel='stylesheet' href='style.css' type='text/css' />
<?php include 'header.php'; ?>
</head>
<body >
<div id="container_vanjski">
<div id="container">
<form method="post">
<br/>
<?php echo (isset($message) ? $message : ''); ?>
<br/>
<div id="log">
<label for="username">Korisničko ime:</label><input type="text" name="username" /><br />
<label for="password">Lozinka:</label><input type="password" name="password" /><br />
<br />
<input type="submit" name="submit" value="Prijava" id="button" />
</div>
</form>
</div>
<?php include 'footer.php'; ?>
</div>
</body>
</html>
Headers must be sent before any other content is generated on the server. Move your login handling code to the start of the file before the opening HTML tag. It may have worked on your localhost as some configurations can be a little forgiving with header's being sent mid code but it is not compliant and you will probably find that is the issue.
Index.php Page
I am a beginner.
This is index page in which i print a name of user who is logged in and i want to update the username whenever a user edit his detail i try to update it,it's updating the username but when i edit detail then i have log out first then login again then the name will update.I want to update the name instantly when a user edit his detail and redirect to index page just like facebook do.
i almost spend a week for solving this problem.Please give me code if anything needs to with ajax.
Thank you
<?php
session_start();
require_once("inc/connection.php");
if (empty($_SESSION['usersession'])) {
header("Location: login.php");
}
if (isset($_SESSION['msg'])) {
echo $_SESSION['msg'];
unset($_SESSION['msg']);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>WELCOME TO USER AREA</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<div id="main">
<nav id="nav">
<div class="logout">
WELCOME <?php echo $_SESSION['usersession']['name']; ?> // echo name of user
Log out
</div>
<ul>
<li>Home</li>
<li>Register</li>
<li>Edit</li>
<li>Delete(not recommended)</li>
</ul>
</nav>
<div class="para">
some text
</div>
</div>
</body>
</html>
Edit.php
This is edit.php code
<?php
session_start();
if (empty($_SESSION['usersession'])) {
header("Location: login.php");
}
if (isset($_SESSION['msg'])) {
echo $_SESSION['msg'];
unset($_SESSION['msg']);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>REGISTER HERE</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<div id="reg2">
<?php
if (isset($_POST['btn'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];
$id = $_SESSION['usersession']['id'];
if (!empty($name && $email && $password)) {
if (!empty($password)) {
$password = sha1($password);
require_once("inc/connection.php");
$query = mysqli_query($conn, "UPDATE register SET name='$name',email='$email',password='$password' WHERE id='$id'");
if ($query) {
header("Location: index.php");
} else {
echo "not updated right now please try again later";
}
$_SESSION['msg'] = "Your detail has been updated successfully";
}
} else {
echo "please put your updated password";
}
}
?>
</div>
<div id="form">
<form method="post" action="edit.php">
<label>NAME</label><p>
<input class="int" type="text" class="nm" name="name" placeholder="Please Enter Your Name Here" value="<?php echo $_SESSION['usersession']['name']; ?>" /><p>
<label>EMAIL</label><p>
<input class="int" type="email" class="em" name="email" placeholder="Please Enter Your Email Here" value="<?php echo $_SESSION['usersession']['email']; ?>" /><p>
<label>PASSWORD</label><p>
<input class="int" type="password" name="password" placeholder="Please Enter Your new Password Here" />
<p></p>
<input type="hidden" name="id[]" value="<?php echo $_SESSION['usersession']['id']; ?>"/>
<input type="submit" name="btn" id="btu" value="Update">
</form>
</div>
</body>
</html>
When updating your Database you didnt change the value in your $_SESSION.
You have to do that manually.
// Add that under $_SESSION['msg'] = '....'
$_SESSION['usersession']['username'] = $name; // Same with email and password
Note that your code is vulnerable to mysql-injection. You should mysql_real_escape_string to avoid that.
Furthermore you display your message before even outputting your <!DOCUMENT html>. Please dont do that. Instead echo the message somewhere in your html!
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>