how to fix this problem(Array to string conversion) - php

this is my url http://localhost/mymvc/index.php?url=controller/method
I want to catch 'method' by $_GET Super Global Variable and get access class of Controller method.
I want to get all method dynamic way
Here is my index file code.
<?php
include 'inc/header.php';
include_once 'system/libs/MController.php';
include_once 'system/libs/Main.php';
$url = $_GET['url'];
$url = rtrim($url, '/');
$url = explode("/", $url);
include 'app/controllers/'.$url[0].'.php';
$ctlr = new $url[0]();
$ctlr->$url[1](); //---->(1) here is problem. I can't access my method this way
include 'inc/footer.php';
?>
Here is my Controller.php file code
<?php
/**
* controller
*/
class Controller extends MController{
public function __construct(){
// parent::__construct();
}
public function method(){
echo "Mohammad Arman from method";
}
}
?>
But when I show this output. Showing below this error and notice
**
1)Notice: Array to string conversion in
C:\Users\USER\Documents\wamp\www\mymvc\index.php on line 15
2)Notice: Undefined property: Controller::$Array in
C:\Users\USER\Documents\wamp\www\mymvc\index.php on line 15
3)Fatal error: Uncaught Error: Function name must be a string in
C:\Users\USER\Documents\wamp\www\mymvc\index.php:15 Stack trace: #0
{main} thrown in C:\Users\USER\Documents\wamp\www\mymvc\index.php on
line 15**

You need to make sure the name you are using as the function name is properly delimited,
$ctlr->$url[1]();
could be interpreted as $ctlr->$url and then [1], but what you really want is...
$ctlr->{$url[1]}();

Related

This happens only on live server: Fatal error: Uncaught Error: Call to a member function signin() on boolean in

Confession:
I read many similar questions on this platform, but nothing seems closely aligned to my situation. Most of the questions seem to originate from binding params in prepared statements or execute statement.
In my case, the website runs smooth on a local server(Apache2). However, it throws the error below when published on live server.
Fatal error: Uncaught Error: Call to a member function signin() on boolean in /storage/ssd5/815/17670815/app/controllers/signin.php:16 Stack trace: #0 /storage/ssd5/815/17670815/app/core/app.php(33): Signin->index() #1 /storage/ssd5/815/17670815/public_html/index.php(4): App->__construct() #2 {main} thrown in /storage/ssd5/815/17670815/app/controllers/signin.php on line 16
Context
I'm using MVC (OOP) in PHP and here the relevant parts mentioned in the error. I hope this is not too much.
In the main index page, the line referred in the error is a core class(App) instantiation
<?php
session_start();
require_once '../app/initializer.php';
$app = new App(); //this is the line 4 mentioned in the error
In Signin controller class the line referred in the error is indicated below
<?php
class Signin extends Controller{
function index(){
//you can do this if passing data to view
$data["Page_title"] = "Signin";
if($_SERVER['REQUEST_METHOD'] == "POST"){
// this is a debuggin code
//echo "I am signin controller <br />";
// show($_POST);
$user = $this->loadModel("User");
$user->signin($_POST); //this the line referred in the error
}
$this->view("zac/signin",$data);
}
}
In class APP the line is a callback - check below
<?php
class App {
private $controller = "home";
private $method = "index";
private $params = [];
public function __construct()
{
$url = $this->splitURL();
if(file_exists("../app/controllers/".strtolower($url[0]).".php")){
$this->controller = strtolower($url[0]);
//unset the array position
unset($url[0]);
}
require "../app/controllers/".$this->controller.".php";
// echo file_get_contents('http://smart-ecom.000webhostapp.com/app/controllers/'.$this->controller.".php");
//Create instance of whatever controller class is passed(if it exists, otherwise the home controller)
$this->controller = new $this->controller;
if(isset($url[1])){
if(method_exists($this->controller, $url[1])){
$this->method =$url[1];
unset($url[1]);
}
}
$this->params = array_values($url);
call_user_func_array([$this->controller, $this->method],$this->params); //this is line 33
}
/**
* splitURL gets url from browser and processes against the conroller classes and their methods
* #return array
*/
private function splitURL(){
//check if the the GET is set otherwise set the url to defualt class home
$url = isset($_GET['url']) ? $_GET['url'] :"home";
// return explode("/",filter_var(trim($_GET['url'],"/"), FILTER_SANITIZE_URL));
return explode("/",filter_var(trim($url,"/"), FILTER_SANITIZE_URL));
}
}
?>
The Database class's read function is as follows. This method isn't directly referred in the error message
public function read($query, $data = []){
$stmt = self::$conn->prepare($query);
$result = $stmt->execute($data);
if($result){
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
if(is_array($data) && count($data) > 0){
return $data;
}
}
return false;
}
As I mentioned earlier, this error fires on a live server but the website runs smooth in dev environment with PHP 7.4, Apache2, MySQL 8 Windows 10.
Your help is match appreciated in advance.
I learned this the hard way and I hope this can help someone with similar issues. The cause of the error because of how windows and Linux deals with case sensitivity in file names. In Windows, file names aren't case sensitive while in Linux - they are. So, that was the reason why the website was running smooth in the local dev environment(Windows machine) but throwing an error on a live server(which is Linux). To see the difference, refer to my earlier comment in this thread.
protected function loadModel($model){
if(file_exists("../app/models/". strtolower($model) . ".class.php")){
include "../app/models/".strtolower($model).".class.php";
return $model = new $model();
}else{
return false;
}
}
}
In the "include" line, you can see that I added the strtolower function to include the proper model and that solved the issue.

URL is not working when it's trying it for routing

I'm trying to catch the URL from my localhost, here it is
http://localhost/mvc/index.php?url=Index/category and things are going well but when I'm trying to use the URL /category it is showing error. Here is the error
Notice: Array to string conversion in C:\xampp\htdocs\mvc\index.php on line 21
Notice: Undefined property: Index::$Array in C:\xampp\htdocs\mvc\index.php on line 21
Fatal error: Uncaught Error: Function name must be a string in C:\xampp\htdocs\mvc\index.php:30 Stack trace: #0 {main} thrown in C:\xampp\htdocs\mvc\index.php on line 21
<?php
include_once "system/libs/main.php";
include_once "system/libs/Dcontroller.php";
include_once "system/libs/Load.php";
?>
<?php
$url = isset($_GET['url']) ? $_GET['url'] : NULL;
if ($url != NULL) {
$url = rtrim($url,'/');
$url = explode("/", filter_var($url,FILTER_SANITIZE_URL));
} else {
unset($url);
}
if (isset($url[0])){
include 'app/controllers/'.$url[0].'.php';
$ctlr = new $url[0]();
if (isset($url[2])) {
$ctlr->$url[1]($url[2]);
} else {
if (isset($url[1])) {
$ctlr->$url[1](); //Here is the line where I'm getting the
error
} else {
}
}
}else{
include 'app/controllers/Index.php';
$ctlr = new Index();
$ctlr->home();
}
?>
But when I'm using
category() instead of $url[1]
it's working fine. Here is the Index class.
<?php
class Index extends Dcontroller
{
public function __construct()
{
parent::__construct();
}
public function home()
{
$this->load->view("home");
}
public function category()
{
$data = array();
$catModel = $this->load->model("CatModel");
$data['cat'] = $catModel->catList();
$this->load->view("category", $data);
}
}
two things straight away: "/" is not legal in a url param as part of a get string. you need to encapsulate it with URL encodeing
EG:
http://localhost/mvc/index.php?url=Index%2Fcategory
it's also the fact that "$ctlr->$url[1]" simply doesn't have a function called it.. eg: whatever "$ctlr->$url[1]" resolves to ??category()?? doesn't exist, you need to MAKE it.
add this to your code
function category() {
Index tmp = new Index();
tmp->category();
}
EDIT : I've just noticed, it's even more idiotic than I thought.. your string says Index/category doesn't it?.. make the class method static.. (this code is dreadful by the way it displays almost no sound knowledge of design whatsoever) there is no Index/category because you can't call category inside a class except if it's a static method.
Learn to code.

Php routes does not change the effect in the browser bar

This is my main index file I want that when I write in the browser about it loads the about page but it fails.
<?php
$database = require 'core/bootstrap.php';
require Router::load('routes.php')
->direct(Request::uri());
?>
This is my routes.php file
<?php
$router->define([
'' => 'controllers/index.php',
'about' => 'controllers/about.php',
'about-culture' => 'controllers/about-culture.php',
'contact' => 'controllers/contact.php'
]);
?>
This is my Router file
<?php
class Router
{
protected $routes = [];
public static function load($file)
{
$router = new static;
require $file;
return $router;
}
public function define($routes)
{
$this->routes = $routes;
}
public function direct($uri)
{
if(array_key_exists($uri , $this->routes))
{
return $this->routes[$uri];
}
throw new Exception('No Routes defined for this URL');
}
}
?>
I don`t know what is the error here, I tried a lot and also watch the tutorial and do exactly as he do but I fail to show the output.
require Router::load('routes.php')
->direct(Request::uri());
when I write only the start localhost:8080/start/ (this is the folder where all my files are present , it gives me this error
Fatal error: Uncaught Exception: No Routes defined for this URL in C:\xampp\htdocs\start\core\Router.php:25 Stack trace: #0 C:\xampp\htdocs\start\index.php(8): Router->direct('start') #1 {main} thrown in C:\xampp\htdocs\start\core\Router.php on line 25
and when I load page like about it says object not found.
Request class
<?php
class Request
{
public static function uri()
{
return trim($_SERVER['REQUEST_URI'], '/');
}
}
?>
Basically REQUEST_URI contains the whole url except hostname and protocol since start is your folder name and root directory of your application your have to get request uri after start
for eg
http://localhost/start/about/
REQUEST_URI = /start/about/
after trimming = start/about
which will not match any router.
so you have to pass your base directory to your function somehow one way is to modify your uri function
class Request
{
public static function uri($base = "")
{
$url = str_replace($base,"",$_SERVER['REQUEST_URI']);
return trim( $url , '/');
}
}
and can be called as Request::uri("start")

declaring object in variable variable fatal error accessing empty property

Trying to crate objects dynamically for a plug in system (work in progress)
heres my code using $this->module->load_module('test'); to use the method that creates the dynamic objects. Following code is the function that loads the class's and makes use of an auto loader, i have checked that its getting the correct file etc.
<?php
class BaseModule {
function __construct() {
}
function load_module($module){
echo 'Module = '.$module.'<br />';
$object_name = $module . "Controller";
$this->$$module = new $object_name();
}
}
Here is a test module that it would load when invoking $this->module->load_module('test'); and it creates the object outputting the test strings via echo statements. Heres the code for the test module that was constructed. Which should cause no problems as there is not really a solution but just an output string, but posted any way.
<?php
class testController {
function __construct() {
echo 'test controller from modules <br />';
}
}
However when running the page i am getting some errors can any one help out?
Notice: Undefined variable: test in
/Applications/MAMP/htdocs/tealtique/application/modules/BaseModule.php on line 11
Fatal error: Cannot access empty property in
/Applications/MAMP/htdocs/tealtique/application/modules/BaseModule.php on line 11

rows from db in header, which set to display in all page

In CodeIgniter I'm try to made header with code from DB, my controller code:
public function index()
{
$this->load->model('main_model');
$data['result'] = $this->main_model->get_tipsters();
$this->load->view('template/header_view',$data);
}
And header_view:
<?php foreach($result->result() as $row): ?>
<div id="tipster"><img src="<?=$row->photo;?>" /><br /><?=$row->name;?></div>
<?php endforeach; ?>
Header work's only It self view file, but not In others pages.
I Including header like this in controllers:
$this->load->view('template/header_view');
$this->load->view("/bets/index",$data);
$this->load->view('template/footer_view');
Getting this error
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: result
Filename: template/header_view.php
Line Number: 14
Fatal error: Call to a member function result() on a non-object in /home/user/domains/test.com/public_html/application/views/template/header_view.php on line 14
Line 14 is foreach, I have copied early.
Since your header view file is always expecting $result, you'll need to provide it for all your controller methods:
$this->load->model('main_model');
$data['result'] = $this->main_model->get_tipsters();
$data['main'] = $this->main_model->get_main_data(); //example
$this->load->view('template/header_view',$data);
$this->load->view("bets/index",$data);
$this->load->view('template/footer_view');
This can become cumbersome, so consider creating a MY_Controller file that extends CI_Controller - more about that here.
You can make a function in your Common_model
for fecthing result on your header file.
and directly get result from that function by calling it in a view file.
common_model.php
function your_function()
{
// code for fetching data for header
/// return your result here
}
call directly this function in a view file as
$rs = $this->Common_model->your_function();
Note: common_model is load by default .if disable then you need to load model in a view file.
Best way to load CI object on view element file(header_view) and load and call model method with CI object
$CI = & get_instance()
$CI->load->model('main_model');
$result = $CI->main_model->get_tipsters();
<?php foreach($result->result() as $row): ?>
<div id="tipster"><img src="<?=$row->photo;?>" /><br /><?=$row->name;?></div>
<?php endforeach; ?>
and remove code from controller

Categories