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();
}
Related
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'];
}
?>
I cant seem to validate right when i have an empty field or when the username is wrong or doesnt match. please any help or pointing me would be very helpful. I tried (empty but it doesnt seem to work when i fill in one field and the other is empty its says all fields are empty. and for the wrong credentials its not working at all.
INDEX.PHP
<?php
session_start();
include_once 'php/classes/class.user.php';
$user = new User();
$log = $_SESSION['uid'];
if ($user->get_session($log)){
header("Location: profile.php?uid=".$log."");
}
if (isset($_REQUEST['submit'])) {
extract($_REQUEST);
$login = $user->check_login($emailusername, $password);
if(!empty($login)){
if($emailusername != $login){
if($password != $login){
if ($login) {
// Registration Success
$log_id = $_SESSION['uid'];
header("location: profile.php?uid=".$log_id."");
}
}else
echo "Incorrect Password";
}else
echo "Incorrect Email";
}else
echo "Fill in fields";
}
?>
USERS.PHP
<?php
include "db_config.php";
class User{
public $db;
public function __construct(){
$this->db = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if(mysqli_connect_errno()) {
echo "Error: Could not connect to database.";
exit;
}
}
/*** for login process ***/
public function check_login($emailusername, $password){
$password = md5($password);
$sql2="SELECT uid from users WHERE uemail='$emailusername' or uname='$emailusername' and upass='$password'";
//checking if the username is available in the table
$result = mysqli_query($this->db,$sql2);
$user_data = mysqli_fetch_array($result);
$count_row = $result->num_rows;
if ($count_row == 1) {
// this login var will use for the session thing
session_start();
$emaildb == $_SESSION['uemail'];
$_SESSION['login'] = true;
$_SESSION['uid'] = $user_data['uid'];
return true;
}
else{
return false;
}
}
/*** for showing the username or fullname ***/
public function get_fullname($uid){
$sql = "SELECT * FROM users WHERE uid = $uid";
$result = mysqli_query($this->db, $sql);
$user_data = mysqli_fetch_array($result);
echo $user_data['fullname'], "<br/>";
echo $user_data['uemail'], "<br/>";
echo $user_data['uid'], "<br/>";
}
public function check_user($uid){
$sql5 = "SELECT * from users WHERE uid='$uid'";
$result1 = mysqli_query($this->db, $sql5);
$count_row1 = $result1->num_rows;
return ($count_row1 == 1);
}
/*** starting the session ***/
public function get_session(){
return $_SESSION['login'];
}
public function user_logout() {
$_SESSION['login'] = FALSE;
session_destroy();
}
}
Based on what you have, this is what you would need.
session_start();
include_once 'php/classes/class.user.php';
$user = new User();
// You need a conditional incase this session isn't set
$log = (isset($_SESSION['uid']))? $_SESSION['uid']:false;
if($log !== false && $user->get_session($log)){
header("Location: profile.php?uid=".$log."");
exit;
}
if(isset($_POST['submit'])) {
// This function should be validating your login so you don't need
// any comparisons after the fact.
$login = $user->check_login($_POST['email'], $_POST['password']);
if($login !== false)
header("location: profile.php?uid=".$log_id."");
exit;
else {
foreach($user->error as $kind => $err) {
echo '<h2>'.$kind.'</h2>'.'<p>'.$err.'</p>';
}
}
}
Your user class: You can throw error reporting into this class if you want to.
class User{
public $db;
public $error;
public function __construct(){
$this->db = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if(mysqli_connect_errno()) {
$this->error['db'] = "Error: Could not connect to database.";
echo $this->error['db'];
exit;
}
}
/*** for login process ***/
public function check_login($emailusername='', $password=''){
// Validate that your email is a real one
if(filter_var($emailusername,FILTER_VALIDATE_EMAIL) !== false) {
$password = md5($password);
// --> You can prepare, bind, and execute your values here replacing what you have now....<--
$sql2 = "SELECT uid from users WHERE uemail='$emailusername' or uname='$emailusername' and upass='$password'";
//checking if the username is available in the table
$result = mysqli_query($this->db,$sql2);
$user_data = mysqli_fetch_array($result);
$count_row = $result->num_rows;
if ($count_row == 1) {
$emaildb == $_SESSION['uemail'];
// this login var will use for the session thing
$_SESSION['username'] = $user_data['uemail'];
// $_SESSION['uemail'] = $user_data['uemail'];
$_SESSION['uid'] = $user_data['uid'];
$_SESSION['login'] = true;
}
else
$this->error['account'] = 'ERROR: Invalid Username/Password';
}
else
$this->error['email'] = 'ERROR: Invalid Email Address';
return (!isset($_SESSION['uemail']))? false:true;
}
/*** for showing the username or fullname ***/
public function get_fullname($uid){
// --> You can prepare, bind, and execute your values here replacing what you have now....<--
$sql = "SELECT * FROM users WHERE uid = $uid";
$result = mysqli_query($this->db, $sql);
$user_data = mysqli_fetch_array($result);
echo $user_data['fullname'], "<br/>";
echo $user_data['uemail'], "<br/>";
echo $user_data['uid'], "<br/>";
}
public function check_user($uid){
// --> You can prepare, bind, and execute your values here replacing what you have now....<--
$sql5 = "SELECT * from users WHERE uid='$uid'";
$result1 = mysqli_query($this->db, $sql5);
$count_row1 = $result1->num_rows;
return ($count_row1 == 1);
}
/*** starting the session ***/
public function get_session(){
return $_SESSION['login'];
}
public function user_logout() {
$_SESSION['login'] = FALSE;
session_destroy();
}
}
$login is a boolean variable, while $emailusername and $password are strings, why you compare them.
I replaced my mediocre mysql_* query system with PDO. However, my login script stopped working. It has to be a problem with fetching data, since my username passes, but my password does not.
CODE:
<?php
session_start();
include('config.php');
include('cipher.php');
$usercheck = $_POST["email"];
$passcheck = $_POST["pass"];
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = :usercheck');
$stmt->execute(array(
':usercheck' => $usercheck
));
$num = $stmt->rowCount();
if ($num == 1) {
$bcrypt = new Bcrypt(15);
$record = $stmt->fetchAll();
$hash = $record['password'];
$isGood = $bcrypt->verify($passcheck, $hash);
if ($isGood == 1) {
$_SESSION['fname'] = $record['firstname'];
$_SESSION['lname'] = $record['lastname'];
$_SESSION['email'] = $record['email'];
$_SESSION['user'] = $record['email'];
$_SESSION['uid'] = $record['uid'];
$_SESSION['birthday'] = $record['birthday'];
$_SESSION['type'] = $record['pagetype'];
$_SESSION['backcolor'] = $record['backcolor'];
$_SESSION['barcolor'] = $record['barcolor'];
$_SESSION['activated'] = $record['activated'];
if ($_SESSION['activated'] == 0) {
$_SESSION['newemail'] = $record['email'];
unset($_SESSION['fname']);
unset($_SESSION['lname']);
unset($_SESSION['email']);
unset($_SESSION['user']);
unset($_SESSION['uid']);
unset($_SESSION['birthday']);
unset($_SESSION['type']);
unset($_SESSION['backcolor']);
unset($_SESSION['barcolor']);
header('Location: mustactivate.php');
} else {
if ($_SESSION['type'] == 1) {
header('Location: profile.php');
} else {
if ($_SESSION['type'] == 2) {
header('Location: mypage.php');
} else {
header('Location: setup.php');
}
}
}
} else
header('Location: login.php?error=badpass');
} else
header('Location: login.php?error=bademail');
?>
$record = $stmt->fetchAll();
$hash = $record['password'];
The fetchAll() method returns an array of rows. So there will not be any $record['password'].
Try var_dump($record) to show yourself what's in that variable.
To fix this, you could use $record[0]['password']. Or else you could fetch it with $stmt->fetch() if you just need one row.
Simply because fetchAll will return an array, so use $record[0] instead of $record directly ex: $record[0]['password']
or after $record = $stmt->fetchAll(); add $record = $record[0]; and leave all the rest to $record['field_name']
I just need some help creating a php function out of this code or in other words just to wrap this code in a php function :
if (isset($_GET['id'])){
$username = mysql_real_escape_string($_GET['id']);
if(ctype_alnum($username)){
$check = mysql_query("SELECT username,first_name FROM users WHERE username='$username'");
if(mysql_num_rows($check)===1){
$get = mysql_fetch_assoc($check);
$username = $get['username'];
$firstname = $get['first_name'];
echo '<div id="mini_profile">This is '.$username.'\'s profile.</div>';
}else{
header("Location: index.php");
exit();
}
}
}
Thanks.
Really easy :)
function yourFunc() {
if (isset($_GET['id'])){
$username = mysql_real_escape_string($_GET['id']);
if(ctype_alnum($username)){
$check = mysql_query("SELECT username,first_name FROM users WHERE username='$username'");
if(mysql_num_rows($check)===1){
$get = mysql_fetch_assoc($check);
$username = $get['username'];
$firstname = $get['first_name'];
echo '<div id="mini_profile">This is '.$username.'\'s profile.</div>';
}else{
header("Location: index.php");
exit();
}
}
}
}
function getMyDivElement($name) {
$username = mysql_real_escape_string($name);
if(ctype_alnum($username)) {
$check = mysql_query("SELECT username,first_name FROM users WHERE username='{$username}'");
if(is_resource($check) && ($get = mysql_fetch_assoc($check))) {
$username = $get['username'];
$firstname = $get['first_name']; //You need this?
return '<div id="mini_profile">This is '.$username.'\'s profile.</div>';
}
}
return null;
}
//usage
if (isset($_GET['id'])) {
$div = getMyDivElement($_GET['id']);
if($div) {
echo $div;
} else {
header("Location: index.php");
exit();
}
}
Another way to do it is to return the echo statement as a string.
The idea of creating a function is to provide reuseable code. This means you are encapsulating the logic, allowing you to change the inner workings of the code without it affecting the actual usage of the function and to avoid tedious repetition.
In your example you should think about the areas that fall into this category. I personally can see that several functions that could be made here.
Example, not run but should give you ideas.
<?php
function getUser($username)
{
if (is_string($username) && strlen($username)) {
$query = "
SELECT
username, firstname
FROM
users
WHERE
username = :username
";
$result = executeQuery($query, array("username" => $username));
return $result->fetch();
}
}
function getDatabase($host, $db, $user, $password)
{
return new PDO("mysql:host=$host;dbname=$dbname, $user, $pass");
}
function executeQuery($sql, array $params = array())
{
$db = getDatabase();
$conn = $db->prepare($sql);
return $conn->execute($params);
}
function validateInput($input)
{
return ctype_alnum($input);
}
function advanceTo($page, $params)
{
header("Location: $page.php");
exit();
}
if (isset($_GET["username"])){
if (validateInput($_GET["username"])) {
$user = getUser($_GET["username"]);
if (! empty($user)) {
// authUserAndSetSessionForUser($user);
/** This page is then directed to and welcome message shown **/
advanceTo("user-home-page", array($user));
} else {
advanceTo("index");
}
}
}
?>
I am trying to reference a variable stored in a SESSION() from a SESSION() controller and I'm having a bit of trouble with the code. What I have are two tables, one for articles and one for authors. The author id of the current user logged in is stored in my $id variable via a SQL query in access.inc.php in function databaseContainsAuthor($email, $password, &$id), then referenced in function userIsLoggedIn() and stored in $_SESSION['id']
includes>access.inc.php
<?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;
}
}
Now that I have the variable $id, which contains the current user's id, stored in $_SESSION['id'], I would like to use the SESSION() in a SQL query in my index.php to insert the author's id along with their articles in my article table so the author and the article the author submits are linked. I'm just having a bit of trouble implementing the correct code to reference $_SESSION['id'] in my SQL query for index.php
articles>index.php
<?php
include_once $_SERVER['DOCUMENT_ROOT'] .
'/includes/magicquotes.inc.php';
include $_SERVER['DOCUMENT_ROOT'] .
'/includes/access.inc.php';
if (isset($_GET['add']))
if (!userIsLoggedIn())
{
include $_SERVER['DOCUMENT_ROOT'] . '/includes/login.inc.html.php';
exit();
}
else
{
$pagetitle = 'New Article';
$action = 'addform';
$text = '';
$authorid = '';
$id = '';
$button = 'Add article';
include 'form.html.php';
exit();
}
if (isset($_GET['addform']))
{
include $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.php';
$text = mysqli_real_escape_string($link, $_POST['text']);
$id = $_SESSION['id'];
$sql = "INSERT INTO article SET
articletext='$text',
articledate=CURDATE(),
authorid= '$id'";
if (!mysqli_query($link, $sql))
{
$error = 'Error adding submitted article: ' . mysqli_error($link);
include 'error.html.php';
exit();
}
header('Location: .');
exit();
}
include $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.php';
$result = mysqli_query($link, 'SELECT id, articletext FROM article');
if (!$result)
{
$error = 'Error fetching articles: ' . mysqli_error($link);
include 'error.html.php';
exit();
}
while ($row = mysqli_fetch_array($result))
{
$articles[] = array('id' => $row['id'], 'text' => $row['articletext']);
}
include 'articles.html.php';
?>
The SESSION() I'm trying to reference is under if (isset($_GET['addform'])), but I;m unsure if this is the rite syntax to use to do so. Any help would be greatly appreciated!
The code seems fine.Check if $id has the value you expect it to be just before the query because if it is returning zero every time your authorid must have some default value which always show up,zero in this case.