How do I send data into a Code Igniter Controller index method? - codeigniter

I tried to encode the ID of a journal in the URL of my Code Igniter application and the retrieve it in my controller. My end goal is to access the page http://mysite.com/journal/3 and get to access a page containing details about the journal with ID 3.
In my journal.php controller file, I have
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Journal extends Controller {
public function index($journalId) {
$data['journalId'] = $journalId;
$this->view->load('journalPage', $data);
}
}
?>
In my journalPage.php view file, I have
This event has ID <?= $journalId ?>.
I wrote this rule in my routes.php file.
$route['journal/(:num)'] = 'journal/$1';
Here is the .htaccess file in my html public folder.
<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?$1 [QSA,L]
</IfModule>
However, when I go to mysite.com/journal/3, I get a 404 error. Why?

$route['journal/(:num)'] = 'journal/index/$1';
(:num) will become invalid if you encode
Edit:
If you use CI's encryption class to encode your ID(pointless)
you will need to modify it to make sure the string is uri safe.

Based on what I see above this is just begginers mistake on CI routing.
You .htaccess is ok (you are just removing index.php from url).
On other 2 steps (you have problem in your controller and in your routes config).
First in controller, when creating new controller you should extend CI_Controller
To make story short, this is how your journal.php file should like like:
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Journal extends CI_Controller {
public function __construct() {
parent::__construct(); // This is MUST!
}
public function index($journalId) {
$data['journalId'] = $journalId;
$this->view->load('journalPage', $data);
}
}
Now when you have updated this, we come to routes config.
Config line you wrote only can confuse CI, nothing more, nothing less.
Structure of CI route shoud be like this:
$route['journal/(:any)'] = 'journal/index/$1';
This would redirect all traffic from journal/[ID] to controller named journal, to method named index with param [ID].
You must define index part in routing.
Try this, and everything should be working fine.
Cheers.

First of all: You don't need to create a empty constructor (This is must [nothing!]).
If you want to load some libraries, helpers or models at the beginning of all functions for that controller, so it is needed, otherwise it don't.
Other tip: Try to do not pass parameters on a controller function. You can catch and manipulate uri values with CodeIgniter's URI Class.
Just do this:
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Journal extends CI_Controller
{
public function index()
{
$data['journalId'] = $this->uri->segment(2);
$this->view->load('journalPage', $data);
}
}
You better take a look on the URI Class. It is quite simple a handy!
http://codeigniter.com/user_guide/libraries/uri.html
PS: Don't need to fix anything on routes too.
Hug

Related

How to restrict controller page from direct access from url in Codeigniter?

I have used several codes for restricting direct access of controller page from url, but its not happening.
The below code in controller page is not preventing from direct url access. Is there any proper way to prevent from direct access from url?
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Cont extends CI_Controller
{
public function __construct()
{
parent ::__construct();
$this->load->model('test');
}
public function handle($function){
if($function=='abcd'){
$this->load->view('testpage');
}
}
}
You can use HTTP_REFERER which holds the information(address) about the page that referred you to the current page, if it's empty you can redirect it to your 404 page. Also, you should always check for $_SESSION and redirect if not set.
if( !isset($_SERVER['HTTP_REFERER'])) {
$this->load->helper('url');
redirect('/page404');
}
Alternatively, you can also use HTTP_X_FORWARDED_FOR, but it won't help you in AJAX request. Read more about it here and here.
You can use _remap() function inside your Controller, where we can define where to route the method.
The following code blocks all method call to that controller.
function _remap($method)
{
return false;
}
See the DOC here
From documentation
For the best security, both the system and any application folders should be placed above web root so that they are not directly accessible via a browser. By default, .htaccess files are included in each folder to help prevent direct access, but it is best to remove them from public access entirely in case the web server configuration changes or doesn’t abide by the .htaccess.
If you want to prevent direct access to specific methods then you can try
public function _handle(){ //adding _ before the method name
}
Or
private function handle(){ //private functions cannot access by url
}

Why can't I proceed to login page?

This is the only thing that i can see on my computer at the address http://localhost/onlineExam/login/validate_credentials
Object not found!
The requested URL was not found on this server. The link on the referring page seems to be wrong or outdated. Please inform the author of that page about the error.
If you think this is a server error, please contact the webmaster.
Error 404
localhost
Apache/2.4.39 (Win64) OpenSSL/1.1.1c PHP/7.3.7
class Login extends CI_Controller
{
function index()
{
$data['main_content'] = 'login_form';
$this->load->view('includes/templates', $data);
}
function validate_credentials(){
$this->load->model('user_model');
$query = $this->user_model->validate();
if($query)// if the user's credentials validated...
{
$data = array(
'username' => $this->input->post('username'), 'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('site/users_area');
}
else{
$this->index();
$data['error'] = 'Invalid Username or Password';
$data['main_content'] = 'login_form';
$this->load->view('includes/templates', $data);
}
}
}
Please check .htaccess file is present in the root folder, that is 'onlineExam' as per your URL.
If not present, create/update with this lines:
RewriteEngine On
RewriteBase /onlineExam/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
After that, also check base_url at onlineExam/application/config/config.php
$config['base_url'] = 'http://localhost/onlineExam';
This could be a number of things
1) As Stated above you need to make sure a htaccess file is present in the root of your project folder
2) If your htaccess file isn't removing the index.php part of your URL then your link would not be
http://localhost/onlineExam/login/validate_credentials
but rather
http://localhost/onlineExam/index.php/login/validate_credentials
3) Make sure your filename is the same as your class name. At times too case sensitive operating system may affect your files. Login.php != login.php (This is a rare case and happened to older version of some OS')

Codeigntier: redirect within config/routes.php file?

I'm updating a website and have a bunch of old URLs that need to be rerouted to their new equivalents. I want to do this server-side (rather than with .htaccess)
It would be neat if in my config/routes.php I could just declare something like this:
$route['old_url_1'] = redirect('/new/url/1', 'location', 301);
$route['old_url_2'] = redirect('/new/url/2', 'location', 301);
$route['old_url_3'] = redirect('/new/url/3', 'location', 301);
Obviously it doesn't work, but is anything like this possible, ie. keep this code in my routes file (more logical) or do I need to go and set up functions in some controller?
Thanks.
Yes, You need to create something(method at controller), that will redirect browser with 301-code. Something like this:
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Redirectme extends MY_Controller {
public function index($url=false) {
if($url===false)
redirect('/');
redirect('/new/url/'.$url,'location',301);
}
}
?>
and add to route.php
$route['old_url_(:any)'] = "redirectme/index/$1";
Anyway, best practice to redirect via .htaccess (because it will not call even php-module from webserver).

how to forced https instead of http after user login in zend framework2

I want user redirect to https insetad of http just after login in my new website made in zend framework2. please help.
I there any method available in zend freamework2 to get current used protocol(http or https).
You can redirect the user to the https version of a page inside the application. Above solution simply redirects all requests to it's http variant, and only for Apache. I would rather do it inside the application (then you're more in control) and make it server agnostic (what happens when you switch to nginx?)
An example is based on an answer I gave earlier here: ZF2 and force HTTPS for specific routes
The solution: create a controller plugin which you can call every time you need it.
Specify the pages you need to force a redirect (i.e. the page you show the login form):
use Zend\Http\Response;
public function loginAction()
{
// If return value is response, this means the user will be redirected
$result = $this->forceHttps();
if ($result instanceof Response) {
return $result;
}
// code here
}
And then you could create a controller plugin (call it ForceHttps) to return a response when the user should be redirected:
use Zend\Uri\Http as HttpUri;
class ForceHttps extends AbstractPlugin
{
public function __invoke()
{
$request = $this->getController()->getRequest();
if ('https' === $request->getUri()->getScheme()) {
return;
}
// Not secure, create full url
$plugin = $this->getController()->url();
$string = $plugin->fromRoute(null, array(), array(
'force_canonical' => true,
), true);
$url = new HttpUri($string);
$url->setScheme('https');
return $this->getController()->redirect()->toUrl($url);
}
}
What happens is
Check if the current scheme is https. If not, continue
Grab the current used url from the url() plugin, use the current route name (hence the first parameter is null), force the canonical version (i.e. with a full scheme and domain name) and reuse the current route match parameters (the true as last parameter).
Import the url (as a string) in the Zend\Url\Http object
Reset the scheme to the https version
Pass the url to the redirect plugin to grab a response which will perform the redirect
on your .htaccess write these rules
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.yoursite.com/$1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ public/index.php [NC,L]
note that public/index.php is the root so you have to modify it and www.yoursite.com too
for logged-in user you have to do with php
$auth = Zend_Auth::getInstance();
if($auth->hasIdentity()) {//redirection should be here//}

Dynamic CMS pages and static pages CodeIgniter

I'm using Codeigniter 2, and i have some dynamic pages (CMS) which are created from the back office and have the page name as ID . And some pages are static , there is a example :
Dynamic pages :
www.domain.com/privacy
www.domain.com/about
and static page :
www.domain.com/invitation
So the question is how can route this pages : i tried to use :
$route['([a-z0-9\-]+)'] = 'home/cms/$1';
But it gives me 404 for static pages ( www.domain.com/invitation )
Any help and thank you in advance
You can either explicitly remove the static files from the redirection in your .htaccess file:
RewriteEngine on
RewriteCond $1 !^(invitation\.php|index\.php|images|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]
or, you can use the _remap function. Inside the _remap function, you would check for existence of a physical file for your "method" - if there, load it - if not, route to the controller method:
public function _remap($method, $params = array())
{
$filepath = BASEPATH.$method.".php";
if (file_exists($filepath))
{
include($filepath);
return;
}
else if (method_exists($this, $method))
{
return call_user_func_array(array($this, $method), $params);
}
else
{
show_404();
}
}

Resources