At the very bottom I have posted what is visible on the webpage. Not sure what I'm doing, I will post other .php files that are linked to this if necessary. The webpage is also unusable, clicking login will do nothing except refresh the page. Not sure what changed but it was working before adding a few lines of code. I had trouble with new on login.php which accesses my database with connect.php
<?php
session_start();
include("classes/connect.php");
include("classes/login.php");
$email = "";
$password = "";
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$login = new Login();
$result = $login->evaluate($_POST);
if($result != "")
{
echo "<div style='text-align:center;font-size:12px;color:white;background-color:grey;'>";
echo "<br>The following errors occured:<br><br>";
echo $result;
echo "</div>";
}else
{
header("Location: profile.php");
die;
}
$email = $_POST['email'];
$password = $_POST['password'];
}
?>
This is what is displayed at the top of the webpage
'''
evaluate($_POST);
if($result != "")
{
echo "
else
{
header("Location: profile.php");
die;
}
$email = $_POST['email'];
$password = $_POST['password'];
}
?>
'''
My login.php class starting throwing errors due to changing
'''
$DB = new Database();
$result = DB->read($query);
'''
to
'''
$DB = Database();
$result = (new db)->read($query);
'''
Here is the login.php class I have stored in my classes folder
'''
<?php
class Login
{
private $error = "";
public function evaluate($data)
{
$email = addsLashes($data['email']);
$password = addsLashes($data['password']);
$query = "select * from users where email = '$email' limit 1 ";
$DB = Database();
$result = (new db)->read($query);
if($result)
{
$row = $result[0];
if($password == $row['password'])
{
//create session data
$_SESSION['site_userid'] = $row['userid'];
}else
{
$error .= "wrong password<br>";
}
}else
{
$error .= "No such email was found<br>";
}
return $error;
}
}
'''
This is able to connect to the database using the code from connect.php where I created the Database class
'''
<?php
class Database
{
private $host = "localhost";
private $username = "root";
private $password = "root";
private $db = "site_db";
function connect()
{
$connection = mysqli_connect($this->host,$this->username,$this->password,$this->db);
return $connection;
}
function read($query)
{
$conn = $this->connect();
$result = mysqli_query($conn,$query);
if(!$result)
{
return false;
}
else
{
$data = false;
while($row = mysqli_fetch_assoc($result))
{
$data[] = $row;
}
return $data;
}
}
function save($query)
{
$conn = $this->connect();
$result = mysqli_query($conn,$query);
if(!$result)
{
return false;
}else
{
return true;
}
}
}
?>
'''
I really think changing the new function messed everything up. I am following a tutorial which did not use (new db) and just new Database. Using new Database will throw a fatal error.
Looks like a copy/paste error where there's some duplicate code.
Is the following what you want?
<?php
session_start();
include("classes/connect.php");
include("classes/login.php");
$email = "";
$password = "";
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$login = new Login();
$result = $login->evaluate($_POST);
if($result != "")
{
echo "<div style='text-align:center;font-size:12px;color:white;background-color:grey;'>";
echo "<br>The following errors occured:<br><br>";
echo $result;
echo "</div>";
}else
{
header("Location: profile.php");
die;
}
$email = $_POST['email'];
$password = $_POST['password'];
}
?>
Related
Okay so heres the issue, I am trying to making a fancy login system that stores the users data in a php class so it is easy to access. However when I try to call the function that will build the user data it throws this exception.
Fatal error: Uncaught Error: Call to a member function buildUserData() on string in C:\xampp\htdocs\cfgs\submit\login.php:38 Stack trace: #0 {main} thrown in C:\xampp\htdocs\cfgs\submit\login.php on line 38
Here is the userData class code
<?php
class userData {
public $accId = null;
public $username = null;
public $rank = null;
public $vip_rank = null;
public $email = null;
public $auth = null;
function buildUserData($id) {
$result = $db->query("SELECT * FROM users WHERE id = '$id'");
while ($row = $result->fetch_assoc()) {
$this->accId = $id;
$this->username = $row['username'];
$this->rank = $row['rank'];
$this->vip_rank = $row['rank_vip'];
$this->email = $row['mail'];
$this->auth = $row['auth'];
}
}
}
?>
This is the login.php code
<?php
require_once '../../global.php';
if(!isset($_POST['submit'])) {
header("Location: ../../index");
return;
} else {
$user = $db->escapestring($_POST['user']);
$pass = $db->escapestring($_POST['pass']);
if (empty($user) || empty($pass)) {
$_SESSION['logError'] = "Both fields must be filled!";
header("Location: ../../index");
return;
} else {
$result = $db->query("SELECT * FROM users WHERE username = '$user'");
$result = $db->getrows($result);
if ($result < 1) {
$_SESSION['logError'] = "Username does not exist!";
header("Location: ../../index");
return;
} else {
$pass = md5($pass);
$result = $db->query("SELECT * FROM users WHERE username = '$user' AND password = '$pass'");
$result = $db->getrows($result);
if ($result < 1) {
$_SESSION['logError'] = "Details do not match!";
header("Location: ../../index");
return;
} else {
$result = $db->query("SELECT * FROM users WHERE username = '$user' AND password = '$pass'");
while($row = $result->fetch_assoc()){
$username = $row['username'];
$id = $row['id'];
}
$user->buildUserData($id);
$_SESSION['logError'] = "Hello ". $user->username;
header("Location: ../../index");
return;
}
}
}
}
?>
This is the global.php code
<?php
session_start();
require_once 'cfgs/class.database.php';
require_once 'cfgs/class.user.php';
$user = new userData; // I don't want to build data just yet
$db = new database;
$db->conn = $db->connect();
?>
And finally my database handler
<?php
class database {
public $host = "_";
public $user = "_";
public $pass = "_";
public $db = "_";
public $conn = null;
function connect() {
return mysqli_connect($this->host, $this->user, $this->pass, $this->db);
}
function query($sql) {
return mysqli_query($this->conn, $sql);
}
function escapestring($string){
return mysqli_real_escape_string($this->conn, $string);
}
function getrows($sql){
return mysqli_num_rows($sql);
}
}
?>
I did search for a solution myself but it turns out to be one of those specific things that is difficult to find the answer you're looking for.
while you initialise $user just fine:
$user = new userData;
you later overwrite the variable:
$user = $db->escapestring($_POST['user']);
one of the 2 needs a new name,
where should I declare my session, then how to call my variable session, I need it to show user data. Correct if my question is wrong
this is login.php for my condition
session_start();
$_SESSION["Username"]="$Username";
require_once '../include/DBOperations.php';
$response=array();
if($_SERVER['REQUEST_METHOD']=='POST'){
if(isset($_POST['Username']) && isset($_POST['Password'])){
$db=new DBOperations();
if($db->login($_POST['Username'],$_POST['Password'])){
$response['error'] = false;
$response['Auth'] = "Success";
} else {
$response['error']=true;
$response['Auth'] = "Failed";
$response['message']="invalid Username or Password";
}
} else{
$response['error']=true;
$response['Auth'] = "Invalid";
$response['message']="Required fields are missing";
}
}
echo json_encode($response);
?>
this is DBOperations.php
function login($Username,$Password){
$anotherConnection = mysqli_connect("localhost","root","","sisro1");
$sql = "SELECT * FROM Pengguna WHERE Username='$Username' AND Password='$Password'";
$result = mysqli_query($anotherConnection,$sql);
$row = mysqli_num_rows($result);
if ($row == 1){
return true;
} else {
echo(mysqli_error($anotherConnection));
return false;
}
}
this isDBConnect.php for my connection
function connect(){
include_once dirname(__FILE__).'/Constrants.php';
//$con = new mysqli(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
$dbName = "sisro1";
$dbHost = "Localhost";
$user = "root";
$pass = "";
$con = new PDO("mysql:host=$dbHost;dbname=$dbName", $user, $pass);
if(mysqli_connect_errno()){
echo "Failed to connect with database".mysqli_connect_err();
}
return $this->con;
}
you should start you session in the if condition of you login function
if ($row == 1){
$_SESSION["Username"]=$Username;
return true;
} else {
echo(mysqli_error($anotherConnection));
return false;
}
I have made php session, and i have problems with how to display it.
Actually here's the whole code (but variables are in Slovenian language and its too much to change every one of it, so sorry about it).
My login.php file:
<?php
session_start();
if (!(isset($_SESSION['login']) && $_SESSION['login'] != '')) {
header ("Location: index1.php");
}
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$uname = $_POST['uporabnisko1'];
$pword = $_POST['geslo1'];
$_SESSION['uporabniskoime1'] = $_POST['uporabnisko1'];
$user_name = "root";
$pass_word = "";
$database = "spletnabaza";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $pass_word);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$SQL = "SELECT * FROM uporabnik WHERE uporabnisko = '$_POST[uporabnisko1]' AND geslo = '$_POST[geslo1]'";
$izpisImena ="SELECT '$ime' FROM uporabnik WHERE uporabnisko = '$_POST[uporabnisko1]' AND geslo = '$_POST[geslo1]'";
$_SESSION['imeuporabnika'] = $izpisImena;
$result = mysql_query($SQL);
$num_rows = mysql_num_rows($result);
if ($result) {
if ($num_rows > 0) {
session_start();
$_SESSION['login'] = "1";
header ("Location: Stranzaindexom.php");
}
else {
session_start();
$_SESSION['login'] = "";
header ("Location: index1.php");
}
}
else {
$errorMessage = "Napaka pri vpisu";
}
mysql_close($db_handle);
}
else {
$errorMessage = "Napaka pri vpisu";
}
}
?>
My signup.php file:
<?php
session_start();
if (!(isset($_SESSION['login']) && $_SESSION['login'] != '')) {
header ("Location: index1.php");
}
$uname = "";
$pword = "";
$errorMessage = "";
$num_rows = 0;
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$name1 = $_POST['ime'];
$surname = $_POST['priimek'];
$uname = $_POST['uporabnisko'];
$pword = $_POST['geslo'];
$_SESSION['geslo1'] = $_POST['geslo'];
$_SESSION['uporabniskoime'] = $_POST['uporabnisko'];
$uLength = strlen($uname);
$pLength = strlen($pword);
if ($uLength >= 3 && $uLength <= 20) {
$errorMessage = "";
}
else {
$errorMessage = $errorMessage . "Uporabniško ime mora biti dolgo od 3 do 20 znakov". "<BR>";
}
if ($pLength >= 3 && $pLength <= 16) {
$errorMessage = "";
}
else {
$errorMessage = $errorMessage . "Geslo mora biti dolgo od 3 do 20 znakov" . "<BR>";
}
if ($errorMessage == "") {
$user_name = "root";
$pass_word = "";
$database = "spletnabaza";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $pass_word);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$SQL = "SELECT * FROM uporabnik WHERE uporabnisko = $uname";
$result = mysql_query($SQL);
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
$errorMessage = "To uporabnisko ime že obstaja!";
}
else {
$SQL = "INSERT INTO uporabnik (id, ime, priimek, uporabnisko, geslo) VALUES (NULL, '$_POST[ime]', '$_POST[priimek]', '$_POST[uporabnisko]', '$_POST[geslo]')";
$result = mysql_query($SQL);
mysql_close($db_handle);
session_start();
$_SESSION['login'] = "1";
header ("Location: ../index1.php");
}
}
else {
$errorMessage = "Database Not Found";
}
}
}
?>
And than my file in Stranzaindexom.php where i want to display the variables:
At top:
<?php
session_start();
?>
In middle:
Pozdravljen/-a:
<?php
echo $_SESSION['imeuporabnika'];
?>
And when i'm signed in my page with root i get printed:
Pozdravljen/-a: SELECT 'ime' FROM uporabnik WHERE uporabnisko= 'root' AND
geslo= ''
Insted of Pozdravljen/-a, professor. (professor is the name of root username)
Did i miss something ?
Before executing any of the above queries, check the user input ($_POST variables). This can be done easily with the mysql_real_escape_string function. You might also want to use strip_tags() and trim() functions. For example:
$name = mysql_real_escape_string($_POST['name']);
The mysql_* functions are deprecated, I would recommend you to start using mysqli or, even better in my opinion, PDO. Also, your queries won't work, here is a working example:
$query = "SELECT `id` FROM `users` WHERE `name` = '{$name}'";
Don't store any session before actually loggin in or registering. Do this after the user has succesfully registered or logged in. Also don't store any valuable variables like a password, just the user_id would be enough for you. You could easily check if a user is logged in:
if(isset($_SESSION['user_id'])) {
//User is logged in
} else {
//User is not logged in
}
Also, only connect to the DB once and use session_start() once per script. Even prettier would be to do this in a file named config.php. Then simply do this in the beginning of your scripts:
require_once('config.php');
There are more things, but this will give you a good start and enough to work on :-). Good luck.
Hello Ladies and Gentlemen, I have been working on this project for some time now. And all of a sudden when I go into the web page to login I just get a blank screen at the 'success_login.php' which is literally just the login script that runs once login is clicked on my screen.
Here is the success_login.php script:
<?php
require_once($_SERVER['DOCUMENT_ROOT'] . '/luke/classes/userFunctions.php');
$userFunctions = new userFunctions();
session_start();
//assign all posted values to a session
if (!empty($_POST)) {
foreach($_POST as $key => $value) {
$_SESSION['login_info'][$key] = $value;
}
}
//Get the username and password
$username = htmlentities($_POST["username"], ENT_QUOTES);
$password = htmlentities($_POST["password"], ENT_QUOTES);
//Get the user id if the login was valid
$userId = $userFunctions->validLogin($username,$password);
if($userId != 0) {
$_SESSION['login_info']['username'] = $username;
$_SESSION['login_info']['password'] = $password;
$_SESSION['login_info']['user_id'] = $userId;
header('LOCATION: home.php');
exit;
}
header('LOCATION: login.php');
exit;
?>
and here is the function it refers to:
public function validLogin($username,$password) {
$dbact = new DbInteraction();
$query = "select * from person";
$result = $dbact->interact($query,true);
$row = mysql_numrows($result);
$valid = false;
$userId = 0;
while ($row = mysql_fetch_array($result)) {
//Check to see if the username and password are valid
$validUsername = strcmp($username,$row['username']);
if($validUsername == 0) {
$hashedPassword = md5($password . Constants::SALTED);
$validPassword = strcmp($hashedPassword,$row['password']);
if($validPassword == 0) {
$valid = true;
$userId = $row['idperson'];
}
}
}
if(!$valid) {
$_SESSION['login_info']['username'] = "error";
$_SESSION['login_info']['password'] = "";
header('LOCATION: login.php');
exit;
return $userId;
} else {
$_SESSION['login_info']['username'] = "";
$_SESSION['login_info']['password'] = "";
return $userId;
}
}
Like I said, its been working for months and now all of a sudden its not anymore, and it has me really worried. Could someone shed some light for me?
Thanks a million for your time!
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();
}