It's possible this question exists elsewhere, and if so, I apologize. After searching for an hour without success, I can't help but think I'm on the wrong track.
Essentially what I am looking for is a method to enforce a description or title in a page's URL. I am using CodeIgniter, so it is pretty simple to make a pretty URL go where ever I wish.
I could have:
http://mysite.com/controller/function/what-ever-i-want/can-go-here
and it will always go to:
http://mysite.com/controller/function/
with the variable values what-ever-i-want and can-go-here
What I would like is for the URL to be automatically rewritten to include the title if only the controller/function is given.
So, if someone went to:
http://mysite.com/controller/function/
it should automatically rewrite the url as
http://mysite.com/controller/function/a-more-descriptive-title/
A great example of the functionality that I am talking about is the SO URL. if you go to https://stackoverflow.com/questions/789439 it will automatically rewrite it to https://stackoverflow.com/questions/789439/how-can-i-parse-descriptive-text-to-a-datetime-object
I suspect that mod_rewrite is involved, but I would like to come up with the solution that works most gracefully with CodeIgniter.
I am very new to the pretty-url scene and desperately call upon the advice of someone with more experience. Thanks in advance for any help given!
I used Fiddler2 to see how Stackoverflow does this.
Part of the respnse from http://stackoverflow.com/questions/12205510/
HTTP/1.1 301 Moved Permanently
Location: /questions/12205510/how-can-i-enforce-a-descriptive-url-with-codeigniter
Vary: *
Content-Length: 0
So basically when we go to controller/function/ we need to redirect user to controller/function/my-awesome-title. I've written simple controller that does just that:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Controller extends CI_Controller
{
protected $_remap_names = array();
function __construct()
{
parent::__construct();
$this->_remap_names['func'] = "My Awesome Title";
}
function _remap($method, $arguments)
{
if(
isset($this->_remap_names[$method])
&& sizeof($arguments) == 0
&& method_exists($this, $method)
)
{
$this->load->helper("url");
$title = str_replace(" ", "-", $this->_remap_names[$method]);
$title = strtolower($title);
$url = strtolower(__CLASS__)."/$method/$title";
$url = site_url($url);
// if you dont want to have index.php in url
$url = preg_replace("/index\.php\//", "", $url);
header("HTTP/1.1 301 Moved Permanently");
header("Location: $url");
header("Vary: *");
}
else
{
call_user_func_array(array($this,$method), $arguments);
}
}
function func()
{
echo "<h1>";
echo $this->_remap_names[__FUNCTION__];
echo "</h1>";
}
};
Docs for CodeIgniters _remap function can be found here in Remapping Function Calls section.
I don't use CodeIgniter, but you should be able to place code in a controller's __construct, or in some kind of pre-action event if CI has those.
You just look up the appropriate URL for the entity being viewed and do a 301 redirect if necessary.
Related
I am trying to send a url from view page to controller but it does not seem to work the way i am thinking.
View Page
Product
User
I want to get "tbl_product"
Controller admin
<?php
class Admin extends CI_Controller {
public function test() {
echo $this->uri->segment(4);
}
}
?>
but if the segment(4) is changed to segment(3), it shows up with displaying "product" in the screen
your controller function should have arguments for your url segments
for example:
public function test($product = 'product', $tbl = 'tbl_product') {
echo $tbl // contains the string tbl_product
}
Since you said your routes look like this:
$route['default_controller'] = "admin";
$route['404_override'] = ''
and your URL is like this:
<?= base_url() ?>admin/test/product/tbl_product
Then if your base_url() is localhost/my_app, your URL will be read as this:
http://localhost/my_app/admin/test/product/tbl_product
http://localhost/my_app/CONTROLLER/METHOD/PARAMETER/PARAMETER
So in your controller, you can do this:
class Admin extends CI_Controller {
public function test($product = NULL, $tbl_product = NULL) {
echo $product;
echo $tbl_product;
}
}
It's strange to use codeigniter for this purpose, because codeigniter uses as default the url format bellow.
"[base_url]/[controller]/[method]"
I think it will be better and more easy to just pass the values you want as get parameters and make some httaccess rules to make your url more readable for the user and robots. That said you can do that:
Product
<?php
class Admin extends CI_Controller {
public function test() {
echo $this->input->get('product');
//should output 'tbl_product'
}
}
?>
If you prefer to use uri instead u should route your uri's so it will be like.
In your routes file you probably I'll need something like this.
$route['product/(:any)'] = "Admin/test";
This way you will probably access the uri segments correctly.
Thank you so much for going through.
$this->uri->segment(4); // is now working :S
its not working properly after all I made changes to routes.php and came back to default again. I seriously have no idea what the reason behind not displaying the result before.
If I ignore the 302, I see that redirect() stops output, but header() doesn't. redirect() uses header() to set the 302 response. Different behaviour, same function. What gives?
Some context: I'm building a site with CodeIgniter, and I'm playing with how the site should deal with guests and members.
Extending the CI Core:
class MY_Controller extends CI_Controller {
if (! $authenticated) redirect('/login');
}
Now a controller:
class Members_only extends MY_Controller {
function index()
{
// Display members only content
}
}
Then I thought, what if Alice (an unauthenticated visitor) ignores the 302 response? Can she see the rest of the content after the redirect? So I tested it, and now I'm totally confused. There's two functions that are available to me to send a 302 redirect.
header('Location: http://mywebsite.com/login', TRUE, 302);
And from CI's URL helper:
redirect('/login');
Here is what it looks like from the inside:
function redirect($uri = '', $method = 'location', $http_response_code = 302)
{
if ( ! preg_match('#^https?://#i', $uri))
{
$uri = site_url($uri);
}
switch($method)
{
case 'refresh' : header("Refresh:0;url=".$uri);
break;
default : header("Location: ".$uri, TRUE, $http_response_code);
break;
}
exit;
}
site_url() is returning "http://mywebsite.com/login".
Can someone point out what I'm missing here?
Do you see the exit in the CI redirect function? So whenever you use it, it will cause your application to stop processing whatever code you have left. This is the "different" behavior your are experiencing.
http://php.net/manual/en/function.exit.php
I'm using the template library for CodeIgniter, http://williamsconcepts.com/ci/codeigniter/libraries/template/reference.html, and now I want to implement custom error pages too. I found one method involving a MY_Router extending the default router: http://maestric.com/doc/php/codeigniter_404 but that only treats 404 errors. I want all errors to show a simple user-friendly page, including database errors etc, and I want it to go through a controller, partly so I can use the template library, and partly so I can also implement an email function to send myself information about the error that occurred.
Someone asked about extending the functionality of the above MY_Router method for other errors, like error_db, but got no answer from the author, so I'm turning here to see if anyone knows how to do this, along the lines of the above method or any other simple way of achieving it. Please note that I'm a newbie, so do not assume too much about my knowledge of basic CodeIgniter functionality :-)
I've created an extension for the Exceptions class.
In this extension I've replaced the $this->Exceptions->show_error(); method, witch is used by the show_error() function of CI.
when I call show_error('User is not logged in', 401); this custom method is looking for an error_$status_code file first. In the case of the example above, it will look for an error_401.php file.
When this file does not exists, it wil just load the error_general.php file, like the default $this->Exceptions->show_error(); does.
In your case, you can use the following code to use in your library, controller or whatever should throw an error.
<?php
if(!(isset($UserIsLoggedin))){
$this->load->view('template/header');
show_error('User is not logged in', 401);
$this->load->view('template/footer');
}
?>
Your error_401.php file should than look like this:
<div id="container">
<h1><?php echo 'This is an 401 error'; ?></h1>
<?php echo $message; ?>
</div>
/application/core/MY_Exceptions.php:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Exceptions extends CI_Exceptions
{
function show_error($heading, $message, $template = 'error_general', $status_code = 500)
{
if((!isset($template)) || ($template == 'error_general')){
if(file_exists(APPPATH.'errors/error_'.$status_code.'.php')) {
$template = 'error_'.$status_code;
}
}
if (!isset($status_code)) $status_code = 500;
set_status_header($status_code);
$message = '<p>'.implode('</p><p>', ( ! is_array($message)) ? array($message) : $message).'</p>';
if (ob_get_level() > $this->ob_level + 1)
{
ob_end_flush();
}
ob_start();
include(APPPATH.'errors/'.$template.'.php');
$buffer = ob_get_contents();
ob_end_clean();
return $buffer;
}
}
?>
I do it like this:
I create my own error page, and whenever I should throw a 404 error, I actually load my 404 page.
So say my default controller is site.php, my site.php looks like this:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Site extends CI_Controller {
public function index()
{
$this->load->view('welcome_message');
}
public function view($page = "home" , $function = "index")
{
do_something();
if($status == "404")
{
$function = "404";
}
$this->load->view('templates/header', $data);
$this->load->view($page.'/'.$function, $data);
$this->load->view('templates/footer', $data);
}
}
/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */
So I serve the home/404.php whenever an error occurs. i.e., I don't allow CodeIgniter to call show_404(); therefore the 404 page looks like any other page.
p.s. I assume that you followed the nice tutorial in CodeIgniter's website.
The simplest way to create custom error pages is to edit the files at /application/views/errors/html/error_*.php such as error_404.php (for 404s), error_db.php (for database errors) and error_general.php (for most other errors).
As these pages are within your application directory, you are free to customise them to your needs.
If your normal view template looks something like this:
<?php $this->load->view('includes/header'); ?>
...
...
<?php $this->load->view('includes/footer'); ?>
You can adapt this in your /application/views/errors/html/error_*.php files like so:
<?php
$page_title = $heading;
include VIEWPATH.'includes'.DIRECTORY_SEPARATOR.'header.php';
?>
<div class="well">
<h1><?php echo $heading; ?></h1>
<?php echo $message; ?>
</div>
<?php include VIEWPATH.'includes'.DIRECTORY_SEPARATOR.'footer.php'; ?>
Notice that we're no longer using views, but instead including the view files for the header & footer.
Another thing to note:
In the header view, I'm passing a $data object which includes $data['page_title']. As the error pages don't use views, you have to add any variables that you'd normally pass into the view, hence the presence of $page_title.
config/routes.php
edit
$route['404_override'] = '';
type here your controller for example Error
create a function index and load your view
I am pretty new to codeigniter. I do know php.
How can I accomplish to load the right view?
My url: /blog/this-is-my-title
I’ve told the controller something like
if end($this->uri->segment_array()) does exist in DB then load this data into some view.
I am getting an 404-error everytime I access /blog/whatever
What am i seeing wrong?
unless you're using routing, the url /blog/this-is-my-title will always 404 because CI is looking for a method called this-is-my-title, which of course doesn't exist.
A quick fix is to put your post display code in to another function and edit the URLs to access posts from say: /blog/view/the-post-title
A route like:
$route['blog/(:any)'] = "blog/view/$1";
may also achieve what you want, if you want the URI to stay as just `/blog/this-is-my-title'
The may be more possibilities:
The most common - mod_rewrite is not active
.htaccess is not configured correctly (if u didn't edited it try /blog/index.php/whatever)
The controller does not exist or is placed in the wrong folder
Suggestion: if you only need to change data use another view in the same controller
if (something)
{
$this->load->view('whatever');
}
else
{
$this->load->view('somethingelse');
}
If none of those works post a sample of code and configuration of .htaccess and I'll take a look.
The best way to solve this problem is to remap the controller. That way, you can still use the same controller to do other things too.
No routing required!
enter code here
<?php
class Blog extends Controller {
function __construct()
{
parent::__construct();
}
public function _remap($method, $params = array())
{
if (method_exists($this, $method))
{
$this->$method();
}
else
{
$this->show_post();
}
}
function index()
{
// show blog front page
echo 'blog';
}
function edit()
{
// edit blog entry
}
function category()
{
// list entries for this category
}
function show_post()
{
$url_title = $this->uri->segment(2);
// get the post by the url_title
if(NO RESULTS)
{
show_404();
}
else
{
// show post
}
}
}
?>
I need to put https on some of the URL but not on all the URL. I am using zend URl view helper for all the links. I have a *.example.com SSL certificate for whole site. Now I open site with https://www.example.co, then all the link on home page or other pages contains https in URL. How can I make some specific request on the https url and other page should be opened normal.
I also need to pt some redirection so that if somebody open the specific pages in normal URL then they redirected on https url. I think the .htaccess redirection will work for that.
Any help ????
Thanks in advance!!!
the URL ViewHelper only assembles paths, absolute from the hostname. so you need to explicitly prefix your https links
<? $url = $view->url(array('some' => 'params') /*, $route, $reset*/) ?>
my explicit https link
you should maybe create a an own small viewhelper which does that work for your and also checks if HTTP_HOST is set etc, maybe also take it from the config instead from $_SERVER.
$view->httpsUrl(array('some' => 'params')/, $route, $reset/);
to be secure that defined reqeust must be https can easily be done by adding a front controller plugin or even an abstract controller-class you base all your otehr controller on.
a plugin could look like this
My_Controller_Plugin_HttpBlacklist extends Zend_Controller_Plugin_Abstract
{
public function preDispatch(Zend_Controller_Request_Abstract $request)
{
// when /foo/bar/baz is requested
if (($request->getModuleName() == 'foo' &&
$request->getControllerName() == 'bar' &&
$request->getControllerName() == 'baz')
/* || (conditions for more requests)*/) {
//very basic confifiotn to see if https is enabled, should be done better...
if (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != 'on') {
// should be done with Zend_Http_Reponse instead
header('Location: https://'. $_SERVER['HTTP_HOST] . $_SERVER['REQUEST_URI']);
exit;
}
}
}
}
then simply plug it in
$frontController->registerPlugin(new My_Controller_Plugin_HttpBlacklist);
I rather used a simple method and that does not required any change in urls generation/route. I wrote following lines in routeStartup function of a plugin and haven't made any change in URLs route.
public function routeStartup(Zend_Controller_Request_Abstract $request)
{
$controller=$this->_controller = $this->_front->getRequest()->getControllerName();
$action=$this->_controller = $this->_front->getRequest()->getActionName();
if($_SERVER['SERVER_PORT']!=443)
{
//controller and actions array to check ssl links
$actionArr=array('index'=>array('registration'),'account'=>array('editacc','edit'),'dealer'=>array('*'));
if(array_key_exists($controller,$actionArr)!==false)
{
if(in_array($action,$actionArr[$controller]) || $actionArr[$controller][0]=='*')
{
$redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
$redirector->gotoUrl(SITE_LIVE_URL_SSL.$controller."/".$action);
}
}
}
else
{
//controller and action array that should not be on ssl.
$notAactionArr=array('usersearch'=>array('mainserarch'),'account'=>array('index'),'onlineusers'=>array('*'));
if(array_key_exists($controller,$notAactionArr)!==false)
{
if(in_array($action,$notAactionArr[$controller]) || $notAactionArr[$controller][0]=='*')
{
$redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
$redirector->gotoUrl(SITE_LIVE_URL.$controller."/".$action);
}
}
}
}