Okai, so I attempted to post this a bit earlier, although my question has changed slightly.
I have identified the problem to be in between my login.php (where I assign the $_SESSION value) and my members.php page (where I try to pick up the $_SESSION variable again, but fail to recover it). The way I identified this problem was by running a var dump on session in my members.php file which gave me 0. I also did this after I asign the value in login.php and I got the asigned value as an outcome.
If you help me out I will really appreciate it!
This is my login.php page:
<?php
session_start();
require('connect.php');
$username = $_POST['username'];
$password = $_POST['password'];
if (isset($username) && isset($password))
{
$query = mysql_query("SELECT * FROM login WHERE username='$username' AND password='$password'");
$result = mysql_num_rows($query);
if($result > 0)
{
echo "You have been logged in. <a href='members.php'>Go to the members page</a>";
$username = $_SESSION['login'];
}
else
{
echo "Password is incorrect. Try again.";
}
}
else
{
echo "You have to enter your username and password. Try again";
}
?>
This is my members.php page:
<?php
session_start();
if (isset($_SESSION['login']))
{
echo "Welcome " . $login . " | <a href='logout.php'>Logout</a>";
}
else
{
header('Location: index.php');
}
?>
Solved in Chat:
Turns out var_dump(is_writable(session_save_path())); returned bool(false).
The session_save_path() was /var/php_sessions/.
realpath(dirname(__FILE__)); was /hermes/bosoraweb124/b185/dom.gjertgjersundcom/public_html.
I tried moving the session save path -- however for some reason the folder within public_html couldn't be written, same with read (couldn't read). In any case, it's a bad idea to have sessions in the public folder for everyone to see anyway.
I recommended the OP contact their host provider to run the command of chmod 766 -R /var/php_sessions/.
Solved: The staff at his webhost applied the permissions and it works fine now.
Your session "login" variable is not set because you never set it in your login file...
You should specifically set it with $_SESSION['login'] = "blah";
I assume your problem is you meant to set login and not the username when you log in the user...
swap
if($result > 0)
{
echo "You have been logged in. <a href='members.php'>Go to the members page</a>";
$username = $_SESSION['login'];
}
with
if($result > 0)
{
echo "You have been logged in. <a href='members.php'>Go to the members page</a>";
$_SESSION['login'] = $username;
}
Then you should be able to access your "login" session variable from your member page.
Also on your member page I do not see you set your $login variable. So I assume that would be a blank space and you meant to echo your session login variable with $_SESSION['login'].
Related
I'm trying to create a password protected area of a website.
I'd like to allow access by checking username and password from a MySql table, then start a session and allow access to a number of pages while the session is active. If someone tries to directly access one of these pages directly, I'd like to redirect them to login page.
My code for the login page is:
if (isset($_POST['submit']))
{
include("config.php");
session_start();
$username=$_POST['username'];
$password=$_POST['password'];
$passwordc=md5($password);
$query = "SELECT username FROM admin WHERE username='$username' AND password='$passwordc'";
$result2 = $conn->query($query);
if ($result2->num_rows != 0) {
$_SESSION["username"] = $user;
echo "<script language='javascript' type='text/javascript'> location.href='admin_view.php' </script>";
}else{
echo "<script type='text/javascript'>alert('User Name Or Password Invalid!')</script>";
}
}
It seems to work (correctly redirects if username and password matches, shows alert if not).
What I fail to do, is actually protect my pages from display if session is not active.
session_start();
if (!$_SESSION["username"]) {
header("Location: login.php");
}
I'm not a programmer or fully-educated web developer. I know HTML and CSS, and I'm barely able to use ready-to-use php and js scripts following readme files.
Any help would be greatly appreciated.
modify your login code as
if (isset($_POST['submit']))
{
include("config.php");
$username= $crud->escape_string($_POST['username']);
$password= $crud->escape_string($_POST['password']);
$passwordc=md5($password);
$query = "SELECT username FROM admin WHERE username='$username' AND
password='$passwordc'";
$result2 = $conn->query($query);
if ($result2->num_rows != 0) {
session_start();
$_SESSION["username"] = $user;
header("Location:admin_view.php");
}else{
$Message = urlencode("user name password invalid!");
header("Location:login.php?Message=".$Message);
}
}
if your values successfully stored in session then you can use like
session_start();
if(!isset($_SESSION['username']))
{
header("Location: login.php");
}
on everypage top
you must store name from query into session
I've looked everywhere and tried all solutions but it's still not getting me anywhere. Here's my code:
<?php
if(!empty($_SESSION['LoggedIn']) && !empty($_SESSION['Username']))
{
header('Location: /public_html/index.php');
exit;
}
elseif(!empty($_POST['username']) && !empty($_POST['password']))
{
$username = mysql_real_escape_string($_POST['username']);
$password = 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;
header('Location: /public_html/index.php');
exit;
}
else
{
echo "<h1>Error</h1>";
echo "<p>Sorry, your account could not be found. Please click here to try again.</p>";
}
}
?>
When I upload this into my server and login it brings me to a blank php page. What am I doing wrong with this code? I've tried using " instead of ' . I'm trying to redirect the user to a page outside of the folder hence the "/public_html/". Any help would be much appreciated.
if outside the folder than use
header("Location:../public_html/index.php");
Starting your URL with / and followed with the folder name means, you want to go to the top/root directory, and followed with the folder name you've specified.
For example:
Getting to /public_html means you're redirecting to http://www.example.com/public_html which I believe to be non-existance in your case
To get around this problem, do this:
add a double dot: ..
Getting to ../public_html means you're redirecting from http://www.example.com/some_project/some_folder/ to http://www.example.com/some_project/public_html/ (for example).
refer to Vicky's answer,
header("Location:../public_html/index.php");
exit();
and do not forget to add the exit(); in the end.
edit: Please cease using the ancient PHP-MySQL. There's a better alternative for you to use, for your own safety:
PHP MySQLi
PHP PDO MySQL
I've been following some tutorials and managed to get my login and logout scripts working. What I"m now trying to do it get it to only allow access to pages when the user is logged in. Right now it's just redirecting users to the login page every time, which tells me that the session isn't being set or or my code is just wrong (and I've tried everything I can think of)
This is the login.php script that my form runs in order to set the session:
<?php
// establishing the MySQLi connection
require 'init.php';
if (mysqli_connect_errno())
{
echo "MySQLi Connection was not established: " . mysqli_connect_error();
}
// checking the user
if(isset($_POST['login'])) {
$username = mysqli_real_escape_string($conn,$_POST['username']);
$pass = mysqli_real_escape_string($conn,$_POST['password']);
$sel_user = "select * from login where username='$username' AND password='$pass'";
$run_user = mysqli_query($conn, $sel_user);
$check_user = mysqli_num_rows($run_user);
if($check_user>0) {
$_SESSION['username']=$username;
echo "<script>window.open('index.php','_self')</script>";
} else {
echo "<script>alert('Sorry. Your username or password is not correct, try again!')</script>";
}
}
?>
And this is what I'm including at the top of every page:
<?php
session_start();
if (!(isset($_SESSION['username']) && $_SESSION['username'] != '')) {
header ("Location: account-login.php");
}
require 'init.php';
?>
I switched the login.php file from directing to a page to a popup telling me that I logged in and I get the popup, so the user and password are registering fine, it's just not storing the session somehow. Any ideas? Thanks!
OK, so I got it to work finally!
Apart from all the comments (which helped a TON), I also decided to change the name I was setting in $_SESSION. I think it may be because the session name matched the name or POST data and that eas causing a conflict somewhere.
Changed this:
$_SESSION['username']=$username;
Which I think conflicted to this:
$_SESSION['session_id']=$username;
Worked!
THANK YOU!!!!!!!
I am new to php and I am making a basic login script.
All I want to do is log in and have the cookie for my user_id stored.
It works on all of my other pages, except my index page which is one directory up.
So on my index page, I have this if statement:
<?php
if (!isset($_COOKIE['user_id'])) {
sign_in();
} else {
echo "You're already logged in!";
}
?>
No matter what I do, the sign_(); function always shows.
But here's the kicker:
On my login script, the whole thing goes through as if I successfully logged in.
I send it back to this page using:
header("Location: ../index.php");
(It is up one directory)
However, when I make it link to a page in the same directory, it registers the cookie and everything is alright.
header("Location: show_user.php");
If you want a hands on view, you can go to http://patti-bee2.dcccd.edu/coleman/wonder%20penguin/php/signup.php to make your account. And http://patti-bee2.dcccd.edu/coleman/wonder%20penguin/php/show_user.php to view it. And notice how the index page doesn't register the cookie.
How I tried to set the cookie:
if (isset($_POST['usernamelogin'])) {
$user_login = $_REQUEST['usernamelogin'];
$pass_login = $_REQUEST['passwordlogin'];
$pass_login = trim(crypt($pass_login, $user_login));
$login_query = sprintf("SELECT username, user_id FROM user WHERE username = '%s' and password = '%s';", mysql_real_escape_string($user_login), mysql_real_escape_string($pass_login));
$loginresult = mysql_query($login_query, $dbConn);
echo $login_query;
if (mysql_num_rows($loginresult) == 1) {
$userinfo = mysql_fetch_array($loginresult);
$username = $userinfo['username'];
$userid = $userinfo['user_id'];
setcookie('username', $username);
setcookie('user_id', $userid);
header("Location: show_user.php");
exit();
} else {
echo "Couldn't find your account!";
}
}
Please excuse my unrefined page and amateur mistakes. I have a lot to learn.
Any ideas?
Thank you for your time.
Check if you have the cookie with the following
<?php
var_dump($_COOKIE);
//if (!isset($_COOKIE['user_id']))
if (empty($_COOKIE['user_id']))
{
sign_in();
}
else {
echo "You're already logged in!";
}
?>
I'm not very good at PHP and I have a little problem. I've been playing around with this script.
And I can't for the life of me figure out how to echo the username of a logged in user.
I tried to print all the information of the session like this:
var_dump($_SESSION)
but I just got the hashed password and the userlevel int.
Can someone maybe help me here? I just want to be able to echo the username.
You have to store the username in the session for it to be available on another page load, currently the script only stores these values in the session;
$_SESSION['loggedin'] = $row[$this->pass_column];
$_SESSION['userlevel'] = $row[$this->user_level];
What you have to do is add the $username to the session that is passed into the login function, like below;
$_SESSION['username'] = $username;
The username will now be stored in the session with the key username.
To be able to use it on another page, make sure that before attempting to use it you initiate the session by calling the function session_start().
Basically, just write it inside like
session_start();
echo $_SESSION['username'];
or
echo $_SESSION['password'];
A brief explanation of how sessions work.
first you start the session and assign any value to a session ex:
session_start();
$_SESSION['username'] = 'john';
then echoing works like:
echo $_SESSION['username']; // will echo out 'jonh'
note session_start() must be shared in-between the pages you want to use the session
You have session_start(); on top ?
In the login function you should write the username to the session after a successful login.
//instantiate if needed
include("class.login.php");
$log = new logmein();
$log->encrypt = true; //set encryption
if($_REQUEST['action'] == "login"){
if($log->login("logon", $_REQUEST['username'], $_REQUEST['password']) == true){
//do something on successful login
$_SESSION['username'] = $_REQUEST['username'];
}else{
//do something on FAILED login
}
}
<?php
include('db.php');
session_start();
$name=$_POST['name'];
$password=$_POST['password'];
echo $sql="SELECT * FROM register WHERE (name='$name' OR email='$name') AND password='$password'";
$result=mysqli_query($conn,$sql);
$num_rows = mysqli_num_rows($result);
if ($num_rows > 0)
{
$_SESSION['user']=mysqli_fetch_assoc($result);
$row = $_SESSION['user'];
$role = $row['role'];
if($role == 1)
{
header('location:usermanagement.php');
}
else{
header('location:user.php');
}
}
else
{
echo "Wrong Username or Password";
header('location:login.php');
}
$conn->close();
?>