Setting Session Variables and Calling them on Another Page - php

I salute you all for your previous help.
Would anyone imagine this very simple error, which has put me down for a couple of hours.
From the Login Page, I compare (authenticate) the login username and password with the database values. If they match, I store them in session variables and redirect to the dashboard page.
Before redirection, I print_r ($_SESSION) to see whether the variables are set or not. They output was TRUE (session is set).
But on the dashboard, calling the session variables returned session !set.
Please check the following code.
[LOGIN PAGE]
<?php
session_start();
require_once('../data/conString_mysqli.php');
$uNameErr = $pWordErr = "";
$uName = $pWord = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//*************************************
if (!empty($_POST["username"])) {
$uName = test_input($_POST["username"]);
} else {
$uNameErr = "Email is required!";
// check if e-mail address is well-formed
if (!filter_var($uName, FILTER_VALIDATE_EMAIL)) {
$uNameErr = "Invalid email format";
}
}
if (!empty($_POST["password"])) {
$pWord = test_input($_POST["password"]);
$hashed = md5($pWord);
} else {
$pWord1Err = "Password is Required!";
if ($pWord < 8) {
$pWordErr = "Invalid Password.";
}
}
}//end if... IS_POST
function test_input($data) {
//require connection file
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}//end function
?>
<?php
if (!empty($uName) && !empty($pWord)){
$hashed = md5($pWord);
$read_data = mysqli_query($connect, "SELECT * FROM service_providers WHERE activated='1' AND ppword ='".$hashed."' AND pemail='".$uName."'") or die(mysqli_error());
$count = mysqli_num_rows($read_data);
if($count >= 1){/*echo '<script type="text/javascript">alert("Records Found!");</script>';*/
//store session variables
$row = mysqli_fetch_array($read_data);
$_SESSION[ 'serv_pid' ] = $row[ 'serv_pid' ];
$_SESSION[ 'providerName' ] = $row[ 'pname' ];
echo '<script type="text/javascript">alert("Session Name: '.$_SESSION['providerName']." - Session ID: ". $_SESSION['serv_pid'].'");window.location="../dashboard/";</script>';
/*echo "<pre>";
print_r ($_SESSION);
echo "</pre>";
*/
}else{echo '<script type="text/javascript">alert("Invalid Login Details");window.location="../login/";</script>';
}
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" style="margin-top: 1.5em;">
<div class="form-group">
<div class="input-group">
<input type="text" name="username" class="form-control text-center" placeholder="username (your email)" value="<?php echo $uName;?>"><span class="error"> <?php echo $uNameErr;?></span>
<span class="input-group-addon btn btn-warning" style="background: #f0ad4e; color: #fff;">
<span class="glyphicon glyphicon-user" style="margin: 0;"></span>
</span>
</div>
</div>
<div class="form-group">
<div class="input-group">
<input type="password" name="password" class="form-control text-center" placeholder="password" value="<?php echo $pWord;?>"><span class="error"> <?php echo $pWordErr;?></span>
<span class="input-group-addon btn btn-warning" style="background: #f0ad4e; color: #fff;">
<span class="glyphicon glyphicon-lock" style="margin: 0;"></span>
</span>
</div>
</div>
<p style="font-size: 16px !important;"><a style="color: #fff; text-decoration: none; margin-top: 2em; display: block;" href="../sign-up/">Don't have an Account? <u>Get one!</u></a> <span style="color:#FF0000; font-weight:bold; text-decoration:underline;"><em>Forgot your password?</em></span></p>
<div class="col-md-6 col-md-offset-3 text-center" style="margin-top: 5px;">
<button type="submit" name="login" class="btn btn-warning btn-lg btn-custom" style="margin-right: 1em; border-width: 3px;">LOGIN</button>
SIGN UP
</div>
<div class="clearfix"></div>
</form>
[DASHBOARD PAGE]
<?php
session_start();
echo "<pre>";
print_r ($_SESSION);
echo "</pre>";
/*
if (!isset($_SESSION['serv_pid'])){// or !isset($_SESSION['providerName'])){
die('<script type="text/javascript">alert("You do not have permission to access beyond the previous page.");window.location="../login/";</script>');
}else{
$serv_pid = $_SESSION['serv_pid'];
$pName = $_SESSION['providerName'];
}*/
?>
From the Login Page, the result returned by print_r is:
Array
(
[serv_pid] => 1
[providerName] => No Name
)
But on getting to the login page, it's like the session is destroyed.
The result returned by print_r is:
Array
(
)
Please help me with any ideas.
Thank you in advance.

When you start a session in PHP, it sets a session cookie, that's sent to the browser when you print the first character outside php brackets or at your first echo.
I think the problem is when you try to redirect the user to the dashboard page. You're setting the session, writing to the browser a script that redirects to another page, but in the meanwhile the server doesn't stop the processing on the page.
Try replacing the echo "<script>..." with a header("Location: dashboard.php") in PHP, followed by a exit(0); instruction.
The first one actually tells the browser to redirect to the dashboard.php page (or whatever the page is), the second tells the browser to stop executing the page.
Moreover, delete the blank row between ?> and <?php brackets. That row actually sends the headers to the browser, along with cookies, even if it's a blank character.

There were excess session_start() functions on the landing page and on the sending page. Each session_start() cancelled the other and the variables were destroyed before getting to the landing page.
However, I had to drop the entire pages and recreate them one line at a time. So, it's working now.
I really want to appreciate Marco Todisco, who also contributed suggestive responses to assisting me on my coding.

Related

Data not saving in session variable

The data is not storing in session everything is working fine the login system all things but the Data like username user pass and user Id should be saved in session but it's not I know it because if it was saving when you login successfully it should show welcome {username}.
Proceed to forums the main page but it is not showing username it was showing before but I got to problems and when all problems fixed this error came out.
Code:
<style>
<?php include 'signin.css'; ?>
</style>
<script type="text/javascript" src="signup.js"></script>
<?php
//signin.php
include 'connect.php';
include 'header.php';
//first, check if the user is already signed in. If that is the case, there is no need to display this page
if(isset($_SESSION['signed_in']) && $_SESSION['signed_in'] == true)
{
echo 'You are already signed in, you can sign out if you want.';
}
else
{
if($_SERVER['REQUEST_METHOD'] != 'POST')
{
/*the form hasn't been posted yet, display it
note that the action="" will cause the form to post to the same page it is on */
echo '<form action="" method="post" >
<div class="all" >
<div class="container" >
<div class="first" >
<h2>SIGN IN</h2>
</div>
<div class="user" >
<input class="use" type="text" placeholder="Username" id="username" name="user_name" required>
</div>
<div class="userimg" >
<img src="user.png" style="height:2em;width:2em;" >
</div>
<div class="pass" >
<input type="password" placeholder="Password" id="password" name="user_pass" minlength="8" required >
<img src="lock.png" >
</div>
<div class="show">
<img src="visible.png" id="visible" class="visible" onclick="myFunction()">
<img src="invisible.png" id="invisible" class="invisible" onclick="mynot()" >
</div>
<div class="check" >
<input type="checkbox" required >
</div>
<div class="box" >
<p>I accept all <a href="#" >terms</a> and <a href="#" >privacy</a>.</p>
</div>
<div class="submit" >
<input type="submit" name="submit" onclick="submit()" value="Sign in">
</div>
<div class="close" >
<input type="button" value="Back" >
</div>
<div class="log" >
dont have an account? <a href="#" >Login</a>
</div>
<div class="organic" >
<img src="logo.png" class="organicpe" >
</div>
<div>
<h2 class="back" ><a href="#" >Go Back</a></h2>
</div>
</div>
</div>
</form>';
}
else
{
/* so, the form has been posted, we'll process the data in three steps:
1. Check the data
2. Let the user refill the wrong fields (if necessary)
3. Verify if the data is correct and return the correct response
*/
$errors = array(); /* declare the array for later use */
if(!isset($_POST['user_name']))
{
$errors[] = 'The username field must not be empty.';
}
if(!isset($_POST['user_pass']))
{
$errors[] = 'The password field must not be empty.';
}
if(!empty($errors)) /*check for an empty array, if there are errors, they're in this array (note the ! operator)*/
{
echo 'Uh-oh.. a couple of fields are not filled in correctly..';
echo '<ul>';
foreach($errors as $key => $value) /* walk through the array so all the errors get displayed */
{
echo '<li>' . $value . '</li>'; /* this generates a nice error list */
}
echo '</ul>';
}
else
{
//the form has been posted without errors, so save it
//notice the use of mysql_real_escape_string, keep everything safe!
//also notice the sha1 function which hashes the password
$sql = "SELECT
user_id,
user_name,
user_level
FROM
Users
WHERE
user_name = '" . mysql_real_escape_string($_POST['user_name']) . "'
AND
user_pass = '" . sha1($_POST['user_pass']) . "'";
$result = mysqli_query($conn,$sql);
if(!$result)
{
//something went wrong, display the error
echo 'Something went wrong while signing in. Please try again later.';
//echo mysql_error(); //debugging purposes, uncomment when needed
}
else
{
//the query was successfully executed, there are 2 possibilities
//1. the query returned data, the user can be signed in
//2. the query returned an empty result set, the credentials were wrong
if(mysqli_num_rows($result) == 0)
{
echo 'You have supplied a wrong user/password combination. Please try again.';
}
else
{
while ($row = $result -> fetch_row())
session_start();
//set the $_SESSION['signed_in'] variable to TRUE
$_SESSION['signed_in'] = true;
//we also put the user_id and user_name values in the $_SESSION, so we can use it at various pages
{
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['user_name'] = $row['user_name'];
$_SESSION['user_level'] = $row['user_level'];
}
while ($row = mysqli_fetch_array($result)) {
//set the $_SESSION['signed_in'] variable to TRUE
$_SESSION['signed_in'] = true;
//we also put the user_id and user_name values in the $_SESSION, so we can use it at various pages
while($row = mysqli_fetch_assoc($result))
{
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['user_name'] = $row['user_name'];
}
}
echo '<h3>Welcome, ' . $_SESSION['user_name'] . '. Proceed to the forum overview.</h1>';
}
}
}
}
}
include 'footer.php';
?>
You need to start every php file use session with
session_start();

Setting up a logout link properly

Currently working a little Sign-Up/Login system with PHP. Here is the situation:
I have this first page named "signup.php" for signing up and logging in. Once you submit your form, you are redirected to a second page called "diary.php". Once you click the submit button, a session is created respectively with your id within the "users" database. Without the diary.php, there's a logout link.
If you signed up or logged in and you are now viewing diary.php, you cannot view the signup.php page unless you press logout. Once you press logout, you are redirected to the signup.php page, but with a logout variable in the $_GET array.
<a href='signup.php?logout=1'>Logout</a>
I'm using this logout variable to check the moment there is a "logout" key exists in $_GET array, it destroys the session and redirects me back to the signup.php page.
Now here is the problem. Say I signed up for a new account, then logged out. Once I log out there's going to be a "logout" key within the GET, right? (to destroy session). If I try to sign up for another account, it actually is going to sign up me (on the database), but it automatically logs out for me since I had the logout key in my link and also because there was no session (I have in my code few lines that automatically take you back to signup.php if there is no session).
I hope that was enough to make it clear for you all. I'm going to leave the code for my two pages for you to examine. Thank you!
signup.php
session_start();
$conn = mysqli_connect("localhost","root","","diary");
$error = '';
$success = '';
if (array_key_exists("submit",$_POST)) {
if (!$_POST['email']) {
$error.= "Email field is missing.<br>";
}
if (!$_POST["password"]) {
$error .= "Password field is missing.<br>";
}
if ($error != '') {
$error = "Fill in the missing field(s):<br>".$error;
}
else if ($_POST["submit"] == "Sign up") {
$email = $_POST["email"];
$query = "SELECT * FROM users WHERE email = '$email';";
$result = mysqli_query($conn,$query);
if (mysqli_num_rows($result) != 0) {
$error .= "This account already exists!";
} else {
$email = $_POST["email"];
$password = $_POST["password"];
$query1 = "INSERT INTO users (email,password) VALUES ('$email','$password');";
mysqli_query($conn,$query1);
$success.= "Successfully signed up!";
$query = "SELECT id FROM users WHERE email = '$email';";
$row = mysqli_fetch_array(mysqli_query($conn,$query));
$id=$row["id"];
$_SESSION["id"] = $id;
header("Location: diary.php");
if (!isset($_POST["signUpRemember"])) {
} else {
setcookie("id",$id,time() + 60*60*24*30);
}
}
} else if ($_POST["submit"] == "Login") {
$email = $_POST["email"];
$password = $_POST["password"];
$query = "SELECT * FROM users WHERE email = '$email';";
if (mysqli_num_rows(mysqli_query($conn,$query)) == 0) {
$error.= "This account does not exist, sign up for a new account!";
} else {
$query = "SELECT password FROM users WHERE email = '$email';";
$rows = mysqli_fetch_array(mysqli_query($conn,$query));
if ($password != $rows["password"]) {
$error.= "You have inserted the wrong password for this account. Please, try again!";
} else {
$query = "SELECT id FROM users WHERE email = '$email';";
$rows = mysqli_fetch_array(mysqli_query($conn,$query));
$_SESSION["id"] = $rows["id"];
if (!isset($_POST["signUpRemember"])) {
} else {
setcookie("id",$rows["id"],time() + 60*60*24*30);
}
header("Location :diary.php");
}
}
}
}
if (array_key_exists("logout",$_GET)) {
unset($_SESSION["id"]);
setcookie("id","",time() - 60*600);
}
if (array_key_exists("id",$_SESSION)) {
header("Location: diary.php");
}
?>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js" integrity="sha384-o+RDsa0aLu++PJvFqy8fFScvbHFLtbvScb8AjopnFD+iEQ7wo/CG0xlczd+2O/em" crossorigin="anonymous"></script>
<title>Secret Diary</title>
<style>
body {
margin:0;
height: 0;
}
#error {
background-color: red;
}
body {
background-image: url("img/bg.jpg");
background-color: #cccccc;
}
#containerLogin {
margin: auto;
width: 30%;
padding: 10px;
margin-top: 5%;
}
#containerSignup {
margin: auto;
width: 30%;
padding: 10px;
margin-top: 5%;
}
.switchBtt {
margin-top: 5%;
width: 70%;
}
.display-4 {
font-weight: 300;
}
</style>
</head>
<body>
<div id="error"><?php if ($error != "") { echo $error; } else { echo "<script>$( '#error' ).css('background-color', 'green');</script>"; echo $success;} ?></div>
<div id="containerLogin">
<center><h1 class="display-4 text-muted "><font color="#6D3E6C">Secret Diary</font></h1>
<br>
<h5 class=" text-muted "><font color="#DFD2CA">Welcome back!</font></h5>
<br>
<form method="post" name="signup">
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" name="email" aria-describedby="emailHelp" placeholder="Enter email">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" name="password" placeholder="Password">
</div>
<div class="form-group form-check ">
<input type="checkbox" class="form-check-input" value="checked" name="signUpRemember">
<label class="form-check-label" for="signUpRemember">Keep me signed in</label>
</div>
<input class="btn btn-primary" type="submit" value="Login" name="submit">
</form>
<div class="btn btn-secondary switchBtt">Switch to sign-up panel ↹ </div>
</center>
</div>
<div id="containerSignup">
<center><h1 class="display-4 text-muted "><font color="#6D3E6C">Secret Diary</font></h1>
<br>
<h5 class="text-muted "><font color="#DFD2CA">Sign up today, for free!</font></h5>
<br>
<form method="post" name="signup">
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" name="email" aria-describedby="emailHelp" placeholder="Enter email">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" name="password" placeholder="Password">
</div>
<div class="form-group form-check ">s
<input type="checkbox" class="form-check-input" value="checked "name="LoginRemember">
<label class="form-check-label" for="LoginRemember">Keep me signed in</label>
</div>
<input class="btn btn-primary" type="submit" value="Sign up" name="submit">
</form>
<div class="btn btn-secondary switchBtt">Switch to login panel ↹ </div>
</center>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
</body>
<script>
$("#containerLogin").hide();
$(".switchBtt").click (function () {
$("#containerLogin").toggle();
$("#containerSignup").toggle();
});
</script>
</html>
diary.php
session_start();
if (array_key_exists("id",$_SESSION)) {
echo "<p>Logged In! <a href='signup.php?logout=1'>Logout</a></p>";
echo "<br>";
echo $_SESSION["id"]."<br>";
} else {
header("Location: signup.php");
}
?>
You generally shouldn't be using GET query strings to change state in your application for pretty much this exact reason.
GET requests are not supposed to have any side effects and browsers will try to take advantage of this to speed up page loads by either pre-requesting pages before a user clicks on them or by caching a page and not actually requesting it from the server. Either of these cases will result in unexpected behavior. Also, if someone bookmarks the page with ?logout=1 on it they'll (probably accidentally) log themselves out any time they return to the page.
It'd be better to use the POST verb for this. You can easily do with with an HTML <form> tag and a submit button:
<form action="signup.php" method="POST" id="logout_form">
<input type="hidden" name="logout" value="1" />
<input type="submit" value="Logout" />
</form>
In your PHP you can detect if someone has hit the button by doing the following:
if(isset($_POST['logout'])) {
//log user out
}
Michael's answer is a good one (and accepted!), but at the moment where I work is going through an accessibility audit, so I have that on my mind. Screen readers, people who use high contrast custom style sheets, etc. can't deal with a form button as easily as plain text.
Also I've had issues in (old) PHP clearing sessions with session_destroy, so I loop through the session variables and unset them.
Log out
And then logout.php:
<?php
session_start();
foreach($_SESSION as $sk=>$sv){
unset($_SESSION[$sk]);
}
header("location: /");
?>

Login Header does not work

I'm trying to code a login-system, but I've got a problem with the login:
As you join the webpage you get to
../?p=Login
As you press the Login-button then you should be send to
../?p=index
But the header should be
../?a=loggedin
because the standard is
Includes/index.php
The PHP-code in index:
if(isset($_GET['p'])) {
$p = htmlspecialchars($_GET['p']);
} else {
$p = "index";
}
include 'Includes/' . $p . ".php";
In the Includes/index.php is a output if a equals loggedin:
if(isset($_GET['a'])) {
if($_GET['a'] == "loggedin") {
echo('<div class="Password-true"> Du hast dich erfolgreich angemeldet.
</div>');
}
}
I think the problem might be in the login code but as I don't know where
the problem is, I inserted all of the code:
<?php
if(isset($_POST['username'], $_POST['password'])) {
$username = htmlspecialchars($_POST['username']);
$password = password_hash(htmlspecialchars($_POST['password']),
PASSWORD_DEFAULT );
$login_statement = $pdo->prepare("SELECT * FROM user_users WHERE username
LIKE :username OR email LIKE :username");
$login_statement->bindParam("username", $username);
$login_statement->execute();
$user = $login_statement->fetch();
if($user != null) {
if(isset($_SESSION)) {
session_start();
}
$_SESSION['username'] = $user['username'];
header("Location: /?a=loggedin");
} else {
echo('<div class="login-false"> Benutzername und Passwort stimmen nicht
überein. </div>');
}
}
<div class="login">
<div class="login-header">
<h1>Login</h1>
<hr size="3" />
</div>
<div class="login-content">
<form method="post" action="/?p=Login">
<h3> Benutzername / E-Mail </h3>
<input type="text" class="datainput" name="username" style="height: 30px;
padding-left: 5px;" required placeholder="Nutzername oder E-Mail" /><br>
<br>
<h3> Passwort</h3>
<input type="password" class="datainput" name="password" style="height:
30px; padding-left: 5px;" required placeholder="Passwort" /><br><br><br>
<br><br>
<input type="submit" value="Login" style="height: 30px; width: 100px;" />
</form>
</div>
<div class="login-footer">
<hr size="3" />
Fülle alle Felder aus, um dich anzumelden.
</div>
</div>
Finally I want to add, that I used a tutorial on YouTube and I use Bootstrap and jQuery.
My website is: http://mysticsouls.developed-media.de
(It isn't nice yet).
Thank you for your help!
header() will not work if the headers were already sent... aka if some code/html is displayed before this part is executed.
An alternative would be to echo some JavaScript. Since you have jquery in there I thought you might be open to an alternative ;)
<script>window.location = '/?a=loggedin'</script>
From what I can see your code has some serious security issues. You should work on a local copy first, I'd even go as far as disabling the live version... For now...
It sounds like you wanting this for a url:
/?p=index&a=loggedin
Then you can $_GET both p and a from this. Otherwise, can you clarify more?

PHP session is working on localhost but not on actual server

i'm having trouble to pass session variable to another page. It is working on localhost but not on server. I would want to pass $_SESSION['user_check'] to editpasswordsignup.php but whenever i click submit, $_SESSION['user_check'] is empty.
This is loginsignup.php
<?php
include('db.php');
session_start();
?>
<div id="wrapper">
<div id="wrapper-bg">
<div id="wrapper-bgtop">
<div class="container" id="header">
<div class="container" id="logo">
<h1></h1>
</div>
</div>
<div class="container" id="page">
<div id="loginbox">
<form action="" class="formbox" method="post">
<label>Email Address:</label>
<input class="box1" name="email" type="text">
<label>Password:</label>
<input class="box2" name="password" type="password">
<a class="myButton1" href="forgetpassword.php">Forgot Password</a><br>
<input class="submit5" name="submit" type="submit" value="Login">
Create Account
</form>
<?php
if (isset($_POST['submit']))
{
$email = ($_POST["email"]);
$password =($_POST["password"]);
$_SESSION['user_check'] = $_POST["email"];
$sql = mysql_query ("SELECT * FROM user WHERE email = '$email' ");
$row = mysql_fetch_array($sql);
$drawemail = $row['email'];
$drawpassword = $row['password'];
if (($drawemail == $email ) && ($drawpassword == $password ))
{
?>
<script>window.location = "../wordsignup.php";</script>;
<?php
}
else
{
echo "wrong password or username";
}
}
?>
</div>
</div>
<div class="container" id="footer-content-bg">
<div id="footer-content">
<ul>
<li class="footer1">
About us
</li>
<li>
Term and Conditions
</li>
<li>
Privacy Advertising
</li>
<li>
Policy
</li>
<li>
User Agreement
</li>
</ul><br>
<div id="copyright">
© . All Rights Reserved.
</div>
</div>
</div>
</div>
This is editpasswordsignup.php
<?php
include('db.php');
session_start();
$user_check = $_SESSION['user_check'];
?>
<div id="wrapper">
<div id="wrapper-bg">
<div id="wrapper-bgtop">
<div class="container" id="header">
<div class="container" id="logo">
<h1></h1>
</div>
</div>
<div class="container" id="page">
<div id="forgetpassword">
<div style="font-size:20px; color:#000080; font-weight:bold; border-width:1px; border-style:none; width:600px; margin:10px 0px 0px 175px;">
Edit Password
</div>
<div style="font-size:16px;border-style:none; width:560px; margin:20px 0px 10px 175px; font-weight:bold;">
Please enter your old password below and we will send you your password.
</div>
<div id="forgetpasswordbox">
<form class="forgetpassword" method="post">
Please enter your old password<br>
<input class="oldpassword" name="oldpassword" type="password"><br><br>
Please enter your new password<br>
<input class="newpassword" name="newpassword" type="password"><br><br>
Please re-enter new password<br>
<input class="confirmpassword" name="confirmpassword" type="password"><br><br>
<input name="submit" type="submit" value="Send" class="send">
</form>
</div>
</div>
</div>
<div class="container" id="footer-content-bg">
<div id="footer-content">
<ul>
<li class="footer1">
About Us
</li>
<li>
Term and Conditions
</li>
<li>
Privacy Advertising
</li>
<li>
Policy
</li>
<li>
User Agreement
</li>
</ul><br>
<div id="copyright">
© . All Rights Reserved.
</div>
</div>
</div>
</div>
</div>
</div>
<?php
if (isset($_POST['submit']))
{
$oldpassword = $_POST['oldpassword'];
$newpassword = $_POST['newpassword'];
$confirmpassword = $_POST['confirmpassword'];
$sql = mysql_query (("SELECT * FROM user WHERE email='user_check' AND password='$oldpassword' "),$conn);
$row = mysql_fetch_array($sql);
$email = $row['email'];
$selectpassword = $row['password'];
if ($oldpassword == "")
{
echo '<script language="javascript">';
echo 'alert("pls enter your oldpassword")';
echo '</script>';
exit;
}
if($newpassword=="")
{
echo '<script language="javascript">';
echo 'alert("pls enter your newpassword")';
echo '</script>';
exit;
}
if($confirmpassword=="")
{
echo '<script language="javascript">';
echo 'alert("pls enter your confrimpassword")';
echo '</script>';
exit;
}
if (($oldpassword) != ($selectpassword))
{
echo '<script language="javascript">';
echo 'alert("No user exists with this password '.$selectpassword.' ")';
echo '</script>';
exit;
}
if ($newpassword == ($confirmpassword))
{
mysql_query("UPDATE user SET password = '".$newpassword."' WHERE email='".$email."'");
$message = "Your password ".$newpassword." and click the link uploadsignup.php to upload your photo";
mail($email, "Change Password", $message);
?>
<script>
alert("Password Successfully change...!!!!\nClick OK to upload photo\nNewpassword will send to your email address");
window.location="uploadsignup.php";
</script>
<?php
}
else
{
echo '<script language="javascript">';
echo 'alert("new password does not match")';
echo '</script>';
}
}
?>
As you said it's working on localhost and not on the particular server, you might have a different settings in php.ini. Check out http://php.net/manual/en/session.configuration.php
I once had this problem for hours. My sessions worked on localhost but were not passing from page to page. The issue was the comments I had above the session starting. For some reason it didn't affect localhost but my server was just not having it.
So if there is anyone else reading this post with this issue, this is something else you can try.
There are several things that need to be corrected here:
1) Do not use styles in the page, use CSS classes and Id's rather than Styles. I have edited the question to remove these as they get in the way of the real code we're interested in.
2) Do not use MySQL, it is deprecated meaning it is no longer supported and the reason it is no longer supported is there are various flaws and security issues and I HIGHLY recommend looking into MySQLi or PDO as alternative methods of connecting to a database. Seriously.
3) Your issue is syntx - we'll start with brackets - see:
$email = ($_POST["email"]);
$password =($_POST["password"]);
Should be:
$email = $_POST['email'];
$password =$_POST['password'];
You do not need to put values in brackets when assigning variables. Also note that array values are in single quotes ' not double quotes. So:
$_SESSION['user_check'] = $_POST['email'];
Will work better, alternatively try this:
if (!empty($_POST['email'])){
$_SESSION['user_check'] = $_POST['email'];
}
else {
$_SESSION['user_check'] = "No Email value given in form";
}
to replace the above line.
4) Your HTML code is incomplete, your form has no action value in the second code block, these things are probably not critical but this code is ripe for errors due to being ambiguous.
5) At the top of editpasswordsignup.php (after session_start) put this:
var_dump($_SESSION['user_check']); and with the above code from point 3, this should give you an output.
6) Check your SQL:
$sql = mysql_query (("SELECT * FROM user WHERE email='user_check' AND password='$oldpassword' "),$conn);
Your email value is a string, not a variable. Your SQL here is also a complete mess, what is the reason for this?
replace the above with:
$sql = mysql_query("SELECT * FROM user WHERE email='$user_check' AND password='$oldpassword' LIMIT 1");
Complete all of the above and your code will work.
According to the op question and the answer needed why code is working on local host and not server the correct answer seems by Arun.
Too bad he has been down voted but that could be because he has not explained anything in his answer.
I have met this problem before.
The solution is make sure you do not have space above or below
<?php
line.
I am fairly certain that is why Arun has drawn lines to indicate your other php code should follow emediately.
I just had the same problem and I ended here. Even though I don't see there session_set_cookie_params() maybe you've typed it on db.php. Because of using LOCALHOST on session_set_cookie_params(time()+600,'/','LOCALHOST',false,true); session didn't work, so if you used session_set_cookie_params() you have to make sure you've replaced LOCALHOST with your domain
Try like this:
<?php session_start();
-----
-----
?>

getting processed value back in same page in php

I want that when I press login button I get the response back in the same page e.g. if user name doesn't exist or is duplicate it should show the error message on the same page, one more thing this data goes to another page and after some database action it returns the value, I got the value in the page where I use that database query, but how to get it back to the very first page from where I actually submitted it
this is the scenario login->function selector->controller(database query page)
what I need to do is to get value from controller to login after a successful query generation here is a glimpse of code
<form method="post" action="selector.php?type=login" id="login" id="loginForm">
<div class="row">
<div class="offset1 span1">
<div class="lbel"><label class="control-label" for ="loginName">Username/Email</label></div>
<div class="lbl_inpuCnt"><input type="text" class="input-xlarge" id="loginName" name="loginName" maxlength="50"/></div>
<div id="usernameError" style="font-size: 10px; color: red;"> </div>
<div class="lbel"><label class="control-label" for="loginPassword">Password</label></div>
<div class="controls">
<input type="password" class="input-xlarge" id="loginPassword" name="loginPassword" maxlength="50"/>
</div>
<div id="passwordError" style="font-size: 10px; color: red;"> </div><br/>
</div>
</div>
<div style="margin-left: 55px;">
<input class="btn" style="width: 80px;" type="reset" name="reset" value="Reset" onclick="clearFields()"/>
<input class="btn" style="width: 80px;" type="submit" name="submit" value="Login" onclick="return validateForm();"/>
</div>
</form>
then comes the selector page
<?php
include_once 'classes/controller.php';
$controller = new controller();
switch ($_GET['type']) {
case 'signup':
$registerStatus = $controller->register($_POST);
$_POST['username'] = $registerStatus;
break;
case 'login':{
$result= $controller->login($_POST);
echo $result; //here i get the value from next page after process, i need it back to login page to show error there!
}
break;
case 'uploadSongs':
$controller->uploadSongs();
break;
case "delete":
echo "Function Called";
break;
}
?>
and this is the controller function in controller.php
public function login($request = array()) {
$login = $request['loginName'];
$password = ($request['loginPassword']);
$query = "select * from user where (user_name = '" . $login . "' OR email = '" . $login . "') AND (password = '" . $password . "')";
$user = $this->model->select($query);
if (is_array($user) && isset($user[0]['user_id'])) {
$_SESSION['uid'] = $user[0]['user_id'];
echo $_SESSION['name'] = $user[0]['first_name'];
$this->redirect("userArea.php");
} else {
echo "-1";
return $login;
}
exit;
}
Login page can submit to itself, and on a successful login, you redirect to member area. On a failed login, you simply display a message.

Categories