I think It is not a hard problem, but I was stuck in it.
Currently I built up a log in and sign up(registration) interface using php.
My thought is direct:
index.php shows "log in" and "sign up", if you do not have an account in database, you are led to "sign up" page, after filling out all information needed, I would like to direct the user to a page which shows "you are registered as ". The problem is here, I tried to use $_SESSION['username'] to correspond to who the user is. But unfortunately no username is print out. I used isset() in registered.php to check if $_SESSION['username'] is set. It shows it is not set, but it should be there!!!
The flow line is signup.php -> register.php -> registered.php. My question is $_SESSION['username'] should be passed down in the php files after declaration of session_start(). Below is my code, would some one point out where I went wrong.
Thanks a lot.
signup.php
<?php
session_start(); // attention add session_start() again, am I wrong?
$title = "Sign up";
print_r($_SESSION);
?>
<html>
<head>
<title><?= $title ?></title>
<!--
<link href="index.css" type="text/css" rel="stylesheet"></link>
-->
<link href="signup.css" type="text/css" rel="stylesheet"></link>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="index.js"></script>
</head>
<body>
<div id="main-content">
<form method="post" action="register.php">
<label><input class="defaultText" title="username" name="username" type="text"></label><br/>
<label><input class="defaultText" title="email" name="email" type="text"></label><br/>
<label><input class="defaultText" title="company" name="company" type="text"></label><br/>
<label class = "password">password:<input name="pass1" type="password" /></label><br/>
<label class = "password">password (again):<input name="pass2" type="password"/></label><br/>
<input type="submit" value="Sign up!">
</form>
<div style="clear: both;"></div>
</div>
</body>
</html>
register.php
<?php
if(isset($_REQUEST['username']) && isset($_REQUEST['email']) && isset($_REQUEST['company']) && isset($_REQUEST['pass1']) && isset($_REQUEST['pass2'])){
$username = $_REQUEST['username'];
$email = $_REQUEST['email'];
$company = $_REQUEST['company'];
$pass1 = $_REQUEST['pass1'];
$pass2 = $_REQUEST['pass2'];
if(strlen($username) <= 0) {
die("Username must be greater than 0 characters\n");
}
if(strlen($email) <= 0) {
die("Email must be greater than 0 characters\n");
}
if(strlen($company) <= 0) {
die("Company name must be greater than 0 characters\n");
}
if($pass1 != $pass2 && $pass1 <= 0) {
die("Passwords are not the same.");
}
$hash = hash('sha256', $pass1);
# connect to world database on local computer
check(mysql_connect("localhost", "root", "123456"), "connect");
$connect = mysql_connect("localhost", "root", "123456");
# in order to insert data into database tables, database is already there built via mySQL command from terminal
# connect with the database
check(mysql_select_db("product"), "selecting db");
# mysql_real_escape_string() This function must always (with few exceptions) be used to make data safe before sending a query to MySQL.
$username = mysql_real_escape_string($username);
$email = mysql_real_escape_string($email);
$company = mysql_real_escape_string($company);
# this $query query is to send the "insert values" query into a table
$query = "INSERT INTO admins ( username, hash, email, company ) VALUES ( '$username', '$hash', '$email', '$company' );";
$results = mysql_query($query);
check($results, "adding user"); // if not pass show error message
header("Location: registered.php");
}
function check($result, $message) {
if (!$result) {
die("SQL error in $message: " . mysql_error());
}
$_SESSION['username'] = $_REQUEST['username'];
$_SESSION['email'] = $_REQUEST['email'];
$_SESSION['company'] = $_REQUEST['company'];
}
?>
registered.php
<?php
$title = "Registered!";
?>
<html>
<head>
<title><?= $title ?></title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="index.js"></script>
</head>
<body>
<?php
print_r($_SESSION);
if(isset($_SESSION['username']))
print "hello";
print $_SESSION['username'];
echo $_SESSION['company'];
?>
<div id="main-content">
<h3>You have registered in administration system as <?= $_SESSION['username'] ?></h3>
<table border="1">
<tr>
<th>Name</th>
<th>Company</th>
<th>Email</th>
</tr>
<tr>
<td><?= $_SESSION['username'] ?></td>
<td><?= $_SESSION['email'] ?></td>
<td><?= $_SESSION['company'] ?></td>
</tr>
<h3>please log in into the administration system</h3>
<h4>Log In</h4>
</table>
<div style="clear: both;"></div>
</div>
</body>
</html>
You need to add session_start(); on every page before any content.
register.php and registered.php are missing the session starter and they both use $_SESSION
Edit: like Mike Brant said, make a global file which starts the session and include it in every file before any content. That way you can have all your common variables and session in a single file.
Related
I am unable to display $_SESSION['username'] on my index.html/auth.php page after logging in. It's strange because it's able to detect $_SESSION['username'] on other pages after logging in, just not my index/auth page.
EDIT: When logging in correctly, login.php goes to index.html. index.html is then displaying the 'login' button from auth.php, as ' Login '
login.php, where the user will enter the username and password to login and $_SESSION['username'] is created.
<?php session_start();
require('db.php');
// If form submitted, insert values into the database.
if (isset($_POST['username'])){
// removes backslashes
$username = stripslashes($_REQUEST['username']);
//escapes special characters in a string
$username = mysqli_real_escape_string($con,$username);
$password = stripslashes($_REQUEST['password']);
$password = mysqli_real_escape_string($con,$password);
//Checking is user existing in the database or not
$query = "SELECT * FROM `users` WHERE username='$username'
and password='".md5($password)."'";
$result = mysqli_query($con,$query) or die(mysql_error());
$rows = mysqli_num_rows($result);
if($rows==1){
$_SESSION['username'] = $username;
// Redirect user to index.html
header("Location: ../index.html");
}else{
echo "<div class='form'>
<h3>Username/password is incorrect.</h3>
<br/>Click here to <a href='login.php'>Login</a></div>";
}
}else{
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Login</title>
<link rel="stylesheet" href="login.css" />
</head>
<body>
<div class="form">
<h1>Log In</h1>
<form action="" method="post" name="login">
<input type="text" name="username" placeholder="Username" required style="text-align: center;"/>
<input type="password" name="password" placeholder="Password" required style="text-align: center;"/>
<input name="submit" type="submit" value="Login" />
</form>
<a href='resetpassword.php'>Forgotten Password?</a>
<br/><a href='registration.php'>Register Here</a>
</div>
<?php } ?>
</body>
</html>
index.html, where the auth.php page is called (the rest of my index.html page is not important to this issue, replaced with 'blah blah blah').
EDIT: My server is configured so that index.html can run php.
<?php session_start(); ?>
<?php require('login/auth.php'); ?>
<?php include('login/checkadmin.php'); ?>
<?php include('login/getoutages.php'); ?>
<!doctype html>
<html>
blah blah blah
</html>
auth.php, where the database is used and where $_SESSION['username'] is meant to show but doesn't!
<?php session_start();
ob_end_clean();
if(isset($_SESSION['username'])) {
?>
<table id="signedin">
<tr>
<td colspan="5">
Welcome, <?php echo $_SESSION['username']; ?>!
</td>
</tr>
<tr>
<td align="right">
<a id="logouts" href="login/logout.php">Sign Out</a>
</td>
<td align="right">
</td>
<td align="left">
<a id="profiles" href="login/profile.php">Profile</a>
</td>
</tr>
</table>
<?php } else if(!isset($_SESSION['username'])) { ?>
<div id="notsignedin"><a id="logins" href="/login/login.php">Login</a></div>
<?php } ?>
Any information is helpful! Thank you!
EDIT: I have updated my code to run session_start(); before anything else.
Still unable to detect $_SESSION['username'].
EDIT2: Switched $username = $_SESSION['username']; in login.php to $_SESSION['username'] = $username; Still not showing on auth.php
You should start the session in every file before anything else
<?php session_start(); ?>
At least if you are calling every page separately
You need to call session_start() before checking the issest($_Session['username'])
You need to put session_start(); before it calls $_SESSION variables on that page, therefore if(isset($_SESSION['username']) will not be "set" until the session is started, just move it to above in the page, it's good practice to call it in first. I usually put it in my config page along with my DB connection and include it in every page :)
Hope this helps
I have some problem in php. Here is my code:
if (isset($_POST['submit'])) { // Form has been submitte
echo "Submitted";
$username = trim($_POST['username']);
$password = trim($_POST['password']);
// Check database to see if username/password exist.
$found_user = User::authenticate($username, $password);
if ($found_user) {
$session->login($found_user);
redirect_to("index.php");
}
} else { // Form has not been submitted.
$username = "";
$password = "";
}
?>
<html>
<head>
<title>Photo Gallery</title>
<link href="../stylesheets/main.css" media="all" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="header">
<h1>Photo Gallery</h1>
</div>
<div id="main">
<h2>Staff Login</h2>
<form action="login.php" method="post">
<table style="float: left;">
<tr>
<td>Username:</td>
<td>
<input type="text" name="username" maxlength="30" value="
<?php echo htmlentities($username); ?>" />
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<input type="password" name="password" maxlength="30" value="
<?php echo htmlentities($password); ?>" />
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="submit" value="Login" />
</td>
</tr>
</table>
</form>
</div>
<div id="footer">Copyright <?php echo date("Y", time()); ?>, Gio baramidze</div>
</body>
</html>
My problem is that when i try to log in with incorrect user everything works fine and message "submitted" comes on the screen. But when i write correct username and password and click "Log in" it doesn't even show me the message ("submitted"). It means that "if (isset($_POST['submit']))" this condition isn't true. Despite the fact that I've clicked Submit. Thanks.
My guess is above code is index.php. When a user is found it redirects to the same page (quickly) and thus no $_POST is set since it is reloaded.
if ($found_user) {
$session->login($found_user);
redirect_to("index.php"); //If user found redirect without $_POST information.
}
You should make use of the $_SESSION array. This is a server side array, you can fill it with a user ID once a user logs in. On every page where you need to check a login you should include a script that checks for the this ID. You can also use this to store a users name or other stuff you need frequent access to:
$_SESSION['USER_ID'] = //Some ID
$_SESSION['USERNAME'] = $username
To make $_SESSION work you need something like this:
<?php
session_start();
//other code...
if ($found_user) {
$session->login($found_user);
//give the user an ID
$_SESSION['USER_ID'] = //some id, usually fetched from a database
//Let's give a name too
$_SESSION['USERNAME'] = $username;
//Now redirect
redirect_to("index.php"); //If user found redirect without $_POST information.
}
//Other code...
?>
Now from index.php we start again with session_start(); and we can use php to retrieve his ID and name. Put this on top and you see that $_SESSION gets carried over to other pages on the server.
<?php
session_start();
echo $_SESSION['USER_ID'];
echo $_SESSION['USERNAME'];
//or something nicer
if (isset($_SESSION['USER_ID']))
{
echo "User ".$_SESSION['USERNAME']." has logged in and has user id [".$_SESSION['USER_ID']."].";
}
else
{
echo "Not logged on."
}
?>
For testing purpose you can store the above code in whatever.php and redirect to whatever.php inside your login.php. It should pass the if statement if a user is found on login.php and thus show the username and ID.
You might change isset($_POST['submit']) by
if(isset($_POST['username']) && isset($_POST['password'])){
//do your stuff here
}
Alright, SO. After about five hours of sifting through potential duplicates and applying would-be solutions to my project and even downloading a PHP IDE to make sure that my syntax is all nice and tidy for everyone.. I am finally at the point where I need some advice.
My two problems (which may be related):
When someone logs in, successfully with the test parameters I have stored in the DB, they are not redirected (maybe my if statement is not correct?)
When the page loads without first attempt, my "wrong password - username combination" message is displaying. I'm fairly certain as to why but not too sure how to fix it.
<?php session_start(); // this line of code has been added by the instruction of a comment.
if(isset($submit)) {
$username = $_POST['username'];
$password = $_POST['password'];
}
$con = mysqli_connect("***","***","***","***");
$S_username = mysqli_real_escape_string($con, $username);
$S_password = mysqli_real_escape_string($con, $password);
if(mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = mysqli_query($con, "SELECT * FROM `users` WHERE `username` = '$S_username' AND `password` = '$S_password'");
if(!$sql) {
die(mysqli_error($con)) ;
}
$check_again = mysqli_num_rows($sql);
if($check_again == 1) {
session_start(); // this line of code has been deleted
$_SESSION['logged in'] = TRUE;
$_SESSION['username'] = $S_username;
header("Location: http://terrythetutor.com/submitvideo.php");
}
else {
echo "Your username and password combination was not recognised. Please try again." ;
}
?>
<html>
<head>
<title>Login Page</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<?php include_once 'googleanalytics.php'; ?>
<body>
<a href="http://terrythetutor.com">
<div class="banner"> </div>
</a>
<?php include 'menu.php'; ?>
<h1 align="center">Please login to access restricted files</h1>
</br>
</br>
</br>
</br>
<div align="center">
<form action = "login.php" method = "post">
Username: <input type = "text" name = "username"></br></br>
Password: <input type = "password" name = "password"></br></br>
<input type = "submit" value = "Login" name="submit">
</form>
</div>
</body>
</html>
Any and all feedback is welcomed. Thank you.
use session_start(); only once and at the top ..
I am creating a form for log in and log out .
My problem is when a user submit their username and password then display welcome message with that username.Files are given below.
include.php
<?php
session_start();
$host = "VKSolutions";
$username = "VKSolutions";
$password = "VKSolutions#1";
$db = "VKSolutions";
#mysql_connect($host,$username,$password) or die ("error");
#mysql_select_db($db) or die("error");
?>
login.php
<?php
require_once('include.php');
$error = '';
$form = $_POST['submit'];
$user = $_POST['user'];
$password = $_POST['password'];
if( isset($form) ) {
if( isset($user) && isset($password) && $user !== '' && $password !== '' ) {
$sql = mysql_query("SELECT * FROM `accounts` WHERE user='$user' and
password='$password';");
if( mysql_num_rows($sql) != 0 ) { //success
$_SESSION['logged-in'] = true;
header('Location: members.php');
exit;
} else { $error = "Incorrect login info"; }
} else { $error = 'All information is not filled out correctly';}
}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Login</title>
</head>
<body>
<table width="80%" border="0"><form action="<?php $PHP_SELF; ?>" method="post" >
<tr>
<td><label>Employee Name:</label></td>
<td><input name="user" placeholder="Enter Name" type="text" value="<?php echo "$user";?>" /></td>
</tr>
<tr>
<td><label>Password:</label></td>
<td><input name="password" placeholder="Enter Password" type="password" /></td>
</tr>
<tr>
<td> </td>
<td><input valin="right" name="submit" type="submit" value="Log In" /></td>
</tr></form>
</table>
<?php
echo "<br /><span style=\"color:red\">$error</span>";
?>
</body>
</html>
members.php
<?php
require_once('include.php');
if ( !isset($_SESSION['logged-in']) || $_SESSION['logged-in'] !== true) {
header('Location: login.php');
exit;
}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Staff Area</title>
</head>
<body>
<div style="margin-top:50px; color:#00F; margin-left:50px; font-size:18px; position:absolute">Welcome<?php echo "$user";?></div>
</body>
</html>
logout.php
<?php
session_start();
// if the user is logged in, unset the session
if (isset($_SESSION['logged-in'])) {
unset($_SESSION['logged-in']);
}
// now that the user is logged out,
// go to login page
header('Location: login.php');
?>
In my members.php it is log in but not display with username. I need that username.
Please find out what is wrong.
Thanks.
You need to create $_session variable since HTTP is a stateless protocol. Your variables defined in login.php is not available to members.php unless you store them in session.
first in the login.php
session_start();
$_SESSION['user'] = $_POST['user'];
then in your members.php file
session_start();
$user = $_SESSION['user'];
will allow you to access it.
Just use a session variable like $_SESSION['user']= $_POST['user']; and then display it using echo $_SESSION['user'].
Also make sure that you add session_start(); at the beginning of the php file.
You need to register your session username like this
session_start();
$_SESSION['user'] = $_POST['user'];
then retrieve your session username to display username message
echo $_SESSION['user'];
The PHP script I have for the login.php which is the form is the code below.
<?php
include 'dbc.php';
$user_email = mysql_real_escape_string($_POST['email']);
if ($_POST['Submit']=='Login')
{
$md5pass = md5($_POST['pwd']);
$sql = "SELECT id,user_email FROM users WHERE
user_email = '$user_email' AND
user_pwd = '$md5pass' AND user_activated='1'";
$result = mysql_query($sql) or die (mysql_error());
$num = mysql_num_rows($result);
if ( $num != 0 ) {
// A matching row was found - the user is authenticated.
session_start();
list($user_id,$user_email) = mysql_fetch_row($result);
// this sets variables in the session
$_SESSION['user']= $user_email;
if (isset($_GET['ret']) && !empty($_GET['ret']))
{
header("Location: $_GET[ret]");
} else
{
header("Location: myaccount.php");
}
//echo "Logged in...";
exit();
}
header("Location: login.php?msg=Invalid Login");
//echo "Error:";
exit();
}
?>
<link href="styles.css" rel="stylesheet" type="text/css">
<?php if (isset($_GET['msg'])) { echo "<div class=\"msg\"> $_GET[msg] </div>"; } ?>
<p> </p><table width="40%" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td bgcolor="#d5e8f9" class="mnuheader" >
<div align="center"><font size="5"><strong>Login
Members</strong></font></div></td>
</tr>
<tr>
<td bgcolor="#e5ecf9" class="mnubody"><form name="form1" method="post" action="">
<p> </p>
<p align="center">Your Email
<input name="email" type="text" id="email">
</p>
<p align="center"> Password:
<input name="pwd" type="password" id="pwd">
</p>
<p align="center">
<input type="submit" name="Submit" value="Login">
</p>
<p align="center">Register | Forgot</p>
</form></td>
</tr>
I want to create a session vairable like the $_SESSION['user']= $user_email; which i can use in other pages. The problem is i don't know how to do so and i want to select a different row from my database called points. So it will be something like
$sql = "SELECT id,user_email,points FROM users WHERE
user_email = '$user_email' AND
user_pwd = '$md5pass' AND user_activated='1'";
Like i say i want it to select the number of points so it can be used on all pages where the session has been start.
Here is an account page which echos the logged in user. But i want it to also echo the points row from my database.
<?php
session_start();
if (!isset($_SESSION['user']))
{
die ("Access Denied");
}
?>
<h2>My Account </h2>
<?php if (isset($_SESSION['user'])) { ?>
<p>Logged as <?php echo $_SESSION['user']; ?>
Settings
Logout </p>
<?php } ?>
Thank you for your help!
put the session_start() start of the page
<?php
session_start();
your code follows this line the variables were working.
You must place session_start() at the top of any pages you want to carry the session over to, so try that and see if that works :)
you should have the following to return a assoc array with the users details into a variable $user.
$sql = "SELECT * FROM users WHERE user_email = '{$_SESSION['user']}'";
$res = mysqli_query($sql);
$user = mysqli_fetch_assco($res);
Also, mysql_ is depreciated, so you should change all of your references of mysql_ to mysqli_
To creat a session variable,try doing the same as $_SESSION['user']= $user_email
So $_SESSION['WhateverYouWant']= $Anything