Get current url path - php

How many examples I have not seen, all are essentially the same, and perform the same thing. Let's take a look at one of them.
Route::current()->uri()
We have url https://example.com/test and we get test, and in all examples the same
But how to make sure that we get not just test but with a slash /test?

You can get it with this piece of code:
request()->getPathInfo();
Laravel Illuminate/Http/Request extends Symfony Request class which contains getPathInfo method.
Docs: https://symfony.com/doc/current/components/http_foundation.html#identifying-a-request
Definition of that method you can find here.

You can get url in laravel :
// Get the current URL without the query string...
echo url()->current();
// Get the current URL including the query string...
echo url()->full();
// Get the full URL for the previous request...
echo url()->previous();

You can try this:
request()->getPathInfo();
You can find the method definition here

Related

How to get last part of url in blade file (HTML) using laravel 5.2?

I am new to laravel.
I want to get the last part of my url in the blade file(HTML file).
I have done this one using php functionality .
Is there any way I can get it using any laravel functionality .
Below is my code ,its working fine
<?php
$url = url()->current();
echo $end = end((explode('/', $url)));
?>
I have also used this one to get
Request::segment(2)
Here my url is http://localhost/blog/public/user/add-user.
I want to get add-user in the html file.
Thank you
Try this code for getting last value of URL
$uri_path = $_SERVER['REQUEST_URI'];
$uri_parts = explode('/', $uri_path);
$request_url = end($uri_parts);
The answer to your question is: "No there is not any Laravel functionality" or more precisely Laravel helpers for getting the last segment, but fortunately you can just use php. The end has been mentioned and end works on an array, but I don't think it is possible to use directly on Request::segments(). That means you have to put Request::segments() into a variable (like $lastSegment) first and then use end on the variable.
The best and slimmest way I could find to do this is:
{{ basename(Request::url()) }}
Use this in blade, but of course like mentioned before you can add this in the controller or a Laravel view composer.
{{last(request()->segments())}}
If you specifically want the last segment (it may be the 2nd, 3rd, 4th etc) you can use end(Request::segments()) to conistently always get the last segment.
Also, if you don't want to call functions in your templates and be a bit more 'Laravel' why not bind it to your view from the controller?
In your controller:
public function show()
{
return view('your.view')->with('lastSegment', end(Request::segments()));
}
Then in your view you can do this:
<p> The last segment is {{$lastSegment}} </p>
Also, if you want to have $lastSegment be available in all your views without having to code it in all your controllers, look into using Laravel's view composer. Very powerful for making templates.

Modify request path info

Now, let me guess what y'all may be thinking... "It's a bad idea to modify the path info before it's processed. Why would you ever want to do that? This is malicious behavior!!!"
I am trying to get a controller/action representation of my previous URL; gotten through Yii::app()->getRequest()->getUrlReferrer().
From Yii 2 issues, it's possible to set the path info for a new request and parse that request. However, from the Yii 1 source, the only methods which deals with the path info are getPathInfo() and decodePathInfo(). If there was a setPathInfo(), I could have used that and the urlManager->parseUrl() to achieve this. But we aren't allowed to set the path info.
How can I arrive at a controller/action representation of my previous URL?
Using PHP $_SERVER['HTTP_REFERER'] it's good way to find previous location but will give you incomplete url.
You can try this way in Yii 1.0 -
if your url like - www.domain.com?r=site/page
if(isset($_REQUEST['r']) && !empty($_REQUEST['r'])){
$previous_location = $_REQUEST['r'];
Yii::app()->user->setState('previous_location', $previous_location);
}
Another way-
$controller_name = Yii::app()->controller->id;
$action_name = Yii::app()->controller->action->id;
Yii::app()->user->setState('previous_location', $controller_name.'/'.$action_name);
so you can find out your previous location by -
echo Yii::app()->user->getState('previous_location');
It's may be help you to resolve your issue.
Yii does not allow the CHttpRequest object live past the parsing of the routes. And creating a new CHttpRequest is impossible after the app is created.
I realized the only way to go about this is the vanilla Yii::app()->controller->action object. From this, I could get the module, controller and action ID for the specific URL.

Using multiple nested _GET variables in a single URL

Setup:
Script that generates word images from multiple letter images
(autotext.php)
URL is formatted:
www.whatever.com/autotext.php?text=hello%20world
Script that alters images server-side to run filters or generate
smaller sizes (thumbnail.php)
URL is formatted:
www.whatever.com/thumbnail.php?src=whatever.png&h=XXX&w=XXX
Use-case:
I want to generate a smaller version of the autotext server-side. So my call would look something like:
www.whatever.com/thumbnail.php?src=autotext.php?text=hello%20world&h=XXX&w=XXX
As you can see, I would like to treat a URL with _GET variables as a variable itself. No amount of playing with URI encoding has helped make this work.
I have access to the PHP for both scripts, and can make some simple alterations if that's the only solution. Any help or advice would be appreciated. I would not even rule out a Javascript frontend solution, though my preference is to utilize the two scripts I already have implemented.
You should be able to do this by urlencoding all the $_GET params into a variable then assigning that variable to another, like this (untested):
// Url generation
$url = www.whatever.com/thumbnail.php?src=(urlencode(http_build_query($_GET)));
Then you should be able to retrieve on other side:
$src = urldecode(explode('&', $_GET['src']));
I've seen this exact behavior when trapping where to redirect a user, after an action occurs.
---- Update ----
Your "use case" url was correct:
www.whatever.com/thumbnail.php?src=autotext.php?text=hello%20world&h=XXX&w=XXX
.... except that you CANNOT have more than one ? within a "valid" url. So if you convert the 2nd ? to a &, you should then be able to access $_GET['text'] from the autotext.php script, then you can urldecode it to get the contents.

how to process php REST url resources

I have read many about REST api in php articles. but I still get quite confusing.
they basically rewrite the url to a index.php, which process the url and depends on the method, then send response
but which is the properly way to process the url? this looks doen't look correct...
get the uri and split it
I should know what to do with each portion, eg. for GET /usr/1 I should do something like:
if($myUri[0]=="usr")
getUser($myUri[1]);
if the request url is like GET www.domain.com/user/1
it would call getUser($id);
but what happen if you can also retrieve the user by name, or maybe e-mail? so the url can also be www.domain.com/user/john or www.domain.com/user/john#gmail.com
and each url should call different methods like getUsrByName($name) or getUsrByEmail($mail)
The proper way of handling this would be to have URLs like this:
domain.com/user/id/1 -> user::getById
domain.com/user/email/foo#bar.com -> user::getByEmail
domain.com/user/username/foo -> user::getByUsername
However, specifying multiple "parameters" is more like a search, I'd go against using resources for that, because a path should be absolute. Which means:
domain.com/user/name/Kossel/likes/StackOverflow
And:
domain.com/user/likes/StackOverflow/name/Kossel
Are not the same resource. Instead I'd do:
domain.com/user/?name=Kossel&likes=StackOverflow
This is what Stack Overflow uses:
stackoverflow.com/questions/tagged/php
stackoverflow.com/tags/php/new
stackoverflow.com/questions/tagged/mysql?sort=featured
To avoid long if/else statement, use variable function names. this allows you to use the url string to call the correct function.
http://php.net/manual/en/functions.variable-functions.php
Also, you may want to use classes/class methods instead of functions. this way you can set up an __autoload function, which will allow you to only load code that you are going to use each time the index.php is called.
MVC architecture usually breaks their urls into /class_name/class_method_name/arguments...

variable number of parameters from a url/paramname/valueparam in an array?

basicly I would like to read url params in an array so finding params don't depend on their place in url
I have a url for seach with controller/action/paramA/valueparamA/paramB/valueparamB
theses params are optional : I have direct url with search params inside
to read params from url we have to use action(valueparamA, valueparamB)
but for me it seems really rigid
I want to read parameters by their name, not by their place in url!
so I can have different urls like
urlA = controller/action?paramA=valueA
*(or controller/action/paramA/valueA)*
urlB controller/action?paramB=valueB
than I can use with the same action, like we do with a form with $_POST array (it and $_GET[} seems always empty when direct url params)
the best would be to have all parameters in an array[paramname=>paramvalue] like in a form
what I DON'T want is tu use differents actions for different parameters possibles! :)
the best I saw was to use juste on array like parameter :
controller/action/array[paramname=>paramvalue]
(passing arrays as url parameter)
but it seems to complicate something basic :
just read the normal url parameters like every framework knows :) with
url?nameparam=valueparam&...
hope there is a solution !
I begin tor eally like the light and quick of ci but sometimes (like for extending model) it seems a little "rigid" ;)
think in advance for any idea!
Yep the URI class provides this functionality in the form of
$this->uri->uri_to_assoc(n);
This returns an array containing all parameters (keys and values must be defined in the URL).
Full details can be found on the Codigniter Userguide:
http://codeigniter.com/user_guide/libraries/uri.html

Categories