$_SESSION doesn't start - php

When user is logged in nothing is displayed on the screen(Error-reporting is on).
It's like the $_SESSION is not true?
<?php
include_once('../includes/connection.php');
if (isset($_SESSION['logged_in'])) {
?>
<html>
<head>
<title>wa</title>
<link rel="stylesheet" type="text/css" href="../assets/stylesheet.css">
</head>
<body>
<div class="container">
CMS
<br />
<ol>
<li>Add Article</li>
<li>Delete Article</li>
<li>Logout</li>
</ol>
</div>
</body>
</html>
<?php
} else {
if (isset($_POST['username'], $_POST['password'])) {
$username = $_POST['username'];
$password = md5($_POST['password']);
if (empty($username) or 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) {
$_SESSION['logged_in'] = true;
header('Location: index.php');
exit();
} else{
$error = 'Incorrect details!';
}
}
}
?>
<html>
<head>
<title>Visuality dashboard</title>
<link rel="stylesheet" type="text/css" href="../assets/stylesheet.css">
</head>
<body>
<div class="container">
CMS
<br /><br />
<?php if (isset($error)) { ?>
<small style="color:#aa0000;"><?php echo $error; ?>
<br /><br />
<?php } ?>
<form action="index.php" method="post" autocomplete="off">
<input type="text" name="username" placeholder="något">
<input type="password" name="password" placeholder="något">
<input type="submit" value="Login" />
</div>
</body>
<footer>
</footer>
</html>
<?php
}
?>

You need to call session_start(); at the beginning of your PHP file. If you have multiple files then adding it once to your connection file will work for all of them.
Read more on Sessions in PHP here

At line 39 md5$_POST['password']); you missed "("
md5($_POST['password']);

Every php file which has $_SESSION variable needs to include session_start(); on the top of the page.
When page gets a white screen after loading, you should see php_error_log for possible syntax errors (could be missing ";").
Please, review your code.
Hope it helps you.

Related

Trying to create a CMS but having trouble with the login

CMS Tutorial and the stage I'm up to https://youtu.be/QNxU3Qa6QZs?t=1817
When I enter the wrong details it says that they are incorrect like it should but when I enter the correct details it is meant to login like in the video it shows a blank page but mine just refreshes the page and shows the login form again. I would really appreciate if anyone can help me out, thanks.
<?php
session_start();
include_once('../includes/connection.php');
if (isset($SESSION['logged_in'])) {
?>
<html>
<head>
<title>CMS Tutorial</title>
<link rel="stylesheet" href="../assets/style.css">
</head>
<body>
<div class="container">
CMS
<br>
<ol>
<li>Add Article</li>
<li>Delete Article</li>
<li>Logout</li>
</ol>
</div>
</body>
</html>
<?php
} else {
if (isset($_POST['username'], $_POST['password'])) {
$username = $_POST['username'];
$password = md5($_POST['password']);
if (empty($username) or 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) {
$_SESSION['logged_in'] = true;
header('Location: index.php');
exit();
} else {
$error = 'Incorrect Details!';
}
}
}
?>
<html>
<head>
<title>CMS Tutorial</title>
<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>
<br> <br>
<?php } ?>
<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
}
?>
See this on line 6?
$SESSION['logged_in']
The PHP super global is: $_SESSION. Add an underscore there and it should work.

Why won't header redirect work after login?

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 '&nbsp<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 '&nbsp<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 = '&nbsp<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 = '&nbsp<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.

redirect loop error in login page

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");

Header redirection on the same page

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

PHP blank page after the login

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>

Categories