I'm trying to pass parameters to a control in codeigniter, but I'm getting 404 page not found error, I don't get it, I did what the guide says: https://www.codeigniter.com/user_guide/general/controllers.html#passing-uri-segments-to-your-methods
When I remove the params in the index function and just access the controller everything works fine, but I can't pass a value to it...
Here is the code the way I'm trying to send a param: http://mysite/123
<?php
class Main extends Controller {
function index($username) {
echo $username;
}
}
?>
How can I get more info regarding this error from codeigniter?
Thank you.
The URL needs to be http://mysite/Main/index/123.
CodeIgniter URLs are http://<url>/<Controller>/<Method>/<params>.
Check out the /application/config/routes.php file and set the default controller to main like this:
$route['default_controller'] = 'main';
//For CI 2.0.2
//main.php
<?php
class Main extends CI_Controller {
function index($username) {
echo $username;
}
}
?>
// application/config/routes.php
$route['default_controller'] = 'main';
And then try this in URL::
http://mysite/index.php/main/index/123
hope this works for you
As far as I know, the data is passed only when there are more than two uri segments.
Try this,
<?php
class Main extends Controller {
function index() {
$username = $this->uri->segment(3);
echo $username;
}
}
?>
And then go to http://mysite/index.php/main/index/123
Add this function into your control. This will help out get passing arg into index function if method doesn't.
function _remap($method)
{
$param_offset = 2;
// Default to index
if ( ! method_exists($this, $method))
{
// We need one more param
$param_offset = 1;
$method = 'index';
}
// Since all we get is $method, load up everything else in the URI
$params = array_slice($this->uri->rsegment_array(), $param_offset);
// Call the determined method with all params
call_user_func_array(array($this, $method), $params);
}
route file in add this code and any parameters accepted for your home page
$route['default_controller'] = 'main';
$route['(:any)'] = "main/$1";
Related
I'm creating my own framework. It works like this
localhost/controller/action/firstVariable/second/third (And so on...)
My bootstrap look like this:
$request = Util::getInput('request');
$requestList = explode("/",$request);
$modelName = #ucwords($requestList[0]);
$action = #$requestList[1];
$parameters = array_slice($requestList,2);
$controllerName = $modelName.'s'.'Controller';
I'm getting parameters from an url and save them in a variable $parameters. I would like to send them to the current action in my controller the way Laravel 5 is doing.
Example, in Laravel I specify parameters in the url and thats it.
To call them, I need to do a simple step. Just define them:
public function firstAction($first,$second){
}
When I go to an url like:
localhost/Main/firstAction/first/second/
Function of action 'firstAction' will catch those 2 parameters and then basically I can call them inside of the controller and send it to view.
My extends Controller class:
class Controller{
public function __construct($model,$action){
$modelClass = new main();
$reflection = new ReflectionClass($model.'sController');
$reflection->hasMethod($action) ? $this->$action() : die ('Base Controller call error: Method '. $action .' does not exist in Controller '. $model.'sController');
}
public static function renderView($action,$model,$data){
$model = str_replace('sController','',$model);
//include '../application/views/'.$model.'/'.$action.'.php';
$loader = new Twig_Loader_Filesystem('../application/views/'.$model);
$twig = new Twig_Environment($loader);
echo $twig->render($action.'.php', $data);
}
}
class MainsController extends Controller {
private $_data = array();
public function __construct($model,$action){
parent::__construct($model,$action);
}
public function firstAction($first,$second){
echo 'Hoi';
}
}
How can I do it, the good way? I can of course send the variable $parameter to MainController and than call
$this->_data inside of my action but It is not efficient.
I think I need to use arrays to do it, but I have no idea how.
Thank you.
Check out http://php.net/manual/en/function.call-user-func-array.php
P.S.
You do not have to use reflection in order to check if method on that object's instance exist. Single function call can be enough. Check out http://php.net/manual/en/function.is-callable.php
It would be nice if you would use more descriptive names. Now they are confusing.
I try to pass a parameter to my controller functions from my views but I always get "Page Not Found".
I've been looking for any solutions possible for my problem from here, here, and here but I still couldn't find working solutions and I still don't know what could be the problem. I think I've set everything right, but it's not working. Please tell me if there's something I'm doing wrong.
Here is my controller: Controll.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Controll extends CI_Controller{
public function about($thing){
$case = "About Us";
$data['page'] = $case;
$data['p'] = $thing;
print($thing);
//$this->load->view('/header/header',$data);
$this->load->view('about_us',$data);
$this->load->view('/footer/footer');
}
public function mountain_destination($thing){
$data['page'] = "Mountain Destination";
$data['p'] = $thing;
//$this->load->view('/header/header',$data);
$this->load->view('mountain_destination',$data);
$this->load->view('/footer/footer');
}
}
?>
Here's my routes setting:
$route['(:any)'] = "controll/$1";
$route['default_controller'] = "controll";
$route['404_override'] = '';
And here's one of my script called by onClick that tries to call that controller function:
function goTab(thing,tab){
switch(thing){
case "about":
$body.load("<?php echo site_url('about'); ?>/"+$(tab).text().toLowerCase().replace(/ /g,''));
break;
case "mountain":
$body.load("<?php echo site_url('mountain_destination'); ?>/"+$(tab).text().toLowerCase().replace(/ /g,''));
break;
}
My script runs well and it produces right url. For example, I put parameter "myteam" into "goTab" function, it produces link like this:
"http://127.0.0.1/about/myteam". This link's supposed to call "about" function inside my controller and pass "myteam" as parameter. But instead it returns "Page Not Found". And when I try to call "about" function without any parameters like this: "http://127.0.0.1/about", I get missing argument error like this:
Severity: Warning
Message: Missing argument 1 for Controll::about()
Filename: controllers/Controll.php
Line Number: 22
Please help me.
Thanks in advance.
You're not passing it to your about method. You're looking for a method called myteam within your Controll controller.
Amend your Routes to this;
$route['about/(:any)'] = 'controll/about/$1';
$route['mountain_destination/(:any)'] = 'controll/mountain_destination/$1';
Hope this helps.
This answer of mine might also help you;
Codeigniter Menu from Database
You can create a variable and pass it within constructor and simply use that whenever you need as
class Controll extends CI_Controller {
private $thing;
public function __construct() {
parent::__construct();
$this->thing = $this->uri->segment(3);
}
public function about() {
$data['p'] = $this->thing;
echo $this->thing;
}
public function mountain_destination($thing) {
$data['p'] = $this->thing;
echo $this->thing;
}
}
i have method "A_method" inside the controller. and inside A_method i would like to call another method in same controller "B_method".how can i call method "B_method" inside "A_method"
function A_mehtod()
{
$rsl = B_method(10);
echo $rsl;
}
function B_method($data)
{
retun ($data+1);
}
please give me a solution in Php MVC. because i'm working on opencart and i'm new to it
$rsl = $this->B_method($data);
That's all. Have a nice day!!
function A_mehtod() {
$rsl = $this->B_method(10);
echo $rsl;
}
I'm reading opencart php source code, and I can't figure this out.
Please take a look at function rewrite() at "$url = $rewrite->rewrite($url);"
<?php
class Url {
private $url;
private $rewrite = array();
public function link($route, $args = '', $connection = 'NONSSL') {
....
foreach ($this->rewrite as $rewrite) {
$url = $rewrite->rewrite($url);
}
return $url;
}
public function addRewrite($rewrite) {
$this->rewrite[] = $rewrite;
}
}
?>
Why above code doesn't generate error ?
The rewrite function is not defined in class Url, and class Url doesn't extend anybody ??
But then I track deeper, it seems that function rewrite is at seo_url class.
class ControllerCommonSeoUrl extends Controller {
// Add rewrite to url class
if ($this->config->get('config_seo_url')) {
$this->url->addRewrite($this);
}
...
public function rewrite($link) {
if ($this->config->get('config_seo_url')) {
$url_data = parse_url(str_replace('&', '&', $link));
....
Why ? I don't see any connection between 'Url' and this 'ControllerCommonSeoUrl' yet. Am I missing some concept here ? What I should do to understand these codes ? Need little guidance here.
foreach ($this->rewrite as $rewrite) {
Iterates over whatever values in:
private $rewrite = array();
And maybe that Url->rewrite array contains an instance of ControllerCommonSeoUrl, that would explain why $rewrite->rewrite() calls ControllerCommonSeoUrl->rewrite().
Also, you'd do yourself a favor by trying to learn to use a debugger :)
check if the controller is loading any model in the script if so , the model method can be simply accessed inside the script which might be the case with your script as $this->rewrite.
The Url class is a generic class that can have multiple URL rewrite method's called, making it possible for people to change the URL rewriting code. Triggering the SEO URL code to add it to the Url class is done in the index.php file by the following
// SEO URL's
$controller->addPreAction(new Action('common/seo_url'));
When that Action is executed, the ControllerCommonSeoUrl executed the index() method, and as with the code you provided, it checks if SEO URL's are active in the settings. If they are, then the current class is added to the array of rewrite's in the Url class. Then whenever someone calls $this->url->link() each of the rewrite classes have their rewrite() method called and the subsequent URL is passed back
I don't have alot of experience with OOP programming in PHP, and my search has given no result but solutions to direct methods. What I need is this:
// URL Decides which controller method to load
$page = $_GET['page'];
// I want to load the correct controller method here
$this->$page();
// A method
public function home(){}
// Another method
public function about(){}
// e.g. ?page=home would call the home() method
EDIT: I've tried several of the suggestions, but what I get is a memory overload error message. Here is my full code:
<?php
class Controller {
// Defines variables
public $load;
public $model;
public function __construct() {
// Instantiates necessary classes
$this->load = new Load();
$this->model = new Model();
if (isset($_GET['page'])) {
$page = $_GET['page'];
$fc = new FrontController; // This is what crashes apparently, tried with and without ();
}
}
}
If I understand your question correctly, you'd probably want something more like this:
class FrontController {
public function home(){ /* ... */ }
public function about(){ /* ... */ }
}
$page = $_GET['page'];
$fc = new FrontController;
if( method_exists( $fc, $page ) ) {
$fc->$page();
} else {
/* method doesn't exist, handle your error */
}
Is this what you're looking for? The page will look at the incoming $_GET['page'] variable, and check to see whether your FrontController class has a method named $_GET['page']. If so, it will be called; otherwise, you'll need to do something else about the error.
You can call dynamic properties and methods using something like this:
$this->{$page}();
Use a class.
Class URLMethods {
public function home(){ ... }
public function about(){ ... }
}
$requestedPage = $_GET['page'];
$foo = new URLMethods();
$foo->$requestedPage();
You can achieve this by using call_user_func. See also How do I dynamically invoke a class method in PHP?
I think you'd like also to append another string to the callable functions like this:
public function homeAction(){}
in order to prevent a hacker to call methods that you probably don't want to be.