So I'm building a website for PHP & MySQL practice and I'm attempting to set up a member's system. What is supposed to happen is the user goes to the login page and logs in using a registered username and password (Which works in the registration process) and then the page will refresh and take them to the 'members' area. Here's my code:
<?php
if(!empty($_SESSION['LoggedIn']) && !empty($_SESSION['Username'])) {
echo "<h1>Member Area</h1>";
echo "<p>Thanks for logging in! You are <b>" . $_SESSION['Username'] . "</b> and your email address is <b>" . $_SESSION['EmailAddress'] . "</b>.</p>";
} elseif(!empty($_POST['username']) && !empty($_POST['password'])) {
$username = mysql_real_escape_string($_POST['username']);
$password = md5(md5(mysql_real_escape_string($_POST['password'])));
$checklogin = mysql_query("SELECT * FROM users WHERE Username = '".$username."' AND Password = '".$password."'");
if(mysql_num_rows($checklogin) == 1) {
$row = mysql_fetch_array($checklogin);
$email = $row['EmailAddress'];
$_SESSION['Username'] = $username;
$_SESSION['EmailAddress'] = $email;
$_SESSION['LoggedIn'] = 1;
echo "<center>";
echo "<h1>Success</h1>";
echo "<p>We are now redirecting you to the member area.</p>";
echo "<meta http-equiv='refresh' content='2;login.php' />";
echo "</center>";
} else {
echo "<h1>Error</h1>";
echo "<p>Sorry, your account could not be found. Please click here to try again.</p>";
}
} else {
echo "<center>";
echo "<h1>Login</h1>";
echo "<p>Thanks for visiting! Please either login below, or click here to register.</p>";
echo "<form method=\"post\" action=\"login.php\" name=\"loginform\" id=\"loginform\">";
echo "<label for=\"username\">Username:</label><input type=\"text\" name=\"username\" id=\"username\" /><br />";
echo "<label for=\"password\">Password:</label><input type=\"password\" name=\"password\" id=\"password\" /><br /> ";
echo "<input type=\"submit\" name=\"login\" id=\"login\" value=\"Login\" />";
echo "</form>";
echo "</center>";
}
?>
So basically, the page loads and checks if the user is already logged in and if they are, it loads the members area. If not, it checks to see if the user is trying to log in and if not it shows the login form.
My problem is that, every time I or somebody else tries to log in, the page reloads, but instead of taking them to the 'member' area, it takes them back to the login form...
Also, at the top of the document I have a line which is:
<?php include "base.php"; ?>
and in the base.php file I have a session_start(), but maybe that is irrelevant?
Any suggestions? Thanks.
EDIT:
The code to register a user is in a different php file. Again, the base.php file with session_start(); is included at the top of the document:
if(!empty($_POST['username']) && !empty($_POST['password'])) {
$username = mysql_real_escape_string($_POST['username']);
$password = md5(md5(mysql_real_escape_string($_POST['password'])));
$email = mysql_real_escape_string($_POST['email']);
$checkusername = mysql_query("SELECT * FROM users WHERE Username = '".$username."'");
if(mysql_num_rows($checkusername) == 1) {
echo "<h1>Error</h1>";
echo "<p>Sorry, that username is taken. Please go back and try again.</p>";
} else {
$registerquery = mysql_query("INSERT INTO users (Username, Password, EmailAddress) VALUES('".$username."', '".$password."', '".$email."')");
if($registerquery) {
echo "<h1>Success</h1>";
echo "<p>Your account was successfully created. Please click here to login.</p>";
} else {
echo "<h1>Error</h1>";
echo "<p>Sorry, your registration failed. Please go back and try again.</p>";
}
}
} else {
echo "<h1>Register</h1>";
echo "<p>Please enter your details below to register.</p> ";
echo "<form method=\"post\" action=\"register.php\" name=\"registerform\" id=\"registerform\">";
echo " <label for=\"username\">Username:</label><input type=\"text\" name=\"username\" id=\"username\" /><br /> ";
echo " <label for=\"password\">Password:</label><input type=\"password\" name=\"password\" id=\"password\" /><br /> ";
echo " <label for=\"email\">Email Address:</label><input type=\"text\" name=\"email\" id=\"email\" /><br />";
echo " <input type=\"submit\" name=\"register\" id=\"register\" value=\"Register\" />";
echo "</form>";
}
?>
You seem to be missing a
session_start()
at the top of that php script
Always ensure that session_start() is at the top of all other pages concerned also. I would use isset as apposed to !empty.
session_start();
if(isset($_SESSION['LoggedIn']) && isset($_SESSION['Username'])) {
For every page you want to carry over the session to, you have to do
session_start();
even if the session is already created.
assuming you will want a logout page, when you are going to log the users out on a page like logout.php, you must have:
session_start();
session_destroy();
The session_start(); is necessary to destroy the session
mysql_real_escape_string is deprecated, use MySQLi or PDO instead!!!
Also a session_start(); might be useful to work with sessions.
Related
I have a page name authentication.php once licked login it will show the session information in the same page, but when i try to display the same logged user information in another page like userprofile.php it won't show anything
<?php
if ($_POST) {
$logdb = new PDO('mysql:host=localhost;dbname=mydbname', 'root', '12345');
$logdb->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $logdb->prepare("SELECT * FROM users WHERE username=:username AND password=:password");
$stmt->bindParam(":username", $_POST['username']);
$stmt->bindParam(":password", $_POST['password']);
$stmt->execute();
$atributes = $stmt->fetch(PDO::FETCH_OBJ);
if ($atributes) {
session_start();
//$_SESSION["loggedIn"] = true;
$_SESSION['username'] = $_POST['username'];
$_SESSION["ID"] = $atributes->ID;
$_SESSION["country"] = $atributes->country;
} else {
echo 'Login failed!';
}
} else {
echo '<form name="login" action="" method="POST">
Username: <br />
<input type="text" name="username"/><br />
Password: <br />
<input type="password" name="password"/><br />
<button type="submit">Login</button>
Register</form>';
}
?>
<?php
echo ($_SESSION["ID"]);
echo ($_SESSION["username"]);
echo $atributes->country;
?>
Here is what i use in a new page to display logged user information but am not getting any result and also no error please can you assist me on that?
<?php
session_start();
if(!isset($_SESSION['username'])) {
$_SESSION["ID"] = $atributes->ID;
$_SESSION["username"] = $atributes->username;
$_SESSION["country"] = $atributes->country;
} ?>
<?php
echo ($_SESSION["ID"]);
echo ($_SESSION["username"]);
echo $atributes->country;
?>
Also at the header of my page i have a navbar like this
<?php if(!isset($_SESSION['username'])) {
include($root . 'includings/unloggedU.php');
}else{
include($root . 'includings/loggedU.php');
} ?>
On the first page set $_SESSION['country'] = $atributes->country; as there is currently no session variable set for that in your code.
And on the second page you should have access to all of the session variables - which you can test individually to see if they are set if you want to.
<?php
session_start(); // always put this at the top of the page see Ryan's comments
echo $_SESSION["ID"] . "<br />";
echo $_SESSION["username"] . "<br />";
echo $_SESSION["country"] . "<br />";
?>
I am learning PHP, and I'm busy with this tutorial over here:
https://www.youtube.com/watch?v=kebwxI1Bw88
I did everything according to the video and went over it 3 times, but my script isn't working... and I was wondering if anyone can help me figure out why? My code seems to be exactly like the guy's code on the video.
The video is about creating the login functionality for a forum. What happens with my script is.... It does what it's supposed to when I type in the WRONG user/pass combination (showing the message that it's supposed to show). But, when I type in the RIGHT user/pass combination... The file redirects to the index like it's supposed to... but it's still displaying the login form and not showing the "You are logged in as _ " message.
My Login Form on the index page:
if (!isset($_SESSION['uid'])) {
echo "<form action='login_parse.php' method='post'>
Username: <input type='text' name='username' />
Password: <input type='password' name='password' />
<input type='submit' name='submit' value='Log In'>
";
} else {
echo "<p>You are logged in as ".$_SESSION['username']." $bull; <a href='logout_parse.php'>Logout</a>";
}
My login_parse.php file:
session_start();
include_once("connect.php");
if (isset($_POST['username'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE username='".$username."' AND password='".$password."' LIMIT 1";
$res = mysql_query($sql) or die (mysql_error());
if (mysql_num_rows($res) == 1) {
$row = mysql_fetch_assoc($res);
$_SESSION['uid'] = $row['id'];
$_SESSION['username'] = $row['username'];
header("Location: index.php");
exit ();
} else {
echo "Invalid login information. Please return to the previous page. ";
exit ();
}
}
Check if $_SESSION['uid'] has a value.
print_r($_SESSION);
to see all the values
The following script works fine, it allows a user to log in.
After they log in, this line of code requests them to click on a link to go to the members.php page.
die("You are now logged in. Please <a href='members.php'>" ."click here</a> to continue.<br /><br />");
Is there a way that I can get the page to automatically redirect to members.php after they log in?
<?php // login.php
include_once 'header.php';
echo "<div class='main'><h3>Please enter your details to log in</h3>";
$error = $user = $pass = "";
if (isset($_POST['user']))
{
$user = sanitizeString($_POST['user']);
$pass = sanitizeString($_POST['pass']);
$pass_hash = md5($pass);
if ($user == "" || $pass == "")
{
$error = "Not all fields were entered<br />";
}
else
{
$query = "SELECT user,pass FROM members
WHERE user='$user' AND pass='$pass_hash'";
if (mysql_num_rows(queryMysql($query)) == 0)
{
$error = "<span class='error'>Username/Password
invalid</span><br /><br />";
}
else
{
$_SESSION['user'] = $user;
$_SESSION['pass'] = $pass;
die("You are now logged in. Please <a href='members.php'>" . "click here</a> to continue.<br /><br />");
}
}
}
echo <<<_END
<form method='post' action='login.php'>$error
<span class='fieldname'>Username</span><input type='text'
maxlength='16' name='user' value='$user' /><br />
<span class='fieldname'>Password</span><input type='password'
maxlength='16' name='pass' value='$pass' />
_END;
?>
<br />
<span class='fieldname'> </span>
<input type='submit' value='Login' />
</form><br /></div></body></html>
Yes, there is:
header('Location: members.php');
exit;
Remember to include the exit so that your code stops running even if there is a problem processing the header.
Also note, this needs doing before any output is made whatsoever.
http://php.net/manual/en/function.header.php
<?php
if(isset($_POST['user'])){
$user = sanitizeString($_POST['user']);
$pass = sanitizeString($_POST['pass']);
$pass_hash = md5($pass);
if ($user == "" || $pass == ""){
$error = "Not all fields were entered<br />";
}else{
$query = "SELECT user,pass FROM members WHERE user='$user' AND pass='$pass_hash'";
if (mysql_num_rows(queryMysql($query)) == 0){
$error = "<span class='error'>Username/Password invalid</span><br /><br />";
}else{
$_SESSION['user'] = $user;
$_SESSION['pass'] = $pass;
header('Location: members.php');
exit;
}
}
}
include_once 'header.php'; //Any output must be after your header code
echo <<<_END
<form method='post' action='login.php'>$error
<span class='fieldname'>Username</span><input type='text' maxlength='16' name='user' value='$user' /><br />
<span class='fieldname'>Password</span><input type='password' maxlength='16' name='pass' value='$pass' />
_END;
?>
<br />
<span class='fieldname'> </span>
<input type='submit' value='Login' />
</form><br /></div></body></html>
BTW - I have not checked any of your code except that which I mention above
At the point where you have the die() line, you can do this
ob_clean();
header('Location: http://www.example.com');
exit;
If headers are giving you a hard time, you can use this alternate (meta) method:
Where you presently have die("You are now logged in... do:
echo "You are not logged in. You will be redirected in 5 seconds...";
echo "<meta http-equiv=Refresh content=5;url=http://www.yoursite.com/members.php>";
Sidenote: Replace the 5 in content=5 with the amount of seconds you wish to take for the redirection. Using 0 will redirect right away.
It's not the best method but it works in many instances.
Another method is to add ob_start(); under your opening <?php tag which works at times.
Example:
<?php
ob_start();
// login.php
include_once 'header.php';
echo "<div class='main'><h3>Please enter your details to log in</h3>";
$error = $user = $pass = "";
...
$_SESSION['user'] = $user;
$_SESSION['pass'] = $pass;
// die("You are now logged in....
// keep the http:// and replace with your website address
header('Location: http://www.example.com/members.php');
exit;
...
Ok im stuck with this. I tried the isset function but nothing happens...
Once logged in, the user will be redirected to a specific page.
If moderator is her user_type then she'll be redirected to moderator.php page
If agent is her user_type she'll be redirected to agent.php
I've here the index.php where login form is included
<form action="index.php" method=get>
<?php
session_start();
if ($_SESSION["logging"] && $_SESSION["logged"]) {
printme();
}
else {
if (!$_SESSION["logging"]) {
$_SESSION["logging"] = true;
loginform();
}
else if ($_SESSION["logging"]) {
$number_of_rows = checkpass();
if ($number_of_rows == 1) {
$_SESSION[user] = $_GET[userlogin];
$_SESSION[logged] = true;
echo "<h1>You have logged in successfully</h1><br/>";
echo "<a href='logout.php'>Logout</a> | <a href='users.php'>Click to proceed</a>";
}
else {
loginform();
}
}
}
function loginform() {
print ("<center><div id='login_header'><b><font face='Arial Black' color='black' size='4px'>Sign in to Minquep!</font></b></div></cen ter>");
print("<br/><br/>");
print ("<center><label>Username:</label><input type='text' name='userlogin' size='20'><br/><label>Password:</label><input type=' password' name='password' size='20'></center>");
print "<br/><input type='submit' value='Submit' name='submit' class='submit'>";
}
function checkpass() {
$dbHost = 'localhost';
$dbUser = 'root';
$dbPass = '';
$dbname = 'minquep_test';
$conn = mysql_connect($dbHost, $dbUser, $dbPass); // Connection Code mysql_select_db($dbname, $conn); // Connects to database
$sql = "select * from users where login='$_GET[userlogin]' and password='$_GET[password]'";
$result = mysql_query($sql, $conn) or die(mysql_error());
$fetched = mysql_fetch_array($result);
if ($fetched['user_type'] == "moderator") {
echo '<script type="text/javascript">window.alert("You have logged in successfully!\n")</script>';
print("<b><h1>hi mr.$_SESSION[user]</h1>");
echo "<meta http-equiv=\"refresh\" content=\"0;URL=pages/moderator.php\">";
}
else if ($fetched['user_type'] == "agent") {
echo '<script type="text/javascript">window.alert("You have logged in successfully!\n")</script>';
echo "<meta http-equiv=\"refresh\" content=\"0;URL=pages/agent.php\">";
}
}
function content() {
print("<b><h1>hi mr.$_SESSION[user]</h1>");
print "<br><h2>only a logged in user can see this</h2>";
}
function printme() {
echo '<script type="text/javascript">window.alert("You have logged in successfully!\n")</script>';
}
?>
</form>
From that code above this is how I redirect users to their specific pages based on their user_type.
if ($fetched['user_type'] == "moderator") {
echo '<script type="text/javascript">window.alert("You have logged in successfully!\n")</script>';
print("<b><h1>hi mr.$_SESSION[user]</h1>");
echo "<meta http-equiv=\"refresh\" content=\"0;URL=pages/moderator.php\">";
}
else if ($fetched['user_type'] == "agent") {
echo '<script type="text/javascript">window.alert("You have logged in successfully!\n")</script>';
echo "<meta http-equiv=\"refresh\" content=\"0;URL=pages/agent.php\">";
}
Now inside my moderator.php
I just call the moderator_include.php where I supposed to print the username and user_type of the logged in user.
moderator.php
<div id="wrapper">
<div id="container">
<div id="header">
<?php include "moderator_header.php"; ?>
</div>
It includes the moderator_header.php which is
<div class="logo">
<img class="logo_img" src="../images/minquepLOGO.png"/>
</div>
<div id="title">
<img src="../images/title.gif"/>
</div>
<br/>
<?php
session_start();
if ($_SESSION["logged"] = true) {
print("<b><h1>hi mr. $_SESSION[user] . You are logged in as /*THE USER_TYPE GOES HERE */ </h1>");
}
?>
I tried to output the username as
if (isset($_SESSION['logged'])){
print("<b><h1>hi mr. $_SESSION[user] . You are logged in as /*THE USER_TYPE GOES HERE */ </h1>"); }
But nothing happens...
About how to output the user_type of the user... I dont have any idea how to this because it's not a part of session happened in index.php
Btw my logout.php is like this
<?php
session_start();
if (session_destroy()) {
print"<h2><B><blink>you have logged out successfully</B></blink></h2>";
print "<h3><a href='index.php'>back to main page</a></h3>";
}
?>
please help me...thanks
sometimes php gets a little tricky ... a few things to remember
1) always start the session before anyoutput, it means at top of your code, before starting the session there shouldnt be even a single blank space or an empty line.
2) when you have a file that starts session, and includes another file, youd dont have to start it again in the file included.
and inorder to trace your session, in any page you want just add this code :
<pre><?php print_r($_SESSION); ?></pre>
and see what the result is.
print("<b><h1>hi mr " . $_SESSION['user'] . "You are logged in as" . $userType . "</h1>"); }
Try it :)
EDIT
edit the variable $userType to what it should be...
This is my login.php
<form action="index.php" method=get>
<?php
error_reporting(E_ALL & ~E_NOTICE);
?>
<?php
session_start();
if( $_SESSION["logging"]&& $_SESSION["logged"])
{
printme(); }
else {
if(!$_SESSION["logging"])
{
$_SESSION["logging"]=true;
loginform();
}
else if($_SESSION["logging"])
{
$number_of_rows=checkpass();
if($number_of_rows==1)
{
$_SESSION[user]=$_GET[userlogin];
$_SESSION[logged]=true;
echo "<h1>You have logged in successfully</h1><br/>";
echo "<a href='logout.php'>Logout</a> | <a href='users.php'>Click to proceed</a>";
}
else {
loginform();
}
}
}
function loginform()
{
print ("<center><div id='login_header'><b><font face='Arial Black' color='black' size='4px'>Sign in to Minquep!</font></b></div></cen ter>");
print("<br/><br/>");
print ("<center><label>Username:</label><input type='text' name='userlogin' size='20'><br/><label>Password:</label><input type=' password' name='password' size='20'></center>");
print "<br/><input type='submit' value='Submit' name='submit' class='submit'>";
}
function checkpass()
{
$dbHost = 'localhost';
$dbUser = 'root';
$dbPass = '';
$dbname = 'minquep_test';
$conn = mysql_connect($dbHost,$dbUser,$dbPass); // Connection Code
mysql_select_db($dbname,$conn); // Connects to database
$sql = "select * from users where login='$_GET[userlogin]' and password='$_GET[password]'";
$result = mysql_query($sql,$conn) or die(mysql_error());
$fetched = mysql_fetch_array($result);
if ($fetched['user_type'] == "moderator"){
echo '<script type="text/javascript">window.alert("You have logged in successfully!\n")</script>';
echo "Welcome {$_SESSION['user']}";
echo "<meta http-equiv=\"refresh\" content=\"0;URL=pages/moderator.php\">";
}
if ($fetched['user_type'] == "agent"){
echo '<script type="text/javascript">window.alert("You have logged in successfully!\n")</script>';
echo "<meta http-equiv=\"refresh\" content=\"0;URL=pages/agent.php\">";
}
}
function content(){
print("<b><h1>hi mr.$_SESSION[user]</h1>");
print "<br><h2>only a logged in user can see this</h2>";
}
function printme(){
echo '<script type="text/javascript">window.alert("You have logged in successfully!\n")</script>';
}
?>
</form>
Now whenever a user logs in... if his user_type is "moderator" he will be redirected to moderator.php
and if his user_type is "agent" he will be redirected to agent.php
what i want to happen is to output the username and usertype in the pages that a user will be redirected to.
This is what I've got in my agent.php and moderator.php
<?php session_start();
echo "Welcome {$_SESSION['user']} . And You are Logged in as /*USER TYPE SHOULD BE DISPLAYED HERE */ ";
?>
I get this error:
try this in your agent.php
<?php session_start();
if (array_key_exists('user', $_SESSION) && !empty($_SESSION['user'])) {
echo "Welcome {$_SESSION['user']} . And You are Logged in as /*USER TYPE SHOULD BE DISPLAYED HERE */ ";
} else {
echo "Welcome stranger";
}
?>
Since you have different PHP files, moderator.php and agent.php, you may simply use;
In moderator.php,
echo "Welcome {$_SESSION['user']} . And You are Logged in as MODERATOR";
and in agent.php,
echo "Welcome {$_SESSION['user']} . And You are Logged in as AGENT";
No big tasks..