In most web applications we need global var base_url. In cakephp to get base_url currently i put the following code on beforeRender method in app_controller.php
function beforeRender(){
$this->set('base_url', 'http://'.$_SERVER['SERVER_NAME'].Router::url('/'));
}
Is there any alternative? Means is there any global variable available to get the base url rather than this?
Yes, there is. In your view, you may access:
<?php echo $this->webroot; ?>
Also, your host information is stored in the $_SERVER['HTTP_HOST'] variable in case you want that.
In your controller, if you want full URLs, use this:
Router::url('/', true);
Use anyone option below
<?php echo $this->Html->url('/');?>
<?php Router::url('/', true); ?>
<?php echo $this->base;?>
<?php echo $this->webroot; ?>
Define constant in Config/core.php as define("BASE_URL", "www.yoursite.com/"); and use BASE_URL anywhere in your project
and create a common helper with following functions
<?php
class CommonHelper extends AppHelper {
function get_url($url){
return BASE_URL.$url;
}
function get_src($url){
echo BASE_URL.$url;
}
}
?>
and use anywhere in project
$this->redirect($this->Common->get_url("login");
login
Don't forgot to include Common helper in controller
I recommend method 2 and 5 because they give complete url.
You may use
<?php echo Router::fullbaseUrl();?>
as well.
Refer http://book.cakephp.org/2.0/en/core-libraries/global-constants-and-functions.html for more details.
Use Router::url('/', true) anywhere in your app.
Specifically in the View, you can use $this->Html->url('/', true) (or any other Helper in fact, the Helper::url method is inherited by all Helpers), which is just a wrapper for the above Router method.
In either case, the second true parameter causes it to return the full URL.
You can use
Router::fullBaseUrl()
If you have for example example.com/test and you want to ignore /test, you can use 'full' => false.
Also if you want to force ssl you can add '_ssl' => true.
i.e.
Router::fullBaseUrl(null, [ '_ssl' => true, 'full' => false]
Make sure you pass null as the first parameter as this is the base url in case you want to pass it.
note:
you need to import Router so you can use above function:
use Cake\Routing\Router
For most purposes I'd suggest using the CakePHP HtmlHelper to generate URLs, that way you won't need to worry about the base URL. The most user friendly way of getting the base URL in your view, however, would be <?php echo $html->webroot; ?>.
You can use FULL_BASE_URL constant.
Related
I am trying to get the base URL for the project in Yii 2 but it doesn't seem to work. According to this page you used to be able to do:
Yii::app()->getBaseUrl(true);
In Yii 1, but it seems that that method in Yii 2 no longer accepts a parameter?
I've tried doing it without true, such as:
Yii::$app->getBaseUrl();
But it just returns empty.
How can you do this in Yii 2?
To get base URL of application you should use yii\helpers\Url::base() method:
use yii\helpers\Url;
Url::base(); // /myapp
Url::base(true); // http(s)://example.com/myapp - depending on current schema
Url::base('https'); // https://example.com/myapp
Url::base('http'); // http://example.com/myapp
Url::base(''); // //example.com/myapp
Url::home() should NOT be used in this case. Application::$homeUrl uses base URL by default, but it could be easily changed (for example to https://example.com/myapp/home) so you should not rely on assumption that it will always return base URL. If there is a special Url::base() method to get base URL, then use it.
My guess is that you need to look at aliases.
Using aliases would be like:
Yii::getAlias('#web');
You can also always rely on one of these two:
Yii::$app->homeUrl;
Url::base();
To get base URL Yii2 using:
Url::home(true)
Use it like this:
Yii::$app->getUrlManager()->getBaseUrl()
More information on base, canonical, home URLs:
http://www.yiiframework.com/doc-2.0/yii-helpers-url.html
Try this:
$baseUrl = Yii::$app->urlManager->createAbsoluteUrl(['/']);
may be you are looking for this
Yii::$app->homeUrl
you can also use this
Url::base().
or this
Url::home();
I searched for a solution how we can do like in codeigniter, routing like
e.g.
base_url()
base_url('profile')
base_url('view/12')
Only way we can do that in Yii2
<?=Url::toRoute('/profile') ?>
You can reach your base URL by this:
Yii::$app->request->baseUrl
In yii 1 this code return the hostname
Yii::app()->getBaseUrl(true);
In yii2 the following
Yii::$app->getBaseUrl();
not exists as method of Yii::$app and it triggers an error with message
Calling unknown method: yii\web\Application::getBaseUrl()
You could use Request class that encapsulates the $_SERVER
Yii::$app->request->hostInfo
Try below code. It should work. It will return base URL name
use yii\helpers\Url;
Url::home('http') // http://HostName/
OR
Url::home('https') // https://HostName/
I'm repeatedly having to include one variable when I display my views:
$this->load->view('login', array('logged_in' => $this->auth->is_logged_in()));
$this->load->view('somepage', array('logged_in' => $this->auth->is_logged_in()));
$this->load->view('anotherpage', array('logged_in' => $this->auth->is_logged_in()));
How can I include this one variable across all of my view outputs? Is there a simpler method than extending the templating class?
One simpler way would be to make the array into a variable, so you dont have to type it out all the time, e.g.
$params = array('logged_in' => $this->auth->is_logged_in());
$this->load->view('login', $params);
$this->load->view('somepage', $params);
$this->load->view('anotherpage', $params);
An alternative would be to create a Helper that returns whether a user is logged in. Helpers are globally available in your controllers and views. See http://codeigniter.com/user_guide/general/helpers.html and also
CodeIgniter: Create new helper?
how about using sessions?
$this->session->userdata($var);
or cookies
$this->input->cookie($var, TRUE);
thanks.
Great solution, Gordon! But, depending on the case, it's also possible to use the Most Simple Template Library.
Regards!
You can also access the class directly from within your view:
<?php if( $this->auth->is_logged_in() ): ?>
Hello!
<?php endif; ?>
It's not the greatest solution but I find it works well with user conditionals.
I've integrated GeoIP into my CakePHP. Now I have to call it from my view-file. I made in my controller such function:
function getCountry($ip)
{
$this->GeoIP->countryName($ip);
}
GeoIP is a included component.
When I wrote in my view globally something like this:
$this->GeoIP->countryName('8.8.8.8') it works well, but, as I remember, this is wrong for MCV architecture. So the right way is to call requestAction for my controller.
Here I have 2 problems: I have to do this in php function which is located in view-file:
// MyView.php:
<?php
function Foo()
{
$this->GeoIP->countryName(...);
}
?>
First mistake is that $this isn't available inside the function, the second one is how to call getCountry from my component and pass need ip address into $ip?
I've tried:
echo $this->requestAction('Monitoring/getCountry/8.8.8.8');
Monitoring is a controller name.
But this returns nothing without any errors. What's the right way and how to call this in function?
Something like this:
Layout -> View/Layouts/default.ctp (works on any other view/element or block)
<h1>My Website</h1>
<?php echo $this->element('GeoIP') ?>
Element -> View/Elements/GeoIP.ctp (use an element so you can cache it and don't request the controller every time)
<?php
$country = $this->requestAction(array('controller' => 'Monitoring', 'action' => 'ipToCountry'));
echo "You're from {$country}?";
?>
Controller -> Controller/MonitoringController.php
public function ipToCountry() {
// Only accessible via requestAction()
if (empty($this->request->params['requested']))
throw new ForbiddenException();
return $this->GeoIP->countryName('8.8.8.8');
}
One of the basic principles in MVC is that you must not use logic in your view files (except some conditions). In your controller you must set the value in the view and use it there.
I you absolutely need to call your method after all the logic in the controller, you can use the beforeRender() method in your controller and it will be called right before rendering. You can set your value from there.
I don't see why you'd like to call a controller function in the view, unless you have business logic in there. That should be moved in the controller.
Hope I helped!
Is there any way to set variables for the partial in the controller level?
Because everytime I need variables inside a partial I always have to pass them:
<?php
echo $this->partial('travels/_steps.phtml',
array('searchHotel' => $this->searchHotel,
'actionName' => $this->actionName))
?>
I would really just like actionName to be available on all partials - for instance.
You could extend the Zend_View_Helper_Partial class to a class that keeps that variable in scope. You would need to override the cloneView() function:
public function cloneView()
{
$view = parent::cloneView();
$view->actionName = $this->view->actionName
return $view;
}
You could use $this->render() instead. With it, you wouldn't need to pass the view variables every time.
Hope that helps,
You could also just sent the current view as a parameter to the partial:
<?php
echo $this->partial('travels/_steps.phtml', array('parentView' => $this));
Then, in the partial:
<?php
$view = $this->parentView;
echo $view->searchHotel, $view->actionName;
In my humble opinion, you're doing exactly what you're supposed to do - passing just those variables you'll need in the partial.
If this causes you pain, perhaps you might consider that you're using partials unnecessarily.
Or, put another way, if you want to have some variable available in all partials then perhaps the partial is not where you should be using those variables.
Maybe have a look at Placeholders and rethink how you go about rendering your views.
Pretty often I need to access $config variables in views.
I know I can pass them from controller to load->view().
But it seems excessive to do it explicitly.
Is there some way or trick to access $config variable from CI views without
disturbing controllers with spare code?
$this->config->item() works fine.
For example, if the config file contains $config['foo'] = 'bar'; then $this->config->item('foo') == 'bar'
Also, the Common function config_item() works pretty much everywhere throughout the CodeIgniter instance. Controllers, models, views, libraries, helpers, hooks, whatever.
You can do something like that:
$ci = get_instance(); // CI_Loader instance
$ci->load->config('email');
echo $ci->config->item('name');
$this->config->item('config_var') did not work for my case.
I could only use the config_item('config_var'); to echo variables in the view
Your controller should collect all the information from databases, configs, etc. There are many good reasons to stick to this. One good reason is that this will allow you to change the source of that information quite easily and not have to make any changes to your views.
This is how I did it. In config.php
$config['HTML_TITLE'] = "SO TITLE test";
In applications/view/header.php (assuming html code)
<title><?=$this->config->item("HTML_TITLE");?> </title>
Whenever I need to access config variables I tend to use: $this->config->config['variable_name'];
echo $this->config->config['ur config file']
If your config file also come to picture you have to access like this for example I include an app.php in config folder I have a variable
$config['50001'] = "your message"
Now I want access in my controller or model .
Try following two cases one should work
case1:
$msg = $this->config->item('ur config file');
echo $msg['50001']; //out put: "your message";
case2:
$msg = $this->config->item('50001');
echo $msg; //out put: "your message"
$config['cricket'] = 'bat'; in config.php file
$this->config->item('cricket') use this in view
If you are trying to accessing config variable into controller than use
$this->config->item('{variable name which you define into config}');
If you are trying to accessing the config variable into outside the controller(helper/hooks) then use
$mms = get_instance();
$mms->config->item('{variable which you define into config}');
Example, if you have:
$config['base_url'] = 'www.example.com'
set in your config.php then
echo base_url();
This works very well almost at every place.
/* Edit */
This might work for the latest versions of codeigniter (4 and above).