0

I have a login function on my website (using MySQL & PHP).

The problem I am having is that I am getting an error where I shouldn't be. When the user logs in, I would like their username to be shown In the navbar using a variable I have called user_data, however, when I try to run the code, I get the error:

Notice: Undefined variable: user_data in C:\xampp\htdocs\exampledirectory\includes\prefs\header.php on line 31.

Now, I have checked all my code, and It all seems to be correct... It just doesn't want to work!

I have the header.php or navbar included into my index.php like this:

INDEX.php:

<?php
   require_once 'core/init.php'; <!-- notice the init file !-->
?>
<html>
   <?php 
      include 'includes/prefs/header.php';
   ?>
   <!-- body of html !-->
</html>

and this is my HEADER.php:

<li style="cursor:pointer;">
   <?php
      if(!logged_in()){
   ?>
   <a>USER</a>
   <ul>
      <li><a href="./login">SIGN IN</a></li>
      <li><a href="./register">REGISTER</a></li>
   </ul>
   <?php
      }else{
   ?>
   <a><?php echo $user_data['username']; ?></a> <!-- this is line 31 !-->
      <ul>
         <li><a href="./profile">PROFILE</a></li>
         <li><a href="./settings">SETTINGS</a></li>
      </ul>
   <?php
      }
   ?>
</li>

now, the user_data variable comes into play once the user has logged in from a form on my login page which redirects all the data to another login page in a redirection folder

LOGIN.php:

<form action="./redir/login" method="post">
    <input type="text" class="input-style" placeholder="Username" name="username"><br><br>
    <input type="password" class="input-style" placeholder="Password" name="password"><br><br>
    <input type="submit" value="Login"><br>
</form>

REDIR/LOGIN.php:

<?php
include 'core/init.php';

if (empty($_POST) === false){
    $username = $_POST['username'];
    $password = $_POST['password'];

    if (empty($username) === true) {
        $errors[] = 'That user does not exist.';
    } else if (user_exists($username) === false) {
        $errors[] = 'That user does not exist.';
    } else if (user_active($username) === false) {
        $errors[] = 'This user is currently inactive. If you would like to know more, please click <a href="./help/9141320">here.';
    } else {        
        $login = login($username, $password);
        if ($login === false) {
            $errors[] = 'The username or password you entered are incorrect.';
        } else {
            // query if credentials = true return (home)
            $_SESSION['user_id'] = $login;
            header('Location: ../index');
            exit();
        }
    }
} else {
    header('Location: index.php');
}
if (empty($errors) === false) {
?>
<!-- error html !-->

all the login data goes to my login function on my users.php

USERS.php:

function user_data($user_id) {
    $data = array();
    $user_id = (int)$user_id;

    $func_num_args = func_num_args();
    $func_get_args = func_get_args();

    if ($func_num_args > 1) {
        unset($func_get_args[0]);

        $fields = '`' . implode('`, `', $func_get_args) . '`';
        $data = mysql_fetch_assoc(mysql_query("SELECT $fields FROM `users` WHERE `user_id` = $user_id"));

        return $data;
    }
}

function logged_in() {
    return (isset($_SESSION['user_id'])) ? true : false;
}

/* exists */

function user_exists($username){
    $username = sanitize($username);
    $query = mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username'");
    return (mysql_result($query, 0) == 1) ? true : false;
}

function email_exists($email){
    $email = sanitize($email);
    $query = mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `email` = '$email'");
    return (mysql_result($query, 0) == 1) ? true : false;
}

/* active */ 

function user_active($username){
    $username = sanitize($username);
    $query = mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username' AND `active` = 1");
    return (mysql_result($query, 0) == 1) ? true : false;
}

/* misc login */

function user_id_from_username($username) {
    $username = sanitize($username);
    return mysql_result(mysql_query("SELECT (`user_id`) FROM `users` WHERE `username` = '$username'"), 0, 'user_id');
}

function user_id_from_email($email) {
    $email = sanitize($email);
    return mysql_result(mysql_query("SELECT (`user_id`) FROM `users` WHERE `email` = '$email'"), 0, 'user_id');
}

function login($username, $password) {
    $user_id = user_id_from_username($username);

    $username = sanitize($username);
    $password = md5($password);

    return (mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username' AND `password` = '$password'"), 0) == 1) ? $user_id : false;
} 
?>

and if the login details are correct it returns the user_id or if not it returns false.

and finally this is my INIT.php file:

<?php
session_start();
//error_reporting(0);

require 'database/connect.php';
require 'functions/general.php';
require 'functions/users.php';

$current_file = explode('/', $_SERVER['SCRIPT_NAME']);
$current_file = end($current_file);

if (logged_in() === true) {
    $session_user_id = $_SESSION['user_id'];
    $user_data = user_data($session_user_id, 'username', 'password', 'email', 'first_name', 'last_name', 'CCNo', 'desc', 'avatar', 'type', 'group', 'active');
$errors = array();
?>

the INIT.php is what creates the user_data variable from the user_data function (if that makes sense).

I hope I have explained it well enough for people to understand and help me with.

The basic outline is: I want my user_data variable function to work (so I can use it to echo out information).

Cheers

  • Is that the code exactly as is? There are syntax errors throughout. – bmcculley Apr 27 '16 at 04:22
  • 1
    You have `echo $user_data['username'];` in the `else` of `if(logged_in() === true)`. So you are trying to use `$user_data` when the user is not logged in. – Sean Apr 27 '16 at 04:24
  • @bmcculley yes mostly, I have left out a few things that I knew would not matter. but can you please tell me these errors? thanks :) –  Apr 27 '16 at 04:24
  • @Sean ah yes, I did that because when I set it to `false`, It does not do anything. rather, it will stay just "user" whether or not I am logged in –  Apr 27 '16 at 04:25
  • your error says there's a problem on line 31. can you point out line 31 in the code? – FuzzyTree Apr 27 '16 at 04:25
  • 1
    @FuzzyTree sure! check the edit I just made in the `header.php` area :) –  Apr 27 '16 at 04:26
  • @FuzzyTree still not working... the error does not show anymore, however, it only displays `user` now, even If I am logged in (which I stated before) –  Apr 27 '16 at 04:31
  • @nerdtweak then the problem is in your `logged_in()` function because it's returning false even when you're logged in – FuzzyTree Apr 27 '16 at 04:33
  • @FuzzyTree hmm.. would you mind telling me how I might fix that ? as I viewed the code before and all seems fine. –  Apr 27 '16 at 04:34
  • @FuzzyTree did you find a fix? –  Apr 27 '16 at 05:14
  • In init.php just before ` if (logged_in() === true) {` add this line `$user_data = '';` and run your code. Tell me what you get. – Navid Apr 27 '16 at 05:33
  • @NMoeini nothing happens :( –  Apr 27 '16 at 05:40
  • Change `require_once 'core/init.php';` in index.php to `require 'core/init.php';` and test. – Navid Apr 27 '16 at 06:40

2 Answers2

0

It seems user_data variable is not initialized. So you need to run sql query in "header.php" file and initialize the user_data variable.

swdpankaj
  • 107
  • 2
  • 11
  • `header.php` is included inside of the `index.php` file, therefore, it is not needed as the initialization file is already required inside of `index.php` –  Apr 27 '16 at 04:28
  • but your query variable is not called and hence this is the error. – swdpankaj Apr 27 '16 at 13:29
0

In your init.php, You're only initializing user_data if the user is logged in. Based on the logic in your header.php, it should be like that:

  if(!logged_in()){
?>
<a>USER</a>
<ul>
  <li><a href="./login">SIGN IN</a></li>
  <li><a href="./register">REGISTER</a></li>
</ul>
<?php
  }else{
?>
<a><?php echo $user_data['username']; ?></a> <!-- this is line 31 !-->

If the user is NOT logged in, you'd want to display the Sign in/Register buttons not the other way around correct?

Ralph Melhem
  • 767
  • 5
  • 12
  • I have already fixed this problem (in the above comment, you will see) –  Apr 27 '16 at 05:47
  • Can you edit your question and apply the code that you're actually using and are you still getting the same error? – Ralph Melhem Apr 27 '16 at 05:50
  • @RalphMelham I just did so :) yes, I am still getting an error. It appears my `login` function doesn't work and Is the reason It is not displaying the username e.t.c. Do you think you might be able to help with that? thanks –  Apr 27 '16 at 05:54
  • @nerdtweak Sure thing I can help you troubleshoot and fix it. Are you getting a specific error? How did you know your problem lies in the login function? – Ralph Melhem Apr 27 '16 at 05:58
  • well, it's not actually outputting an error, however, when the user logs in, it's supposed to display the username rather than "user". therefore, the actual login function isn't working, otherwise, `logged_in` would return the user_id rather than `false` (if that makes sense) –  Apr 27 '16 at 06:03
  • Well you'll need to add flags throughout your code to see which step isn't working properly. Before doing that, please change all the "=== false" identifiers to ! (ie: instead of "if(empty($username) === true)", use if(empty($username))). Then add echo "stepName"; *replace stepName by the actual step name so you know how your code is running and which if/else it's accessing. Once you do that, we can see flaws in the process if there are any, and if not, we'll see on which function it's stopping, and debug it – Ralph Melhem Apr 27 '16 at 06:10
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/110335/discussion-between-ralph-melhem-and-nerdtweak). – Ralph Melhem Apr 27 '16 at 06:17