Hello reading websites and forums i have learned that, content can be prevented using sessions.I have a index.php page which checks sessions and give results as per the condition:
<?php
session_start();
if( $_SESSION['user'] != $name ) { echo "Sorry,no session found or is expired";
require( 'login.php' );
}
else {
echo "hello,you have session existing";
}
?>
I have table created details
FNAME
LNAME
BDAY
PASS
EMAIL
CODES
login.php is as follows:
<?php
$name = $_POST['name'];
$pass = $_POST['pass'];
mysql_connect('mysqlhost','user','pass','userdatabase');
$query=mysql_query(sprintf("SELECT FNAME FROM `details` WHERE FNAME=$name AND PASS=$pass";
mysql_real_escape_string($PASS)));
if($query) { while($row = mysql_fetch_assoc($query)) { $rows[1] = $row; } }
if( isset($name) || isset($pass) )
{
if( empty($name) ) {
die ("ERROR: Please enter username!");
}
if( empty($pass) ) {
die ("ERROR: Please enter
password!");
}
if( $name == $rows[1][FNAME] &&
$pass == $rows[1][PASS] )
{
session_start();
$_SESSION['user'] = $_POST['name'];
header('Location: index.php');
}
else {
echo "ERROR: Incorrect username
or password!";
}
}
else {
?>
<html>
<head>
<body>
//Load login form here & save $SESSION value in "name"
</html>
<?php } ?>
So,my code is going wrong somewhere and cannot see "hello,you have session existing".Any help again would be gratefull.(Code can be half viewed, sorry for that)
Try this -
if( !isset( $_SESSION[ "user" ] ) )
instead of
if( $_SESSION['user'] != $name )
In login.php you must somehow pass the value of $_POST['name'] as $name to index.php, and also it's really a bad idea to put session as password, few tips:
1) use a user id, say 1,2,3... and add a primary key to it, and use that id to do stuff like granting access.
2)md5 your pass while registering, and check it like
if (md5($_POST['pass']) == $pass) {
//some code
};
Related
Here i am using header function to redirect to home.php after login, but header function is not redirecting to that page. Even when i run same code on my local computer it works fine.
<?php
ob_start();
session_start();
require_once 'phpconnection.php';
// it will never let you open index(login) page if session is set
if ( isset($_SESSION['user'])!="" ) {
header("Location:home.php");
exit;
}
$error = false;
if( isset($_POST['btn-logIn']) ) {
// prevent sql injections/ clear user invalid inputs
$email = trim($_POST['email']);
$email = strip_tags($email);
$email = htmlspecialchars($email);
$pass = trim($_POST['password']);
$pass = strip_tags($pass);
$pass = htmlspecialchars($pass);
// prevent sql injections / clear user invalid inputs
if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) {
$error = true;
$errMsg = "Please enter valid email address.";
}
// if there's no error, continue to login
if (!$error) {
$res=mysql_query("SELECT userId, userfName, userlName,userPassword FROM userdata WHERE userEmail='$email'");
$row=mysql_fetch_array($res);
$count = mysql_num_rows($res); // if uname/pass correct it returns must be 1 row
if( $count == 1 && $row['userPassword']==$pass ) {
$_SESSION['user'] = $row['userId'];
header("Location:home.php");
} else {
$errMsg = "Try again...";
}
}
}
?>
You do not need the !="" on line 5 because isset() already checks for existence. Either its there or its not.
if (isset($_SESSION['user'])){
header("Location: home.php");
exit;
} else {
echo "something here";
}
You can use !isset() to get the opposite result as well.
Try your code with this code,
<?php
ob_start();
session_start();
if ( isset($_SESSION['user'])!="" ) {
header("Location:home.php");
exit;
}
require_once 'phpconnection.php';
// it will never let you open index(login) page if session is set
?>
I'm creating a system that the header will show 'login' if the user is not logged in, and if they are, it'll display logout. I've simplified it for now, just showing if the user is logged in or not. With "Login!" meaning they need to login, and "Welcome!" if they are logged in. I used the PHP Code Checker website (https://phpcodechecker.com/) and it couldn't find any errors. I also searched stackoverflow, and everyone else's seems to work.
<?php
ob_start();
session_start();
require_once 'dbconnect.php';
if( !isset($_SESSION['user']) ) {
echo "Login!";
} else {
echo "Welcome!";
}
?>
is the code that checks if the user is logged in or not.
My login page works for EVERYTHING else, for my homepage is shows that the user is logged in, but here is the code anyway. (This is only the PHP code, there is HTML for the submit button, ect.)
<?php
ob_start();
session_start();
require_once 'dbconnect.php';
// it will never let you open index(login) page if session is set
if ( isset($_SESSION['user'])!="" ) {
header("Location: index.php");
exit;
}
$error = false;
if( isset($_POST['btn-login']) ) {
// prevent sql injections/ clear user invalid inputs
$email = trim($_POST['email']);
$email = strip_tags($email);
$email = htmlspecialchars($email);
$name = trim($_POST['name']);
$name = strip_tags($name);
$name = htmlspecialchars($name);
$pass = trim($_POST['pass']);
$pass = strip_tags($pass);
$pass = htmlspecialchars($pass);
// prevent sql injections / clear user invalid inputs
if(empty($name)){
$error = true;
$nameError = "Please enter your username.";
}
if(empty($pass)){
$error = true;
$passError = "Please enter your password.";
}
// if there's no error, continue to login
if (!$error) {
$password = hash('sha256', $pass); // password hashing using SHA256
$res=mysql_query("SELECT userId, userEmail, userPass FROM users WHERE
userName='$name'");
$row=mysql_fetch_array($res);
$count = mysql_num_rows($res); // if email/pass correct it returns must be
1 row
if( $count == 1 && $row['userPass']==$password ) {
$_SESSION['user'] = $row['userId'];
header("Location: dashboard.php");
} else {
$errMSG = "Incorrect Credentials, Try again...";
}
}
}
?>
It connects to the database fine, and i'm certain there is no problems with the database, since it works on my other pages.
I've spent a long-while trying to figure this out, and can't.
Thanks!
In your code
if ( isset($_SESSION['user'])!="" ) {
you are comparing true|false != ""
change it to if (isset($_SESSION['user'])) {
or
if (isset($_SESSION['user']) && ($_SESSION['user']!="")) {
How to create a session variable, and once logout is successful no need to navigate to the page that is visited before.
The Login.php and logout.php pages are provided below:
Login.php
require( 'dbConfig.php');
session_start();
$msg = "";
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $_POST["userid"];
if ($name == '' ) {
$msg = "You must enter all fields";
}
else
{
$sql = "SELECT * FROM user WHERE userid = '$name' ";
$query = mysql_query($sql);
if ($query === false) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($query) > 0) {
$_SESSION['userid'] = $name;
header('Location: teams.php');
exit;
}
$msg = "Username do not match";
}
}
?>
Logout.php
<?php
session_start();
if(session_destroy())
{
header("Location: index.php");
}
?>
ISSUE : After successful logout the page is navigating to the page visited before.
Any help is appreciated, thanks in advance.
In your logout.php page, instead of if condition, simply write:
session_destroy();
So your page code would be :
<?php
session_start(); // not compulsory to write
session_destroy();
?>
<?php
session_start();
$root = 'root';
mysql_connect('localhost',$root,'') or die(mysql_error());
mysql_select_db("test_create_database") or die(mysql_error());
$result = mysql_query("SELECT * FROM members");
$row = mysql_fetch_assoc($result);
$username="";
$password="";
$id="";
if(isset($_POST["submit"]))
{
if(isset($_POST["submit"]) && !empty($_POST["username"]) && !empty($_POST["password"]) && !empty($_POST["id"]))
{
if(isset($_POST["username"]) && isset($_POST["password"]) && isset($_POST["id"]))
{ $username = $row["username"];
$password = $row["password"];
$id = $row["id"];
if($username == "John" && $password =="1234" && $id =="1")
{
echo "you're in";
}
else
{
echo "you're out!";
}
}
}
elseif (isset($_POST["submit"]) && (empty($_POST["username"]) || empty($_POST["password"]) || empty($_POST["id"])))
{
echo "enter all fields please!!!!";
}
}
session_destroy();
?>
if at first all the fields are filled in correctly and the submit button is pressed, the text "you're in" is printed onto the webpage and the text in the fields disappears. but if I refresh the page again, the printed text "you're in" still remains even though I have invoked the session_destroy() function. I don't understand why the session has not been destroyed. Any help would be appreciated.
The bits about session_start() and session_destroy() do not influence the POST-variables. As BugFinder pointed out, refreshing the page often re-submits whatever data you've just submitted. That's why the 'you're in'-message is presented again.
A way of preventing this behaviour is by redirecting after the submitted data has been processed. You could then set a session variable to keep track of the message you still need to display (or, if the user is logged in or not).
Your code would look something like this:
<?php
session_start();
$root = 'root';
mysql_connect('localhost',$root,'') or die(mysql_error());
mysql_select_db("test_create_database") or die(mysql_error());
$result = mysql_query("SELECT * FROM members");
$row = mysql_fetch_assoc($result);
$username="";
$password="";
$id="";
if(isset($_POST["submit"]))
{
if(isset($_POST["submit"]) && !empty($_POST["username"]) && !empty($_POST["password"]) && !empty($_POST["id"]))
{
if(isset($_POST["username"]) && isset($_POST["password"]) && isset($_POST["id"]))
{ $username = $row["username"];
$password = $row["password"];
$id = $row["id"];
if($username == "John" && $password =="1234" && $id =="1")
{
//do stuff
$_SESSION['message'] = "you're in";
}
else
{
$_SESSION['message'] = "you're out!";
}
}
}
elseif (isset($_POST["submit"]) && (empty($_POST["username"]) || empty($_POST["password"]) || empty($_POST["id"])))
{
$_SESSION['message'] = "enter all fields please!!!!";
}
$selfLink = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
$selfLink .= "?" . $_SERVER['QUERY_STRING'];
}
header('location: '.$selfLink);
exit;
}
if (isset($_SESSION['message'])) {
echo $_SESSION['message'];
unset($_SESSION['message']);
}
?>
Note that the redirecting to the page itself seems a bit forced (using $_SERVER['QUERY_STRING'] to fetch the current page's location). It works more intuitively if you know the file name or if you're redirecting to a different page after handling form input.
isset($_POST["submit"]) remove this check in elseif.
After submit form and explicit refresh of page $_POST["submit"] is set but if u go manually to that page $_POST["submit"] will not be set.
<?php
$userid = $_POST["userid"];
$pword = $_POST["pword"];
# session
session_start();
# check that session is valid and set
if(!isset($_SESSION['login']))
{
header('Location: login.php');
}
# check that the required values have been entered
$testin1 = ($userid);
$testin2 = ($pword);
if($testin1 == "")
{
print "<hr><h1> No Username Entered, Please return to the Login page</h1></hr>";
}
elseif ($testin2 == "")
{
print "<hr><h1> No Password Entered, Please return to the Login page</h1></hr>";
}
# Connect to database
$connect = mysql_connect ("localhost","root") or die("Error Connecting to SQLServer");
$db = mysql_select_db ("test");
# query
$query = mysql_query ("select username from login where username = '$userid' and pword = '$pword';");
if($query === FALSE)
{
die(mysql_error());
}
$result = mysql_fetch_array($query);
$record = $result['username'] ;
if ($record != null)
# check if session is operational, if so redirect the user to the correct page
{
$_SESSION['login'] = true;
header( 'Location: index.php' ) ;
}
else if ($record == null)
{
header( 'Location: login.php' );
}
?>
Does anyone know where this is not functioning? It seems to be 'error free' however keeps redirecting me back to the login.php page as opposed to the index.php page. any help would be great as i am a relative novice in PHP.
Thanks
You are using mysql_fetch_array(). In order to access a result by the key you need to use mysql_fetch_assoc().
$result = mysql_fetch_assoc($query);
$record = $result['username'] ;
Keep in mind that it is always best to escape any user input with mysql_real_escape_string().
It looks like you might possible be outputting data to the user before the header() is output. You have <HR>s and output (I know that it is only if there is an error) but if you are using those, you could well have <HTML> and the like above the code.
If that is the case, then no other header will function.
(Posting as answer as too long for comment - and might be the issue.
Try this code:
<?php
session_start();
$userid = $_POST["userid"];
$pword = $_POST["pword"];
// check that the required values have been entered
$testin1 = ($userid);
$testin2 = ($pword);
if($testin1 == "")
{
print "<hr><h1> No Username Entered, Please return to the Login page</h1></hr>";
}
if ($testin2 == "")
{
print "<hr><h1> No Password Entered, Please return to the Login page</h1></hr>";
}
// Connect to database
$connect = mysql_connect ("localhost","root") or die("Error Connecting to SQLServer");
$db = mysql_select_db ("test");
// query
$query = mysql_query ("select username from login where username = '$userid' and pword = '$pword';");
if($query === FALSE)
{
die(mysql_error());
}
$result = mysql_fetch_array($query);
$record = $result['username'] ;
if ($record != null)
// check if session is operational, if so redirect the user to the correct page
{
$_SESSION['login'] = true;
header( 'Location: index.php' ) ;
}
else if ($record == null)
{
header( 'Location: login.php' );
}
?>
I looked through and moved a few things around as well as modifying the logic ever so slightly.
The problem seems to be in your session, check $_SESSION['login'] whether it is set or not, because you are checking if !isset() then you are redirecting to login.php page.
Just verify the session variable by debugging your code