How to get complete current url for Cakephp - php

How do you echo out current URL in Cake's view?

You can do either
From a view file:
<?php echo $this->request->here() ?>">
Which will give you the absolute url from the hostname i.e. /controller/action/params
Or
<?php echo Router::url(null, true) ?>
which should give you the full url with the hostname.

I prefer this, because if I don't mention "request" word, my IDE gives warning.
<?php echo $this->request->here; ?>
API Document:
class-CakeRequest
Edit:
To clarify all options
Current URL: http://example.com/en/controller/action/?query=12
// Router::url(null, true)
http://example.com/en/controller/action/
// Router::url(null, false)
/en/controller/action/
// $this->request->here
/en/controller/action/
// $this->request->here()
/en/controller/action/?query=12
// $this->request->here(false)
/en/controller/action/?query=12
// $this->request->url
en/controller/action
// $_SERVER["REQUEST_URI"]
/en/controller/action/?query=12
// strtok($_SERVER["REQUEST_URI"],'?');
/en/controller/action/

<?php echo $_SERVER[ 'REQUEST_URI' ]; ?>
EDIT: or,
<?php echo $this->Html->url( null, true ); ?>

The following "Cake way" is useful because you can grab the full current URL and modify parts of it without manually having to parse out the $_SERVER[ 'REQUEST_URI' ] string and then manually concatenating it back into a valid url for output.
Full current url:
Router::reverse($this->request, true)
Easily modifying specific parts of current url:
1) make a copy of Cake's request object:
$request_copy = $this->request
2) Then modify $request_copy->params and/or $request_copy->query arrays
3) Finally: $new_url = Router::reverse($request_copy, true).

Cakephp 3.5:
echo $this->Url->build($this->getRequest()->getRequestTarget());
Calling $this->request->here() is deprecated since 3.4, and will be removed in 4.0.0. You should use getRequestTarget() instead.
$this->request is also deprecated, $this->getRequest() should be used.

I know this post is a little dated, and CakePHP versions have flourished since. In the current (2.1.x) version of CakePHP and even in 1.3.x if I am not mistaken, one can get the current controller/view url like this:
$this->params['url'];
While this method does NOT return the parameters, it is handy if you want to append parameters to a link when building new URL's. For example, we have the current URL:
projects/edit/6
And we want to append a custom parameter action called c_action with a value of remove_image, one could make use of $this->params['url]; and merge it with an array of custom parameter key => value pairs:
echo $this->Html->link('remove image', array_merge($this->params['url'], array('c_action' => 'remove_image'));
Using the above method we are able to append our custom parameters to the link and not cause a long chain on parameters to build up on the URL, because $this->params['url] only ever returns the controll action URL.
In the above example we'd need to manually add the ID of 6 back into the URL, so perahaps the final link build would be like this:
echo $this->Html->link('remove image', array_merge($this->params['url'], array($id,'c_action' => 'remove_image'));
Where $is is a the ID of the project and you would have assigned it to the variable $id at controller level. The new URL will then be:
projects/edit/6/c_action:remove_image
Sorry if this is in the slightest unrelated, but I ran across this question when searching for a method to achieve the above and thought others may benefit from it.

Getting the current URL is fairly straight forward in your view file
echo Router::url($this->here, true);
This will return the full url http://www.example.com/subpath/subpath
If you just want the relative path, use the following
echo $this->here;
OR
Ideally Router::url(“”, true) should return an absolute URL of the current view, but it always returns the relative URL. So the hack to get the absolute URL is
$absolute_url = FULL_BASE_URL + Router::url(“”, false);
To get FULL_BASE_URL check here

for CakePHP 3:
$this->Url->build(null, true) // full URL with hostname
$this->Url->build(null) // /controller/action/params

Getting current URL for CakePHP 3.x ?
In your layout :
<?php
$here = $this->request->here();
$canonical = $this->Url->build($here, true);
?>
You will get the full URL of the current page including query string parameters.
e.g. http://website.example/controller/action?param=value
You can use it in a meta tag canonical if you need to do some SEO.
<link rel="canonical" href="<?= $canonical; ?>">

In the request object you have everything you need.
To understand it:
debug($this->request->url);
and in your case
$here = $this->request->url;

To get the full URL without parameters:
echo $this->Html->url('/', true);
will return http(s)://(www.)your-domain.com

The simplest way I found is it that includes host/path/query and
works in Controllers (Cakephp 3.4):
Cake\View\Helper\UrlHelper::build($this->request->getRequestTarget());
which returns something like this (we use it as login callback url) :
http://192.168.0.57/archive?melkId=12

After a few research, I got this as perfect Full URL for CakePHP 3.*
$this->request->getUri();
the Full URL will be something like this
http://example.com/books/edit/12
More info you can read here: https://pritomkumar.blogspot.com/2017/04/how-to-get-complete-current-url-for.html

The Cake way for 1.3 is to use Router::reverse:
Link to documentation
$url = Router::reverse($this->params)
echo $url;
yields
/Full/Path/From/Root/MyController/MyAction/passed1/named_param:bob/?param1=true&param2=27

Cakephp 3.x anywhere:
Router::reverse(Router::getRequest(),true)

for CakePHP 3.x You can use UrlHelper:
$this->Url->build(null, true) // output http://somedomain.com/app-name/controller/action/params
$this->Url->build() // output /controller/action/params
Or you can use PaginatorHelper (in case you want to use it in javascript or ...):
$this->Paginator->generateUrl() // returns a full pagination URL without hostname
$this->Paginator->generateUrl([],null,true) // returns a full pagination URL with hostname

for cakephp3+:
$url = $this->request->scheme().'://'.$this->request->domain().$this->request->here(false);
will get eg:
http://bgq.dev/home/index?t44=333

In View:
Blank URL: <?php echo $this->Html->Url('/') ?>
Blank Full Url: <?php echo $this->Html->Url('/', true) ?>
Current URL: <?php echo $this->Html->Url($this->here) ?>
Current Full URL: <?php echo $this->Html->Url($this->here, true) ?>
In Controller
Blank URL: <?php echo Router::url('/') ?>
Blank Full Url: <?php echo Router::url('/', true) ?>
Current URL: <?php echo Router::url($this->request->here()) ?>
Current Full URL: <?php echo Router::url($this->request->here(), true) ?>

I use $this->here for the path, to get the whole URL you'll have to do as Juhana said and use the $_SERVER variables. There's no need to use a Cake function for this.

All previously proposed approaches didn't satisfy my requirements for getting a complete URL (complete as in qualified) e.g. to be used in an email send from controller action. I need the scheme and hostname as well then, and thus stumbled over the following approach:
<?php echo Router::url( array( $id ), true ) ?>
Due to providing router array current controller and action is kept, however id isn't and thus has to be provided here again. Second argument true is actually requesting to prepend hostname etc. for getting full URL.
Using Router::url() is available in every situation and thus can be used in view files as well.

Yes, is easy FULL URL in Controler Work in CakePHP 1.3 >
<?php echo Router::url( array('controller'=>$this->params['controller'],'action'=>$this->params['action']), true );
Saludos

Use Html helper
<?php echo $this->Html->url($this->here, true); ?>
It'll produce the full url which'll started from http or https

In CakePHP 3 $this->here will be deprecated. The actual way is using this method:
Router::url($this->request->getRequestTarget())

For CakePHP 4.*
echo $this->Html->link(
'Dashboard',
['controller' => 'Dashboards', 'action' => 'index', '_full' => true]
);

If you want to return the base path, you can check that the Router class is using Configure::read ('App.fullBaseUrl'). So if you are a fan of hexagonal architecture, you can create a Cake implementation for creating URLs that will only use Configure from all CakePHP framework.

Related

Use hyphen(-) instead of slash(/) or underscore( _ ) in Routes

I'm Using Codeigniter 3.x , Using routes.php I want to create dynamic routes, for example I have a class name Class1.
I want output url
mysite.com/Class1-Student-Search
But using hyphen(-) is not working
If I put a slash(/), it works,
$route['(:any)/Student-Search'] = "search";
it returns
mysite.com/Class1/Student-Search
and using underscore (_) also work.
$route['(:any)_Student-Search'] = "search";
returns
mysite.com/Class1_Student-Search
But I want to use hyphen(-), if I put it, it will go to 404 error page, I used these four solutions but not work for me.
$route['(:any)-Student-Search'] = "search";
$route['([a-zA-Z]+)-Student-Search'] = "search";
$route['([a-zA-Z-0-9]+)-Student-Search'] = "search";
$route['(.*)-Student-Search'] = "search";
And if i hardcode the value in route
$route['Class1-Student-Search'] = "search";
Then it also working
You trying to create a dynamic routes which is not possible in codeigniter if you see the following flow chart of codeigniter you understand what i mean.
also you can see this chart in codeigniter official website
when you try to redirect or call some url it's work like this
Every request first goes to route there for you can't make it dynamic
Here is my solution, it is working for me, do like this.
$route['(:any)-Student-Search'] = "search";
then in your link button, hopefully in your view, href the link like this.
href="/<?php echo $row->classname; ?>-Student-Search"
the point is that not only you have to make your routes, also suffix it in your href link also the same way.

Cleanest way to include urls in Moodle emails

I'd like to know which is the cleanest way to insert an url in an email sent by Moodle module.
So far I'm using this formula, what IMHO I don't think is the cleanest way:
$url = $CFG->wwwroot.'/mod/<mymodulename>/view.php?id='.$cm->id;
The things I don't like here are:
Using $CFG->wwwroot
/mod/<mymodulename> needs to be provided always. (Assume here that I'm using a constant instead of a hardcoded string).
I expected Moodle to have a function to provide this out of the box just when providing module script. I've tried moodle_url but this function doesn't provide the path to the php script when used this way:
new moodle_url('view.php?id='.$cm->id);
I just get:
view.php?id=XX
Thanks in advance.
I would do it like this
$url = new moodle_url('/mod/<mymodulename>/view.php', array('id' => $cm->id));
echo html_writer::link($url, get_string('linktitle', 'mod_mymodulename'));
You can use following statement:
This is Absolute path of file
$url = new moodle_url($CFG->wwwroot.'/mod//view.php', array('id' => $cm->id));

Symfony routing is not working?

I am working on existing project. I have following two URLs
http://example.dev/en/course/myUserName/myCourseName/150/myChapterName/1016/page/1/?hcid=147
http://example.dev/en/course/myUserName/myCourseName/150/myChapterName/1016/page/2/?hcid=147
2nd URL is working fine but 1st URL is giving me following error:
Unable to find a matching route to generate url for params "array ( 'action' => 'showChapter', 'module' => 'course', 'courseowner' => 'myUserName', 'coursename' => 'myCourseName', 'courseid' => '150', 'chaptername' => 'myChapterName',)".,
referer: http://example.dev/en/course/myUserName/myCourseName/150/myChapterName/1016/page/1/?hcid=147
I have following entry in routing.yml:
course_chapter:
url: /:sf_culture/course/:courseowner/:coursename/:courseid/:chaptername/:chapterid/:page/:pageid/
param: { module: course, action: showChapter }
requirements:
courseid: \d+
url_for():
<?php $headchapter = ($hcid) ? '?hcid='.$hcid : '' ?>
<a href="<?php echo url_for('course/showChapter?courseowner='.$sf_params->get("courseowner").'&coursename='.$sf_params->get("coursename").'&courseid='.$sf_params->get("courseid").'&chaptername='.$chapter->getName().'&chapterid='.$chapter->getId().'&page=page&pageid=1').$headchapter ?>">
I cant understand how it is working for 2nd URL and not for first URL. I have checked the action and view and I did not find any error.
Any Idea or debugging technique ??
Don't do your links like that. There is a cleaner way.
<a href="<?php echo url_for('course/showChapter?courseowner='.$sf_params->get("courseowner").'&coursename='.$sf_params->get("coursename").'&courseid='.$sf_params->get("courseid").'&chaptername='.$chapter->getName().'&chapterid='.$chapter->getId().'&page=page&pageid=1').$headchapter ?>">
Do this instead:
link_to("Link text","course_chapter",array("courseowner"=>$sf_params->get("courseowner"),
"coursename"=>$sf_params->get("coursename"),
"courseid"=>$sf_params->get("courseid"),
"chaptername"=>$chapter->getName(),
"chapterid"=>$chapter->getId(),
"pageid"=>1,
"hcid"=>$hcid))
If a param doesn't exist in your routing url, it'll get appended like ?hcid=2
Why are you using sf_params to generate the URL params and not the database? i.e why is it $sf_params->get('courseid') and not $course->getId() from a doctrine object?
Also instead of using course/showChapter use the route id of course_chapter
I'd advise that you go back to the symfony manual and re-read the routing section.
EDIT:
In your route definition, you have:
url: /:sf_culture/course/:courseowner/:coursename/:courseid/:chaptername/:chapterid/:page/:pageid/
why is page a parameter if it's always the same value, i.e. it's always gonna be page.
This would be better:
url: /:sf_culture/course/:courseowner/:coursename/:courseid/:chaptername/:chapterid/page/:pageid/
And don't chapterid and pageid need to be part of the requirements of \d+ too?

Getting the URL of a node in Drupal 7

Goal: To send an email with a list of URLs generated from nodes.
In my custom module I have managed to get the node id which the user wants and I now want to get the URL of each node to put into my email.
I searched the db and used google but I can't seem to find the right solution.
It seems we need to construct the URL something like this:
<?php
global $base_url;
$link=$base_url."// few more parameters
You can use the url() function:
$options = array('absolute' => TRUE);
$nid = 1; // Node ID
$url = url('node/' . $nid, $options);
That will give you the absolute path (i.e. with http://example.com/ in front of it), with the URL aliased path to the node page.
You can also try drupal_lookup_path('alias',"node/".$node->nid).
Also you can get it by
$path=drupal_get_path_alias('node/'.$nid);
absolute path for nid
url('node/' . $node->id(), ["absolute" => TRUE]);
You can also use the l() function.
l(t('Link text'), 'node/123', array('options' => array('absolute' => TRUE)));
use
$node_url;
it will give you the current node url

Magento get language code in template file

I need a helper function to get the current language code. I want to use it in a templete file, like /products/view.phtml, only for testing purposes.
Does it already exist?
I have something in mind like the URL-helper
$url = $this->helper('core/url')->getCurrentUrl();
You can get the current locale code this way :
$locale = Mage::app()->getLocale()->getLocaleCode();
Result for answers given in this topic for "Belgium:French" (Be_Fr):
strtolower(Mage::getStoreConfig('general/country/default')); = be
substr(Mage::getStoreConfig('general/locale/code'),0,2); = fr
Mage::app()->getLocale()->getLocaleCode(); = fr_BE
Note that
Mage::app()->getLocale()->getLocaleCode() == Mage::getStoreConfig('general/locale/code')
but with the second one, you can specify an other store than default one (Mage::getStoreConfig('general/locale/code', $storeId)), so I would recommand it.
Afaik there is no such helper function, but you could of course build your own using:
Mage::getStoreConfig('general/locale/code', Mage::app()->getStore()->getId());
Try
$_language_code = substr(Mage::getStoreConfig('general/locale/code', $_store->getId()),0,2);
where $_store is current store object
You can also use :
$languageCode = Mage::app()->getStore()->getLanguageCode();
Don't forget to configure your store locales in your admin. Go to menu :
System -> Configuration -> General -> Locale Options
And set the correct Locale for each Websites or stores
For use in the html elements lang attribute etc.
echo strtolower(Mage::getStoreConfig('general/country/default')); // "en"

Categories