I am writing an app using the Phalcon framework for PHP and I have to implement the feature to allow users to write messages on each others walls. So with JQuery I would write:
function postMessage() {
var message = $("#messageBox").val().trim().replace(/\n/g, '<br/>');
if(message) {
$.post("// request handler", {msg: message, wall: {{ user.id }},
writer: {{ session.get('user')['id'] }})
.done(function() {
$("#messageBox").val('');
alert( "Message posted" );
})
.fail(function() {
alert( "Error posting message, please try again" );
});
}
}
And this script would be located in the page domain.com/user/foobar
My question is what (or rather where) should my request handler be. I've thought about it a bit and asked my friend and came up with three options:
Post to the same url the above script is in (Ex.
domain.com/user/foobar)
Post to another url which routes to
another action in the same controller as option 1 (Ex.
domain.com/postmessage. Both option 1 and 2 are in the same
controller but they are different actions)
Post to an API url (Ex. api.domain.com)
Some pros I thought of were:
Both option 1 and 2 can access the session variable, so I can check
if the user is logged in or not. With option 3, I cannot but I can
(unrealistically) hope no one tries to abuse the system and post
messages with Fiddler or something by not being logged in.
Option 2 is a bit cleaner than option 1
Option 2 and 3 both provide central request handlers so if I wanted
to implement the same message on wall writing system I would only
have to copy the Jquery code and put it in the new view or page.
With option 1 I have to copy the code from the user controller and
repaste it into the controllers for each of the new pages.
Some cons I thought of were:
Option 2 means I have to add more routes to my router. This makes
routing more complicated. (And maybe slower???)
( Ex.
// Option 1
$router->add('/user/{id}',
array(
'controller' => 'user',
'action' => 'show'
)
);
// Option 2
$router->add('/user/post/{id}',
array(
'controller' => 'user',
'action' => 'writeMessage'
)
);
)
Which way is recommended and used?
I would keep defining routes as needed. Or define a single route and pass an extra parameter in the post request that hooks into the remote procedure.
Be cautious where the users are concerned and close any loopholes. Think about adding a nonce.
Thanks,
C
Never ever assume that all your users will be kind and smart, it's how people break a system. Test everything.
Usually : 1 route = 1 action
If you haven't any route for posting message, adding one is the way to go.
A route is like a simple "if" test, it'll be done in a few nanoseconds.
As of my knowledge these both are used for creating links :
What is the main difference between $this->Html->url and $this->Html->link in Cakephp?
Is there any performance issues occurs for using these?
What if i want to open link in new tab using "$this->Html->url"
What i tried :
<?php echo $this->Html->url($item['News']['link'],array('target'=>'_blank', 'escape' => false)); ?>
but its not working. open link in same tab.
Thanks in advance.
Well, according to CakePHP Documentation, the HTML->url takes two arguments, the 2nd one is a boolean while the first is a routing array. Try this:
<?php echo
$this->Html->url(
array(
'href' => $item['News']['link'],
'target' => '_blank',
'escape' => false
),
false // Second argument, true means prepend the path of my site before the link while false means don't prepend
); ?>
References:
http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::url
http://book.cakephp.org/2.0/en/appendices/glossary.html#term-routing-array
This is what the $this->Html->link() method is for. It takes an array of options as parameters to do this.
I am working on cakephp project. I have removed index.php from URL using .htaccess file and now I want to remove view name from URL & add some other two varying parameter. Suppose I choose country & city then these two parameter should appear in URL on selecting them.
The problem I am facing is as cakephp takes
www.example.com/Controllername/viewname
But my requirement is like this
www.example.com/Controllername/param1/param2
If I pass this way It looks for param1 as controller and param2 as view.
Initially should be like:
www.example.com/Controllername/
In your APP/routes.php:
// www.example/com/Controllername
Router::connect('/Controllername',
array('controller'=>'Controllername', 'action'=>'index'));
// www.example.com/Controllername/param1/param2
Router::connect('/Controllername/:param1/:param2',
array('controller'=>'Controllername', 'action'=>'index'),
array('pass' => array('param1', 'param2')));
and your controller:
// set to null/a value to prevent missing parameter errors
public function index($param1=null, $param2=null) {
//echo $param1 . ' and ' . $param2;
}
When generating links:
array('controller'=>'Controllername', 'action'=>'index', 'param1'=>'foo', 'param2'=>'bar');
Order matters. Change paramX to anything you want i.e. country and town
note this does not cover: controllername/param1 - both must be present in this example.
There are other ways to achieve this.
I think you should first make sure that mod-rewrite module is enabled. You shouldn't have had to remove index.php from the url using .htaccess if mod_rewrite were enabled. Check how to enable it in the manual of your webserver and the default .htaccess of cakephp should be able to handle the rest of the routing for you.
After you have enable rewrite module, you can modify the routes as pointed out by #Ross in the previous answer in you APP/routes.php:
// www.example/com/Controllername
Router::connect('/Controllername',
array('controller'=>'Controllername', 'action'=>'index'));
// www.example.com/Controllername/param1/param2
Router::connect('/Controllername/:param1/:param2',
array('controller'=>'Controllername', 'action'=>'index'),
array('pass' => array('param1', 'param2')));
Isn't it much slower concerning development time ?
What are the advantages of of HTML->link ?
Thanks !
It's just a question of whether you want to generate your own URLs and hard-code them, or if you want Cake to do the work for you. For simple urls leading to the homepage of your site using cake may seem slower, but it's actually useful for dynamic urls, for example:
Say you're printing a table of items and you have a link for each item that deletes that item. You can easily create this using:
<?php
echo $this->Html->link(
'Delete',
array('controller' => 'recipes', 'action' => 'delete', $id),
array(),
"Are you sure you wish to delete this recipe?"
);
Notice how using an array specifying the controller and action as a URL allows you to be agnostic of any custom routes. This can have its advantages.
The corresponding way to do it without the HTML helper would be:
Delete
It can also be really useful for constructing URL query strings automatically. For example, you can do this in array format:
<?php
echo $this->Html->link('View image', array(
'controller' => 'images',
'action' => 'view',
1,
'?' => array('height' => 400, 'width' => 500))
);
That then outputs this line of HTML:
View image
It could be a pain to generate that URL manually.
In summary, while it may seem awkward for simple links, the HTML helper definitely has its uses. For further uses, consult the cakePHP book on the HTML helper's link function.
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¶m2=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.