$_SESSION not storing values - php

I am having an issue with storing $_SESSION variables, i am a little new at PHP and I like it to the extent of my current knowledge.
first my creds:
Win 7 Pro 64
PHP 5
Remote Server(not sure of its config)
So what I am trying to do is set up a Login Page that contains a hardcoded username and password for testing purposes.
I want to display the username on a successor page to confirm it.
Login.php
<?php session_start();?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head >
<title>Login</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta http-equiv="content-language" content="en-gb" />
<script type="text/javascript">
// Perform Client side validation of Username and Password
function redirect() {
var username = document.getElementById("username");
var password = (document.getElementById("password"));
if (!username.value == " ") {
if (!password.value == " ") {
if (username.value == "aknight") {
if (password.value == "00226291") {
window.location = "Home.php";
exit();
} else
alert("Username or Password Invalid");
}
} else
alert("Password is required");
} else
alert("Username is required");
}
</script>
</head>
<body>
<div id="header">
<h1>Product Order System</h1>
<br/>
<h2>The most expensive crap youll ever find...</h2>
</div>
<div id="content">
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$_SESSION['username'] = $_POST['username'];
}else{
?>
<form action="" method="POST">
<fieldset>
<legend>Login Information</legend>
<p>
<label for="Username">Username:</label>
<input type="text" name="username" id="username" />
</p>
<p>
<label for="Password">Password:</label>
<input type="password" name="password" id="password" />
</p>
<p>
<input type="button" name="login" value="Login" onclick="redirect();"/>
<input type="button" name="cancel" value="Cancel" />
</fieldset>
</form>
<?php }
include ('includes/footer.html');
?>
home.php
<?php
session_start();
$page_title = 'Home';
include ('includes/header.php');
if(isset($_SESSION['username'])) { $name = $_SESSION['username'];}else{echo "<p>error</p>";}
echo "<h3>Welcome ".$name."!</h3>" ;
?>
I have tried printing out the $_SESSION values and they are coming up empty.
producing this result
<?php
echo "<pre>".print_r($_SESSION)."</pre>";
?>
Array {
[username] =>
}
Please do not mind the JS, it is preschool client validation just to move forward.
Any help would be greatly appreciated.

Give your login form a name, and then in your JavaScript validation function, instead of window.location, do a document.forms['yourformname'].submit().

I think your Javascript validation is actually what's causing the issue.
You're setting the session variable in Login.php using the POST request, but no POST is actually being sent to Login.php since your Javascript is redirecting to Home.php once the form is considered valid. You need to submit the form at some point in the process, so you actually get some POST values which you'll use to populate your SESSION variables.
If you want to keep your Javascript validation, maybe have a look at submit() : http://www.w3schools.com/jsref/met_form_submit.asp
You'll have to set a correct action property on your form before submitting it.

So heres a fix that seems to be working
<?php session_start();?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head >
<title>Login</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta http-equiv="content-language" content="en-gb" />
<script type="text/javascript">
// Perform Client side validation of Username and Password
function redirect() {
var username = document.getElementById("username");
var password = (document.getElementById("password"));
if (!username.value == " ") {
if (!password.value == " ") {
if (username.value == "aknight") {
if (password.value == "00226291") {
document.forms[0].submit();
exit();
} else
alert("Username or Password Invalid");
}
} else
alert("Password is required");
} else
alert("Username is required");
}
</script>
</head>
<body>
<div id="header">
<h1>Product Order System</h1>
<br/>
<h2>The most expensive crap youll ever find...</h2>
</div>
<div id="content">
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$_SESSION['username'] = $_POST['username'];
header('Location : ../Home.php');
}else{
?>
<form action="Home.php" name="login" method="POST">
<fieldset>
<legend>Login Information</legend>
<p>
<label for="Username">Username:</label>
<input type="text" name="username" id="username" />
</p>
<p>
<label for="Password">Password:</label>
<input type="password" name="password" id="password" />
</p>
<p>
<input type="button" name="login" value="Login" onclick=" redirect();"/>
<input type="button" name="cancel" value="Cancel" />
</fieldset>
</form>
<?php }
include ('includes/footer.html');
?>
Will post again if the nex series of pages has a similiar issue
Thanks

Related

I have problems with "echo" empty in php

I tell you, I have a form where only email addresses are loaded
The idea is that when a user enters for example pepito#pepito.com the page says, "you enter pepito#pepito.com" the problem I have with the echo is that when you enter the page, you show me input "you income ", how can I eliminate that?
<?php echo "you income $email"; ?>
I created a simple example for it
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Example</title>
</head>
<body>
<?php echo !empty($_POST['email']) ? 'you enter ' . $_POST['email'] : ''; ?>
<form action="" method="post">
<input name="email" placeholder="somebody#example.com" />
<input type="submit">
</form>
</body>
</html>
I am using the ternary operator after check the email parameter with empty()
it will check if form is submitted or not and if submitted it will echo the email.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Example</title>
</head>
<body>
<?php
if(isset($_POST['submit'])) {
echo "you entered ". $_POST['email'];
}
?>
<form action="" method="post">
<input name="email" type="email" placeholder="somebody#example.com" required
placeholder="Enter Email">
<input type="submit" name="submit">
</form>
</body>
</html>

How can ask login if it write on url

index.php
<?php session_start(); ?>
<?php include('dbcon.php'); ?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="form-wrapper">
<form action="#" method="post">
<h3>Login here</h3>
<div class="form-item">
<input type="text" name="user" required="required" placeholder="Username" autofocus required></input>
</div>
<div class="form-item">
<input type="password" name="pass" required="required" placeholder="Password" required></input>
</div>
<div class="button-panel">
<input type="submit" class="button" title="Log In" name="login" value="Login"></input>
</div>
</form>
<?php
if (isset($_POST['login']))
{
$username = mysqli_real_escape_string($con, $_POST['user']);
$password = mysqli_real_escape_string($con, $_POST['pass']);
$query = mysqli_query($con, "SELECT * FROM users WHERE password='$password' and username='$username'");
$row = mysqli_fetch_array($query);
$num_row = mysqli_num_rows($query);
if ($num_row > 0)
{
$_SESSION['user_id']=$row['user_id'];
header('location:home.php');
}
else
{
echo 'Invalid Username and Password Combination';
}
}
?>
</div>
</body>
</html>
Here is my page for login the system. When the username and password is then it will go to home pages. It work properly. but if I write in browser after log out.
localhost/logg/home.php it is automatically go to that pages it not asking for login. So How to make proper login page where it asking log or automatically it will go login panned for all the pages is that is connected with home page.
home.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Client Management System</title>
<link rel="stylesheet" type="text/css" href="css/style_entry.css" />
<link rel="stylesheet" type="text/css" href="css/home_menu.css" />
<link rel="stylesheet" type="text/css" href="css/container.css" />
</head>
<body style="background-color:gray"/>
<div class="container">
<div class="dropdown">
<button class="dropbtn">Entry</button>
<div class="dropdown-content">
Market Information
bank Information
Client Information
</div>
</div>
Edit
Bill Process
Bill Print
Bill Posting
Report
Admin
Help
Help
<li style="float:right"><a class="active" href="logout.php">Logout</a></li>
</body>
logout.php
<?php
session_start();
session_destroy();
header('location:index.php');
?>
How can I secure it ?? how can I set if I write the url in browser then it will automatically go to the login page.
1st : On top of every page you need to check session is exists or not . if session exists allow user to see the page otherwise redirect the page to login page .
if(!isset($_SESSION['user_id'])){
header('Location:login.php');
exit();
}
Note : Session is globally accessible variable . Based on that you need to make logic .
make a file 'login_check.php'
<?php
if(isset($_SESSION['user_id'])){
}else{
header("location:login.php");
}
?>
include this file in those pages which should only be accessible to logged in user.

Error Count - PHP

I have a form which has email as field name. What I am trying to do is if the email is it no equal to $emailToCheck is not equal to $_POST['email'], it should throw an error first time. The second time if the user enters wrong email id again it should always redirect to "error.htm" even if the page refreshes.
It doesn't work the form always shows even if the email id is entered wrong twice.
<?php
if (!empty($_POST['email'])) {
$email="website#test.com";
if($email!=$_POST['email'])
{
$count="1";
}
if($count=="2"){
header("Location: /error.htm");
exit(0);
}
}
if($count!="2"){
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Form</title>
</head>
<body id="main_body" >
<div id="form_container">
<h1><a>Form</a></h1>
<form id="form_1123848" class="appnitro" method="post" action="">
<div class="form_description">
<h2>Form</h2>
<p> <input type="text" name="email" value="" /></p>
</div>
<ul >
<li class="buttons">
<input id="saveForm" class="button_text" type="submit" name="submit" value="Submit" />
</li>
</ul>
</form>
</body>
</html>
<?
}
?>
You have two issues here:
1. You are defining $count as a string, and never incrementing it. If you look over your code, $count is getting specifically set to 1 every time there is a mismatch. How is supposed to ever get to 2?
2. Furthermore, data here is stateless. How is the script supposed to know what $count was set to on the previous call? You need to also set $count as a session variable so that the script will know what its previous value.
You should try updating your code to something similar to this:
// Check if `email` passed in POST request:
if ($_POST['email']) {
$email = "website#test.com"; //Manually define expected email address.
// Check if provided email does *not* match the expected email:
if ($email !== $_POST['email']) {
// Record the mismatch attempt in session and increment:
if (!($_SESSION['incorrectEmailCount'])) {
// If this is the first mismatch, define the session variable, and set to 1.
$_SESSION['incorrectEmailCount'] = 1;
} else {
// Session variable already set due to previous mismatch. Increment it.
$_SESSION['incorrectEmailCount']++;
}
}
// If user entered incorrect email more than once:
if ($_SESSION['incorrectEmailCount'] > 1) {
// Redirect to error page and stop execution.
header("Location: /error.htm");
exit(0);
}
}
Once the form is submitted, the page reloads, resetting the counter. In order to actually count, you need to provide that value in the form and pass it along to the PHP when the form is submitted.
<?php
// Try to get the amount of attempts from the POSTed data
$count = isset($_POST['count']) ? $_POST['count'] : 0;
if (isset($_POST['email'])) {
$email = "website#test.com";
if ($email != $_POST['email']) {
$count++;
}
if ($count == 2) {
header("Location: /error.htm");
}
}
if ($count <= 2):
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Form</title>
</head>
<body id="main_body" >
<div id="form_container">
<h1><a>Form</a></h1>
<form id="form_1123848" class="appnitro" method="post" action="">
<!-- Let the POST data know this is the x attempt -->
<input type="hidden" name="count" value="<?php echo $count; ?>">
<div class="form_description">
<h2>Form</h2>
<p> <input type="text" name="email" value="" /></p>
</div>
<ul>
<li class="buttons">
<input id="saveForm" class="button_text" type="submit" name="submit" value="Submit" />
</li>
</ul>
</form>
</div>
</body>
</html>
<?php endif; ?>
Also, your coding style is far from consistent. Try to work on that!

header() is not redirecting to the page in PHP

I have the following PHP printExam.php page:
<?php
$logins = array(
'user' => 'pass',
'user1' => 'pass1',
'user2' => 'pass2',
'user3' => 'pass3',
'user4' => 'pass4'
);
// Clean up the input values
foreach($_POST as $key => $value) {
$_POST[$key] = stripslashes($_POST[$key]);
$_POST[$key] = htmlspecialchars(strip_tags($_POST[$key]));
}
/******************************************************************************/
if (isset($_POST['submit'])){
$user = isset($_POST['user']) ? strtolower($_POST['user']) : '';
$pass = isset($_POST['pass']) ? $_POST['pass'] : '';
$report = $_POST['typereport'];
if ((!array_key_exists($user, $logins))||($logins[$user] != $pass)) {
showForm("Wrong Username/Password");
exit();
}
else {
if ($report == "Clinical") {
?>
<html>
<head>
</head>
<body>
CLINICAL PAGE
</body>
</html>
<?php
}
elseif ($report == "Annual Education") {
?>
<html>
<head>
</head>
<body>
ANNUAL EDUCATION PAGE
</body>
</html>
<?php
}
}
} else {
showForm();
exit();
}
function showForm($error=""){
?>
<!DOCTYPE html>
<html><head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
<title>Certificate Printing :: Login</title>
<script src="http://code.jquery.com/jquery-1.7.1.min.js" type="text/javascript"></script>
<Script>
$(function() {
$("#user").focus();
});
</Script>
</head>
<body>
<form id="login" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="pwd">
<h1>Log In</h1>
<fieldset id="inputs">
<input id="user" name="user" placeholder="Username" autofocus="" required="" type="text">
<input id="pass" name="pass" placeholder="Password" required="" type="password">
</fieldset>
<fieldset id="actions">
<input type="radio" name="typereport" id="cbox" value="Clinical" checked="yes" /> Clinical
<input type="radio" name="typereport" id="cbox" value="Annual Education" /> Annual Education
</fieldset>
<fieldset id="actions">
<input id="submit" name="submit" value="Log in" type="submit">
</fieldset>
<div class="caption"><?php echo $error; ?></div>
</form>
</body>
</html>
<?php
}
?>
For printCert.php and printCertHR.php, the very first line is:
<?php require_once('printExam.php'); ?>
What it is suppose to do is call the printExam.php page each time the user visits either pages. If the username AND password matches and depending on the selection, whether it's clinical or annual education, it should take the user to the correct page. I know the form is working correctly, because if I enter wrong username/password it shows me the error but once correct, it doesnt redirect. Any idea how to resolve it?
Please Note: the username/password is simplified for the example only!
The 'Location' header command in PHP should be followed with an exit;
Otherwise the code below is executed, ie any output is sent to the browser.
See the examples from the PHP header page:
<?php
header("Location: http://www.example.com/"); /* Redirect browser */
/* Make sure that code below does not get executed when we redirect. */
exit;
Location (or any other header) needs to be the first thing echoed by your script. Remove the blank lines in your script.
You have contents being displayed before the header is being called (as for your comment to Rob W). The way to get around it is, put ob_start(); at the top of your php code, and ob_end_flush(); at the end of your code so the header can be called anywhere in between your code.
Is it possible that you might need to use PHP's Output Buffer to fix that? When the script is parsed, having the output of the form in a function might be throwing it off, as the function will be parsed before the rest of the script is run.
Also, you should use strcmp for comparing strings, not the == sign. strcmp vs ==
Try using the output buffer functions and see if that fixes it. it's gonna look something like this:
function showForm($error=""){
ob_start(); ?>
<!DOCTYPE html>
<html><head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
<title>Certificate Printing :: Login</title>
<script src="http://code.jquery.com/jquery-1.7.1.min.js" type="text/javascript"></script>
<Script>
$(function() {
$("#user").focus();
});
</Script>
</head>
<body>
<form id="login" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="pwd">
<h1>Log In</h1>
<fieldset id="inputs">
<input id="user" name="user" placeholder="Username" autofocus="" required="" type="text">
<input id="pass" name="pass" placeholder="Password" required="" type="password">
</fieldset>
<fieldset id="actions">
<input type="radio" name="typereport" id="cbox" value="Clinical" checked="yes" /> Clinical
<input type="radio" name="typereport" id="cbox" value="Annual Education" /> Annual Education
</fieldset>
<fieldset id="actions">
<input id="submit" name="submit" value="Log in" type="submit">
</fieldset>
<div class="caption"><?php echo $error; ?></div>
</form>
</body>
</html>
<?php
return ob_get_flush();
}
Output Buffers (php.net)
After your elseif ($report == "Annual Education") { block, try print_r($report) - ensure it's what you are expecting...
if ($report == "Clinical") {
header ("Location: printCert.php");
}
elseif ($report == "Annual Education") {
header ("Location: printCertHR.php");
}
print_r($report);
Also, try monitoring FireBug's NET tab (or CHROME's)

Updating a Database With PHP

I'm trying to update my database records with the following code but am having no luck what so ever. Anybody care to help? Thanks
<?php include "base.php"; ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Project Sproom</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<?php if(!empty($_SESSION['LoggedIn']) && !empty($_SESSION['Username']))
{
if(!empty($_POST['username']) && !empty($_POST['email']))
{
$newusername = mysql_real_escape_string($_POST['username']);
$newemail = mysql_real_escape_string($_POST['email']);
$edit = mysql_query("UPDATE users (Username, EmailAddress) VALUES('".$newusername."', '".$newemail."') WHERE UserID=".$_SESSION['UserID']."");
// }
?>
<div id="container">
<div id="homemenu">
<ul id="navlist">
<li id="active">Home</li>
<li>Edit Profile</li>
</ul>
</div>
<div id="homemain">
<h1>Edit Profile</h1>
<p>This will be the edit profile when i have figured out how to do it...</p>
<br />
<form method="post" action="profile.php" name="editprofile" id="editprofile">
<label for="username">Username: </label> <input type="text" name="username" id="username" value="<?=$_SESSION['Username']?>"/><br />
<label for="email">E-Mail: </label> <input type="text" name="email" id="email" value="<?=$_SESSION['EmailAddress']?>"/> <br />
<input type="submit" name="editprofile" id="editprofile" value="Submit" />
</fieldset>
</form>
</div>
</div>
<?php
}
else
{
?>
<meta http-equiv="refresh" content="0;index.php">
<?php
}
?>
You're using INSERT syntax for an UPDATE query. The syntax should be like this:
UPDATE users SET Username = 'username', EmailAddress = 'email' WHERE UserID = 1;
Docs here.
You haven't connected to the MySQL database, have you?
I didn't see that in this code...
Or is that part of the included "base.php" on top of this script?
I am afraid you need fist establish a connection to a certain MySQL database before trying to update a row in a table.
Edit:
Okay, well then. Try issue the following line of code after the update:
echo "edit was " .$edit;
This is to check whether the update query was executed successfully (in which case it should echoes true) or failed (in which case it echoes false).
So at least you can tell the result of such a mysql_query.
$edit = mysql_query("UPDATE users SET Username='".$newusername."', EmailAddress='".$newemail."' WHERE UserID=".$_SESSION['UserID']."");
Try this

Categories