oop cant get this small script to work properly logging in - php

I can't figure out why this isn't working. I'm new and just learning.
login.php
<?php
include 'core/init.php';
if (empty($_POST) === false) {
$username = $_POST['username'];
$password = $_POST['password'];
$user = new User();
if (empty($username) === true || empty($password) === true) {
echo 'you need to enter a username and password';
} else if ($user->userExists($username) === false) {
echo 'we cant find that username. have you registered?';
} else echo 'ok';
}
?> <?php
include 'core/init.php';
if (empty($_POST) === false) {
$username = $_POST['username'];
$password = $_POST['password'];
$user = new User();
if (empty($username) === true || empty($password) === true) {
echo 'you need to enter a username and password';
} else if ($user->userExists($username) === false) {
echo 'we cant find that username. have you registered?';
} else echo 'ok';
}
?> <?php
include 'core/init.php';
if (empty($_POST) === false) {
$username = $_POST['username'];
$password = $_POST['password'];
$user = new User();
if (empty($username) === true || empty($password) === true) {
echo 'you need to enter a username and password';
} else if ($user->userExists($username) === false) {
echo 'we cant find that username. have you registered?';
} else echo 'ok';
}
?>
User.php
<?php
require_once 'core/classes/Connect.php';
class User {
private $db;
public function __construct() {
$this->db = new Connect();
$this->db = $this->db->dbConnect();
}
public function userExists($username) {
$st = $this->db->prepare("SELECT COUNT(user_id) FROM users WHERE username=?");
$st->bindParam(1, $username);
$st->execute();
if ($st->rowCount() == 1) {
return true;
} else return false;
}
}
?>
Ive been tring to learn OOP and everyone tells me the best way to learn is to try rather than ask for help. I'm tring to build a simple login and then make it more complex.
When I enter the correct username it doesn't echo ok. Instead, it echos we can't find that username. Have you registered? Any help please. Thanks

I don't know how your Connect-class (and especially the method rowCount) works, but the problem seems to be the following: Your query returns the number of user_ids with the given username but you count rows.
Replacing
$st = $this->db->prepare("SELECT COUNT(user_id) FROM users WHERE username=?");
with
$st = $this->db->prepare("SELECT user_id FROM users WHERE username=?");
should do the trick.
And since you are learning some more comments:
empty($username) === true is equal to empty($username). Most programmers prefer the latter (since its shorter).
Also it seems to make more sense to declare the method userExists as static.

Related

PHP script not recognising my mysql query

I am new to php and mysql and I have began coding a simple social media network. So I am currently working on my login.php page which seem to have no errors, but it is not working as it should and I am assuming it is because the query is not being recognised as a statement. i.e "password" should not be highlighted as a key word but it is a field in the database. I am also aware that I have not considered injection. When I run this in the browser there are no errors but it returns "User not registered" even when a user is in the database. Any insight would be great thanks!
Here is my code:
<?php
include('classes/DB.php');
if (isset($_POST['login'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if (DB::query('SELECT username FROM users WHERE username=:username',
array(':username'=>$username))) {
if (password_verify($password, DB::query("SELECT password FROM
users WHERE username=:username", array(':username'=>$username))[0]
['password'])) {
echo 'Logged in!';
} else {
echo 'Incorrect Password!';
}
} else {
echo 'User not registered!';
}
}
Here is my DB.php class:
<?php
class DB {
private static function connect() {
$pdo = new PDO('mysql:host=127.0.0.1;dbname=SocialNetwork;charset=utf8', 'root', '');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
}
public static function query($query, $params = array()) {
$statement = self::connect()->prepare($query);
$statement->execute($params);
if (explode(' ', $query)[0] == 'SELECT') {
$data = $statement->fetchAll();
return $data;
}
}
}
<?php
include('classes/DB.php');
if (isset($_POST['login'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if (DB::query('SELECT username FROM users WHERE username=:username',
array('username'=>$username))) {
if (password_verify($password, DB::query("SELECT password FROM
users WHERE username=:username", array('username'=>$username))[0]
['password'])) {
echo 'Logged in!';
} else {
echo 'Incorrect Password!';
}
} else {
echo 'User not registered!';
}
}

Not redirecting to home page (index.php)

Is there something wrong about my code? It works but its not redirecting to my index.php it always ended up in the login.php where the form is located.
<?php
include 'core/ini.php';
if (empty($_POST) === false) {
$username = $_POST ['username'];
$password = $_POST ['password'];
if (empty ($username) === true || empty ($password) === true ) {
$errors[] = 'You need to enter a username and password!';
} else if (user_exists($username) === false) {
$errors[] = 'We can\'t find that username. Have you registered?';
} else if (user_active($username) === false) {
$errors[] = 'You haven\'t activated your account! ';
} else {
$login = login($username, $password) ;
if ($login === false) {
$errors[] = 'That username/password combination is incorrect ';
} else {
$_SESSION['user_id'] = $login;
header('Location :index.php');
exit();
}
}
print_r($errors);
}
?>
thanks!
EDIT *
this is my login.php
<?php
include 'core/ini.php';
if (empty($_POST) === false) {
$username = $_POST ['username'];
$password = $_POST ['password'];
if (empty ($username) === true || empty ($password) === true ) {
$errors[] = 'You need to enter a username and password!';
} else if (user_exists($username) === false) {
$errors[] = 'We can\'t find that username. Have you registered?';
} else if (user_active($username) === false) {
$errors[] = 'You haven\'t activated your account! ';
} else {
$login = login($username, $password) ;
if ($login === false) {
$errors[] = 'That username/password combination is incorrect ';
} else {
$_SESSION['user_id'] = $login;
header('Location :index.php');
exit();
}
}
print_r($errors);
}
?>
this is where the process go. I don't know where should I put my start session but I don't know why it works without having an error.
change header('Location :index.php'); to header('Location: index.php'); That space might be the cause.
I guess you missed the session_start(); on top of the page since you are storing session. Initiate the session_start();.
Also does your login() function returns TRUE? Echo something to check whether the function returns TRUE as expected.
You hae to use session_start on top of page and I think you should remove exit after headerlocation..

How do I fix this code (due to MySql deprecated)

So I have written this login system, but there is one big problem. Everytime I try to get the $errors to print when the values inputted are contradictory to the code, it doesn't work. This is the user login code
<?php
if (empty($_POST) === false) {
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) === true || empty($password) === true) {
$errors[] = 'Fill out this field!';
} else if (user_exists($username) === false) {
$errors[] = 'Are you sure you\'ve registered?';
} else if (user_active($username) === false) {
$errors[] = 'you haven\'t activated your account!';
} else {
//Login com.
}
print_r($errors);
}
?>
So I don't see any problems here. Where I suspect problems to be are here. This is the general file:
<?php
function sanitize($data) {
return mysqli_real_escape_string($data);
}
?>
and here is the users code:
<?php
function user_active($username, $con){
$username = sanitize($username, $con);
$q = "SELECT COUNT(`user_id`)
FROM `users`
WHERE `username` = '{$username}'
AND `active` = 1";
if($query = mysqli_query($con, $q)){
return (mysqli_num_rows($query) > 0) ? true : false;
} else {
//TODO: Replace in production
trigger_error('<p>Query ' . mysqli_error($con) . '</p>');
}
}
?>
This is the connect code:
<?php
$con = mysqli_connect('localhost', 'root', '') or die(mysql_error());
mysqli_select_db($con, 'users');
?>
I know that MySql is deprecated so I converted to MySqli but it just caused more problems as the codes kept contradicting each other. Any help would be appreciated. Thank you!
Modify like this,
<?php
function sanitize($data, $con) { //$con parameter added
return mysqli_real_escape_string($con, $data); //$con parameter added
}
?>
Read out here

redirect based on user role stored in mysql database

I've made a website that users can now successfully login to but depending on which group the user is in, I would like to redirect them to different pages after logging in. I have a database with a row "training_group" and if for example, they are in group 2013_1, they would be directed to homepage_20131.php after logging in.
I've been looking for tutorials online and have found a possible solution with a switch function? but I am unsure of how/where to implement this. I just started learning php and would be grateful for any advice given!
Right now, my login page looks like this:
<?php
include 'core/init.php';
if (empty($_POST) === false) {
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) === true || empty($password) === true) {
$errors[] = 'please input a username and password first! ';
} else if (user_exists($username) === false) {
$errors[] = 'We could not locate you in our database.';
}
$login = login($username, $password);
if ($login === false) {
$errors [] = 'That username/password combination is incorrect';
}
else {
$_SESSION['user_id'] = $login;
header('Location:logged_in/templates/logged_in_home.php');
exit ();
}
}
else {
$errors [] = 'No data received';
}
include 'includes/overall/header.php';
if (empty ($errors) === false) {
?>
<h2>We tried to log you in, but...</h2>
<?php
echo output_errors($errors);
}
include 'includes/overall/footer.php';
?>
Here are a couple snippets that might get you going in the right direction.
function login($username, $password){
//... your login code .. database call
if($validLogin){
$user_id = id from database;
$group_id = id from database;
$return = array('user_id' => $user_id, 'group_id' => $group_id);
}
else{
$return = false;
}
return $return;
}
$userinfo = login($username, $password);
if ($userinfo === false) {
$errors [] = 'That username/password combination is incorrect';
}
else {
$_SESSION['user_id'] = $userinfo['user_id'];
$_SESSION['group_id'] = $userinfo['group_id'];
$page = 'homepage_' . str_replace('_', '', $userinfo['group_id'] . '.php';
header('Location:' . $page);
exit ();
}

Dont know what i did wrong php login script

As instructed i have to insert the code inbetween the dashed lines.
Supposed to refresh and see 'exists'
I have the correct database, table, everything im pretty sure but
i see no exist.
Should i keep following the guide or did i mess up?
Does anyone have a guide that is GUARANTEED to work if i follow it correctly?
my login.php
<?php
include 'core/init.php';
-----------------------------------------
if (user_exists('alex') === true) {
echo "exists";
}
die('no exist');
-------------------------------------------
if (empty($_POST) === false) {
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) === true || empty($password) === true) {
$errors[] = 'You need to enter a username and password';
} else if (user_exists($username) === false) {
$errors[] = 'We can not find that user';
}
}
?>
i have init.php
<?php
session_start();
error_reporting(0);
require 'database/connect.php';
require 'functions/general.php';
require 'functions/users.php';
$errors = array();
?>
i have users.php
<?php
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;
}
?>
i have general.php
<?php
function sanitize($data) {
return mysql_real_escape_string($data);
}
?>
i use:
<form action="login.php" method="post">
note: if anyone is familiar with phpacademy i am following his guide
Your die is always called, you should change your code to:
if (user_exists('alex') === true) {
echo "exists";
}
else{
die('no exist');
}

Categories