0

I tried to make a simple login system and I am seriously stuck. The problem is with the sessions. When I press login, I am redirected at the login page. Now as far as I could see, a session is started in the login page.session_id() gives some number.

But the protected page shows NULL. How to start the session on the protected page? I tried to implement some code of some examples - still redirects to login page. I tried with new empty page,just the form on the page but with the same db and still redirects to login page.

This is the login page

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    require('dbcon.php');
    if (isset($_POST['email']) && ($_POST['password'])) {
        $e = mysqli_real_escape_string($dbcon, $_POST['email']);
        $p = mysqli_real_escape_string($dbcon, $_POST['password']);
        $q = "SELECT uid,mail,psword,unm FROM pics WHERE (mail='$e' AND psword=SHA1('$p'))";
        $result = mysqli_query($dbcon,$q);
            if(mysqli_num_rows($result) == 1){
                session_start();
                $uid = mysqli_fetch_array ($result, MYSQLI_ASSOC);
                $_SESSION['uid'] = $uid['uid'];
                header("location: members.php");
                exit();
                mysqli_free_result($result);
                mysqli_close($dbcon);
            }else{
                echo 'no match';
            }
    }else{
        echo 'Empty fields...';
    }
}
?>

And this is on top of the "protected" page

<?php
session_start();
if(!isset($_SESSION['uid'])){
    header("Location:index.php");
}
?>

session info

session
Session Support     enabled
Registered save handlers    files user
Registered serializer handlers  php_serialize php php_binary wddx
Directive   Local Value Master Value
session.auto_start  Off Off
session.cache_expire    180 180
session.cache_limiter   nocache nocache
session.cookie_domain   no value    no value
session.cookie_httponly Off Off
session.cookie_lifetime 0   0
session.cookie_path /   /
session.cookie_secure   Off Off
session.entropy_file    no value    no value
session.entropy_length  0   0
session.gc_divisor  1000    1000
session.gc_maxlifetime  1440    1440
session.gc_probability  1   1
session.hash_bits_per_character 5   5
session.hash_function   0   0
session.name    PHPSESSID   PHPSESSID
session.referer_check   no value    no value
session.save_handler    files   files
session.save_path   C:\xampp\tmp    C:\xampp\tmp
session.serialize_handler   php php
session.upload_progress.cleanup On  On
session.upload_progress.enabled On  On
session.upload_progress.freq    1%  1%
session.upload_progress.min_freq    1   1
session.upload_progress.name    PHP_SESSION_UPLOAD_PROGRESS PHP_SESSION_UPLOAD_PROGRESS
session.upload_progress.prefix  upload_progress_    upload_progress_
session.use_cookies On  On
session.use_only_cookies    On  On
session.use_strict_mode Off Off
session.use_trans_sid   0   0
Grimnack
  • 29
  • 1
  • 5
  • 2
    Consult these following links http://php.net/manual/en/mysqli.error.php and http://php.net/manual/en/function.error-reporting.php and apply that to your code. – Funk Forty Niner Mar 12 '16 at 16:12
  • 3
    frustrated? try to write `session_start();`on top of each `.php` page just after `` in your `php` pages make sure no empty lines will be there. – Alive to die - Anant Mar 12 '16 at 16:14
  • 2
    I like it how you `_free_result` and `_close` when you have both `header(location: ..` **and** `exit()` on the previous lines... (Yep, sarcasm xD) – FirstOne Mar 12 '16 at 16:15
  • 1
    start by writing `exit;` after each header redirection on the protected page, and by taking your `require` (and `include`) values out of their brackets, they're unneeded. – Martin Mar 12 '16 at 16:15
  • 3
    Aside: SHA1 isn't suitable for passwords, and it is unsalted as well. Not your problem here, but worth improving for the future. – halfer Mar 12 '16 at 16:15
  • 1
    Actually @halfer's point is way more important than the problem exposed in the question. Please take care of that first, then fix all your login issues (besides, authentication may be slightly more complex than you could probably think. Unless it's an homemade for fun project, please read some topics here in SO, it's full of questions->answers about authentication and what is safe and what isn't). – briosheje Mar 12 '16 at 16:18
  • Add `print_r($_SESSION);` to your protected page, what does it show you? your `$uid['uid']` value is probably `NULL`, check your SQL query. – Martin Mar 12 '16 at 16:18
  • @FirstOne and that's why we all loved George Carlin so much ;-) God bless his soul. – Funk Forty Niner Mar 12 '16 at 16:19
  • I get no error..at all. – Grimnack Mar 12 '16 at 16:20
  • @Fred-ii-: he had a joke about HTTP redirects? `:-p` – halfer Mar 12 '16 at 16:21
  • 1
    @halfer He must've had *some* type of Web-related joke somewhere in his repertoire ;-) – Funk Forty Niner Mar 12 '16 at 16:22
  • Can you explain what you just said, no error as in.... what? – Martin Mar 12 '16 at 16:22
  • 1
    btw, if your *unshown* form has no specific post method used, `
    ` is equal to `
    ` and it will fail *silently* on you. As will having too short a length for the password column (and unknown db schema). Things you should be posting as *relevant* information but deemed that it wasn't.
    – Funk Forty Niner Mar 12 '16 at 16:24
  • 1
    `WHERE (mail='$e' AND psword=SHA1('$p'))` that may also be failing *silently* on you. Brackets are mostly used for subqueries. – Funk Forty Niner Mar 12 '16 at 16:26
  • @Fred-ii- OP seems to have no trouble reaching the target page,so the `header` is run but the SQL query is returning NULL values, – Martin Mar 12 '16 at 16:27
  • @Martin True. And he/she needs to find out why that is. A few of my comments may be part of the problem. There isn't anything we can do, except to setup a db, hash the password, insert it, query and login. And I'm not up to that "task". That's up to them to do that. *Cheers* – Funk Forty Niner Mar 12 '16 at 16:28
  • @Fred-ii- I'm watching updates on this question as I dig around George Carlin Quotes relating to the interwebz :D – Martin Mar 12 '16 at 16:29
  • I get no error..at all.I tried to start session everywhere...on top of page,in the middle,in the end,include with ext file....nothing.The query works.I verified it.Var_dump $_SESSION['uid'] and $uid returns the correct result while on the login page.It returns NULL on the protected page.I am aware about SHA1,i'll improve it.Also a strange thing is this,if i rename the folder in htdocs then i am allowed to login once....and then never again. – Grimnack Mar 12 '16 at 16:30
  • 1
    @Martin *lol!* - I had the good fortune of seeing him live once. Hilarious guy. The "real" stuff is a lot better "live" ;-) – Funk Forty Niner Mar 12 '16 at 16:31
  • @Fred-ii- unfortunately most of the quotes attributed to him relating to things like internet explorer, *etc.* are claimed as bogus... – Martin Mar 12 '16 at 16:32
  • Grimnack, can you state that after you've made the database call, you can write: `$_SESSION['uid'] = $uid['uid'];` *then* `print_r($_SESSION);exit;` an that that holds the correct value for the uid? – Martin Mar 12 '16 at 16:33
  • And `session_start();` should **always be set at the start of the page** , no point putting it in the middle of the page. – Martin Mar 12 '16 at 16:34
  • Martin i've tried everything.And yes $_SESSION['uid'] = $uid['uid'] hold the same value.I tried that with var_dump.The problem is with the protected page.That page doesen't see the session. – Grimnack Mar 12 '16 at 17:47

3 Answers3

1

Assumptions I made which are not stated by the Question:

  • That form data is submitted with a POST type and with the correct character set (so a u is a u is a u)

  • That all code shown in the question is in the files referenced in the headers and are not in includes and other "tucked away corners".

Some Code Improvements

<?php
session_start(); //at the start.
error_reporting(E_ALL); //as suggested by others add error logging
ini_set('display_errors',1); //and debugging to tell you info. 
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    require 'dbcon.php'; //no need for brackets here.
    if (!empty($_POST['email']) && !empty($_POST['password'])) {
        // you had a syntax error here. Also use empty() rather than
        // isset as POSTED forms will still send the data containers
        // even if it contains nothing.
        $e = mysqli_real_escape_string($dbcon, $_POST['email']);
        $p = mysqli_real_escape_string($dbcon, $_POST['password']);
        $q = "SELECT uid,mail,psword,unm FROM pics WHERE mail='$e' AND psword=SHA1('$p')"; //no need for brackets here.
        $result = mysqli_query($dbcon,$q);
            if(mysqli_num_rows($result) == 1){
                $uid = mysqli_fetch_array ($result, MYSQLI_ASSOC);
                if(is_array($uid) && count($uid) > 0){
                    //added a further debug qualifier here 
                    // to check that your SQL result is as expected.
                    $_SESSION['uid'] = $uid['uid'];
                    mysqli_free_result($result); //These occur AFTER the 
                    mysqli_close($dbcon); // exit statement which stops the script. 
                    //so put them before hand. but it's pretty worthless as
                    //mysqli will stop the connection anyway unless 
                    //specifically told otherwise.
                    header("location: members.php");
                     exit();
                      }
                 else {
                  die("your SQL returned an empty result");
                  }
             }else{
                echo 'no match';
            }
    }else{
        echo 'Empty fields...';
    }
}
// removed PHP closing marker.  Unneeded.  

As a note, why do you select 4 values from the table when you only use one value?

Destination Page

So now you have assured us that the values are being grabbed by the SQL ok and are being saved to the SESSION ok, so the issue is with finding the session on the destination page?

First, start the session:

Then, as others have stated - Error log and debugging:

then see what has been passed to the session handler:

session_start(); //always at the start!!!
error_reporting(E_ALL); //always use for error reporting in development
ini_set('display_errors',1); //always!!! 
print_r($_SESSION);

If no errors are shown up here then you need to go back to your login page and check sessions are being saved correctly, so:

           $uid = mysqli_fetch_array ($result, MYSQLI_ASSOC);
           $_SESSION['uid'] = $uid['uid'];
           $_SESSION['sausages'] = "roasted";
           ...
           header("location: members.php");
           exit();

And then go back and see if this static varible string appears on your members.php page,

  • If it does, then that shows that your SQL query and not your session is invalid and failing, which I'm not going to go into here, but enough to say that the session is not the problem. A probable error here is you are not storing the hashed value (SHA1) correctly in your database. But we would need more info to provide specific assistance in the case it's an SQL error.

  • If it does not appear then that does indicate either a session issue or a file handling issue, mainly you need to have a clear path to were the code is in the file structure, is the "protected" page code you have shown us actually in the page referenced in the header, and is this page in the same directory as the login page (rather than any mod_rewrite jibjag etc.)?

Tell me what light this shines on identifying exactly where your problem begins.


In other notes it's worth noting your password system is not up to production quality and a different approach should be used. Please research StackOverflow.


EDIT:

Session details:

  • turn session.cookie_httponly to on.
  • check that the folder sessions are stored in (C:\xampp\tmp) has all read write and execute settings (chmod 0777).
  • change session.use_strict_mode to on.
  • Set session.auto_start to on.

Although I must admit that aside from making absolutely sure that PHP has permisson to read and write to the specified session directory, nothing in your session info stands out to me as a possible cause.

Do you have any errors/warnings on your server logs (the program that runs PHP on your machine)?

You can find a good explanation of chmod here.

THIS POST might be a lot of help to you as well.

Community
  • 1
  • 1
Martin
  • 22,212
  • 11
  • 70
  • 132
  • Thanks for the usefull info.Now the query works because after if(mysqli_num_rows($result) == 1){ session_start(); $uid = mysqli_fetch_array ($result, MYSQLI_ASSOC); var_dump($uid) returns the correct credentials.Password is encripted. var_dump($_SESSION['uid']) holds the correct value. Any way the page finaly started to behave accordingly.With no change to the code.Just change in the name.htdocs/testing/index.php now is htdocs/testing123/index.php.Which is strange cuz i've tried earlier and it didnt work.I'll apply your corrections,i just hope i don't break the code.Wish me luck. – Grimnack Mar 12 '16 at 17:55
  • So no errors are shown on both pages. I've tried you advice $uid = mysqli_fetch_array ($result, MYSQLI_ASSOC); $_SESSION['uid'] = $uid['uid']; $_SESSION['sausages'] = "roasted"; print_r($_SESSION); Prints Array ( [sausages] => roasted ) And the "protected" page session_start(); error_reporting(E_ALL); ini_set('display_errors',1); print_r($_SESSION); Shows Array ( ) So it must be a session issue.Both pages are in the same directory. Dear God..... – Grimnack Mar 12 '16 at 20:31
  • @Grimnack hmmm,I don't have any immediate solutions to that aside from viewing the SESSION details in PHP and seeing what sort of settings your server is running. Have a look at this and see if you can view `phpinfo` and see what sort of session details are being returned: http://stackoverflow.com/questions/155920/php-session-data-not-being-saved – Martin Mar 12 '16 at 20:54
  • @Grimnack If possible can you edit your original question and add in the `PHPinfo()` information regarding sessions (as exampled in the link'd SO question in my above comment). Cheers – Martin Mar 12 '16 at 21:04
  • (@Grimnack also for sessions to work you need to have cookies enabled on your browser) – Martin Mar 12 '16 at 21:09
  • @Grimnack what version of PHP are you running? (last comment for now, I promise!) – Martin Mar 12 '16 at 21:10
  • According to xampp i'm running php 5.6.19 ver.I think cookies are enabled on the browser.Besides,i have this problem with chrome also. – Grimnack Mar 13 '16 at 00:43
  • I edited the php.ini file and still no luck.But now i get a notice. Notice: A session had already been started - ignoring session_start() in C:\xampp\htdocs\testing123\members.php on line 2 Also there are a write permissions on the folder. When i tried to login,it redirected me at login page.as always. And i saw in tmp folder that 3 sess files are created.One has info the other two are empty.They all have different id. – Grimnack Mar 13 '16 at 18:03
  • Yes I had thought that `session.auto_start` wasn't needed but it was a popular solution on the link that looked useful. Seems not needed in this case. I can't really think of any new ideas for finding you a solution, @Grimnack – Martin Mar 13 '16 at 22:55
  • Bummer.I'll start with new project.I tested this with other pages and they work.It seems that the problem is with this template only.Maybe its cursed. :P Is it possible some js/html code to be in conflict with php code?Unlikely but still... – Grimnack Mar 14 '16 at 11:17
  • if the code you've shown on this question is the only code there is then, no, that's unlikely to be the issue. @Grimnack. If you can pastebin your full page code for both pages I can take a more detailed look at it, if there's more than you've put in this question. – Martin Mar 14 '16 at 11:27
0

Is this line header("location: members.php"); working?

I don't really see the need of the following lines:

exit();
mysqli_free_result($result);
mysqli_close($dbcon);

Because your page is already been redirected.

Now, what exactly have you written in the members.php page? If my idea is correct, have you included this protected page on top of members.php?

Indrasis Datta
  • 8,692
  • 2
  • 14
  • 32
0

I dl html5 boiler plate,opened a new project and i started adding the html files one by one.I had a backup of the site right before i started coding the login.Then i copied the php code.Then the css and js files.So far the login works as it should with the same code as long as i don't change the name of the folder.I hope it will stay that way.Thank you for your time and help.I appreciate it.

Grimnack
  • 29
  • 1
  • 5