HTML alert gets displayed before hitting the submit button [duplicate] - javascript

This question already has answers here:
Checking if form has been submitted - PHP
(9 answers)
Closed 7 months ago.
i have been trying to create a login page linked to a database . I have created an alert which is supposed to be displayed after invalid login or empty login but it gets displayed
right after the login page is loader(i.e. before any submission) .For example as soon as the page loads it displays an alert which says"Username password cannot be empty" .I want this alert to be shown after the user hits the submit button.Please Help.Here's the
image
Here's the code:
<?php
//error
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once "config.php";
session_start();
if (isset($_SESSION['username'])) {
header('location: home.php');
exit;
}
$username = "";
$password = $err = "";
if (isset($_POST)) {
if (empty(trim($_POST['username'])) || empty(trim($_POST['password']))) {
$err = "Username or Password cannot be blank";
} else {
$username = trim($_POST['username']);
$password = trim($_POST['password']);
}
if (empty($err)) {
echo "in";
$sql = "SELECT id,username,password FROM users where username=?";
$stmt = mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, "s", $param_username);
$param_username = $username;
if (mysqli_stmt_execute($stmt)) {
mysqli_stmt_store_result($stmt);
//if username exists
if (mysqli_stmt_num_rows($stmt) == 1) {
mysqli_stmt_bind_result($stmt, $id, $username, $hashed_password);
if (mysqli_stmt_fetch($stmt)) {
if (password_verify($password, $hashed_password)) {
//password correct
session_start();
$_SESSION['username'] = $username;
$_SESSION['id'] = $id;
$_SESSION['loggedin'] = true;
header("location: home.php");
}
}
} else {
$err = "Invalid Username or Password";
}
}
}
}
?>
Here's HTML:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Spotify</title>
<link rel="stylesheet" href="style1.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Varela+Round&display=swap" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
</head>
<body class="bds">
<nav>
<ul>
<a>
<li class="brand"><img class="hello" src="./images/logo.png" alt="Spotify">Spotify</li>
<div class="buttons">
<button class="home">Home</button>
<button class="home">About</button>
</div>
<div class="logbutton">
<button class="loginbutt">Register</button>
</div>
</ul>
</nav>
<div class="container mt-4">
<h3>Login Here</h3>
<hr>
<form action="" method="post">
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="text" name="username" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter Username">
<small id="emailHelp" class="form-text text-muted">We'll never share your details with anyone else.</small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" name="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
</div>
<br>
<?php
if (!empty(trim($err))) {
echo "<div id='warningus' class='alert alert-warning alert-dismissible fade show' role='alert'>
<strong>Holy guacamole!</strong> " . $err . "
<button type='button' class='btn-close' data-bs-dismiss='alert' aria-label='Close'></button>
</div>";
$err="";
}
?>
<br>
<button type="submit" class="btn btn-primary">Log in</button>
</form>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"></script>
</body>
</html>

Create an input with type="hidden" and give it a name and value. Then check for that input to determine if the page is loaded after a submit.

Related

Why image is not saved to the database?

I am trying to do a register page where a user must fill up its details and upload a picture of its choice. When i pressed the registered button, i have the following errors : "( ! ) Notice: Undefined index: image in /strath-cis/2018/SmartCommute/php/register.php " and "( ! ) Warning: file_get_contents(): Filename cannot be empty in /strath-cis/2018/SmartCommute/php/register.php "
On my database I do have a field called "image" of type BLOB.
I am sure that my details to connect with my database are correct.
Do anyone have a clue why this is happening?
Bellow is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
<meta name="mobile-web-app-capable" content="yes"/>
<meta name="apple-mobile-web-app-capable" content="yes"/>
<link rel="stylesheet" type="text/css" href="../css/normalize.css"/>
<link rel="stylesheet" type="text/css" href="../css/register_css.css"/>
<title>Smart Commute</title>
</head>
<body>
<header id="headerBar">Smart Commute - Register</header>
<form class="needs-validation" novalidate action="" method="post">
<p><input type="file" accept="image/*" name="image" id="file" onchange="loadFile(event)" style="display: none;"></p>
<p><label for="file" style="cursor: pointer;">Upload Image</label></p>
<p><img id="output" width="200" /></p>
<script>
var loadFile = function(event) {
var image = document.getElementById('output');
image.src = URL.createObjectURL(event.target.files[0]);
};
</script>
<p>Name: <input type="text" class="form-control" name="name" id="name" placeholder="John Doe" autocomplete="off" value="<?php if(isset($_POST['Register'])){echo $_POST['name'];} ?>" required></p>
<p>Email: <input type="text" class="form-control" name="email" id="email" placeholder="fake#mail.com" autocomplete="off" value="<?php if(isset($_POST['Register'])){echo $_POST['email'];} ?>" required></p>
<p>Password: <input type="password" class="form-control" name="password" id="password" placeholder="Enter password" autocomplete="off" value="<?php if(isset($_POST['Register'])){echo $_POST['password'];} ?>" required></p>
<br><br>
<!-- <input type="submit" value="Submit" name="Register">-->
<button name="Register">Register</button>
</form>
</body>
</html>
<?php
session_start();
if (isset($_POST['Register']) && isset($_POST["image"]) ) {
if (empty($_POST['password']) || preg_match('/\s/', $_POST['password'])) {
echo "No spaces allowed in new password!";
} else {
include("../include/db_config.php");
include("../include/db_connect.php");
// image file directory
$image = addslashes(file_get_contents($_FILES['image']['tmp_name'])); //SQL I
$name = mysqli_real_escape_string($db, $_POST['name']);
$email = mysqli_real_escape_string($db, $_POST['email']);
$password = mysqli_real_escape_string($db, $_POST['password']);
$encryptedPassword = md5($password);
$sql = "SELECT * FROM `cs317madt`.`useracc` WHERE `email` = '$email'";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$result = $db->query($sql);
if (mysqli_num_rows($result) == 1) {
echo "User already exists";
} else {
$sql2 = "INSERT INTO `cs317madt`.`useracc` (`id`,`name`,`password`,`email`, `image`) VALUES (NULL, '$name', '$encryptedPassword', '$email','$image');";
if ($result2 = $db->query($sql2)) {
header("location: ../php/home.php");
$_SESSION['logged-in'] = true;
$_SESSION['name'] = $name;
} else {
echo "Something went wrong with creating your account!";
}
}
} else {
echo "Invalid email! Please enter a valid email";
}
}
}
?>
When you are uploading a file, you need to include an enctype="multipart/form-data" attribute to the <form> tag. Have a quick read on the php's manual about file uploads.. You'll notice there is a Note section that explicitly mentions this.
So, for example:
<form enctype="multipart/form-data" class="needs-validation" novalidate action="" method="post">

invisible recaptcha v2 not checking required input fields

I am adding an invisible recaptcha; for some reason, it doesn't check for required fields anymore. Previously, I would get a notification from Chrome stating that the fields can't be empty. Now, it's just ignoring this and letting me submit empty forms.
I am submitting requests using ajax. My guess is that the data-callback is not meant to be used to send ajax requests.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Submit a quote</title>
<link rel="stylesheet" href="../css/style.css">
<link rel="stylesheet" href="../css/forms.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="../js/quotes/ajax.js"></script>
<meta name="description" content="Submit your awesome quote today!">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="theme-color" content="#0aff0a">
<meta name="msapplication-navbutton-color" content="#0aff0a">
<meta name="apple-mobile-web-app-status-bar-style" content="#0aff0a">
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
<div id="status-message"></div>
<div class="container">
<form id="form" action="../php/quoteSubmit.php" method="post">
<h3>Submit your quote</h3>
<fieldset>
<textarea rows="20" name="quote" title="quotes" placeholder="Type your quote here...." tabindex="5" required></textarea>
</fieldset>
<fieldset>
<input placeholder="Author" name="author" title="quotes" type="text" tabindex="1" required>
</fieldset>
<fieldset>
<!--<button name="submit" type="submit" id="contact-submit">Submit</button>-->
<button name="submit" type="submit" id="contact-submit" class="g-recaptcha" data-callback="onSubmit" data-sitekey="6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI">Submit</button>
</fieldset>
</form>
</div>
<script>
function onSubmit(e) {
//$("#form").submit(function (e) {
var url = $("#form").attr('action'); // the script where you handle the form input.
ajaxSendData(url, $("#form").serialize());
//});
}
</script>
</body>
</html>
It seems the submit action is cancelled as well.
$("#form").submit(function (e) {
var url = $("#form").attr('action');
ajaxSendData(url, $("#form").serialize());
e.preventDefault();
});
The above snippet only triggers when not using the recaptcha API.
How would I properly send an ajax request to a PHP page?
My full code (if needed):
<?php
include_once "connect.php";
session_start();
if(isset($_POST["quote"], $_POST["author"], $_POST["g-recaptcha-response"])){
if(!isValid()){
http_response_code(400);
exit();
}
$stmt = $conn->prepare("INSERT INTO pending (quote, author) VALUES (?, ?)");
$stmt->bind_param("ss", $quote, $author);
$quote = htmlspecialchars($_POST["quote"]);
$author = htmlspecialchars($_POST["author"]);
$stmt->execute();
echo"Added to pending! Thank you for submitting";
$stmt->close();
$conn->close();
//$_SESSION["lastRequest"] = time();
}else{
http_response_code(400);
exit();
}
function isValid()
{
try {
$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = ['secret' => '6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe',
'response' => $_POST['g-recaptcha-response'],
'remoteip' => $_SERVER['REMOTE_ADDR']];
$options = [
'http' => [
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
]
];
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if($decoded = json_decode($result, true)){
return $decoded['success'];
}
}
catch (Exception $e) {
return null;
}
}
Try to put the recaptcha in separate div
<div class="g-recaptcha" data-sitekey="6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI"></div>
function onSubmit(e) {
//$("#form").submit(function (e) {
var url = $("#form").attr('action'); // the script where you handle the form input.
ajaxSendData(url, $("#form").serialize());
//});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.google.com/recaptcha/api.js"></script>
<div id="status-message"></div>
<div class="container">
<form id="form" action="../php/quoteSubmit.php" method="post">
<h3>Submit your quote</h3>
<fieldset>
<textarea rows="20" name="quote" title="quotes" placeholder="Type your quote here...." tabindex="5" required></textarea>
</fieldset>
<fieldset>
<input placeholder="Author" name="author" title="quotes" type="text" tabindex="1" required>
</fieldset>
<fieldset>
<!--<button name="submit" type="submit" id="contact-submit">Submit</button>-->
<div class="g-recaptcha" data-sitekey="6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI"></div>
<button name="submit" type="submit" id="contact-submit" data-callback="onSubmit">Submit</button>
</fieldset>
</form>
</div>

java script alerts always appear

above the form
<?php require_once "core-admin/init-admin.php";
if( !isset($_SESSION['admin_username']) ){
$_SESSION['msg'] = 'page can not open';
header('Location:admin_login.php');
}
if(isset($_POST['submit']) ){
$press_type = $_POST['press_type'];
$press_picture = $_FILES['press_picture'];
$type_file = $_FILES['press_picture'] ['type'];
$tmp_file = $_FILES['press_picture']['tmp_name'];
$file_size = $_FILES['press_picture'] ['size'];
if(!empty(trim($press_type)) ) {
if(!empty($_FILES['press_picture']['tmp_name']) ){
if($type_file == "image/jpeg" || $type_file == "image/png" || $type_file == "image/jpg" ){
if($file_size <= 300000){
if(add_press($press_type, $press_picture)) {
$message = 'sukses men.';
echo "<SCRIPT type='text/javascript'>
alert('$message');
window.location.replace(\"add_data_press.php\");
</SCRIPT>";
}
} else { ?>
<script>
alert("failed add data");
</script>
<?php }
}else{ ?>
<script>
alert("size should be below 200kb");
</script>
<?php }
}else{ ?>
<script>
alert("image type should be .jpeg .jpg atau .png");
</script>
<?php }
}else{ ?>
<script>
alert("image can not be empty");
</script>
<?php }
}else{ ?>
<script>
alert("please complete the unfilled form");
</script>
<?php
}
?>
form
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title></title>
<!-- Bootstrap core CSS -->
<link rel="stylesheet" href="../view/css/bootstrap.min.css">
<link rel="stylesheet" href="../view/css/dataTables.bootstrap.min.css">
<!-- Custom styles for this template -->
<link href="../view/css/simple-sidebar.css" rel="stylesheet">
<link rel="stylesheet" href="../view/font-awesome/css/font-awesome.min.css">
</head>
<body>
<?php require_once"../view/header-admin.php";?>
<!-- /#sidebar-wrapper -->
<!-- Page Content if tdk ada ini tidak akan tampil apa apa -->
<div id="page-content-wrapper">
<div class="container-fluid">
<i class="fa fa-th text-danger" aria-hidden="" id="menu-toggle"></i>
<div class="row">
<div class="col-md-12">
<h1 class="display-4">Carolyn Tyler</h1>
<h6>handmade fine jewelry</h6>
<br>
<h5>Add data press</h5>
</div>
</div>
<div class="row justify-content-md-center">
<div class="col-lg-8">
<form action="" method="post" enctype="multipart/form-data">
<div class="form-group">
<label class="form-control-label" for="formGroupExampleInput">Press Type</label>
<input type="text" class="form-control" id="formGroupExampleInput" placeholder="Press Type" name="press_type" required="">
</div>
<div class="form-group">
<label for="exampleFormControlFile1">press picture</label>
<input type="file" class="form-control-file" id="exampleFormControlFile1" name="press_picture">
</div>
<button type="submit" class="btn btn-primary" name="submit">Submit</button>
<br> <br>
</form>
</div>
</div>
</div>
</div>
my problem is, when i access this page. I always get the alert "please complete the unfilled form". in this case I have not done any insert yet but have alerted this page.
but if I split the file # abovethepage # alerts do not show up again. is there any way to make # abovethepage # files still on 1 page but alert does not appear again.?
if you check isset($_POST['submit']) is return false on first time page load
if(isset($_POST['submit']))
thats why your else part run first time page load without submitting form data
When you access the page for the first time, the $_POST is empty(It will only contain data if you send HTTP POST request to your script using submit button). In such case, the below else condition satisfies:
else{ ?>
<script>
alert("please complete the unfilled form");
</script>
<?php
}
This is why it always shows the alert message.

Notice: Undefined index: password in E:\x\htdocs\crud\slp\slp\login.php on line 10 [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 5 years ago.
Where I'm wrong? this error only orccur when I use data-toggle="password" - see the code below.
https://gist.githubusercontent.com/pomy/77047de0962f6a17d8459a8a51083952/raw/997f33425212eba407902dfa9e0e6ad52180e033/%2520data-toggle=%2522password%2522
<?php
session_start();
require_once "config.inc.php";
$email = '';
$password='';
$errors = array();
//Checking the request method post to know if the form really posts any data
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$email = strip_tags($_POST['email']);
$password = strip_tags($_POST['password']);
//perfroming the validation
if(empty($email)){
$errors[] = "Email field is required";
}
if(empty($password)){
$errors[] = "Password field is required";
}
//You are goo to go
if(empty($errors)) {
$sth = $conn->prepare("SELECT * FROM users WHERE email = :email LIMIT 1");
$sth->bindParam(':email', $email, PDO::PARAM_STR);
$sth->execute();
$user = $sth->fetch(PDO::FETCH_OBJ);
if(!empty($user)) {
//Verifying the password
$hashedPwdDB = $user->password;
if (password_verify($password, $hashedPwdDB)) {
$_SESSION['user_id'] = $user->user_id;
$_SESSION['name'] = $user->name;
$_SESSION['email'] = $user->email;
header("Location:dashboard.php");
exit;
}
else {
$errors[] = "Invalid login";
}
}
else {
$errors[] = "Invalid login";
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Tutsplanet Login Form</title>
<!-- Bootstrap -->
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" crossorigin="anonymous">
<!-- login with show password -->
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-show-password/1.0.3/bootstrap-show-password.min.js"></script>
</head>
<!-- login with show password // -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" crossorigin="anonymous"></script></head>
<body>
<div class="container" style="width:20%;">
<form class="form-signin" method="post">
<?php if(!empty($errors)):?>
<div class="alert alert-danger">
<?php foreach($errors as $error):?>
<?php echo $error,"<br>";?>
<?php endforeach;?>
<?php endif;?>
</div>
<h2 class="form-signin-heading">Please sign in</h2>
<label for="inputEmail" class="sr-only">Email address</label>
<input type="email" id="inputEmail" class="form-control" placeholder="Email address" required autofocus name="email">
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" id="password" name="password" class="form-control" data-toggle="password" autocomplete="off">
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
</div>
<!-- /container -->
<script type="text/javascript">
$("#password").password('toggle');
</script>
</body>
</html>
I solved it by adding if (isset ($_GET ["password"])) {} after line number 6. Error has gone. Is it a good approach to fix like this?

php - Session Not Carrying Over but Variables Are

I have a page (index.php) which has a login form. When a user logs in, it checks the credentials and if correct, creates a session, sets two variables, auth to yes and user to the username, and redirects to another page(pihome.php) via echoing a javascript window.location.href command. This is where the problem starts. On this page if I run session_start() it used to say session has already been created, ignoring but I was able to access the variables from the previous page. Now using an if condition with session_status() it session_start() works. I have a Logout button on this page which goes to another page (Logout.php). On that page when I try to run session_destroy() it says a session has not been started and when I try to echo the variables it says they have not been defined.
While browsing SO for solutions I saw certain solutions that applied to variables not being carried over but I can access them on the pihome.php page but logout.php doesn't let me access them or execute session_destroy(). I would like to know if I'm using the sessions correctly and if I should place session_start() at the beginning of every page and how to correctly access the variables. Thanks!
index.php
<!DOCTYPE html>
<html>
<head>
<title>PiHome Login</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"> </script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"> </script>
<link rel="stylesheet" href="standardstyle.css">
</head>
<body id="override-background">
<?php
session_start();
?>
<?php
if(isset($_SESSION["Auth"])){
if($_SESSION["Auth"] == "yes"){
echo '<script type="text/javascript">
window.location.href = "pihome.php";
</script>';
}
else{
}}
else{
}
?>
<div class="jumbotron">
<h1 class="text-center">PiHome<br/><small>v1.0.0</small></h1>
</div>
<div class="container-fluid">
<div class="well col-3">
<img src="piHome.png" alt="piHome_logo" class="img-rounded" style="display:block;"></img>
<h3 class="text-center">Login</h3>
<form role="form" action="index.php" method="post">
<div class="form-group">
<label for="user">Username</label>
<input type="text" class="form-control" id="email" name="user">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" name="pass">
</div>
<div class="checkbox">
<label><input type="checkbox" name="remember"> Remember me</label>
</div>
<input type="submit" class="btn btn-primary btn-block" value="Login">
<form>
</div>
</div>
<?php
$server = "localhost";
$user = "root";
$pass = "";
$db = "pihome_users";
//Database Connection
$conn = mysqli_connect($server, $user, $pass, $db);
//Check Connection
if($conn->error){
die("Connection Failed: "+ $conn.error);
}
if(isset($_POST['user'])){
//echo "Set<br>";
//User Authentication
$inputuser = $conn->escape_string($_POST['user']);
$inputpass = $conn->escape_string($_POST['pass']);
//echo $inputuser."<br>";
//echo $inputpass."<br>";
$sql = 'SELECT * FROM users WHERE username="'.$inputuser.'"';
//echo $sql;
//Execute
$result = $conn->query($sql);
if($conn->error){
echo "Load Error";
}
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
if($inputpass == $row["password"]){
echo '<div class="alert alert-success fade in">
x
Your credentials are correct
</div>';
echo '<script type="text/javascript">
window.location.href = "pihome.php";
</script>';
$_SESSION["Auth"] = "yes";
$_SESSION["User"] = $inputuser;
}else{
echo '<div class="container-fluid"><div class="alert alert-danger fade in">
x
Your username or password is incorrect!
</div></div>';
$_SESSION["Auth"] =false;
//echo "Success";
}
} else {
//echo "Failed";
}
}
else{
//echo "Not Set";
}
?>
</body>
</html>
pihome.php
<!DOCTYPE html>
<html>
<head>
<title>PiHome</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"> </script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"> </script>
<link rel="stylesheet" href="standardstyle.css">
</head>
<body>
<?php
$sessionstate = session_status();
if($sessionstate == 1){
session_start();
echo "Started";
}
?>
<?php
if(isset($_SESSION["Auth"])){
if($_SESSION["Auth"] != "yes"){
echo '<script type="text/javascript">
window.location.href = "index.php";
</script>';
echo "You are logged in as: ".$_SESSION["User"];
}else{
echo "Auth Passed";
$_SESSION["Auth"] = "yes";
}
}else{
echo '<script type="text/javascript">
window.location.href = "index.php";
</script>';
}
?>
<div class="jumbotron">
<h1 class="text-center">PiHome<br/><small>v1.0.0</small></h1>
</div>
<div class="container-fluid">
<div class="well col-3">
<h3 class="text-center">Status</h3>
<div id="status">
</div>
</div>
<script>
function AJAX_JSON_Req( url )
{
var AJAX_req = new XMLHttpRequest();
AJAX_req.open( "GET", url, true );
AJAX_req.setRequestHeader("Content-type", "application/json");
AJAX_req.onreadystatechange = function()
{
if( AJAX_req.readyState == 4 && AJAX_req.status == 200 )
{
var response = JSON.parse( AJAX_req.responseText );
//document.write( response.controls[0].type );
document.getElementById("status").innerHTML = response.controls[0].type + " " + response.controls[0].state;
}
}
AJAX_req.send();
}
AJAX_JSON_Req( 'status.json' );
</script>
Logout
</div>
</body>
<html>
logout.php
<?php
$sessionstate = session_status();
if($sessionstate == 1){
session_start();
echo "Started";
session_unset();
}
else if($sessionstate == 2){
session_destroy();
echo "destroyed";
}
/*echo '<script type="text/javascript">
window.location.href = "index.php";
</script>';*/
?>
I solved this by using session_start() before any output including <!DOCTYPE html> as suggested by rjdown in the comments above.

Categories

Resources