Page doesnt display on browser if i uncomment the session_start() code - php

These are the four pages which include the code for sessions. when i run the sign_up.php page an error comes up stating the page cannot be displayed. So the sessions are giving me an problem. I have included the session code on each page however i believe the problem is in the header(location:........); So any solutions please.
sign_up.php
<?php
//session_start();
//if (!isset($_SESSION["user_login"])) {
// header("Location: sign_up.php");
//} else {
// $username = $_SESSION["user_login"];
//}
?>
<!----------------------------------------------------------------------------------------------------->
<h1> Sign Up </h1>
<hr>
<div class = "user_type">
<form action="sign_up.php" method="POST" enctype="multipart/form-data">
<input type="radio" value="Student" id="radioOne" name="account" checked/>
<label for="radioOne" class="radio" chec>Student </label>
<input type="radio" value="Landlord" id="radioTwo" name="account" />
<label for="radioTwo" class="radio">Landlord</label>
<hr/>
<div class = "gender_options">
<input type="radio" value="Male" id="male" name="gender" checked/>
<label for="male" class="radio" chec>Male</label>
<input type="radio" value="Female" id="female" name="gender" />
<label for="female" class="radio">Female</label>
</div>
<input type="text" name="name" id="name" placeholder="Full Name" required/> <br/><br/>
<input type="email" name="email" id="name" placeholder="Email" pattern="[a-z0-9._%+-]+#aston.ac.uk" required/> <br/><br/>
<input type="text" name="password" id="name" placeholder="Password" required/><br/><br/>
<input type="text" name="password2" id="name" placeholder="Retype Password" required/><br/><br/>
By clicking Sign Up, you agree on our terms and condition. <br/><br/>
<input type="submit" name="submit" value="Sign Up"/>
</form>
</div>
<hr>
<!---- log in code--->
<?php
enter code here
if (isset($_POST["user_login"]) && isset ($_POST["user_pass"])){
// formatting field via reg replace to ensure email and password only conisists of letters and numbers preg_replace('#[^A-Za-z0-9]#i','',
$login_user = $_POST["user_login"];
$login_password = $_POST["user_pass"];
// password is encryted in DB (MD5) therefore user inputted password will not match encryted password in DB - we have to assign new var
$decrypted_password = md5($login_password);
// Query which finds user (if valid) from DB - Achieving authentication via username and password
$user_query = mysqli_query($connect, "SELECT * FROM users WHERE email = '$login_user' AND password = '$decrypted_password' AND closed = 'no' LIMIT 1");
$check_user = mysqli_num_rows($user_query); // checking to see if there is infact a user which those credentials in the DB
if ($check_user==1){
while ($row = mysqli_fetch_array($user_query)){
$id = $row['user_id'];
}
enter code here
// if the user credentials are correct, log the user in:
$_SESSION["user_login"] = $login_user;
header( "Location: profile_student.php" ); // refresh page
exit;
// if user row does not equal 1 ...
//exit;
} else {
echo "<div class='wrong_login'>
<p> Email or password is incorrect, please try again. </p>
</div>";
}
}
?>
<h1> Log In </h1>
<hr>
<div class ="login_form">
<form action="sign_up.php" method="POST">
<input type="text" name="user_login" placeholder="Email" pattern="[a-z0-9._%+-]+#aston.ac.uk" required/><br/><br/>
<input type="text" name="user_pass" placeholder="Password" required/> <br/><br/>
<input type="submit" name="login_submit" value="Log In"/>
</form>
</div>
</div>
home.php
<?php
session_start();
if (!isset($_SESSION["user_login"])) {
header("Location: profile_student.php");
} else {
$username = $_SESSION["user_login"];
}
include ("connect.php");
echo "Hello,";
echo"<br/> Would you like to logout? <a href = 'logout.php'>LogOut</a>";
?>
profile_student.php
This is the page for when the user logs in and this page will allow them to access their information etc.
<?php
session_start();
if (!isset($_SESSION["user_login"])) {
header("Location: sign_up.php");
} else {
$username = $_SESSION["user_login"];
}
include ("includes/connect.php");
?>
logout.php
this is the log out code for my website
<?php
session_start();
session_destroy();
unset($_SESSION);
session_write_close();
header( "Location: ../index.php" );
die;
?>

Instead of doing the session_start in each page, make a common.php file and include this file in all the required pages. Also, you need to make sure there is no white space before session is started, otherwise it would throw the header already sent error!

You are true, the problem is the header.
You are creating an infinite loop saying : you come on sign_up ? If $_SESSION['user_login'] doesnt exist, go to sign_up.
And it repeats over and over again. Because $_SESSION['user_login'] cant exist first time you come on sign_up.
So just do this : on your sign_up page.
<?php
session_start();
And so remove the if / else condition.

Related

How to redirect to another page after login success in php?

login.php
<?php
session_start();
error_reporting(0);
include("config.php");
if(isset($_POST['submit']))
{
$pass= $_POST['password'];
$email= $_POST['email'];
if($email=='' && $pass=='')
{
echo '<p id="red">Wrong Email or Password.</p>';
}
else
{
$query=mysqli_query($con, "select * from `user` where `password`='".$pass."' and `email`='".$email."' and status='1'");
$countRow=mysqli_num_rows($query);
$fetch=mysqli_fetch_array($query);
if($countRow > 0)
{
$_SESSION['user_idd']= $fetch['user_id'];
//$_SESSION['user_idd'];
header('location:index.php');
}
else
{
echo '<p id="red">Wrong Email or Password.</p>';
}
}
}
?>
<form method="POST" id="myforms" autocomplete="off" action="<?php echo $_SERVER['PHP_SELF'];?>">
<input type="text" name="email" value="" placeholder="Enter Your Email" class="form-control">
<input type="password" name="password" value="" placeholder="Enter Your Password" class="form-control">
<input type="submit" name="submit" value="Login" class="btn btn-success">
</form>
index.php
<?php
session_start();
error_reporting(0);
include("config.php");
if(!isset($_SESSION['user_idd']))
{
header("location:login.php");
}
echo "hiii";
?>
I have created simple login as you can see in my login.php file. Now, I want to redirect from login.php to index.php page after success but the problem is when I click on submit button it doesn't redirect me on index.php page it show me same page and when I call index.php in url directly then again it show login.php. I don't know where I am doing wrong? Please help me.
Thank You

Struggling with Admin check on session variable

I have 2 pages. I need on "addproduct.php" to check whether the user is logged in as an admin. I have a login script. Apologies if this is a silly question but im brand new to PHP.
I want a user who reaches this page who is not logged in as an admin ('isadmin' is a row in the user database) to be redirected to the login page, and when someone is logged in as an admin for the page to display.
Login.php;
<?php
session_start();
$un = $_POST["username"];
$pw = $_POST["password"];
$conn = new PDO ("mysql:host=localhost;dbname=assign026;", "assign026",
"ziSietiu");
$results = $conn->query("select * from users where username='$un' and
password='$pw'");
$row = $results->fetch();
if($row == false)
{
echo "Incorrect password!";// There were matching rows
}
else
{
$_SESSION["gatekeeper"] = $un;
$_SESSION["isadmin"] = $row["isadmin"];
header ("Location: index.php");
}
?>
And addproduct.php
<?php
session_start();
?>
<?php
// Test that the authentication session variable exists
if(!isset($_SESSION["isadmin"]) || $row["isadmin"] == 1)
{
header('Location: login.html');
exit();
}
else
{
echo ($_SESSION["isadmin"]);
}
?>
<div>
<h2>Add new product</h2>
<form method="post" action="addproductscript.php">
<p>Insert product here</p>
<input type="text" name="name" placeholder="name">
<input type="text" name="manufacturer" placeholder="manufacturer">
<input type="text" name="description" placeholder="description">
<input type="text" name="price" placeholder="price">
<input type="text" name="stocklevel" placeholder="stocklevel">
<input type="text" name="agelimit" placeholder="agelimit">
<input type="submit" value="Submit">
</form>
</div>
Based on your code if(!isset($_SESSION["isadmin"]) || $row["isadmin"] == 1), the $row["isadmin"] is not defined thus it don't have any value.
What you can do is if(!isset($_SESSION["isadmin"]) || $_SESSION["isadmin"] == 1)

PHP- Login to account to working

its my first time creating a login page.
I want users to login, then the page redirects to the customer account page, if they have a account. I have added echo's so i can see whats happening. I have a "Logged in successfully" alert that works perfectly when i login. The page just does not redirect.
HTML
<section class="container">
<form id="myform " class="Form" method="post" action="login.php" accept-charset="utf-8">
<!-- <div id="first">-->
<input type="email" id="email" name="email" placeholder="Email Address" value='' required>
<input class ="login-field" type="password" id="pass1" name="pass1" value="" placeholder="Password" maxlength="30" required>
<input type="submit" name="login" value="login" class="btn ">
<br>
</form>
PHP
<?php
session_start();
require ('./mysql.inc.php');
?>
<?php
if (isset($_POST['login']))
//database varianbles
$c_email = $_POST['email'];
$c_password = $_POST['pass1'];
// select login details
$sel_c = "SELECT * FROM Cus_Register WHERE Cus_Email='$c_email' AND Cus_Password='$c_password'";
$run_c = mysqli_query($dbc, $sel_c);
//check if customer is on databse
$check_customer = mysqli_num_rows($run_c);
if ($check_customer == 0) {
echo "<script> alert('password or email is incorrect please try again')</script>";
exit();
}
else{
$_SESSION['Cus_Email'] = $c_email;
echo "<script> alert ('Logged in successfully')</script>";
echo "<script>window.open('./customer/Cus_Account.php'.'_self') </script>";
}
?>
You may use header() to redirect
else
{
$_SESSION['Cus_Email'] = $c_email;
header('Location: customer/Cus_Account.php');
exit();
}
hope it helps:)
Do you intend window.open('./customer/Cus_Account.php'.'_self') to be window.open('./customer/Cus_Account.php', '_self')?
window.open takes a location and a target parameter and in JavaScript parameters are separated by a comma, not a full stop. In this case './customer/Cus_Account.php' is the location and '_self' is the target.

PHP/ HTML login alert box issue

So essentially I have this PHP code which is a login system for a webpage not using MySQL but using pre-determined values within the PHP code. I am running php 5.5.3.
The page I have designed is a called access.php. If you enter the pre-defined username and password correctly it takes you through to a user.php page, but if either are incorrect it comes up with an alert box: “Incorrect password or username”
However the problem I am having is that when that alert box comes up it fills the same page (access.php) with grey and the alert box is located within the middle losing all of the initial web page design, and then when you accept the alert box by pressing 'ok' it takes you back to the access.php page design again. I want this alert box to come up over the page I have already designed without losing any of the initial design.
Here is the code for PHP:
<?php
session_start();
if (isset($_POST['username'])) {
// Set variables to represent data from database
$dbUsname = "adminDJ";
$dbPassword = "admin";
$uid = "1111";
// Set the posted data from the form into local variables
$usname = strip_tags($_POST['username']);
$paswd = strip_tags($_POST['password']);
// Check if the username and the password they entered was correct
if ($usname == $dbUsname && $paswd == $dbPassword) {
// Set session
$_SESSION['username'] = $usname;
$_SESSION['id'] = $uid;
// Now direct to users feed
header("Location: user.php");
} else {
print 'incorrect username or password.';
}
}
?>
Here is the HTML markup:
<form id="form" action="access.php" method="post"enctype="multipart/formdata">
<h2>DJ Access</h2>
<div class="lineSpacer"></div>
<p>Username <input type="text" name="username" id="userBox"/></p> <br />
<p>Password <input type="password" name="password" id="passBox"/></p> <br />
<input type="submit" value="Login to DJ Access" name="Submit" id="submit"/>
<div class="lineSpacer"></div>
</form>
Is there any way I can have it so PHP either alerts a box within the same page or uses JavaScript to alert a box?
If the above php code is on th esame page access.php then rather than a print set a variable to then use to display a message:
<?php
session_start();
$error = false;
......
} else {
$error = true;
}
then after the form:
<form id="form" action="access.php" method="post"enctype="multipart/formdata">
<h2>DJ Access</h2>
<div class="lineSpacer"></div>
<p>Username <input type="text" name="username" id="userBox"/></p> <br />
<p>Password <input type="password" name="password" id="passBox"/></p> <br />
<input type="submit" value="Login to DJ Access" name="Submit" id="submit"/>
<div class="lineSpacer"></div>
</form>
<?php if($error){ ?>
<div class="error"> There was an issue with the form")</div>
<?php } ?>
or if you want an alert
<?php if($error){ ?>
<script> alert ("There was an issue with the form")</script>
<?php } ?>
Your code does not seem like it should behave how you are describing it but here is an idea using setTimeout():
access.php
<?php
session_start();
if (isset($_POST['username'])) {
// Set variables to represent data from database
$dbUsname = "adminDJ";
$dbPassword = "admin";
$uid = "1111";
// Set the posted data from the form into local variables
$usname = strip_tags($_POST['username']);
$paswd = strip_tags($_POST['password']);
// Check if the username and the password they entered was correct
if ($usname == $dbUsname && $paswd == $dbPassword) {
// Set session
$_SESSION['username'] = $usname;
$_SESSION['id'] = $uid;
// Now direct to users feed
header("Location: user.php");
} else {
// use a setTimeout to display the alert after 100ms
print 'setTimeout(function(){alert(\'whatever you want\');}, 100)';
}
}
?>
<form id="form" action="access.php" method="post"enctype="multipart/formdata">
<h2>DJ Access</h2>
<div class="lineSpacer"></div>
<p>Username <input type="text" name="username" id="userBox"/></p> <br />
<p>Password <input type="password" name="password" id="passBox"/></p> <br />
<input type="submit" value="Login to DJ Access" name="Submit" id="submit"/>
<div class="lineSpacer"></div>
</form>
Just cut out of the php put in the JS and then open the php agsin. Put this where you want the box to appear in the code
?><script> alert("incorrect details"); window.history.back();</script><?php
This should work. :)

Despite creating a session, when a person navigates to a second page, it acts as though the session never existed

For some reason despite the fact that IsLoggedIn() is checking for the session, it acts as though none exists.
I used this to create the functions
<?php
session_start();
function DoLogin($email, $password)
{
$sql = "
SELECT U.id, password, FirstName, LastName
FROM Users U
Join ContactMethods CM On U.id=CM.User_Id
WHERE CM.`Value` = '$email'
";
$conn = getConnection();
$result = $conn->query($sql);
//echo $conn->error;
$rs = $result->fetch_assoc();
$conn->close();
if($rs['password'] == $password)
{
$_SESSION['UserId'] = $rs['id'];
$_SESSION['UserEmail'] = $email;
$_SESSION['UserName'] = $rs['FirstName'] . ' ' . $rs['LastName'];
}
}
function IsLoggedIn()
{
return isset($_SESSION['UserId']);
}
and this on top of pages
require_once('inc/loginauth.php'); // calls the script with the functions listed above
if(isset($_REQUEST['email']))
DoLogin($_REQUEST['email'],$_REQUEST['password']);
?>
and this for the login piece on each page
<?php
session_start();
if(IsLoggedIn()){ ?>
<h2>Welome <?=GetUserName()?>!</h2>
<p class="grey">Would You Like to Log Out?</p>
<p class="grey">Log Out</p>
</div>
<div class="left">
<!-- Login Form --><? }else{ ?>
<form method="post">
<label class="grey" for="email">Email:</label>
<input class="field" type="email" name="email" />
<label class="grey" for="password">Password:</label>
<input class="field" type="password" name="password" />
<input type="submit" class="bt_login" value="Log In" />
</form>
<? } ?>
Put session_start(); at the beginning of the second script (if the session is not started automatically)
Try var_dump($_SESSION); in the second script to see what you have in the session.
Don't use short open PHP tags <? ?>. They are deprecated. Use full tags <?php ?>
Try putting the session start within the php function.
also the start and end delimiters are <?php if(IsLoggedIn()){ ?>

Categories