PHP Page isn't storing cookies - php

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!";
}
?>

Related

PHP Loggin System Session

So I'm new to PHP and atm i try to code a simple LogIn System. I set up a Sign up Site and linked it with the sql server. In the log in file i got this if statement.
if (!$row = mysqli_fetch_assoc($result)) {
echo "Your username or Pw is incorect!";
} else {
$_SESSION['id'] = $row['id'];
}
I did test this (i put a 'echo' tag in the else part and it worked. )
so on my index page i got this
<?php
if (isset($_SESSION['id'])) {
echo $_SESSION['id'];
}else {
echo "ur not logged in";
}
?>
This should give me the User id, but nothing comes out. Anyone spottet a mistake i made ?

Checking if user is admin or normal

I am having problems checking whether the user is admin or not in the database. I made it so if admin has the value 1 for the users profile then they are admin and is redirected to the admin page and if not they are redirected to the login page. However I gave my personal account the value of 1 in the database however it is still redirecting me to the login page.
I have given my code below for you to see if I have done anything wrong, please tell me as I have only just started learning PHP.
<?php
session_start();
// First we cubrid_execute(conn_identifier, SQL)te our common code to connection to the database and start the session
require("include/common.php");
$admin = $_POST['admin'];
$user = $_POST['username'];
// At the top of the page we check to see whether the user is logged in or not
if(empty($_SESSION['user']))
{
// If they are not, we redirect them to the login page.
header("Location: login.php");
// Remember that this die statement is absolutely critical. Without it,
// people can view your members-only content without logging in.
die("Redirecting to login.php");
}
// Everything below this point in the file is secured by the login system
// We can retrieve a list of members from the database using a SELECT query.
// In this case we do not have a WHERE clause because we want to select all
// of the rows from the database table.
$query = "
SELECT *
FROM users
";
try
{
// These two statements run the query against your database table.
$stmt = $db->prepare($query);
$stmt->execute();
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt->fetchAll();
if ($admin == 1) {
$_SESSION['username'] = $user;
header("location: memberlist.php");
}
if ($admin == 0) {
$_SESSION['username'] = $user;
header("location: login.php");
}
Correct you code First:
Try this:
if ($admin == 1) {
$_SESSION['admin'] = $admin; //put you admin in session
header("location: memberlist.php");
}
if ($admin == 0) {
$_SESSION['user'] = $user; //here put your user in session
header("location: login.php");
}
if(empty($_SESSION['user'])) //if user is empty then it redirects to login page
{
header("Location: login.php");
die("Redirecting to login.php");
}
else if(!empty($_SESSION['admin'])) //if admin is not empty it goes to admin area
{
header("location: memberlist.php");
}
else if(!empty($_SESSION['user'])) //same here if user is present,then it leads to user area
{
header("Location: user.php");
}

Losing session values after header redirection

I'm using $_SESSION to keep my users logged in after they have logged in.
When they return to the homepage, they at first appear to be logged in, but after refreshing the page once, they are no longer logged in.
NOTE: I'm still learning PHP programming so please don't mind that most of my code is rather, noobish.
Index.php Code:
<?php
session_start();
$UserOnline = "Guest";
if (isset($_SESSION['username'])) {
$UserOnline = $_SESSION['username'];
}
echo $UserOnline;
?>
Login.php Code:
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username)) {
$InvalidLogin = "Please submit a username";
$_SESSION['IL'] = $InvalidLogin;
header ('Location: http://localhost/practice/index.php');
exit;
} elseif (empty($username)) {
$InvalidLogin = "Please submit a password";
$_SESSION['IL'] = $InvalidLogin;
header ('Location: http://localhost/practice/index.php');
exit;
}
require 'required/connect.php';
$result = mysqli_query($con, "SELECT * FROM users WHERE username='$username'");
$row = mysqli_fetch_array($result);
if ($password == $row['password']) {
$_SESSION['username'] = $username;
echo "Successful Login!";
echo "<br>";
echo "<a href='index.php'>Return to HomePage?</a>";
} else {
$InvalidLogin = "Your info didn't match ours!";
$_SESSION['IL'] = $InvalidLogin;
header ('Location: http://localhost/practice/index.php');
exit;
}
?>
I have tested on the login.php page if the user is in a session there, and I always get the correct return value. The issue is that after I refresh once on the Index.php page, the user is no longer in a session.
Is there something I'm forgetting, or am I not using the $_SESSION correctly? Is there another error that I simply do not know about?
Put exit; after header('location:.....') and your problem will be solved.
Issue is resolved. Error was found in Index.php. Set Variable $UserOnline before the if(isset($_SESSION['username'])). Thanks for the help guys

PHP File cannot recover session variable across pages

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'].

How to prevent browser from going back to login form page once user is logged in?

I'm trying to make a website in which the admin can upload books through an admin portal. I've made a successful login but when the user gets logged in and presses the back button (on the browser) the form page appears again, and the same happens when they log out and press back button, the page that should appear only appears after they login again. I searched a lot on the internet but all in vain. Please make a suggestion about it.
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
if ($username && $password) {
$connect = mysqli_connect("localhost", "root", "") or die ("Could'nt connect to database!"); //database connection
mysqli_select_db($connect, "mahmood_faridi") or die ("Could'nt find database");
$query = ("SELECT * FROM user WHERE username= '$username'");
$result = mysqli_query($connect, $query);
$numrows = mysqli_num_rows($result);
if ($numrows !== 0) {
while ($row = mysqli_fetch_assoc($result)) {
$dbusername = $row['username'];
$dbpassword = $row['password'];
}
if ($username == $dbusername && $password == $dbpassword) {
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
header('location: help.php'); //another file to send request to the next page if values are correct.
exit();
} else {
echo "Password Incorrect";
}
exit();
} else {
die("That user doesn't exists!");
}
} else {
die("Please enter a username and password");
}
?>
On the login screen, in PHP, before rendering the view, you need to check if the user is already logged in, and redirect to the default page the user should see after logged in.
Similarly, on the screens requiring login, you need to check if the user is not logged in and if not, redirect them to the login screen.
// on login screen, redirect to dashboard if already logged in
if(isset($_SESSION['username'])){
header('location:dashboard.php');
}
// on all screens requiring login, redirect if NOT logged in
if(!isset($_SESSION['username'])){
header('location:login.php');
}
You can conditionally add Javascript code to go forward to the intended page.
<script>
history.forward(1);
</script>
This might be annoying or fail when Javascript is not present and/or disabled.
index.php page you should need to add the code in the top of a php file....
<?php
include 'database.php';
session_start();
if (isset($_SESSION['user_name'])) {
header('location:home');
}
if (isset($_POST['submit'])) {
$user = $_POST['user_name'];
$password = $_POST['password'];
$query = "select count(*) as count from users where user_name= '$user' and password = '$password';";
$result = mysqli_query($link, $query) or die(mysqli_error($link));
while ($row = mysqli_fetch_assoc($result)) {
$count = $row['count'];
if ($count == 1) {
$_SESSION['user_name'] = $user;
header('location:home');
}
}
}
?>
This is another page. home.php page you should need also to add the code in the top of a php file to check it first.
<?php
include 'database.php';
if (!(isset($_SESSION['user_name']))) {
header('location:index');
}
?>
I am just modifying #sbecker's answer, use exit() after redirecting.
I have faced the same issue, but now exit(); works for me.
// on login screen, redirect to dashboard if already logged in
if(isset($_SESSION['username'])){
header('location:dashboard.php');
exit();
}
// on all screens requiring login, redirect if NOT logged in
if(!isset($_SESSION['username'])){
header('location:login.php');
exit();
}
you can use this it's easy to use
<?php
if(empty($_SESSION['user_id'])){
header("Location: login.php");
}
else{
header("Location: dashboard.php");
}
?>
My suggestion: the login should happen when the users clicks some link/button
Once the login server side takes place, use the the php function header('url') to redirect the user to the url it should be. (be careful not to echo anything otherwise the redirect will not happen)
[Edit] You say you have the first login file an html one, that is fine to me, but you say it redirects to whatever, then you are using a redirect from client side. In my opinion you should not use that client side redirect for the login. Probably that is causing the confusion.

Categories