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();
}
}
Related
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')
There is no problem when I enter the first parameter but when I enter the second parameter I get the error I mentioned below
.htaccess
RewriteEngine on
RewriteCond $1 !^(index\\.php|resources|robots\\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]
I enter this url: www.domain.com/first-parameter/second-parameter
Returned Error:
A PHP Error was encountered
Severity: Error
Message: Call to undefined function base_url()
Filename: _inc/_head.php
Line Number: 4
Backtrace:
routes.php
/*Ayarlar*/
$route['default_controller'] = 'Home';
$route['404_override'] = '';
/*Ayarlar*/
$route['(:any)'] = 'Home/index/$1';
$route['translate_uri_dashes'] = true;
I enter this url: www.domain.com/first-parameter/second-parameter
Example Local Url: http://localhost/sicacik-yemek-tarifleri-mobile/bilgi/assadad/asasad
controllers/Home.php
class Home extends public_Controller {
public function __construct()
{
parent::__construct();
}
public function index($s1='')
{
if(!empty($s1)){
if (!empty($data['anakategori'])) {
$this->load->view('example',$data);
} elseif (!empty($data['altkategori'])) {
$this->load->view('example',$data);
}elseif(!empty($data['tarif'])){
$this->load->view('example',$data);
} elseif(!empty($kacKalori)){
$this->load->view('example',$data);
}else{
show_404();
}
}else{
$this->load->view('Home',$data);
}
}
}
Don't post images instead of code. Code is used to be copied finding solution in more convinient/easier way.
First this (Important in RED on user guide):
The reserved routes must come before any wildcard or regular expression routes.
so your $route['translate_uri_dashes'] = true; has to be in different place.
Check default file to determine where to put it.
Also,
Routes will run in the order they are defined. Higher routes will always take precedence over lower ones.
so you have to reorder last two
$route['soru-cevap/(:any)/(:any)'] = 'soru_cevap/index/$1/$2'; //this one is more specific one
$route['soru-cevap/(:any)'] = 'soru_cevap/index/$1';
//Take a look of controller and method names.
//Ones with dashes probably won't work.
You need to include $route['(:any)/(:any)'] = 'Home/index/$1/$2'; line in route.php
For www.domain.com/first-parameter/second-parameter url.
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//}
I'm using Codeigniter 2.1.3 with Friendly URL (.htaccess).
In Controller:
public function confirm($key) {
var_dump($this->input->get());
}
But link _http://site.com/confirm/12345 returns "boolean false".
How to enable Query strings in URL, or how to filtering $key ?
My .htaccess:
RewriteEngine on
RewriteCond $1 !^(index\.php|robots\.txt|files|templates)
RewriteRule ^(.*)$ /index.php?/$1 [L]
You receive key as the function argument, so you can do this:
public function confirm($key) {
echo $key;
}
http://site.com/confirm/12345 will echo 12345.
Filtering of characters in this can be done via $config['permitted_uri_chars'] in config.php.
If you want to receive it as a GET parameter and want to perform XSS filtering on it, the URL needs to be
http://site.com/confirm?key=12345 and in your controller
public function confirm() {
echo $this->input->get('key', TRUE); // true implies XSS filtering
}
The second method requires $config['enable_query_strings'] to be set to TRUE.
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