Adding Separate Sections in phpMyAdmin - php

I am having a problem allowing users (teachers) to have their own sections. A section will allow a teacher that registers access to only their students and questions posted by them. When a teacher registers, they will be given a unique number that allows them access to a new separate section.
I have one users table that is filled with students and teachers. I tried adding another column or table for students and teachers with the same section number but I have not been able to get it to work.
Also the id I am using in phpMyAdmin, I am using as a student id number. I tried to use it as a section number which took away the ability to recognize each students' answers in my database (since they are stored as an id). I hope this is clear and thank you all ahead of time.
Here is my users table in my database.
And here is my register.php code...it is deprecated as of now (working on switching it to mysqli later)
<!DOCTYPE html>
<html>
<head>
<title>Registration</title>
<link rel="stylesheet" href="main.css">
</head>
<body class="login" style="margin-bottom: 100px; " >
<?php include 'connect.php'; ?>
<?php include 'functions.php'; ?>
<span style="display: inline-block;"><h1 style="margin-left: 40px; ">Register</h1></span><span style="display: inline-block; padding-left: 165px; "><p>Back</p></span>
<link rel="stylesheet" href="main.css">
<form action="" method="post">
<ul>
<li>
<input type="text" name="username" class="box" size="25" placeholder="Username"><br>
</li>
<li>
<input type="password" name="password" class="box" size="25" placeholder="Password"><br>
</li>
<br><br>
<button type="submit" style="margin-bottom: 5px;" class="subbutton" name="submit">Register</button>
</li>
</ul>
</form>
<?php
if(isset($_POST["submit"])){
if(!empty($_POST['username']) && !empty($_POST['password'])) {
$username=$_POST['username'];
$password=$_POST['password'];
$con=mysql_connect('localhost','root','') or die(mysql_error());
mysql_select_db('project') or die("Cannot select database");
$query=mysql_query("SELECT * FROM users WHERE username='".$username."'");
$numrows=mysql_num_rows($query);
if($numrows==0)
{
$sql="INSERT INTO users VALUES('','$username','$password','','','','1','d')";
$result=mysql_query($sql);
if($result){
echo "Account successfully created!";
} else {
echo "Didn\'t work, try again";
}
} else {
echo "That user ID already exists! Please try again";
}
} else {
echo "All fields are required!";
}
}
?>
</body>
</html>

Related

data in $_POST across multiple pages

I am new to PHP and I wrote scripts for simple login. When successfully login and click the link "back to login", I was not able to have the previous login username filled. I know using $_COOKIE['username'] for the value of username works, but I am wondering why $_POST['username'] does not work? Thank you!
login.php
<!DOCTYPE HTML>
<html>
<head></head>
<body>
<form action="./loginProcess.php" method="post">
Username: <input type="text" name="username" value="<?php echo isset($_POST['username']) ? htmlspecialchars($_POST['username']) : ''; ?>"><br>
Password: <input type="password" name="password"><br>
<input type="submit" name="send">
</form>
</body>
</html>
loginProcess.php
<?php
echo "welcome, ".$_POST['username'].", login success!!";
echo "<br/><a href='login.php'>Back to login</a><br>";
if(!empty($_COOKIE['lastVist'])){
echo "your last login time:".$_COOKIE['lastVist'];
setcookie("lastVist",date("Y-m-d H:i:s"),time()+24*3600*30);
}else{
echo "you first login time:";
}
setcookie("username", $_POST['username'], time()+24*3600*30);
?>
A session is a way to store information (in variables) to be used across multiple pages.
Unlike a cookie, the information is not stored on the users computer and unlike post as it has information for specific request sent by user.
When we use an application, we open it and do some changes, then we close it. This is much like a Session, so to preserve information we have per session global array in php $_SESSION.
A session is started with the session_start() function and values are stored in simply associative array fashion $_SESSION['key'] = $value;.
login.php
<?php
session_start();
?>
<!DOCTYPE HTML>
<html>
<head></head>
<body>
<form action="./loginProcess.php" method="post">
Username: <input type="text" name="username" value="<?php echo isset($_SESSION['username']) ? htmlspecialchars($_SESSION['username']) : ''; ?>"><br>
Password: <input type="password" name="password"><br>
<input type="submit" name="send">
</form>
</body>
</html>
loginProcess.php
<?php
session_start();
echo "welcome, ".$_POST['username'].", login success!!";
echo "<br/><a href='login.php'>Back to login</a><br>";
if(isset($_SESSION['lastVisit'])){
echo "your last login time:".$_SESSION['lastVisit'];
}else{
echo "you first login time:".$_SESSION['lastVisit'];
$_SESSION['lastVisit'] = date("Y-m-d H:i:s", time());
}
$_SESSION['username'] = $_POST['username'];
?>
In principle, in loginProcess.php, if you would have used, for example, a form with a hidden input containing the username value, then this value would have been readable in the login.php - after clicking the "back to login" anchor:
Welcome <?php echo $_POST['username']; ?>, login success!!
<br>
<form id="backToLoginForm" action="login.php" method="post">
<input type="hidden" name="username" value="<?php echo $_POST['username']; ?>" />
<a href="#" onclick="javascript:document.forms['backToLoginForm'].submit();">
Back to login
</a>
</form>
But you really shouldn't do what you want to do. E.g. to go back to the login.php without logging-out first - at least. If you would do it and complete other credentials - in the login.php - as the ones used for the first login, then you would still need to logout the previous user before validating the new credentials. This would be a bad management of active session, cookies, etc.
More of it, the autocomplete of login credentials is a job for the password managers, or of the form fillers, not of your own code - unless it's part of the validation process of the currently given login credentials (see the code example below).
So, as an alternative to your approach, my suggestion would be the following login.php code. No need for a loginProcess.php page anymore:
<?php
session_start();
// Operations upon form submission.
if (isset($_POST['submit'])) {
// Validate the username.
if (!isset($_POST['username']) || empty($_POST['username'])) {
$errors[] = 'Please provide the username.';
}/* Here other password validations using elseif statement. */
// Validate the password.
if (!isset($_POST['password']) || empty($_POST['password'])) {
$errors[] = 'Please provide the password.';
} /* Here other password validations using elseif statement. */
// Get the posted data.
$username = $_POST['username'];
$password = $_POST['password'];
if (!isset($errors)) {
/*
* Check the given credentials in the db. If the user doesn't exist, add an error:
*/
// $errors[] = 'Wrong credentials. Please try again.';
/*
* ... else add only the user id - fetched from db - to session.
* Don't add other user related details to session. If, in other pages,
* you want to use other user details, fetch them there using the user id.
*/
if (!isset($errors)) {
$_SESSION['userId'] = 43;
// Redirect to the welcome page.
header('Location: welcome.php');
exit();
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
<meta charset="UTF-8" />
<!-- The above 3 meta tags must come first in the head -->
<title>Demo - Login</title>
<style type="text/css">
.form-control {
margin-bottom: 10px;
}
label {
display: inline-block;
min-width: 80px;
}
.messages {
margin-bottom: 20px;
}
.error {
color: #c00;
}
button {
padding: 5px 10px;
background-color: #8daf15;
color: #fff;
border: none;
}
</style>
</head>
<body>
<div class="messages">
<?php
if (isset($errors)) {
foreach ($errors as $error) {
?>
<div class="error">
<?php echo $error; ?>
</div>
<?php
}
}
?>
</div>
<form action="" method="post">
<div class="form-control">
<label for="username">Username:</label>
<input type="text" id="username" name="username" value="<?php echo isset($username) ? $username : ''; ?>">
</div>
<div class="form-control">
<label for="password">Password:</label>
<input type="password" id="password" name="password" value="<?php echo isset($password) ? $password : ''; ?>">
</div>
<button type="submit" id="submit" name="submit">
Login
</button>
</form>
</body>
</html>

How can i get PHP login script to log users in correctly?

I am new to PHP and I am trying to develop a simple login system where it echoes a success message and redirects to a secure page and when details are wrong, it echoes an error message and reloads the login form.
I have been trying to for a while now and cannot figure it out, even though I have some functionality in terms of it directing to the correct page.
My database on PhpMyAdmin is correctly configured. Also, any help on sessions would be greatly appreciated.
PHP CODE:
<?php
$servername = "localhost";
$username = "root";
$password = "cornwall";
$con=mysqli_connect('localhost','root','cornwall','ibill');
// This code creates a connection to the MySQL database in PHPMyAdmin named 'ibill':
$username = $_POST['username'];
$password = $_POST['password'];
//These are the different PHP variables that store my posted data.
$login="SELECT * FROM users WHERE username='$username' AND password='$password'";
$result=mysqli_query($con, $login);
$count=mysqli_num_rows($result);
//This is the query that will be sent to the MySQL server.
if($count==1)
{
header('Location: http://localhost/projects/ibill_v3/html/main.html#home');
exit();
}
//This checks the 'user_details' database for correct user registration details and if successful, directs to home page.
else {
header('Location: http://localhost/projects/ibill_v3/html/loginform.html');
echo "Wrong details";
exit();
}
//If login details are incorrect
/** Error reporting */
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
?>
HMTL CODE
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1; minimum-scale=1;">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<link href="/projects/ibill_v3/css/mainstyles.css" rel="StyleSheet"/>
<link href="/projects/ibill_v3/css/loginform.css" rel="StyleSheet"/>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<script src="script.js"></script>
<script type='text/javascript' src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script type='text/javascript'>
$(document).on('pageinit', function(){
$('.loginform').validate({ // initialize the plugin
// rules & options
});
});
</script>
</head>
<body>
<!--********************************LOGIN FORM PAGE**********************************************-->
<!--****************************************************************************************-->
<!--********************************HEADER**********************************************-->
<div data-role="page" id="loginform">
<div data-role="header" data-id="foo1" data-position="fixed">
<h1>Register</h1>
</div>
<!--********************************HEADER**********************************************-->
<!--********************************MAIN**********************************************-->
<div data-role="main" class="ui-content">
<img class="mainlogo" src="/projects/ibill_v3/img/ibill logo.png" alt="iBill Logo" width="250" height="190">
<h2>Sign in</h2>
<section class="loginform">
<form data-ajax="false" method="POST" action="loginform.php" >
<ul>
<li>
<label for="username">Username</label>
<input type="text" name="username" id="username" class="required" minlength="5" placeholder="enter username (min-5 characters)">
</li>
<li>
<label for="password">Password</label>
<input type="password" name="password" placeholder="enter password" minlength="6">
</li>
<div id="loginformbutton">
<button class='active' type='submit' value='submit'>Sign in</button>
</div>
<p>Don't have an account? Sign up!</p>
<div id="registerbutton">
Register
</div>
</ul>
</form>
</section>
</div>
<!--********************************MAIN**********************************************-->
<!--********************************FOOTER**********************************************-->
<div data-role="footer">
<footer class="footer">
<p>awilliams©</p>
</footer>
</div>
</div>
<!--********************************END OF LOGIN FORM PAGE**********************************************-->
<!--****************************************************************************************-->
</body>
...
else
{
header('Location: http://localhost/projects/ibill_v3/html/loginform.html');
echo "Wrong details";
exit();
}
The above is going to redirect before your echo statement is reached, so nothing will be displayed.
Secondly, the following line:
<form data-ajax="false" method="POST" action="loginform.php" > will not send any data back to your file containing the form if you're using echo statements. It is going to redirect to the loginform.php and will stay there if you do not explicitly redirect back the page with your form.
Instead, use:
<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> as your form's action. And then include your loginform.php somewhere before the form in your HTML.
This is going to send data back to the form's file and replaces special characters to HTML entities (for security), it also allows you to use echo's or variables to return messages to the user.
loginform.php will need to check if specific inputs are posted:
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
if($_POST['username'] && $_POST['password'])
{
//do work
}
}
Here is a basic php form tutorial to start you off: php tutorial
I think it's because your redirecting to the same page with no post. I didn't look through all the code, that is just my first stab at it
This will not appear on loginform.html:
echo "Wrong details";
Use something like:
$_SESSION['errorMessage'] = "Wrong details";
header('Location: http://localhost/projects/ibill_v3/html/loginform.html');
exit();
And then on loginform.html, add this code to display the error message:
if(isset( $_SESSION['errorMessage'])) echo $_SESSION['errorMessage'];

How to Properly Start a Session in PHP?

I was recently following a tutorial on how to make a custom CMS for my website. I am currently making the back end, so the users can create and edit pages. The tutorial is kind of old so various functions have been deprecated. I was able to fix most of them, except for the "session_register();" function. I saw on many sites, including this one that told me to use "$_SESSION['admin']=$username;" for example. This is not working for me, since I apply this to many pages, each page is asking me to re-enter the information.
Here are files I am using:
admin_check.php:
<?php
$error_msg="";
if ($_POST['username']){
$username=$_POST['username'];
$password=$_POST['password'];
// Simple hard coded values for the correct username and password
$admin="Admin";
$adminpass="Password";
//connect to mysql here if you store admin username and password in your database
//This would be the prefered method of storing the values instead of hard coding them here into the script
if(($username !=$admin)||($password != $adminpass)){
$error_msg='<h3 class="text-danger">Login information incorrect, please try again.</h3>';
} else{
$_SESSION['admin']=$username;
require_once "index.php";
exit();
}
}
?>
<?php
if ($_SESSION['admin']!="Admin"){
echo '<div class="container" style="background-color: #FFF ;"><h3><i class="glyphicon glyphicon-alert text-danger"></i> Solo los administradores
tienen permiso para ver este directorio. No se admite gente con Lag! </h3><br/>
<!DOCTYPE html
<html>
<head>
<title>Login Administrador</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="UTF-8">
<link href="../css/bootstrap.min.css" rel="stylesheet" />
<link href="../css/styles.css" type="text/css" rel="stylesheet">
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap- glyphicons.css" rel="stylesheet">
</head>
<body style="padding-top: 5px; background-color: #EEE ;">
<div style="max-width: 450px; max-height: 550px; background-color: #CCC; padding-top: 30px; box-shadow: 0 0 15px #DDD; border-radius: 10px" class="container">
<div class="jumbotron" style="background-color: #fff; max-height: 470px; padding: 10px; border-radius: 2; box-shadow: 0 0 12px #777;">
<legend class="text-success">LOGIN ADMINISTRATOR</legend>
<hr />
<p style="font-size: 12pt;">Please enter your username and password to login into the admin site.</p>
<form action="admin_check.php" method="post" target="_self" class="form-group">
<label class="label label-default">username</label>
<input type="text" class="form-control" placeholder="username" name="username" id="username">
<br/>
<label class="label label-default">password</label>
<input type="password" class="form-control" placeholder="password" name="password" id="password">
<br/>
<button class="btn-success" value="submit" type="submit" name="button" id="button" >Submit</button>
</form><br/>
'.$error_msg.'
</div>
</div>
</body>
</html>
<br/><br/>
<center> <a href="../" >Click aquí para regresar a un lugar seguro.</a> </div></center>';
exit();
}
?>
^ As you can see, this is where the admins input the username and password, which I'd like to have stored somehow, like in a cookie, so they can navigate freely without having to input the username and password over and over again.
index.php:
<?php
session_start();
include_once "admin_check.php";?>
<?php
include "admin_header.php";
?>
<body id="home">
<div class="container" style="background-color: white;">
<h2 style="color: #FF691F"><i class="fa fa-home fa-2x"></i> Home</h2>
</div>
</body>
<?php include "admin_footer.php"; ?>
create_blog.php:
<?php
session_start();
include_once "admin_check.php";?>
<?php
include "admin_header.php";
?>
<script type="text/javascript">
function validate_form(){
valid=true;
if(document.form.pagetitle.value===""){
alert("Please Enter a Page Title!");
valid=false;
}else if{
alert("Please Enter Keywords about this Page!");
valid=false;
}
return valid;
}
</script>
<script type="text/javascript">
function validate_form1(){
valid=true;
if(document.form.pid.value===""){
alert("Please Enter a Page ID!");
valid=false;
}
return valid;
}
</script>
<body id="blog">
<div class="container" style="background-color: white; box-shadow: 0 -5px 9px 3px #b2b2b2;">
<br/>
<h2 style="color: #777 ;"><i class="fa fa-book fa-lg"></i> Upload Blog Entry</h2>
<p class="text-danger text-center">Title, Body, and Keywords are required to create new post! None should be left blank!</p>
<h6 class="text-muted pull-right"><< Back Home</h6>
<br/>
<form id="form1" name="form1" method="post" action="edit_blog.php" onsubmit="return validate_form1();" class="form-inline">
<div class="form-group">
<button class="btn-default" type="submit" name="button2" id="button2" value="Edit Post">Edit Post</button>
</div>
<input name="pid" type="text" id="pid" size="8" maxlength="11" class="form-control"/>
<span id="helpBlock1" class="help-block">Enter the ID of the post you want to edit. eg: "blog/article.php?pid=<'this is the id'>"</span>
</form>
<br/>
<form id="form2" name="form2" method="post" action="delete_blog.php" onsubmit="return validate_form2();" class="form-inline">
<div class="form-group">
<button class="btn-default" type="submit" id="button3" name="button3" value="Delete Post">Delete Post</button>
</div>
<div class="form-group"><input type="text" class="form-control" id="pid" name="pid"/></div>
<span id="helpBlock2" class="help-block">Enter the ID of the post you want to delete. eg: "blog/article.php?pid=<'this is the id'>"</span>
</form>
<br/>
<form id="form" name="form" method="post" action="congrat_blog.php" onsubmit="return validate_form();">
<div class="form-group">
<label>Title</label>
<input type="text" name="pagetitle" id="pagetitle" class="form-control" placeholder="Title..." value="<?php echo $pagetitle; ?>"/>
<br/>
<br/>
<label>Body</label>
<textarea name="pagebody" id="pagebody" style="height: 480px; width: 100%" ><?php echo $pagebody; ?></textarea>
<br/>
<label>Keywords</label>
<input type="text" name="keywords" id="keywords" class="form-control" placeholder="blog, mmob, etc..." value="<?php echo $keywords; ?>" />
<br/>
<button type="submit" class="btn-success" name="button" id="button" value="Create this page now">Submit</button>
</div>
</form>
</div>
</body>
<?php include "admin_footer.php"; ?>
^Like this I have multiple pages, all with the php function "session_start();" at the beginning of the document, and I included_once the "admin_check.php" with the "$_SESSION['admin']=$username" function on all of them.
Note: admin_header.php, and admin_footer.php are just HTML header navbar and footer, so I don't have to correct those for individual pages.
I am fairly new to php. Am I on the correct path of doing this?
Basically all I am trying to is a login feature so that the admins can access a back end which will let them upload information into a database, so it populates the site.
Here is the link of the tutorial series I've been following to create this basic CMS:
How to Build PHP and MySQL CMS Website Software
Thanks for your time!
So that tutorial didn't mention having to start the session in every page, but it does.
Therefore session_start(); but be part of all files using sessions.
Error reporting would have helped you here: http://php.net/manual/en/function.error-reporting.php
Another thing that tutorial may not have covered is "passwords".
Use one of the following:
CRYPT_BLOWFISH
crypt()
bcrypt()
scrypt()
On OPENWALL
PBKDF2
PBKDF2 on PHP.net
PHP 5.5's password_hash() function.
Compatibility pack (if PHP < 5.5) https://github.com/ircmaxell/password_compat/
Other links:
PBKDF2 For PHP
Important sidenote about column length:
If and when you do decide to use password_hash() or the compatibility pack (if PHP < 5.5) https://github.com/ircmaxell/password_compat/, it is important to note that if your present password column's length is anything lower than 60, it will need to be changed to that (or higher). The manual suggests a length of 255.
You will need to ALTER your column's length and start over with a new hash in order for it to take effect. Otherwise, MySQL will fail silently.
If you plan on using a database later on, use PDO with prepared statements or mysqli_* with prepared statements
This is just an insight.
Looking at your code, you've forgotten session_start() at the start of your PHP file, it would be a good idea to put this at the top of your PHP file, so that sessions will work. This usually sets (or uses an already passed) cookies which then identifies the user so $_SESSION variables will work.
http://php.net/manual/en/function.session-start.php
Problem : You forgot to start session before setting session in your code.
Solution :
Replace your first portion of code with this one fixed :
<?php
session_start();
$error_msg="";
if ($_POST['username']){
$username=$_POST['username'];
$password=$_POST['password'];
// Simple hard coded values for the correct username and password
$admin="Admin";
$adminpass="Password";
//connect to mysql here if you store admin username and password in your database
//This would be the prefered method of storing the values instead of hard coding them here into the script
if(($username !=$admin)||($password != $adminpass)){
$error_msg='<h3 class="text-danger">Login information incorrect, please try again.</h3>';
} else{
$_SESSION['admin']=$username;
require_once "index.php";
exit();
}
}
?>
Note : Remember to run the session_start() statement on your pages before you try to access the $_SESSION array or trying to set one, and also before any output is sent to the browser.
Reference URL :
http://php.net/manual/en/session.examples.basic.php

PHP - Maintain Session Array Between Pages

I have a session variable that's an array and is supposed to store different usernames. Upon a user trying to log in, the username is checked against the array to see if the name exists within the array. If it's not found within the array the user is re-directed to a registration page, where the user can enter in a username and password.
This page, upon accepting the username and password, is supposed to update the session array, so that the next time the user tries logging in he/she is redirected to a different page.
I am able to register, but think that each time I go back to my main page the usernames array is refreshed to contain 0 entries.
Any way I can make my array more persistent?
products.php
<?php
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Studen Project #6 - M.M.</title>
<link rel="stylesheet" href="mystyles.css" />
</head>
<body>
<h1>Product Listings</h1>
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post">
Username: <input type="text" name="username" /><br>
Password: <input type="password" name="password" /><br><br>
Enter a Quantity for Each Product<br><br>
Pencils: <input type="number" name="pencils" /><br>
Notebooks: <input type="number" name="notebooks" /><br>
Folders: <input type="number" name="folders" /><br><br>
<input type="submit" />
</form>
<h2>Dixon Ticonderoga Wood-Cased Pencils</h2>
<h3>$2.88</h3>
<img src="http://ecx.images-amazon.com/images/I/41OAcvBFqXL.jpg" alt="pencil" />
<p>The World's Best Pencil with an exclusive #2 HB graphite core formula provides extra smooth performance</p>
<h2>Five Star Stay-Put Pocket Folder</h2>
<h3>$5.49</h3>
<img src="http://ecx.images-amazon.com/images/I/71HaaqlhilL._SL1280_.jpg" alt="folder" />
<p>Durable plastic folder helps keep sheets protected and in one place; great for reports, projects, as a take-home folder and for storage</p>
<h2>Five Star Wirebound Notebook</h2>
<h3>$18.98</h3>
<img src="http://ecx.images-amazon.com/images/I/61NgdQwSjIL._SL1000_.jpg" alt="notebook" />
<p>Five-subject plastic cover notebook has 200 college-ruled, 11 x 8.5 inch, 3-hole punched sheets</p>
<?php
$usernames = array();
$_SESSION["usernames"];
$_SESSION["quantity_total"];
$_SESSION["username"];
$_SESSION["pencils"];
$_SESSION["folders"];
$_SESSION["notebooks"];
if($_SERVER["REQUEST_METHOD"] === "POST") {
$_SESSION["usernames"] = $usernames;
$_SESSION["username"] = $_POST["username"];
$_SESSION["pencils"] = $_POST["pencils"];
$_SESSION["folders"] = $_POST["folders"];
$_SESSION["notebooks"] = $_POST["notebooks"];
if(!in_array($_SESSION["username"], $_SESSION["usernames"])) {
header("Location:registration.php");
exit();
} else {
$_SESSION["quantity_total"] = $_SESSION["pencils"] * 2.88 +
$_SESSION["folders"] * 5.49 + $_SESSION["notebooks"] * 18.98;
header("Location:preview.php");
exit();
}
}
?>
</body>
</html>
registration.php
<?php
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Student Project #6 - M.M.</title>
<style>
body {
background-color: lightgreen;
margin: auto;
width: 75%;
text-align: center;
}
h1 {
color: blue;
text-decoration: underline;
}
img {
width: 100px;
height: 100px;
}
form {
padding: 5px;
background-color: lightblue;
font-weight: bold;
font-family: Arial;
}
</style>
</head>
<body>
<h1>Register Here!</h1>
<img src="http://0.media.dorkly.cvcdn.com/36/35/6603dc5a9292104b44c349b85b5aaf7a-5-crazy-fan-theories-that-make-total-sense.jpg"
alt="thumbsup"><br>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"]; ?>">
Username: <input type="text" name="username"><br>
Password: <input type="password" name="password"><br>
<input type="submit" />
</form>
<?php
if($_SERVER["REQUEST_METHOD"] === "POST") {
array_push($_SESSION["usernames"], $_POST["username"]);
header("Location: products.php");
}
?>
</body>
</html>
You might consider rethinking the logic behind storing the list of users/usernames and their properties in the session.
With time, sessions will get bigger and bigger and you're going to have more problems down the line.
Instead, store that information in a database and consult it when needed.
Relative to your issue, the problem you're having with the session array being reset after the data is submitted is caused by this:
#line 41 $usernames = array(); <--- variable set to an empty array
...
if($_SERVER["REQUEST_METHOD"] === "POST") {
#line 50 $_SESSION["usernames"] = $usernames; <---- session variable affected with an empty array
$_SESSION["username"] = $_POST["username"];
...
Hope it helps. Good luck

PHP + MySQL - will not read from database

I'm making a website project for school which requires a log in page. I already have the PHP set up to write to the database, that works no problem. My new problem is that nothing will actually read from the database. I am testing on my localhost, connection is fine. My error I receive is that the email is incorrect, when in fact it is valid. Hopefully you guys can pick up on an easy problem for me! Thanks!
PHP:
<?php
//Setup our DB connection
include('../../connect/local-connect.php');
// Get the user entered elements
$email = $_POST['email'];
$pword = $_POST['password'];
// email query
$query = "SELECT email FROM project WHERE email = '$email'";
//Run email query
$result = mysqli_query($dbc, $query) or die('Read error - email');
// # of results
if (mysqli_num_rows($result) == 0)
{
header('Location:login.php?logerror=1');
exit;
}
//If we got here, we have validated the email
// Build the username query
$query = "SELECT * FROM project WHERE email = '$email' AND password = '$pword'";
// Run the password query
$result = mysqli_query($dbc, $query) or die('Read error - password');
// Did we get a row?
if (mysqli_num_rows($result) == 0)
{
header('Location:login.php?logerror=2');
exit;
}
// If we got here, we have validated an email and password combo.
// Close the DB connection
mysqli_close ($dbc);
// Start a PHP session
session_start();
//Get and store our session variables
$row = mysqli_fetch_array($result);
$_SESSION['sname']=$row['name'];
header('Location:custwelcome.php');
exit;
// Pass a '3' back to login.php for testing (Keep this code at the bottom!)
header('Location:login.php?logerror=3');
exit;
?>
HTML:
<!DOCTYPE html>
<!--
XXXX
login.php
-->
<?php
// Start a PHP session
session_start();
// Check to see if user is already logged in
if(isset($_SESSION["sname"]))
{
header('Location:custwelcome.php');
exit;
}
?>
<html lang="en">
<head>
<!-- Meta tag -->
<meta name="robots" content="noindex.nofollow" />
<meta charset="utf-8" />
<!-- Link tag for CSS -->
<link type="text/css" rel="stylesheet" href="../stylesheet/project.css" />
<!-- Javascript tags -->
<script type="text/javascript" src="../js/messages.js"></script>
<!-- Web Page Title -->
<title>Login Page</title>
</head>
<body>
<div id="header">
<img src="../images/logo.png" alt="Logo" />
<p class="sh1">Shoe Source Unlimited</p>
<p class="sh2">Your source for lightning sales of this season's hot shoes! </p>
<p class="sh3">LeAndra Marx</p>
</div>
<div id="navbar">
<ul id="nav">
<li>
Home
</li>
<li>
Men's
<ul>
<li>Sneakers</li>
<li>Loafers</li>
<li>Athletic</li>
</ul>
</li>
<li>
Women's
<ul>
<li>Boots</li>
<li>Heels</li>
<li>Sandals</li>
</ul>
</li>
<li>
About Us
</li>
<li>
Sign Up
</li>
<li>
Log In
</li>
</ul>
</div>
<div id="external">
<p>
<a href="https://twitter.com/XXXXX" onclick="window.open(this.href); return false;">
<img src="../images/twitter.jpg" alt="twitter" />
</a>
</p>
<p>Follow us on Twitter!</p>
<br/>
<p>
<a href="http://www.facebook.com/ShoeSourceUnlimited" onclick="window.open(this.href); return false;">
<img src="../images/facebook.png" alt="facebook" />
</a>
</p>
<p>Like us on Facebook!</p>
<br/>
<a href="email/projectem.htm">
<img src="../images/email.jpg" alt="pinkemail" />
</a>
<p> Send us an email!</p>
</div>
<div id="main">
<p>Sign in below to start making purchases!</p>
</div>
<p id="registered"> Don't have an account? Sign up here!
<div id="userform">
<p class="fh">Log In Here</p>
<form id="loginform" action="logincheck.php" method="post">
<?php
// Check return codes from logincheck.php
if ($_GET["logerror"] == 1)
{
echo '<p class="loginerror">Invalid Email!</p>';
}
if ($_GET["logerror"] == 2)
{
echo '<p class="loginerror">Invalid Password!</p>';
}
if ($_GET["logerror"] == 3)
{
echo '<p class="loginerror">Returned from logincheck</p>';
}
?>
<p>
<!--Email -->
<label for="email">Email:</label>
<input type="email" id="email" name="email" required autofocus
title="Email: 6-59 characters, lowercase, valid email only!"
pattern="[a-z0-9.-_]+#[a-z0-9-]+\.[a-z]{2,6}"
maxlength="60"
onfocus="emailmsg()" />
<br />
<!--Password -->
<label for="password">Password:</label>
<input type="password" id="password" name="password" required
title="Password: 5-15 characters, U/L, 0-9, . - _ ! $ only!"
pattern="[a-zA-Z0-9.-_!$]{5,15}"
onchange="form.reenter.pattern=this.value;"
onfocus="passmsg()"/>
<br />
<!-- Build buttons so that they are consistent throughout the site
never use get method for confidential data-->
<p class="submit">
<input type="submit"
value=" Log In! "
onfocus="signmsg()"/>
<span class="reset">
<input type="reset" value=" Clear " onclick="history.go(0)"
onfocus="clearmsg()"/>
</span>
</p>
</form>
</div>
<div id="messages">
<p></p>
</div>
<div id="footer">
<p>
©2014, XXXX
</p>
</div>
</body>
</html>
Let me know if any more files need to be looked at I just figured the issue lay in these two files.
MY SOLUTION: All I did was change my table name and it somehow started to work. So that's good, I guess! Thanks to everyone who tried to help :)
is your database connection ok? at first check is connection establish perfectly.
an on top of database connection file please on error reporting to find out error
error_reporing(E_ALL);
ini_set('display_errors',1);
and after database connection use following syntax.. you will get all if any failure in connection
mysql_connect('host','username','password') OR die(mysql_error());
mysql_select_db('dbName') OR die(mysql_error());
<?php
$con=mysqli_connect("host","username","password","my_db");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
for mysqli

Categories