PHP class sessions - php

I'm sorry, I followed WikiHow steps (link is down there) and I made everything but here is the problem:
My index.php contains password input.
if(isset($_POST['login']))
{
require('session.class.php');
if(hash('sha256', $_POST['pass']) == hash('sha256', 'password123'))
{
$session = new session();
$session->start_session('_s', false);
$_SESSION['namesession'] = 'something';
header(location: /mama.php);
}
else
{
echo "<font color='#FF0000'>Wrong password!</font>";
}
}
I don't understand how to put session check on other pages. Other words:
How to put inside if password is correct, you can stay on mama.php page..
http://www.wikihow.com/Create-a-Secure-Session-Management-System-in-PHP-and-MySQL#Create_session.class.php_file_sub

When you start a session, it must be at the very beginning of your code, before any HTML or text is sent.
So if you want to check the post data put the if statement after the session_start().

Related

Why is if (empty($_SESSION['gebruikersnaam']['wachtwoord'])) not working?

first off all my English is not very good. Sorry I do my best. I am developing a CMS system. I need an inlog system for it. If you are not logged in you can't view some of the pages. I created a php session of it but it doesn't work on the other pages... I will include some off the code I wrote.
On the page I check the username and password, I created the session like this. And worked with session to check username and password, so it works on that page.
<?php
session_start();
$_SESSSION['gebruikersnaam'] = $_POST['gebruikersnaam'];
$_SESSSION['wachtwoord'] = $_POST['wachtwoord'];
if(($_SESSSION['gebruikersnaam'] == 'admin')
&& ($_SESSSION['wachtwoord'] == 'admin123')) {
include("adminpanel.php");
} else {
echo "Uw gebruikersnaam of wachtwoord is foutief.";
}
?>
On my other pages I added this to check if the user is logged in. I seem to never get that I am logged in and I can't echo the session out. Here is the code!
if(!empty($_SESSION['gebruikersnaam']['wachtwoord'])) {
echo "not ingelogd";
}
If the conditional statement with the session works, I can redirect the user to the log in page if he is not logged in.
Thanks in advance you would help me a lot!
That's because of a slip of the tongue, its $_SESSION not $_SESSSION and also:
$_SESSION['gebruikersnaam']['wachtwoord'];
Is actually referring to 1 value, not two:
$data = array('gebruikersnaam' => array('wachtwoord' => 'mijnwachtwoord'));
echo $data['gebruikersnaam']['wachtwoord'];
Instead do:
if(!empty($_SESSION['gebruikersnaam']) || !empty($_SESSION['wachtwoord'])){
echo "not ingelogd";
}
However, you should only store a username and id in a session. Storing the password is a potential security breach and is not necessary.
You could also use something like this to scan for required values:
function required_session_fields(array $keys){
foreach($keys as $k){
if(!array_key_exists($k, $_SESSION) && empty($_SESSION[$k])){
return false;
}
}
return true;
}
if(required_session_fields(['gebruikersnaam', 'wachtwoord'])){
echo 'gelukt';
}
If you started the session and included a file, you can still access the $_SESSION variable. On every new server request, make sure the session is started.
On the other pages you must have
session_start();
before
if(!empty($_SESSION['gebruikersnaam']['wachtwoord'])) {
echo "not ingelogd";
}
However this variable $_SESSION['gebruikersnaam']['wachtwoord'] is never created. Currently you have created $_SESSION['gebruikersnaam'] and $_SESSION['wachtwoord']
Perhaps you meant to have something like
if(!empty($_SESSION['gebruikersnaam']) && !empty($_SESSION['wachtwoord'])) {
echo "not ingelogd";
}

PHP login script in a separated file

I have been developing the following php script (+ sqlite database) to create a login for my web.
Up to now I had used just one PHP file, but now I want to use different files for login and protected contents, I mean, I used to have all my web in one file php (contents and password script were together) but now I want to detach it in different php files (one for the login, login.php, and other phps protected: index.php, calendar.php...)
I used this code to password-protect php content:
<?php require_once "Login.php"; ?>
but it doesn't seem to work: it displays the form to login next to the content I wanted to protect.
This is the php script I'm using as login.php:
<?php
$db = new PDO('sqlite:data.db');
session_start();
if (isset($_GET['logout'])) {
unset($_SESSION['pass']);
header('location: index.php');
exit();
}
if (isset($_SESSION['timeout'])) {
if ($_SESSION['timeout'] + 4 < time()) {
session_destroy();
}
}
if (!empty($_POST['pass'])) {
$result = $db->query("SELECT user,password FROM users");
foreach ($result as $row) {
if (password_verify($_POST['pass'], $row['password'])) {
echo "Welcome! You're logged in " . $row['user'] . "! <a href='index.php?logout=true'>logout</a>";
$_SESSION['pass'] = $_POST['pass'];
$_SESSION['timeout'] = time();
}
}
}
if (empty($_SESSION['pass'])) {
echo '<form method="POST" action=""><input type="password" name="pass"><form>';
}
?>
MY QUESTION IS: How can I use my php script to protect different files?Is there any way to embed a logout link too?
One way is to store a token in session variables when a user logs in. Confirm the token is there on each page, if it isn't redirect the user to the login page. For example assert_login.php:
<?php
session_start();
if('' == $_SESSION['token']) {
header("Location: login.php");
exit();
}
?>
Then, in the PHP at the top of each of your pages:
<?php
require('assert_login.php');
?>
You can also clear the session variable on logout, logout.php for example:
<?php
require('assert_login.php'); // has session_start() already
$_SESSION['token'] = ''; // empty the token
unset($_SESSION['token']); // belt and suspenders
header("Location: login.php");
exit();
?>
I was also going through same issue & the way I solved it:
PSEUDO CODE:
PHP SESSION START
if(isset(GET(logout){
SetLogout();
die()}
$redirect=false
if not session[auth] exists
if SERVER REQUEST METHOD IS POST
$redirect=true;
if POST(username) && POST(pass) exists
Sanitize both of them & assign to $user& $pass
if user == "John" && $pass == "secret"
Go To SetLogin();
else{
Go To SetLogout();
echo "Wrong Username or Password"
drawlogin();
die();}
} //user pass comparing ends
} //Server method is NOT POST, so maybe it is GET.
//Do nothing, let the control pass to next lines.
}//SESSION(auth) does not exists, so ask user to login
else {
drawlogin();
}
//Post-Redirect-Get
if ($redirect)
redirect header to this same page, with 301
die()
// Secret Content here.
function SetLogin($user){
$SESSION(auth) = TRUE;}
function SetLogout($user){
if SESSION(auth) exists
unset($SESSION(auth))
redirect back with 301, without query string //shake ?logout
}
function drawlogin(){
echo all the HTML for Login Form
What it does is, it checks various things/variables, and if all passes, the control passes to Secret Content.
Save it as pw.php, & include it on top of any file you want to protect. Logout can be triggered by Logout
Note that this is just a pseudo code, typed on a tablet. I will try to update it with actual version. It is not checked for errors. Use all standard PHP Security precautions..

PHP How to pass error marker after refreshing unsuccessful login

I have a login page and I want to achieve this effect:
If user fails to login, display error message. After user presses refresh button, the error message should not be visible anymore.
I dont want to pass $_GET variable, for example index?page=login$failure. I want to do this in invisible in url way.
<?php
if(isset($_POST['submit_form_register'])) {
...
if($login === false) {
$user->go_to('index.php?page=login'); //Redirects back, cleaning the $_POST data.
}
..
}
?>
Now how do I say for my form, that something before redirect went bad without addint it with $_GET?
Update. So using sessions, can I do like this?
<?php
if(isset($_POST['submit_form_register'])) {
...
if($login === false) {
$_SESSION['is_form_error'] = true;
$user->go_to('index.php?page=login'); //Redirects back, cleaning the $_POST data.
}
..
}
?>
And for HTML output:
<?php if(isset($_SESSION['is_form_error']) and ($_SESSION['is_form_error'] === true)) { ?>
<div>Your email or credential is invalid.</div>
<?php } unset($_SESSION['is_form_error']); ?>
But this one doesnt work for me. I bet its because something wrong with unset. Any tips?
SOLVED: Didn't have exit; after header(); in $user->go_to($url);
You could use Session for show and hide errors
When user enter wrong user/pass you set error session and use it in view and then delete session(after showed)
`//Set Session
if (!$success) {
$_SESSION['login_error'] = 1;
}
//show
if (isset($_SESSION['login_error'])) {
echo "Invalid Username/Password";
unset($_SESSION['login_error']);
}`
Don't forget to start code with session_start();

Session is destroyed on page refresh in PHP

I am developing a web application using PHP in which a user initially has to sign in and view his content. I am using PHP sessions to maintain state. I encountered following problems:
Although I started the session on each page and after relevent session variables are set, the session is destroyed each time the page is refreshed or when I browse the same URL on a different tab.
I need the user to be redirected to his content page when the user browsed login page with he has already logged in.
I'm really new to PHP, So I have no idea how to solve these problems. I referred several questions in the stackoverflow, but they all say that sessions are not destroyed on page refresh. I could not understand what's wrong with my page. Any solution with explaination is greatly appreciated.
Login page
<?php
session_start();
class Sessions{
public static function setSessionState($userdata){
unset($userdata['password']);
unset($userdata['timestamp']);
$_SESSION['user']=$userdata;
}
}
if(isset($_POST['username']) && isset($_POST['password'])){
$dbcon = new DBConnection();
$dbcon->connect();
$username= strip_tags(stripslashes(trim($_POST['username'])));
$password = strip_tags(stripcslashes($_POST['password']));
echo "<script>alert($username);</script>";
$result = $dbcon->getUser($username,$password);
if(mysqli_num_rows($result)==1){
$user = $dbcon->getUserData($result); #getUserData function accepts mysqli result as an input and returns a row(array) of user details.
if(isset($user)){
Sessions::setSessionState($user);
header("location:index.php");
}
else{
echo "user variable is not set!!!";
}
}
else if(mysqli_num_rows($result)==0){
echo "Login error! Username or Password incorrect!";
}
else{
die("Unknown Error occured!");
}
}
............
Index page(in which user's private content is visible)
<?php
session_start();
if(isset($_SESSION['user'])){
print_r($_SESSION['user']);
}
else{
echo "session variable not set";
}
?>
Thank you.
I finally found the answer which is actually my bad. I didn't mention the last part of the index.php file as I though that part is irrelevant.In that part I have a part,
<form action="<?php session_destroy(); ?>">
After commenting that session_destroy() method call, I could solve my problem and keep session alive.
Sorry for incomplete code.
try this
class Sessions{
public static function setSessionState($userdata){
if ( !isset($_SESSION['user']) ) {
$_SESSION['user'] = $userdata;
}
}
}

php session lost after submitting form

The code below page keeps session on GET requests or refreshing browser, but when I submit a form the session data is lost.
$user=$_POST['user']; $pass=$_POST['pass'];
if ($_POST['user'])
{ if($user==$un and $pass=$pw)
{ $_SESSION['uid']=$Xid;header('Location: '.$uri.'?welcome'); }
else { $msg="chybny login"; }
}
if(isset($_GET['logout'])) { session_destroy(); header('Location: '.$uri); }
$cnt=$_SESSION['cnt']+1; $_SESSION['cnt']=$cnt;
Above is the code for login which re-directs me to the welcome page as it was verified, however the session is lost. If I just refresh or repeatedly load the page without submitting, the session holds by echoing the session variable cnt (counts up 1,2,3,...)
After submitting the form, I see session is lost and too cnt variable is reset?
I usually don't work with session directly try the following, place it a the top of your script :
session_start();
$uid = $_SESSION['uid'];
$cnt = $_SESSION['cnt'];
then work with the variable instead
The problem is likely your 'and' statement. It should be &&. The condition is not going to be true.
If you're 100% sure the code is all fine and the PHP.ini is the problem, based on your comments above. Look at this link at check the settings in the .ini http://php.net/manual/en/session.configuration.php
To pass the current session to the next page... I believe is what you are asking...
You are currently not passing the session to the next page and use session_start() at the top of the next page.
Change line 4 to:
{ $_SESSION['uid']=$Xid;header('Location: '.$uri.'?'.SID.'&page=welcome'); } // Where "page" is the name of the data you are retrieving
Or, you can save the session data to a cookie and then retrieve it on the next page.
You can alternately name the session when you use session_start("NameHere") on each page, however if the visitor has recently visited and the session not destroyed, they may see parse errors, if you have them enabled.
First of all, make sure that the the first thing you do on every page is to start a session (I recommend calling it once in a header file that you require on all of your sub sites).
So that you have session_start(); everywhere in the system.
Second of all, tighten up your code; make it easier to read. Something like
$userName = isset($_POST['userName']) ? $_POST['userName'] : false;
$password = isset($_POST['password']) ? $_POST['password'] : false;
$logout = isset($_POST['logout']) ? $_POST['logout'] : false;
$url = '../index.php';
if(!($logout))
{
if($userName && $password)
{
if($userName == $un && $password == $pw)
{
$_SESSION['loggedIn']=true;
$_SESSION['uid']=$Xid;
$_SESSION['message']="success";
}
else
{
$_SESSION['loggedIn']=false;
$_SESSION['message']="fail, incorrect login information.";
}
}
else
{
$_SESSION['loggedIn']=false;
$_SESSION['message']="fail ; username and password not submitted.";
}
header("Location: $url");
}
else
{
session_start();
session_destroy();
session_start();
header("Location: $url");
}
And if you want to display unqiue content depending on whether a user is logged in or not, then you can simply check if the login session is set or not, on each page, instead of modifying the header for that.

Categories