Reputation: 51
I know this answer has been answered already but it seems like I couldn't understand anything in my case (I'm still very new to web developing, learning frontend since this october and I jumped onto php at the start of this month). My function is supposed to check if user is logged in and I couldn't understand the answers I read for my problem cause it seems like in the answers I found, the functions weren't custom? I might be wrong and I hope if I am, you can laugh about it.
So, to get a bit of context, I encounter this error when I try to call the function "check_logged_in()" in one of my controllers, this controller in question (it's called Upload) extends the main Controller from my core folder (and I triple checked if my init file has required it so I can use it globally). Then I call a custom function from the main controller to load models if needed (in this case, I need to load my user model to get access to the "check_logged_in()" function since it's written there). And this is where thing happen. I'll provide a bit of code so you guys can understand what I'm saying.
The Upload controller
<?php
class Upload extends Controller
{
function index()
{
header("location:" . ROOT . "upload/image");
die;
}
function image()
{
$user = $this->loadModel("user");
if(!$result = $user->check_logged_in()){
header("location:" . ROOT . "login");
die;
}
$data['page_title'] = "Upload";
$this->view("upload", $data);
}
}
The main Controller
<?php
class Controller
{
protected function view($view, $data = [])
{
if (file_exists("../app/views/" . $view . ".php")) {
include "../app/views/" . $view . ".php";
} else {
include "../app/views/404.php";
}
}
protected function loadModel($model)
{
if (file_exists("../app/model/" . $model . ".php")) {
include "../app/model/" . $model . ".php";
return $model = new $model();
}
return false;
}
}
And the bit of code from the user model that is called
<?php
class User
{
function check_logged_in()
{
$DB = new Database();
if (isset($_SESSION['user_url'])) {
$arr['user_url'] = $_SESSION['user_url'];
$query = "select * from users where url_address = :user_url limit 1";
$data = $DB->read($query, $arr);
if (is_array($data)) {
//logged in
$_SESSION['user_name'] = $data[0]->username;
$_SESSION['user_url'] = $data[0]->url_address;
return true;
}
}
return false;
}
}
Thanks in advance for your time mates, I hope my noob self is clear enough for you to understand ^^'
Upvotes: 0
Views: 11177
Reputation: 745
Checking for the correct value of the $user variable should fix the error.
...
function image()
{
$user = $this->loadModel("user");
if(!$user || !$user->check_logged_in()){ // Here
header("location:" . ROOT . "login");
die;
}
$data['page_title'] = "Upload";
...
Then on $user
is false
condition will be
!false || !false->check_logged_in()
which will lead to true
.
Otherwise on $user
is User
:
!(object User) || !(object User)->check_logged_in()
will call User::check_logged_in()
method.
Upvotes: 2