As I know the Wordpress has is_home() function to determine home page.
In YII i use solution like this Yii check if homepage
In CI, templates actually, i faced many times with necessity of it. For example, adding some css classes in tag <body>.
All what i found http://ellislab.com/forums/viewthread/194637/#916899
Can anybody help me or write own solution?
Thank in advance
I just wanted to add my answer here as the other method doesn't work with my heavily modified version of CI.
This snippet is what I use to detect if we are on the homepage
if (!$this->uri->segment(1)) {
// We are on the homepage
}
You can use $this->router->fetch_class() to get the current controller and $this->router->fetch_method() to get the method too if needed.
So similar to the Yii example you linked to, you could do something like
$is_home = $this->router->fetch_class() === 'name_of_home_controller' ? true : false;
Or to match method too
$is_home = ($this->router->fetch_class() === 'name_of_home_controller' && $this->router->fetch_method() === 'name_of_home_method') ? true : false;
This way even if the page url is http://yoursite.com/ (assuming the home controller+method is the default), http://yoursite.com/home_controller/, http://yoursite.com/something/that/routes/to/home/controller/, etc, as long as it's calling that controller, it'll set $is_home to true.
Edit: Also you can use ($this->router->fetch_class() === $this->router->default_controller) if you don't want to explicitly state the home controller and it's set to the default controller.
Update for CI v3:
$this->router->fetch_class() and $this->router->fetch_method() were deprecated in CI v3. Use $this->router->class and $this->router->method instead.
if($this->uri->uri_string() == ''){
echo"You are on homepage";
}
If you don't have a custom helper create one; otherwise inside any of your custom helper file just paste any of the following code snippets and you should be able to use is_home() from any location in Codeigniter.
function is_home()
{
$CI =& get_instance();
return (!$CI->uri->segment(1))? TRUE: FALSE;
}
OR
function is_home()
{
$CI =& get_instance();
return (strtolower($CI->router->fetch_class()) === $CI->router->default_controller && $CI->router->fetch_method() === 'index') ? true : false;
}
For better answer you should cover 2 routes for home page:
I assumes there is default controller like this in routes.php:
$route['default_controller'] = 'home';
Your home page without default controller name(like:
yoursite.com)
Your home page with controller name(like:
yoursite.com/home)
if(!$this->uri->segment(1) || $this->uri->segment(1)=='home'){
// YOU ARE ON THE HOME
}
Why not just simply
public function name_of_home_method()
{
$data['is_home'] = true;
}
Related
I have language switcher on my website, it works fine. However, it redirects to base URL.
But when I write redirect($_SERVER["HTTP_REFERER"]); it doesn't redirect correctly. When I change the new language on the home page, I should stay at the same URL and just make the website change the language.
How do I solve this problem?
Here is my controller:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class LanguageSwitcher extends CI_Controller
{
public function __construct() {
parent::__construct();
$this->load->helper('url');
}
function switchLang($language = "") {
$language = ($language != "") ? $language : "azerbaijani";
$this->session->set_userdata('site_lang', $language);
redirect(base_url());
}
}
Also, I have tried this, it did not work for me:
function switchLang($language = "") {
if($this->uri->uri_string() == '') {
$language = ($language != "") ? $language : "azerbaijani";
$this->session->set_userdata('site_lang', $language);
redirect(base_url());
} else {
$language = ($language != "") ? $language : "azerbaijani";
$this->session->set_userdata('site_lang', $language);
redirect($_SERVER["HTTP_REFERER"]);
}
}
Try this
$url = $_SERVER['HTTP_REFERER'];
redirect($url);
You could do this with sessions, but I prefer this approach which makes use of an uri-query: What it does, is adding a ?my-current-url part to the link where you call the new language.
So, in my view, I've a link (button, etc.) which calls the language switcher, adding the current site url as uri-query like this:
<?php
// set pathname from where we came from
$pn=uri_string(); // the uri class is initialized automatically
?>
Azerbaijani
then in your function switchLang() you take care of the redirect:
function switchLang($language = "") {
// get pathname from where we came from
$pn= parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);
$language = ($language != "") ? $language : "azerbaijani";
$this->session->set_userdata('site_lang', $language);
// redirect to where we came from
redirect($pn, 'refresh');
}
Try using :
redirect($uri, 'refresh');
where $uri is the url of the home page that you want to translate
Hope this might help you
$this->load->library('user_agent');
if ($this->agent->is_referral())
{
echo $this->agent->referrer();
}
/*
|--------------------------------------------------------------------------
| Base Site URL
|--------------------------------------------------------------------------
|
| URL to your CodeIgniter root. Typically this will be your base URL,
| WITH a trailing slash:
|
| http://example.com/
|
| WARNING: You MUST set this value!
|
| If it is not set, then CodeIgniter will try guess the protocol and path
| your installation, but due to security concerns the hostname will be set
| to $_SERVER['SERVER_ADDR'] if available, or localhost otherwise.
| The auto-detection mechanism exists only for convenience during
| development and MUST NOT be used in production!
|
| If you need to allow multiple domains, remember that this file is still
| a PHP script and you can easily do that on your own.
|
*/
$config['base_url'] = 'your domain';
Try to change the base_url in your config.php inside application/config directory with your URL address complete.
What I do in all my projects (maybe not an easy solution for what you're asking for, but realy useful for this and other scenarios) is to use two helpers, I called them history() and back().
History saves current url in an array in session:
$history[] = current_url();
$ci->session->set_userdata('history', $history);
Back($num) receives a number and redirect to that position.
i.e: back(1) is equivalent to "send me to the last visited page".
$history = $this->session->userdata('history');
$cant = count($history);
$back = $cant - $num;
redirect($history[$back]);
Then in the __construct() of "CI_Controller" (or whatever class you extend your controllers) call history() once to log every method.
Also, you can add a third controller, I call it no_history().
no_history() deletes the last saved URL (I use it in methods that I don't want to save, for example, ajax requests). You can also check $this->input->is_ajax_request() but it's just an idea.
That's it, now you have a history of visited URLs.
You can change whatever you want, and then back(1).
Also useful for redirect your users to whatever they were doing before login.
Oh! Almost forgot: Remember to limit the size of the array and always delete the oldest url before adding new one. Between five and ten will be fine.
First load under constructor method like as:
function __construct()
{
parent::__construct();
$this->load->library('user_agent');
}
After inserting or updating data then it will work fine.
redirect($this->agent->referrer());
I have /signup/select-plan which lets the user select a plan, and /signup/tos which displays the terms of services. I want /signup/tos to be only accessible from /signup/select-plan. So if I try to go directly to /signup/tos without selecting a plan, I want it to not allow it. How do I go about this?
In the constructor, or the route (if you are not using contructors), you can check for the previous URL using the global helper url().
public function tos() {
if ( !request()->is('signup/tos') && url()->previous() != url('signup/select-plan') ) {
return redirect()->to('/'); //Send them somewhere else
}
}
In the controller of /signup/tos which returns the tos view just add the following code:
$referer = Request::referer();
// or
// $referer = Request::server('HTTP_REFERER');
if (strpos($referer,'signup/select-plan') !== false) {
//SHOW THE PAGE
}
else
{
dd("YOU ARE NOT ALLOWED")
}
What we are doing here is checking the HTTP referrer and allowing the page access only if user comes from select-plan
You are need of sessions in laravel. You can see the following docs to get more info: Laravel Sessions
First of all you need to configure till how much time you want to have the session variable so you can go to your directory config/sessions.php and you can edit the fields 'lifetime' => 120, also you can set expire_on_close by default it is being set to false.
Now you can have following routes:
Route::get('signup/select-plan', 'SignupController#selectPlan');
Route::post('signup/select-token', 'SignupController#selectToken');
Route::get('signup/tos', 'SignupController#tos');
Route::get('registered', 'SignupController#registered');
Now in your Signupcontroller you can have something like this:
public function selectPlan()
{
// return your views/form...
}
public function selectToken(Request $request)
{
$request->session()->put('select_plan_token', 'value');
return redirect('/signup/tos');
}
Now in signupController tos function you can always check the session value and manipulate the data accordingly
public function tos()
{
$value = $request->session()->get('select_plan_token');
// to your manipulation or show the view.
}
Now if the user is registered and you don't need the session value you can delete by following:
public function registered()
{
$request->session()->forget('select_plan_token');
// Return welcome screen or dashboard..
}
This method will delete the data from session. You can manipulate this. You won't be able to use in tos function as you are refreshing the page and you want data to persist. So its better to have it removed when the final step or the nextstep is carried out. Hope this helps.
Note: This is just the reference please go through the docs for more information and implement accordingly.
I would like to bypass core and plugin functions to customize them.
I didn't succeed to do it from template.
I try to add into my tpl_functions.php something like:
if (!function_exists('html_buildlist')) {
function html_buildlist($data,$class,$func,$lifunc='html_li_default',$forcewrapper=false){
// etc.
}
}
My first idea is to check if the page has been visited and then customize the indexmenu plugin.
For example, i make this function to check if a page has been visited:
function wt__pagevisited($id){
if ($id == null) {
global $INFO;
$id = $INFO['id'];
}
// get cookie session info
$crumbs = isset($_SESSION[DOKU_COOKIE]['bc']) ? $_SESSION[DOKU_COOKIE]['bc'] : array();
// check ID into breadcrumb
if( array_key_exists($id,$crumbs) ) {
return true;
}
return false;
}
Any help will be appreciated.
Thank you in advance.
Jean-baptiste
What you're asking has nothing to do with DokuWiki. You want to replace PHP functions. That's not possible without the help of certain PHP extensions. See Is it possible to replace a function in php (such as mail) and make it do something else? for more info.
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);
}
}
}
}