PHP script won't run - php

I'm currently coding a CMS in PHP in order to get back into PHP (I use to use it all the time). However, for some odd reason, when "including" or "requiring" my classes file, it simply stops the php script, my login form (login.php's html) does not show up (whether I am logged in or not). Any help? Here are two of my scripts:
login.php:
<?php
session_start();
include "classes.php";
if(isset($_GET['logout'])) {
setupSession(2);
}
if($_SESSION['status'] == "online") header("location: admin.php");
if($_POST && isset($_POST['username']) && isset($_POST['password'])) {
$un = $_POST['username'];
$pwd = $_POST['password'];
$mysql = new mySql();
$mysql->validateUser($un, $pwd);
} else $attempt = 2;
?>
<html>
<head>
<title>Log In</title>
</head>
<body>
<form method="post" action="">
<label for="username">username: </label>
<input type="text" name="username" />
<label for="password">password: </label>
<input type="password" name="password" />
<input type="submit" value="Log In" name="submit" />
</form>
</body>
</html>
and classes.php
<?php
class mySql {
protected $dbname;
protected $dbuser;
protected $dbpass;
protected $db;
private $conn;
function __construct() {
$conn = new mysqli($dbname, $dbuser, $dbpass, $db);
}
public function validateUser($username, $password) {
$query = "SELECT * FROM users WHERE username = ? AND password = ? LIMIT 1";
if($stmt = $this->conn->prepare($query)) {
$stmt->bind_param('ss', $username, $password);
$stmt->execute();
if($stmt->fetch()) {
$stmt->close();
setupSession(1);
} else $attempt = 1;
}
}
}
function setupSession($status) {
switch($status) {
case 1:
$_SESSION['status'] = "online";
//other user variables
header("location: admin.php");
break;
case 2:
unset($_SESSION['status']);
if(isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time() - 1000);
}
session_destroy();
break;
default:
session_start();
if($_SESSION['status'] != "online") header("location: login.php");
break;
}
}
?>

You have a scope problem.
$conn = mysqli(....)
should be $this->conn = mysqli(....)

There are not lots of reasons for a required script to break the parent : the required file does not exist, it has an error or it calls exit() or die().
Are you sure that the file classes.php is in the same folder as your script, or in the include path ?
Is this the exact code you are using ?
With a constructor like this :
function __construct() {
$conn = new mysqli($dbname, $dbuser, $dbpass, $db);
}
How the hell do you connect to your database ?
$mysql = new mySql();

function __construct() {
$conn = new mysqli($dbname, $dbuser, $dbpass, $db);
}
Should Be
function __construct($dbname, $dbuser, $dbpass, $db) {
$this->dbname = $dbname;
$this->dbuser = $dbuser;
$this->dbpass = $dbpass;
$this->db = $db;
$this->connect();
}
function connect()
{
$this->conn = new mysqli($this->dbname, $this->dbuser, $this->dbpass, $this->db);
}
Something of that nature.

error_reporting (1);

Related

Could not connect to database using PHP and Mysql

I have an issue.i need to connect my database and fetch the table value.But it is not happening like that.I am explaining my code below.
index.php:
<?php
session_start();
include_once 'dbcon/DBConnection.php';
$dbobj = new DBConnection();
$dbobj->connect();
if (isset($_REQUEST['msg'])){
$msg = urlencode($_REQUEST['msg']);
}
if(isset($_POST["login"])){
//echo 'hii';exit;
$loginid=htmlspecialchars(trim($_POST['txtname']));
$password =sha1(htmlspecialchars(trim($_POST['pwd'])));
//echo $password;exit;
$admin = $dbobj->adminLogin($loginid,$password);
//echo ($admin->result);exit;
if($admin->result == 2){
$msg ='2';
}
if($admin->result ==1){
$_SESSION["admin_id"] = $admin->adminid;
$_SESSION["admin_name"] = $admin->adminname;
$_SESSION["admin_loginid"] = $admin->adminloginid;
header("location:dashboard.php");
}
}
?>
<script>
function valid()
{
var obj = document.frmlogin;
if(obj.txtname.value == "")
{
alert("Please Enter Username");
obj.txtname.focus();
return false;
}
if(obj.pwd.value == "")
{
alert("Please Enter Password");
obj.pwd.focus();
return false;
}
else
{
return true;
}
}
</script>
<form method="post" name="frmlogin" id="frmlogin" action="" autocomplete="off" class="mt">
<label for="" class="text-uppercase text-sm">Username</label>
<input type="text" placeholder="Username" name="txtname" class="form-control mb">
<label for="" class="text-uppercase text-sm">Password</label>
<input type="password" placeholder="Password" name="pwd" class="form-control mb">
<div class="checkbox checkbox-circle checkbox-info">
<input id="checkbox7" type="checkbox" checked>
<label for="checkbox7">
Keep me signed in
</label>
</div>
<button class="btn btn-primary btn-block" name="login" id="login" type="submit" onClick="return valid();">LOGIN</button>
</form>
DBConnection.php:
<?php
class DBConnection{
function __construct() {
}
// destructor
function __destruct() {
// $this->close();
}
public function connect() {
require_once 'dbcon/config.php';
$con = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
if ($con->connect_error)die("Connection failed: ");
// return database handler
return $con;
}
public function adminLogin($loginid,$password){
$admin = new AdminUser();
if(ctype_alnum($loginid)){
$sqllogin=sprintf("select * from ".PREFIX."admin where username='%s' and trim(password)='%s' and status=1",mysqli_real_escape_string($con,$loginid),mysqli_real_escape_string($con,$password));
$dbsql=mysqli_query($con,$sqllogin);
$Num = mysqli_num_rows($dbsql);
echo $Num;exit;
if($Num >0){
if($row=mysqli_fetch_array($dbsql)){
$admin->adminid =htmlspecialchars($row['id']);
$admin->adminname =htmlspecialchars($row['name']);
$admin->adminloginid =htmlspecialchars($row['username']);
$admin->result=1;
}
}else{
$admin->result=2;
}
}else{
$admin->result=2;
}
return $admin;
}
}
?>
Here i am trying to echo the number of rows present but its displaying nothing.Please help me to resolve this issue.
As a base of reflection, if you use OOP, use it as OOP and not as function libs.
I started something for you, you just have to use it like this :
$db = new DBConnection('host', 'user', 'pass', 'database_name');
$db->connect();
$data = $db->adminLogin('login', 'password');
-
class DBConnection
{
protected $_host = null;
protected $_user = null;
protected $_pass = null;
protected $_database = null;
protected $_con = null;
public function __construct($host, $user, $pass, $db)
{
$this->_host = $host;
$this->_user = $user;
$this->_pass = $pass;
$this->_database = $db;
}
function __destruct()
{
//$this->close();
}
public function connect()
{
$con = new mysqli($this->_host, $this->_user, $this->_pass, $this->_database);
if ($con->connect_error)
{
die("Connection failed: ");
}
$this->_con = $con;
return $con;
}
public function adminLogin($login, $password)
{
$admin = new AdminUser();
if( ctype_alnum($login) )
{
$sqllogin = sprintf(
"select * from ".PREFIX."admin where username='%s' and trim(password)='%s' and status=1",
mysqli_real_escape_string($this->_con, $login),
mysqli_real_escape_string($this->_con, $password));
$dbsql=mysqli_query($this->_con,$sqllogin);
$Num = mysqli_num_rows($dbsql);
echo $Num;exit;
if($Num >0){
if($row=mysqli_fetch_array($dbsql)){
$admin->adminid =htmlspecialchars($row['id']);
$admin->adminname =htmlspecialchars($row['name']);
$admin->adminloginid =htmlspecialchars($row['username']);
$admin->result=1;
}
}else{
$admin->result=2;
}
}else{
$admin->result=2;
}
return $admin;
}
}
Btw please see about prepare & bindParam & execute & get_result

Login System with a DB Connection Class don't login. Return with else error for invalid login

I'm new with DB classes and working on it. I'm trying to make my old login system work with this DB class but it returns with my else for invalid login error, like there is no such e-mail and password in the DB. But there is.
Connection Class:
class Conexao
{
private $link;
public function __construct($host = null, $username = null, $password = null, $dbName = null)
{
$this->link = mysqli_init();
$this->link->real_connect($host, $username, $password, $dbName) or die("Failed to connect");
}
public function __destruct()
{
$this->link->close();
}
public function Query($sql)
{
return $this->link->query($sql);
}
Login Page:
<?php
include('dbConnect.php');
session_start();
$conexao = new Conexao("localhost", "root", "XXXXX", "festas");
if(isset($_POST['submit'])) {
$email = mysqli_real_escape_string($conexao,$_POST['email']);
$pass = mysqli_real_escape_string($conexao,$_POST['senha']);
$sel_user = $conexao->Query("SELECT * from contas where email='$email' AND senha='$pass'");
$check_user = mysqli_num_rows($sel_user);
$row = mysqli_fetch_assoc($sel_user);
if($check_user>0){
$_SESSION['user_email']=$email;
header('Location: ../adminpage.php');
mysqli_free_result($result);
} else {
header('Location: ../admin.php?erroLogin=1');
}
}
?>
Always it returns with the "else" header('Location: ../admin.php?erroLogin=1'). I think it could be because of "$check_user = mysqli_num_rows($sel_user);" but I tried to fix and can't. Tried also "$conexao->num_rows($sel_user).
I solved it. Here's what I did:
In DB class php:
public function Escape($sql)
{
return $this->link->real_escape_string($sql);
}
then in login php:
$email = $conexao->Escape($_POST['email']);
Thanks!

Login Function [PHP][PDO]

I've been having trouble trying to get my login function to work. Whenever I try to login it always gives me this Syntax error:
Fatal error: Call to a member function prepare() on a non-object in C:\xampp\htdocs\cereal_mod\includes\Cereal.php on line 53
I'm not sure if the Database connection is part of the problem but i'm not totally sure what's the big ideal of it not operating correctly.
Here is Database.php
<?php
namespace Cereal;
ini_set('error_reporting', E_ALL);
class Database Extends \PDO
{
public function __construct($dbHost,$dbName,$dbUser,$dbPass)
{
parent::__construct($dbHost,$dbName,$dbUser,$dbPass);
try
{
$this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e)
{
die($e->getMessage());
}
}
#get the number of rows in a result
public function num_rows($query)
{
# create a prepared statement
$stmt = parent::prepare($query);
if($stmt)
{
# execute query
$stmt->execute();
return $stmt->rowCount();
}
else
{
return self::get_error();
}
}
#display error
public function get_error()
{
$this->connection->errorInfo();
}
# closes the database connection when object is destroyed.
public function __destruct()
{
$this->connection = null;
}
}
?>
Here is the login.php
<?php
ini_set('error_reporting', E_ALL);
include "includes/Cereal.php";
$manager = new Cereal;
session_start();
if(isset($_POST['username'], $_POST['password'], $_POST['submit'])){
$login = $manager->login($_POST['username'], $_POST['password']);
}
?>
<form action="" method="POST">
<div id="login">
<input type="username" name="username" />
<input type="password" name="password" />
<input type="submit" name="submit" />
</form>
</div>
and lastly Cereal.php
<?php
#namespace Cereal;
ini_set('error_reporting', E_ALL);
class Cereal {
private $configObj;
private $databaseObj;
public $playerData;
public function __construct(){
$this->loadConfig();
if($this->configObj){
try {
$dbHost = $this->configObj['Database']['Host'];
$dbName = $this->configObj['Database']['Database'];
$dbUser = $this->configObj['Database']['User'];
$dbPass = $this->configObj['Database']['Pass'];
$this->databaseObj = new Database('mysql:host=' . $dbHost . ';dbname=' . $dbName, $dbUser, $dbPass);
} catch(\PDOException $ex){
$this->__return($ex->getMessage, true);
}
}
}
private function loadConfig(){
$configPath = getcwd() . '/includes/config/Configuration.json';
$configData = file_get_contents($configPath);
$configObj = json_decode($configData, true);
if(!$configObj){
$this->configObj = $configObj;
} else {
}
}
public function __return($message, $die = false){
$successCheck = $die ? 'false' : 'true';
$messageArr = Array('success' => $successCheck, 'message' => $message);
echo json_encode($messageArr);
if($die) die();
}
public function login($username, $password){
try {
$login = $this->databaseObj->prepare("SELECT * FROM users WHERE username=:username AND password=:password");
$login->bindParam(':username', $username);
$login->bindParam(':password', md5($password));
$login->execute();
$row = $login->fetch(PDO::FETCH_ASSOC);
if($row) {
$_SESSION['auth'] = 1;
$_SESSION['username'] = $username;
die(json_encode(array("error"=>false, "message"=>"")));
} else {
die(json_encode(array("error"=>true, "message"=>"Incorrect credentials")));
}
} catch(PDOException $e) {
error_log('PDOException: ' . $e->getMessage());
die(json_encode(array("error"=>true, "message"=>"Database error, this has been logged.")));
}
}
}
?>
If someone could point out what i'm doing wrong I would really appreciate that because I haven't played with PDO in a while and i'm not sure if I am doing this correctly.
In Database.php you need to change
public function __construct($dbHost,$dbName,$dbUser,$dbPass)
{
parent::__construct($dbHost,$dbName,$dbUser,$dbPass);
}
to
public function __construct($dsn, $dbUser, $dbPass)
{
parent::__construct($dsn, $dbUser, $dbPass);
}
You also have to add use Cereal\Database; in top of Cereal.php
and use PDO; in top of Database.php
Try following:
if(!$configObj){
$this->configObj = $configObj;
} else {
}
should it not be if($configObj) ?

How to connect to MySQLi server

I have a login-script, but when i proceed it there com a error:
Undefined property: Users::$host in C:\wamp\www\userlogin\classes\class.database.php on line 8
There is 4 files:
<?php
session_start();
include "classes/class.users.php";
if(isset($_POST['login'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$users->login($username, $password);
}
?>
<!DOCTYPE html>
<head>
<title>Basic Login Script</title>
</head>
<body>
<form method="POST" action="" name="login">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" name="login" value="Login">
</form>
</body>
</html>
<?php
class Database
{
public function __construct()
{
$host = 'localhost';
$user = 'root';
$pass = 'password';
$name = 'usersystem';
$this->mysqli = new mysqli($this->host, $this->user, $this->pass, $this->name);
if ($mysqli->connect_errno)
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
echo $mysqli->host_info . "\n";
}
} ?>
<?php
include "class.database.php";
class Users extends Database
{
public function login($username, $password)
{
$stmt = $this->mysqli->prepare("SELECT username, password FROM users WHERE username = ? and password = ? LIMIT 1");
$stmt->bind_param('ss', $username, $password);
$stmt->execute();
$stmt->bind_result($username, $password);
$stmt->store_result();
if($stmt->num_rows == 1) {
while($stmt->fetch()) {
$_SESSION['username'] == $username;
header("Location: dashboard.php");
}
}
else
return false;
$stmt->close();
$stmt->free_result();
}
}
$users = new users(); ?>
//dashboard
<?php echo "error"; ?>
I use localhost/index.php to run and the 3 files class.database.php and class.users.php dahsboard.php is in the directory: classes
Mybe it is a syntax-error, but i can not locate it.
I have created a database in phpmyadmin and inserted the data.
Can anybody help me?
You can't use $this for local variable, they will need to be property of the class, and you need a public one for the connection, like this:
<?php
class Database {
public $mysqli;
private $host = 'localhost';
private $user = 'root';
private $pass = 'password';
private $name = 'usersystem';
public function __construct() {
$this->mysqli = new mysqli($this->host, $this->user, $this->pass, $this->name);
if ($this->mysqli->connect_errno) {
echo "Failed to connect to MySQL: (". $this->mysqli->connect_errno . ") ";
}else{
echo $this->mysqli->host_info . "\n";
}
}
}
?>
Other thing I notice is you don't start a session before setting it.
You should also exit after redirecting
if($stmt->fetch()) {
session_start();
$_SESSION['username'] == $username;
header("Location: dashboard.php");
exit;
}
Try changing your database connection to this:
class Database
{
// Since you are calling this variable in other methods
// you need to make it available.
public $mysqli;
public function __construct()
{
$host = 'localhost';
$user = 'root';
$pass = 'password';
$name = 'usersystem';
$this->mysqli = new mysqli($host, $user, $pass, $name);
// You are mixing local with class-wide variables. Should all conform.
if ($this->mysqli->connect_errno)
echo "Failed to connect to MySQL: (".$this->mysqli->connect_errno.")".$this->mysqli->connect_error;
echo $this->mysqli->host_info."\n";
}
}
in the __construct method for Database change $user to $this->user, $host to $this->host etc..

Fatal error: Cannot redeclare class Database. How to fix?

I've seen the question asked but the answer wasn't very clear to me.
My code is.
index.php
<?php include 'header.php'; ?>
<?php
include "class.users.php";
if(isset($_POST['login'])) {
$username = $_POST['username1'];
$password = $_POST['password1'];
$users->login($username, $password);
}
?>
class.users.php
<?php
include "connect.php";
class Users extends Database {
public function login($username, $password) {
$stmt = $this->mysqli->prepare("SELECT username, password FROM users WHERE username = ? AND password = ? LIMIT 1");
$stmt->bind_param('ss', $username, $password);
$stmt->execute();
$stmt->bind_result($username, $password);
$stmt->store_result();
if($stmt->num_rows == 1) {
while($stmt->fetch()) {
$_SESSION['username'] == $username;
header("Location: dashboard.php");
}
} else {
return false;
}
$stmt->close();
$stmt->free_result();
}
}
$users = new users();
?>
connect.php
<?php
class Database {
public function __construct() {
$host = 'localhost';
$user = 'root';
$pass = '';
$name = 'meeboo3';
$this->mysqli = new mysqli($host, $user, $pass, $name);
}
}
?>
The class Database isn't called twice? so how is it a error? can anyone explain why in the comments.
you could test to see if its already declared before doing so:
if (!isset($database) && !is_a($database, 'Database')){
$database = new Database();
}
Or
if you're declaring it inside connect.php you could:
include_once 'connect.php';
instead of
include 'connect.php';

Categories