I have small problem with part of my script:
<?php
session_start();
include_once('../includes/connection.php');
if(isset($_SESSION['logged_in'])) {
?>
<html>
<head>
<meta charset="UTF-8">
<title>Login</title>
<link rel="stylesheet" href="../css/style.css">
</head>
<body>
<h1>Markup 1</h1>
</body>
</html>
<?php
} else {
if(isset($_POST['email'], $_POST['password'])) {
$email = $_POST['email'];
$password = $_POST['password'];
$query = $db->prepare("SELECT * FROM user WHERE user_email = ?");
$query->bind_param('s',$email);
$query->execute();
$query->bind_result($user_id,$user_name,$user_email,$user_password);
$query->fetch();
$user = array("user_id"=>$user_id, "user_name"=>$user_name, "user_email"=>$user_email, "user_password"=>$user_password);
if($user['user_id'] != 0) {
$_SESSION['logged_in'] = true;
header("Location: index.php");
die();
} else {
$error = "Incorrect details!";
}
}
}
?>
<html>
<head>
<meta charset="UTF-8">
<title>Login</title>
<link rel="stylesheet" href="../css/style.css">
</head>
<body>
<h1>Markup 2</h1>
<div class="container">
<h3>Please login</h3>
<?php if(isset($error)) { ?>
<h4><?php echo $error; ?></h4>
<?php } ?>
<form action="index.php" method="post" autocomplete="off">
<input type="text" name="email" placeholder="E-mail">
<input type="password" name="password" placeholder="Password">
<input type="submit" value="Login">
</form>
</div>
</body>
</html>
Problem is that script after refreshing (calling header() method) doesn't execute die() statement, and after successfully set session variable and rendering part with "Markup 1" it will also render "Markup 2" part but it shouldn't.
I found this example here: https://www.youtube.com/watch?v=UNTvU--o2q8.
You can try including the second markup section within the else block this is a fairly hackish fix, but it should accomplish what you are aiming for. I would recommend restructuring this section and pulling some of the markup out to separate included files.
<?php
session_start();
include_once('../includes/connection.php');
if(isset($_SESSION['logged_in'])) {
?>
<html>
<head>
<meta charset="UTF-8">
<title>Login</title>
<link rel="stylesheet" href="../css/style.css">
</head>
<body>
<h1>Markup 1</h1>
</body>
</html>
<?php
} else {
if(isset($_POST['email'], $_POST['password'])) {
$email = $_POST['email'];
$password = $_POST['password'];
$query = $db->prepare("SELECT * FROM user WHERE user_email = ?");
$query->bind_param('s',$email);
$query->execute();
$query->bind_result($user_id,$user_name,$user_email,$user_password);
$query->fetch();
$user = array("user_id"=>$user_id, "user_name"=>$user_name, "user_email"=>$user_email, "user_password"=>$user_password);
if($user['user_id'] != 0) {
$_SESSION['logged_in'] = true;
header("Location: index.php");
die();
} else {
$error = "Incorrect details!";
}
} ?>
<html>
<head>
<meta charset="UTF-8">
<title>Login</title>
<link rel="stylesheet" href="../css/style.css">
</head>
<body>
<h1>Markup 2</h1>
<div class="container">
<h3>Please login</h3>
<?php if(isset($error)) { ?>
<h4>
<?php echo $error; ?>
</h4>
<?php } ?>
<form action="index.php" method="post" autocomplete="off">
<input type="text" name="email" placeholder="E-mail">
<input type="password" name="password" placeholder="Password">
<input type="submit" value="Login">
</form>
</div>
</body>
</html>
<?php } ?>
You can't call header() after you write content to the browser. You can sort of hack around this in PHP using output buffers (it's been a long time), but really you should move code that handles headers above all of your markup.
See: http://php.net/manual/en/function.header.php
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 would like for guests to be redirected to a login page whenever they access the site. There won't be a register form, and the site will only be protected by one username/password.
This is my login.php so far:
<!DOCTYPE html>
<html>
<head>
<title>Log in</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/style.css" type="text/css" />
</head>
<div id="lg_outr" class="mn_outr">
<div id="lg_ctnr" class="mn_ctnr">
<div id="lg_innr" class="mn_innr">
<form class="lg_frm">
<h1>Log in</h1>
<input class="usr_fld" type="text" placeholder="Username"/>
<input class="pw_fld" type="password" placeholder="Password"/>
<input class="sub_btn" type="submit" value="Log in"/>
</form>
</div>
</div>
</div>
I need help with:
Checking if a user is logged in through a header.php file
Forcing guests to the login.php page if not logged in
Making the login form actually work
Currently coding the site in localhost. Assuming I won't need a database as there's only one username/password.
Really appreciate any help
Found a solution!
Login.php:
<?php session_start(); ?>
<?php
if(isset($_SESSION['use']))
{
header("Location:index.php");
}
if(isset($_POST['login']))
{
$user = $_POST['user'];
$pass = $_POST['pass'];
if($user == "username1" && $pass == "password1")
{
$_SESSION['use']=$user;
echo '<script type="text/javascript"> window.open("index.php","_self");</script>';
}
else
{
echo "invalid UserName or Password";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Log in</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/style.css" type="text/css" />
</head>
<div id="lg_outr" class="mn_outr">
<div id="lg_ctnr" class="mn_ctnr">
<div id="lg_innr" class="mn_innr">
<form class="lg_frm" action="" method="post">
<h1>Log in</h1>
<input class="usr_fld" type="text" name="user" placeholder="Username"/>
<input class="pw_fld" type="password" name="pass" placeholder="Password"/>
<input class="sub_btn" type="submit" name="login" value="LOGIN"/>
</form>
</div>
</div>
</div>
And then this code at the top of my header.php
<?php session_start();
if(!isset($_SESSION['use'])) // If session is not set then redirect to Login Page
{
header("Location:Login.php");
}
?>
Using PHP -
Use Cakephp. https://www.youtube.com/watch?v=747K6W40ur0
Using python -
Use flask. https://flask-login.readthedocs.io/en/latest/
in any protected page, or contained in a require('config.php') file:
session_start();
$username = 'onlyone';
$password = 'secret';
if(empty($_SESSION['logged_in'])){
if(!empty($_REQUEST['username']) && !empty($_REQUEST['password']) && $_REQUEST['username'] === $username && $_REQUEST['password'] === $password) {
$_SESSION['logged_in'] = true;
} else {
header('Location: login.php');
exit;
}else {
// we're good
}
}
That should get you started and allow you to visualize the concept; but listen to some of the comments below your post as well!
I have a login page wich sends a variable to another page verifying if login is true (1) or false (0). I can echo $_SESSION['logon'] on page1 but just as I go to page2, my session seems to be dead and gives me * Notice: Undefined index: logon in * I have already fiddled with php.ini but to no avail. Register_globals = off by the way. I'm a rookie so I might have passed something wrong, didn't change the right parameter in php.ini, don't know.
Login Page:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="pt-br" xml:lang="pt-br">
<head>
<title>Alpha</title>
<link rel="stylesheet" href="CSS.css">
<script type="text/javascript" src="js/jquery-1.3.1.min.js"></script>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript" src="js/jquery.history.js"></script>
</head>
<body>
<form id="logbox" method="post" action="verylog.php">
User <input id="user" name="user" type="text" required/>
Password <input id="pass" name="pass" type="PASSWORD" required/>
<input id="send" type="submit"/>
</form>
<?php
if(isset($_POST['user'])){
header("Location: verylog.php");
}
?>
</body>
</html>
verylog.PHP "page1"
<?php
session_start();
$user=$_POST['user'];
$pass=$_POST['pass'];
$_SESSION['logon']=0;
$cost = ['cost' => 10,];
$hasheduser=password_hash($user, PASSWORD_BCRYPT,$cost);
$hashedpass=password_hash($pass, PASSWORD_BCRYPT,$cost);
$storeuserhash=file_get_contents('sunburn/userburn.txt');
$storepasshash=file_get_contents('sunburn/passburn.txt');
if(password_verify($user, $storeuserhash) && password_verify($pass, $storepasshash)){
session_regenerate_id(true);
$_SESSION['logon']=1;
header ("Location: ../sunburn/selector.php");
die();
//echo $_SESSION['logon'];
} else{
header ("Location: ../burnlogin.php");
die();
}
?>
selector.php "Page2"
<?php
session_start();
$logon=$_SESSION['logon'];
if($logon==0){
//header("Location: index.php");
exit();
echo $_SESSION['logon'];
}else{
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="pt-br" xml:lang="pt-br">
<head>
<link rel="stylesheet" href="localhost/CSS.css">
<link rel="stylesheet" href="CSS.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<div class="divreg">
<div>
<a href="../sunburn/register.php">
<button type="button" >-REGISTRAR-</button>
</a>
</div>
<div>
<a href="../sunburn/deltePAGE.php">
<button class="button1" type="button" value="deltePAGE" >-DELETAR-</button>
</a>
</div>
</div>
<div id="select">
</div>
</body>
<?php
}
?>
And I'm sorry about any typo I may have sent.
You are using exit before echo and you need to check condition on pag2.php like this :
if(isset($_SESSION['logon']) && $_SESSION['logon'] != "") {
$logon=$_SESSION['logon'];
if($logon==0){
//header("Location: index.php");
echo $_SESSION['logon'];
exit();
}
}
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.
I am going from vulnerable SQL codes into secure one, and I am trying to update my login to this:
if(isset($_POST['login'])){
$username = $_POST['username'];
$password = $_POST['password'];
if($username != '' && $password!=''){
session_start();
$sql = "SELECT * FROM login WHERE username=? and password =?";
$stmt = $con->prepare($sql);
$stmt=bind_param("ss", $username, $password);
$stmt->execute();
$stmt->store_result();
$num->$stmt->num_rows;
$stmt->close();
if($num>0){
$_SESSION["username"] = $username;
header("Location:homepage.php");
die();
} else {
$message = "Invalid Username or Password!";
}
}
}
When I am launching my login page I got this message:
This webpage has a redirect loop
Any help is appreciated.
EDIT
homepage code:
<?php
require_once ('/include/global.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Clinic Form</title>
<link href="css/1140.css" rel="stylesheet" type="text/css" />
<link href="css/style.css" rel="stylesheet" type="text/css" />
<link href="http://fonts.googleapis.com/css?family=Source+Sans+Pro:300" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container12">
<header>
<div class="row" align="center">
<div class="column12"> <img src="images/logo.png"/> </div>
</div>
<div class="row" align="center">
<div class="row" align="center">Logout</div>
</div>
</header>
<h1 id="home" align="center"> </h1>
<div class="alert"></div>
<div class="column12" align="center">
<div class="row"><a href="patients.php">
<input type="image" value="Patient" src="images/patient.png" width="widthInPixels" height="heightInPixels" onmouseover="this.src='images/patient_roll.png';" onmouseout="this.src='images/patient.png';">
</a> </div>
<div class="row"><a href="/clinic form/appoint/appoint.php">
<input type="image" value="Appointments" src="images/appointments.png" width="widthInPixels" height="heightInPixels" onmouseover="this.src='images/appointments_roll.png';" onmouseout="this.src='images/appointments.png';">
</a> </div>
<div class="row"><a href="/clinic form/med/med.php">
<input type="image" value="Medicaments" src="images/med.png" width="widthInPixels" height="heightInPixels" onmouseover="this.src='images/med_roll.png';" onmouseout="this.src='images/med.png';">
</a> </div>
<div class="row"><a href="">
<input type="image" value="Statistics" src="images/stat.png" width="widthInPixels" height="heightInPixels" onmouseover="this.src='images/stat_roll.png';" onmouseout="this.src='images/stat.png';">
</a> </div>
</div>
</div>
</body>
</html>
EDIT 2
global.php file:
<?php
session_start();
$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
$tbl_name=""; // Table name
//if(!session_is_registered(myusername)){
//header("location:index.html");
if(isset($_SESSION['username'])) {
echo "Page seen only by " . $_SESSION['username']."<br>";
$con=mysqli_connect($host,$username,$password,$db_name);
}
else{
session_destroy();
header("location:index.php");
}
?>
EDIT 3
The entire index.php code:
<?php
require_once('/include/global.php');
/*if(isset($_POST['login'])){
if($_POST['username'] != '' && $_POST['password']!=''){
if(!isset($_SESSION))
{
session_start();
session_register('username');
}
$result = mysql_query("SELECT * FROM login WHERE username='" . $_POST["username"] . "' and password = '". $_POST["password"]."'");
$row = mysql_fetch_array($result);
if(is_array($row)) {
$_SESSION["username"] = $row[$_POST["username"]];
$_SESSION['username'] = $_POST["username"];
header("Location:homepage.php");
} else {
$message = "Invalid Username or Password!";
}
}else{
$error_msg="Please fill all the fields";
}
}*/
if(isset($_POST['login'])){
$username = $_POST['username'];
$password = $_POST['password'];
if($username != '' && $password!=''){
session_start();
$sql = "SELECT * FROM login WHERE username=? and password =?";
$stmt = $con->prepare($sql);
$stmt=bind_param("ss", $username, $password);
$stmt->execute();
$stmt->store_result();
$num->$stmt->num_rows;
$stmt->close();
if($num>0){
$_SESSION['username'] = $username;
header("Location: homepage.php") ; die();
} else {
$message = "Invalid Username or Password!";
}
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Clinic Form</title>
<link href="css/1140.css" rel="stylesheet" type="text/css" />
<link href="css/style.css" rel="stylesheet" type="text/css" />
<link href="http://fonts.googleapis.com/css?family=Source+Sans+Pro:300" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container12">
<header>
<div class="row" align="center">
<div class="column12"> <img src="images/logo.png"/> </div>
</div>
</header>
<h1 id="home" align="center">Login</h1>
<form action="" method="POST">
<?php if(isset($message)) echo "<script type='text/javascript'>alert('$message');</script>" ?>
<div class="alert">
<?php if(isset($error_msg)) echo "<script type='text/javascript'>alert('$error_msg');</script>" ?>
</div>
<div class="column12" align="center">
<div class="row">
<input type="text" class="large-fld" name="username" value="" placeholder="Username" />
</div>
<div class="row">
<input type="password" class="large-fld" name="password" value="" placeholder="*****" />
</div>
<div class="row">
<input type="image" name="login" value="Login" src="images/btn.png" width="widthInPixels" height="heightInPixels" onMouseOver="this.src='images/rollOverBtn.png';" onMouseOut="this.src='images/btn.png';">
</div>
</div>
</form>
</div>
</body>
</html>
Maybe it will help you, if you be more specific about your header. When I started I found this little peace of code and use it ever since.
$hostname = $_SERVER["HTTP_HOST"];
$path = dirname($_SERVER["PHP_SELF"]);
header("Location: https://".$hostname.($path == "/" ? "" : $path)."/homepage.php");
die();
But I have another question, where do you set your Session Variable $_SESSION["username"] ?
EDIT:
Ok, your code does this:
You call homepage.php which includes global.php. Since there are no session variables set yet, global.php jumps into this part
else
{
session_destroy();
header("location:index.php");
}
Here you redirect to index.php. In index.php you include global.php again and exactly at this point your loop begins. So your global.php sends you to index.php in which global sends you to index.php and so on.
On way is to simply remove the include of global.php at the very beginning of your index.php.
Further you need to call
$stmt->bind_param("ss", $username, $password);
instead of
$stmt=bind_param("ss", $username, $password);
Please add space in header function after Location: .
header("Location: homepage.php");