My log in isn't working - php

I'm getting error:
Undefined variable: user_data in loggedin.php
My register page is fine it register successfully users.When i log in it displays me all the information but not the user_data.If somebody can write me where is my fault.My
init.php
<?php
session_start();
error_reporting(0);
require 'database/connect.php';
require 'functions/general.php';
require 'functions/users.php';
$_SESSION['user_id'] = (int)1;
if(logged_in() === false) {
$session_user_id = $_SESSION['user_id'];
$user_data = user_data($session_user_id, 'user_id', 'username', 'password', 'first_name', 'last_name', 'email', 'profile', 'textarea', 'writingname', 'writing');
echo $user_data['password'];
if(user_active($user_data['username']) === false) {
session_destroy();
header('Location: index2.php');
exit();
}
}
$errors = array() ;
?>
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;
}
function user_exists($username) {
$username = sanitize($username);
return (mysql_result( mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` ='$username' "), 0) == 1) ? true : false;
}
And my
loggedin.php :
<div class="widget">
<h2 onClick="document.location.href='index2.php'">Hello<?php echo $user_data['first_name']; ?> ! </h2>
<div class="inner">

did you pass your $user_data from init.php to loggedin.php???
$user_data is not a session, so you can't just make $user_data in init.php and echo it in loggedin.php...
CMIIW
var_dump might help you tho'

change you init.php code to this one below.
<?php
session_start();
error_reporting(0);
require 'database/connect.php';
require 'functions/general.php';
require 'functions/users.php';
$_SESSION['user_id'] = (int)1;
if(logged_in() === false) {
$session_user_id = $_SESSION['user_id'];
$user_data = user_data($session_user_id);// just send user id here stored in session.
echo $user_data['password'];
if(user_active($user_data['username']) === false) {
session_destroy();
header('Location: index2.php');
exit();
}
}
$errors = array() ;
?>

Related

Undefined Variable MySQL PHP

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>SIGN IN</li>
<li>REGISTER</li>
</ul>
<?php
}else{
?>
<a><?php echo $user_data['username']; ?></a> <!-- this is line 31 !-->
<ul>
<li>PROFILE</li>
<li>SETTINGS</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
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.
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>SIGN IN</li>
<li>REGISTER</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?

Displaying users profile information

I am having problems with displaying out users profile information when clicking on their profile. the data shown is my own when logged in so it isn't switching. I cannot find the issue and wondering where I maybe going wrong?
So the information should be showing out on profile.php
if (isset($_GET['username']) === true && empty ($_GET['username']) === false) {
$username = $_GET['username'];
if (user_exists($username) === true) {
$user_id = user_id_from_username($username);
$profile_data = user_data($user_id, 'first_name', 'last_name', 'email');
?>
<h1><?php echo $profile_data['first_name']; ?> profile</h1>
<p><?php echo $profile_data['email'] ?></p>
<?php
} else {
echo 'Sorry, that user does not exist';
}
} else {
header('Location: index.php');
exit();
}
It shows my information and not the user I am trying to view. If I type in a bogus username on the URL it does error out and say they do not exist.
Here is my script to pick the data out of the database:
if (logged_in() === true) {
$session_user_id = $_SESSION ['user_id'];
$user_data = user_data($session_user_id, 'user_id', 'username', 'password', 'first_name', 'last_name', 'email', 'type', 'profile');
if(user_active($user_data['username']) === false) {
session_destroy();
header('Location: index.php');
exit();
}
}
$errors = array();
Im using a .htaccess file o initliase the vanity URL
RewriteEngine On
RewriteCon %{REQUEST_FILENAME} !-f
RewriteCon %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /profile.php?username=$1
so my URL would look like this...
http://mywebsite.com/myname
here is the function for user_data
function user_data($user_id) {
$data = array();
$user_id = (int)$unser_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;
}
}
And it does work by changing myname but not switching the user data on the profile page to other users data.
As requested: user_exists() function
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;
}
Try this
function user_data($user_id, $fields = '*') {
// type cast to int
$user_id = (int) $user_id;
// if an array is passed, we implode the array to get fields,
// otherwise we return all rows
if (is_array($fields))
{
$fields = implode('`, `', $fields) . '`';
}
//build query, with LIMIT 1 , I assume username is unique
$qry = "SELECT {$fields} FROM `users` WHERE 'user_id' = {$user_id} LIMIT 1";
$sql = mysql_query($qry);
$result = mysql_fetch_assoc($sql);
// if we have a result, return it, otherwise return false
return (mysql_num_rows($sql) == 1) ? $result : false ;
}
to be used:
$profile_data = user_data($user_id, array('user_id', 'username', 'password', 'first_name', 'last_name', 'email', 'type', 'profile'));
or
$fields = array(
'user_id',
'username',
'password',
'first_name',
'last_name',
'email',
'type',
'profile'
);
$profile_data = user_data($user_id, $fields);

PHP session do not carry after header even with session_start(); on every page

I know this problem is very common, and the usual answer is to place session_start; at the beginning of every page and script. I've done that and still to no prevail. I've spent literally a whole 6 hours trying to find the mistake, but came to no avail, any pointers would be appreciated.
The relevant codes are below, but just to break it down. There is an init.php file that contains all the functions, connections and session_start(); and this is included into the top of every page, before any other code.
init.php (included in header.php, before any HTML) [EDITED to include error reporting]
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
require 'database/connect.php'; //code for connecting to database
require 'functions/general.php'; //contains one sanitize function
require 'functions/users.php'; //user-specific functions (see below)
$errors = array();
?>
//rest of the head and opening body tag
index.php (session_start(); is at the beginning of the code from init.php)
<?php include 'includes/overall/header.php'; ?>
<?php include 'assets/nivo/nivo.php'; ?>
<p>plain text
</p>
<?php
echo ($_SESSION['user_id']);
?>
<?php include 'includes/overall/footer.php'; ?>
<?php include 'includes/overall/scripts.php'; ?>
</body>
</html>
core/functions/users.php (within init.php which contains session_start();)
<?php
function logged_in() {
return (isset($_SESSION['user_id'])) ? true : false;
}
function user_exist($username) {
$username = sanitize($username);
return (mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `user` WHERE `username` = '$username'"), 0) == 1) ? true : false;
};
function user_active($username) {
$username = sanitize($username);
return (mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `user` WHERE `username` = '$username' AND `active` = 1"), 0) == 1) ? true : false;
};
function user_id_from_username($username) {
$username = sanitize($username);
return mysql_result(mysql_query("SELECT `user_id` FROM `user` WHERE `username` = '$username'"), 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 `user` WHERE `username` = '$username' AND `password` = '$password'"), 0) == 1) ? $user_id : false;
};
?>
The login form is included into index.php and sends data to login_pro.php
login_pro.php
<?php
include 'core/init.php';
if (empty($_POST) === false) {
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) === true || empty($password) === true) {
$errors[] = 'Please enter a username and password';
} else if (user_exist($username) === false) {
$errors[] = 'User does not exist';
} else if (user_active($username) === false) {
$errors[] = 'Please activate your account';
} else {
$login = login($username, $password);
if ($login === false) {
$errors[] = 'This username/password combination is incorrect';
} else {
$_SESSION['user_id'] = $login;
header("Location: index.php");
exit();
};
};
print_r($errors);
}
?>
If I place a die function to output SESSION['user_id']; into login_pro.php, like so:
} else {
$_SESSION['user_id'] = $login;
die($_SESSION['user_id']);
header("Location: index.php");
exit();
};
I do get the desired user_id. But this is not carried forward after the header redirected me back to index.php - as indicated by the lack of output in the echo function at index.php
How do I fix this?
I have now resolved this problem. It has to do with my hosting provider. I have posted a full explanation to help others here. If someone deem this question should be deleted, please feel free, I am not very familiar with Stackoverflow traditions.

Cannot redeclare user_data() error

i am creating a user accounts system for my website however when i use the include 'core/init.php'; function i get the error. This could be something really simple as I am a beginner and just learning.
Fatal error: Cannot redeclare user_data() (previously declared in C:\xampp\htdocs\PatchMyPC\core\functions\users.php:3) in C:\xampp\htdocs\PatchMyPC\core\functions\users.php on line 17
here is the code for my users.php & init.php files
init.php
<?php
session_start();
//error_reporting(0);
require 'database/connect.php';
require 'functions/users.php';
require 'functions/general.php';
if (logged_in() === true) {
$session_user_id = $_SESSION['user_id'];
$user_data = user_data($session_user_id, 'user_id', 'username', 'password', 'first_name', 'last_name', 'email');
if (user_active($user_data['username']) === false) {
session_destroy();
header('Location: index.php');
exit();
}
}
$errors = array();
?>
users.php
<?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;
}
function user_exists($username) {
$username = sanitize($username);
return (mysql_result($query = mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username'"), 0) == 1) ? true : false;
}
function user_active($username) {
$username = sanitize($username);
return (mysql_result($query = mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username' AND `active` = 1"), 0) == 1) ? true : false;
}
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 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;
}
?>
Probably you require users.php twice.
use:
require_once('users.php');
in all your files to overcome this problem.

Undefined variable?

I'm getting an undefined variable error for $id variable in lines 15 & 21, could someone please explain why? I can't see what the problem is.
<?php
function userIsLoggedIn()
{
if (isset($_POST['action']) and $_POST['action'] == 'login')
{
if (!isset($_POST['email']) or $_POST['email'] == '' or
!isset($_POST['password']) or $_POST['password'] == '')
{
$GLOBALS['loginError'] = 'Please fill in both fields';
return FALSE;
}
$password = md5($_POST['password'] . 'chainfire db');
if (databaseContainsAuthor($_POST['email'], $password, $id))
{
include 'db.inc.php';
session_start();
$_SESSION['loggedIn'] = TRUE;
$_SESSION['email'] = $_POST['email'];
$_SESSION['password'] = $password;
$_SESSION['id'] = $id;
return TRUE;
}
else
{
session_start();
unset($_SESSION['loggedIn']);
unset($_SESSION['email']);
unset($_SESSION['password']);
unset($_SESSION['id']);
$GLOBALS['loginError'] = 'The specified email address or password was incorrect.';
return FALSE;
}
}
if (isset($_POST['action']) and $_POST['action'] == 'logout')
{
session_start();
unset($_SESSION['loggedIn']);
unset($_SESSION['email']);
unset($_SESSION['password']);
unset($_SESSION['id']);
header('Location: ' . $_POST['goto']);
exit();
}
session_start();
if (isset($_SESSION['loggedIn']))
{
return databaseContainsAuthor($_SESSION['email'], $_SESSION['password'], $_SESSION['id']);
}
}
function databaseContainsAuthor($email, $password, $id)
{
include 'db.inc.php';
$email = mysqli_real_escape_string($link, $email);
$password = mysqli_real_escape_string($link, $password);
$sql = "SELECT COUNT(*) FROM author
WHERE email='$email' AND password='$password'";
$result = mysqli_query($link, $sql);
if (!$result)
{
$error = 'Error searching for author.';
include 'error.html.php';
exit();
}
$row = mysqli_fetch_array($result);
$sql = "SELECT id FROM author
WHERE email='$email'";
$id = mysqli_query($link, $sql);
if (!$id)
{
$error = 'Error searching for id.';
include 'error.html.php';
exit();
}
if ($row[0] > 0)
{
return TRUE;
}
else
{
return FALSE;
}
}
The variable $id is defined in databaseContainsAuthor($email, $password, $id), then stored in the $_SESSION['id'] session so naturally $id = mysqli_query($link, $sql); should have passed but it's not?
Variables changed (or defined) inside a function will not affect the rest of the script. For example:
<?php
function changeVariabe($person) {
$person = 'Bob';
}
$person = 'Alice';
changeVariable($person);
echo "Hello $person!"; // Outputs: Hello Alice!
This can be avoided by passing the variable by reference, like this:
<?php
function changeVariabe(&$person) {
$person = 'Bob';
}
$person = 'Alice';
changeVariable($person);
echo "Hello $person!"; // Outputs: Hello Bob!
You can also use global variables, like this:
<?php
function changeVariabe() {
global $person;
$person = 'Bob';
}
$person = 'Alice';
changeVariable();
echo "Hello $person!"; // Outputs: Hello Bob!
a few things
the variable $id should be defined (not required but good practice) before you use it
so for example
$id = NULL;
if (databaseContainsAuthor($_POST['email'], $password, $id))
also setting the $id inside the databaseContainsAuthor function doesn't mean that $id will change outside the scope of that function.
You could make it global but that is considered bad practice
also your function databaseContainsAuthor
contains this code
if ($row[0] > 0)
{
return TRUE;
}
else
{
return FALSE;
}
which will return TRUE or FALSE. but note that once the code returns a value, none of the code after it will be run
which means this part might as well be commented out, as it is after the return statement it will never be run
$sql = "SELECT id FROM author
WHERE email='$email'";
$id = mysqli_query($link, $sql);
if (!$id)
{
$error = 'Error searching for id.';
include 'error.html.php';
exit();
}

Categories