I've got an if statement to check if a variable within the $_SESSION is active and set, and if it is then a message is returned to the user. Here's my header.php:
<?php
$conn = HIDDEN;
session_start();
$username = '';
$_SESSION['username'] = $username;
?>
<header>
<!DOCTYPE html>
<link rel="stylesheet" type="text/css" href="style/main.css">
<title>webshop</title>
</header>
<div id="LogIn">
<?php
if (isset($_SESSION['username']))
{
echo "its working";
} else {
?><form class="form1" method="post" action="" id="form1">
<fieldset>
<ul>
<p>Please enter your username to continue to the webshop.</p>
<label for="name">User Name:</label><span><input type="text" name="username" placeholder="User Name" class="required" role="input" aria-required="true"/></span>
<input class="submit .transparentButton" value="Next" type="submit" name="Submit"/>
</ul>
<br/>
</fieldset>
</form>
<?php } ?>
</div>
<?php
if (isset($_POST['Submit'])) {
$_SESSION['username'] = $_POST['username'];
}
?>
<?php
if (isset($_POST['Submit'])) {
$_SESSION['username'] = $_POST['username'];
// Use the following code to print out the variables.
echo 'Session: '.$_SESSION['username'];
echo '<br>';
echo 'POST: '.$_POST['username'];
}
?>
The first time running, or before the user logs out (to be implemented later), the site should prompt for a username to be entered and then upon refreshing the page the welcome message should be display.
As of right now the code simply returns "it's working" despite no variable in $username existing. The code:
<?php
if (isset($_POST['Submit'])) {
$_SESSION['username'] = $_POST['username'];
// Use the following code to print out the variables.
echo 'Session: '.$_SESSION['username'];
echo '<br>';
echo 'POST: '.$_POST['username'];
}
?>
should print out the variable underneath the welcome message, or nothing at all if it's empty. As of right now, the welcome message "it's working" is displayed always but no variables are in $username. Can anyone tell me why?
Thanks in advance.
$_SESSION['username'] is SET/NULL but is EMPTY you should try !empty() instead if isset(). See below.
<?php
if (!empty($_SESSION['username']))
{
echo "its working";
} else {
?><form class="form1" method="post" action="" id="form1">
<fieldset>
<ul>
<p>Please enter your username to continue to the webshop.</p>
<label for="name">User Name:</label><span><input type="text" name="username" placeholder="User Name" class="required" role="input" aria-required="true"/></span>
<input class="submit .transparentButton" value="Next" type="submit" name="Submit"/>
</ul>
<br/>
</fieldset>
</form>
<?php } ?>
EDIT 2
As to the comment.
IF statement needed to tell if there was a submit if there was don't display the form else display the form. See below Code
<?php
$conn = ""; //HIDDEN kept throwing error whilst I was testing
session_start();
$username = '';
$_SESSION['username'] = $username;
?>
<header>
<!DOCTYPE html>
<link rel="stylesheet" type="text/css" href="style/main.css">
<title>webshop</title>
</header>
<div id="LogIn">
<?php
if (isset($_POST['Submit'])) {
$_SESSION['username'] = $_POST['username'];
$_SESSION['username'] = $_POST['username'];
// Use the following code to print out the variables.
echo 'Session: '.$_SESSION['username'];
echo '<br>';
echo 'POST: '.$_POST['username'];
} else {
if (!empty($_SESSION['username']))
{
echo "its working";
} else {
?><form class="form1" method="post" action="<?php echo $_SERVER['PHP_SELF']?>" id="form1">
<fieldset>
<ul>
<p>Please enter your username to continue to the webshop.</p>
<label for="name">User Name:</label><span><input type="text" name="username" placeholder="User Name" class="required" role="input" aria-required="true"/></span>
<input class="submit transparentButton" value="Next" type="submit" name="Submit"/> //removed css selector .
</ul>
<br/>
</fieldset>
</form>
<?php } } ?>
</div>
The isset() checks only whether the variable is set or not and it returns true since it is initialized to null string. Here you have to use !empty().
if (isset($_SESSION['username']) && !empty($_SESSION['username'])) {
}
Just a quick solution is to change
if (isset($_SESSION['username']))
to
if (strlen($_SESSION['username']) > 0)
That will work. Im guessing it because technically u did set username so it isset but if u check the length u know its not empty
Related
I don't understand the thing with sessions in php. It says that after you start a session, the session variable are stored and can be seen in multiple pages.But in my pages that are not seen. For example I have my index.php page where I start the session_start(). Then I click a button to login and if everything is ok it should redirect me to profile.php page where I print the session email. But it doesn't recognize my session variable.My code:
if($_POST['actiune'] == 'login'){
$email = $_POST['email'];
$_SESSION['username'] = $email;
$password = $_POST['password'];
$pass = getPassword($email);
$verify = password_verify($password, $pass);
if ($verify) {
header("Location: index.php?page=profile");
}
else {
header("Location: index.php?page=login&msg=PleaseRegister");
}
}
profile.php
echo $_SESSION['username'] ; die();
Any help?
UPDATE:
profile.php
<?php
session_start();
echo $_SESSION['username'] ;
?>
<div id="profile">
<p id="welcome">Welcome :<?php echo $_SESSION['username']; ?></p>
<?php
if ($_SESSION['avatar'] == ""){
?>
<img src = "http://placehold.it/400x200/0000ff/&text=Upload a picture" alt =""/>
<?php
}
else if ($_SESSION['avatar'] != ""){
?>
<img src="avatars/<?php echo $user['file'];?>">
<?php
}
?>
<p id="modifyPf"> Modify</p>
<p id="reset"> Reset password</p>
<p id="articlePf"> Article page</p>
<form action="action.scripts.php" method="POST" enctype="multipart/form-data">
<input type="hidden" name="actiune" value="avatar">
<input type="hidden" name="id" value="<?php echo $user['id'];?>">
<p><label for="avatar">Upload an avatar:</label></p>
<p><input type="file" name="avatar" id="fileToUpload"></p>
<p><input id ="button" class="btn btn-primary" type="submit" name="button" value="Send"/></p>
</form>
You need to call session_start(); in profile.php also.
session_start() creates a session or resumes the current one based on
a session identifier passed via a GET or POST request, or passed via a
cookie.
Update
<?php
if(!isset($_SESSION))
{
session_start();
}
if (isset($_SESSION['username'])){
?>
<div id="profile">
<p id="welcome">Welcome :<?php echo $_SESSION['username']; ?></p>
<?php if ($_SESSION['avatar'] == ""){ ?>
<img src = "http://placehold.it/400x200/0000ff/&text=Upload a picture" alt =""/>
<?php
}
else if ($_SESSION['avatar'] != ""){
?>
<img src="avatars/<?php echo $user['file'];?>">
<?php
}
?>
<p id="modifyPf"> Modify</p>
<p id="reset"> Reset password</p>
<p id="articlePf"> Article page</p>
<form action="action.scripts.php" method="POST" enctype="multipart/form-data">
<input type="hidden" name="actiune" value="avatar">
<input type="hidden" name="id" value="<?php echo $user['id'];?>">
<p><label for="avatar">Upload an avatar:</label></p>
<p><input type="file" name="avatar" id="fileToUpload"></p>
<p><input id ="button" class="btn btn-primary" type="submit" name="button" value="Send"/></p>
</form>
</div>
<?php
}
else {
echo '<pre>';
var_dump($_SESSION);
echo '</pre>';
}
?>
Index.php
<?php
session_start();
if($_POST['actiune'] == 'login'){
$email = $_POST['email'];
$_SESSION['username'] = $email;
$password = $_POST['password'];
$pass = getPassword($email);
$verify = password_verify($password, $pass);
if ($verify) {
header("Location: index.php?page=profile");
}
else {
header("Location: index.php?page=login&msg=PleaseRegister");
}
}
else {
echo 'POST actiune is not login';
}
?>
You need session_start() at the top of every page request - exactly one time per request. It doesn't just create the session; it's required for every request in which you want to use the session. From the docs:
session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.
I have tried all methods but still am not seeing a redirect to index.php as expected.
I also added ob_start() but it doesn't work. Then I tried header('location:...'). It also didn't work. Then I tried to redirect using JavaScript but that also didn't work.
Any suggestions ??
<html>
<head>
<link rel ="stylesheet" href=css/style.css>
</head>
<body>
<?php
ob_start();
require('dbconnect.php');
require('loginservice.php');
session_start();
//if my form is submitted
if(isset($_POST['submit']))
{
$username=$_POST['username'];
$password=$_POST['password'];
$query1= userIdentity($username,$password);
echo 'returning value deisplay';
echo '\n' .$query1 . '\n';
echo 'i am here';
if($query1==1){
//echo 'welcome dude';
$_SESSION['username'] = $username;
// Redirect user to index.php
//echo "<script type='text/javascript'> window.location='index.php'; </script>";
// header("Location: index.php");
//e//cho 'heeeelo';
echo "<script type='text/javascript'>window.location.href = 'index.php'; </script>";
ob_flush();
exit(0);
}
// header("Location: index.php");
else
{
echo " <div class='form'>
<h3>Username/password is incorrent.</h3>
<br/>click here to <a href='login.php'>Login</a></div>";
}
//header("Location: index.php");
}
else {
?>
<div class="form">
<h1>Log In</h1>
<form action="" method='post' name="login">
<input type ="text" name="username" placeholder="username" required />
<input type="password" name="password" placeholder="password" required />
<input name="submit" type="submit" value="login" />
</form>
<p> Not registered yet ? <a href='register.php'>Register Here </a> </p>
</div>
<?php
}
?>
</body>
</html>
Per the PHP manual page for header():
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP.
So move the PHP code above the starting HTML tags, like the example below. I created a variable to hold the message in case the login attempt fails (i.e. $message). Notice how it is set it to a blank message initially (for good scope) and then set when appropriate. Then it is added to the form down below.
Edit:
You can see this demonstrated in this phpFiddle. Try logging in with any username. If you enter the password pw, then you should be taken to index.php, which on that page display an image with the text phpfiddle.org. Also, I removed the HTML from the else block, so it will always show the form (and insert the login failure message if it is set), though you might want to have it not show the form again if the login fails...
<?php
ob_start();
require('dbconnect.php');
require('loginservice.php');
session_start();
$message = ''; //initialize to empty, for good scope
//if my form is submitted
if(isset($_POST['submit']))
{
$username=$_POST['username'];
$password=$_POST['password'];
$query1= userIdentity($username,$password);
if($query1==1){
$_SESSION['username'] = $username;
// Redirect user to index.php</script>";
header("Location: index.php");
//...
}//else:
else {
$message = "<div class='form'><h3>Username/password is incorrect.</h3>
<br />click here to <a href='login.php'>Login</a></div>";
}
?>
<html>
<head>
<!-- the rest of the HTML content -->
and in the body, append that incorrect message if it is defined, e.g.:
<div class="form"><?php echo $message; ?>
<h1>Log In</h1><!-- rest of the HTML for the form-->
Instead of having the html <html><head><body> tags before your php code, have the php code before these and use the header function. Here is the working new version:
<?php
ob_start();
require('dbconnect.php');
require('loginservice.php');
session_start();
//if my form is submitted
if(isset($_POST['submit']))
{
$username=$_POST['username'];
$password=$_POST['password'];
$query1= userIdentity($username,$password);
echo 'returning value deisplay';
echo '\n' .$query1 . '\n';
echo 'i am here';
if($query1==1){
//echo 'welcome dude';
$_SESSION['username'] = $username;
// Redirect user to index.php
//echo "<script type='text/javascript'> window.location='index.php'; </script>";
// header("Location: index.php");
//e//cho 'heeeelo';
header("Location: index.php);
ob_flush();
exit(0);
}
// header("Location: index.php");
else
{
echo " <div class='form'>
<h3>Username/password is incorrent.</h3>
<br/>click here to <a href='login.php'>Login</a></div>";
}
//header("Location: index.php");
}
else {
?>
<html>
<head>
<link rel ="stylesheet" href=css/style.css>
</head>
<body>
<div class="form">
<h1>Log In</h1>
<form action="" method='post' name="login">
<input type ="text" name="username" placeholder="username" required />
<input type="password" name="password" placeholder="password" required />
<input name="submit" type="submit" value="login" />
</form>
<p> Not registered yet ? <a href='register.php'>Register Here </a> </p>
</div>
<?php
}
?>
</body>
</html>
but some how the page is not showing any error message. also it is not redirecting to the page where i want to redirect it after successful login. i want the login page to be redirected at home page and show the message and when the logout link is clicked the page again come back to the login page
<?php
session_start();
error_reporting(E_ALL ^ E_NOTICE);
?>
<?php
if($_REQUEST["logout"]=='yes'){
unset($_SESSION["login"]);
}
?>
<html>
<body>
<form action="" method="post">
<label>Username</label><input type="text" name="unametxt" value="<?php echo $_post["unametxt"]; ?>" />
<label>Password</label><input type="password" value="<?php echo $_post["password"]; ?>" />
<input type="submit" name="sbt" value="Login">
</form>
<?php
if(isset($_post["sbt"]))
{
if($_post["unametxt"]== "debarun" && $_post["password"]=="1234")
{
$_SESSION["login"]="yes";
$_SESSION["uname"]=$_post["unametxt"];
$_SESSION["passwd"]=$_post["password"];
header('location:home.php');
}
else
{
echo "Please enter correct credentials";
}
}
?>
</body>
</html>
and it is my home page script:
<?php
session_start();
if(!isset($_SESSION["login"])){
session_destroy();
header('location:login.php');
}
else{
echo "Welcome".$_SESSION["uname"]."<br/>"."your password is".$_SESSION["passwd"];
}
?>
<html>
<body>
<form action="" method="post">
Logout
</form>
</body>
</html>
please
tell me why it is not working??
Add name attribute in your password element. Because of this, it cannot fetch from $_POST array and your condition will always fail.
Try this,
<label>Password</label><input type="password" name="password" value="<?php echo $_post["password"]; ?>" />
First thing $_post must be up letter case like this $_POST then you forgot to specify name="password" to password input field
take a look
<?php
session_start();
error_reporting(E_ALL ^ E_NOTICE);
?>
<?php
if($_REQUEST["logout"]=='yes'){
unset($_SESSION["login"]);
}
?>
<html>
<body>
<form action="" method="post">
<label>Username</label><input type="text" name="unametxt" value="<?php echo $_POST["unametxt"]; ?>" />
<label>Password</label><input type="password" name="password" value="<?php echo $_POST["password"]; ?>" />
<input type="submit" name="sbt" value="Login">
</form>
<?php
if(isset($_POST["sbt"]))
{
echo $_POST["password"];
if($_POST["unametxt"] == "debarun" and $_POST["password"] == "1234")
{
$_SESSION["login"]="yes";
$_SESSION["uname"]=$_POST["unametxt"];
$_SESSION["passwd"]=$_POST["password"];
header('location:home.php');
}
else
{
echo "Please enter correct credentials";
}
}
?>
</body>
</html>
Put all those validation code at the top. Nothing should be sent to the browser before redirecting. Not even an empty line.
Also, make the L in location capital
header("Location: home.php");
I am new using PHP and I am trying to build a content management site.
I started developing the login pages and at the start the SESSION variables were kept as normal and were working without any issues when using redirect to another page after login was confirmed.
But 2 days ago i tried to develop the forgot password functionality as well and since then and by only changing the output buffering which i just enabled I have an issue.
The SESSION variables are not carried over to the redirected page and thus the login doesn't work.
My code is below:
<?php include("../includes/session.php"); ?>
<?php require_once("../includes/db_connection.php"); ?>
<?php require_once("../includes/functions.php"); ?>
<?php require_once("../includes/validation_functions.php"); ?>
<?php
$username = "";
if (isset($_POST['submit'])) {
// Process the form
// validations
$required_fields = array("username", "password");
validate_presences($required_fields);
if (empty($errors)) {
// Attempt Login
$username = $_POST["username"];
$password = $_POST["password"];
$found_admin = attempt_login($username, $password);
//print_r($found_admin);
if ($found_admin) {
// Success
// Mark user as logged in
$_SESSION["admin_id"] = $found_admin["usr_serno"];
$_SESSION["username"] = $found_admin["username"];
redirect_to("admin.php");
} else {
// Failure
$_SESSION["message"] = "Username/password not found.";
}
}
}else if(isset($_POST['forgot'])) {
redirect_to("forgotPassword.php");
}
?>
<?php $layout_context = "admin"; ?>
<?php include("../includes/layouts/header.php"); ?>
<div id="main">
<div id="navigation">
</div>
<div id="page">
<?php echo message(); ?>
<?php echo form_errors($errors); ?>
<h2>Login</h2>
<form action="login.php" method="post">
<p>Username:
<input type="text" name="username" value="<?php echo htmlentities($username); ?>" />
</p>
<p>Password:
<input type="password" name="password" value="" />
</p>
<input type="submit" name="submit" value="Submit" />
<input type="submit" name="forgot" value="Forgot Password" />
</form>
</div>
</div>
<?php include("../includes/layouts/footer.php"); ?>
the session.php starts the session
and the admin.php will just check if the SESSION[admin_id] isset then it will show the page or else it will redirect again to login.php page, which is what happens.
Any advise or help please?
Trying to redirect a user to index.php after they login successfully. I have everything working except the redirect. Been looking around for about an hour now and no luck..I'm sure it is tied to jQueryMobile owning the page
Have tried
header('Location: index.php');
nothing happens.
Also tried
echo '<script type="text/javascript">$.mobile.changePage($(\'index.php\'), {transition : "slide"});</script>';
Both do a re-direct if I make them the first part of my php code, but when placed where I need it they do nothing.
Here is my code:
<?php include "layouts/header.php";
if (isset($_POST['submit'])) { // Form has been submitted.
$username = trim($_POST['username']);
$password = trim($_POST['password']);
// Check database to see if username/password exist.
$hashpass = sha1($password);
$found_user = User::authenticate($username, $hashpass);
if ($found_user) {
$session->login($found_user);
$message = "Logged in";
// Redirect to index.php ********
} else {
// username/password combo not found
$message = "Username/password combination incorrect.";
$forgotdisplay = "visible";
}
} else { // Form was not been submitted.
$username = "";
$password = "";
}
?>
</head>
<body>
<div data-role="page" id="loginForm">
<div data-role="header">
<h1>Assessment</h1>
</div>
<div data-role="content" class="centerContent">
<h2>Login</h2>
<p><?php echo output_message($message); ?></p>
<form action="login.php" method="post" data-ajax="false">
<table>
<input type="text" id="username" name="username" maxlength="50" placeholder="username" value="<?php echo htmlentities($username); ?>" />
<input type="password" id="password" name="password" maxlength="30" placeholder="password" value="<?php echo htmlentities($password); ?>" />
<input type="submit" name="submit" value="Login" />
</form>
Sign Up
Forgot Your Password?
<p id="validate-status"></p>
</div>
</div>
</body>
</html>
When valid credentials are submitted the $message does correctly change to "Logged in" so I know that I am getting that far in the script. Have also tried with data-ajax="false" and "true"
Hello you may want to put the full domain in there. I had this problem too
header('location: www.yourdomain.com/index.php');
I believe that should do the trick