Passing "\" and "/" in variable via Laravel Route - php

First off, apologies if this is a bad question/practice. I'm very new to Laravel, so I'm still getting to grips with it.
I'm attempting to pass a variable that contains forward slashes (/) and backwards slashes () in a Laravel 5 route and I'm having some difficulties.
I'm using the following: api.dev/api/v1/service/DfDte\/uM5fy582WtmkFLJg==.
Attempt 1:
My first attempt used the following code and naturally resulted in a 404.
Route:
Route::group(array('prefix' => 'api/v1'), function() {
Route::resource('service', 'ServiceController');
});
Controller:
public function show($service) {
return $service;
}
Result:
404
Attempt 2:
I did a bit of searching on StackOverflow and ended up using the following code, which almost works, however, it appears to be converting \ to /.
Route:
Route::group(array('prefix' => 'api/v1'), function() {
Route::get('service/{slashData}', 'ServiceController#getData')
->where('slashData', '(.*)');
});
Controller:
public function getData($slashData = null) {
if($slashData) {
return $slashData;
}
}
Result:
DfDte//uM5fy582WtmkFLJg==
As you can see, it's passing the var but appears to be converting the \ to /.
I'm attempting to create an API and unfortunately the variable I'm passing is out of my control (e.g. I can't simply not use \ or /).
Does anyone have any advice or could point me in the right direction?
Thanks.

As you can see from the comments on the original question, the variable I was trying to pass in the URL was the result of a prior API call which I was using json_encode on. json_encode will automatically try and escape forward slashes, hence the additional \ being added to the variable. I added a JSON_UNESCAPED_SLASHES flag to the original call and voila, everything is working as expected.

You should not do that. Laravel will think it is a new parameter, because of the "/". Instead, use htmlentitites and html_entity_decode in your parameter, or use POST.

Related

404 not found : laravel api with parameter

Call to Laravel API with parameter gets an error of 404: page not found, But while removing the parameter It works fine.
API.php have the following code
Route::get('Parties/{aToken}',"CustomerController#apiParties");
The controller has the following Code
function apiParties(request $request,$token){
$parties = DB::table('parties')
->Where("status","1")
->get()
->take(20);
return json_encode($parties);
}
Tried too many things but not working. I'm working on the server, not in localhost so don't have a terminal.
Change this
->get()->take(20);
to
->take(20)->get();
more fluently :
return DB::table('parties')
->Where("status","1")
->take(20)
->toJson();
Only use Request when you need it, i see that you not really use it on this scope of code. And make sure you already import DB Facades correctly :
use Illuminate\Support\Facades\DB;
If you want to make the parameter optional then add ? before the close brace.
Second thing is that you need to use Request $request starting with capital letter.
Always use small letters in the URLs and for the parameters.
Also, the parameter in the controller method should be Request instead of request.

Symfony 3 Ajax call routing issue

I'm setting up a simple Ajax call in one of my forms. When a user enters characters in a field, the following Ajax call is activated:
self.modify = function (input_field) {
if ($(input_field).val().length > 5) {
$.post("{{path('get_bio_control_sample')}}", {sample_number: $(input_field).val()},
function (response) {
if (response.code == 100 && response.success) {
alert(response.sample_number);
}
}, "json");
}
};
Which is meant to access the following controller action:
class BioControlController extends Controller {
/**
* #Route("/bio_control/sample", name="get_bio_control_sample")
*/
public function getBioControlSampleAction(Request $request){
$sample_number = $request->query->get('sample_number');
$response = array("code" => 100, "success" => true, "sample_number" => $sample_number, "sample_data" => "test");
return new JsonResponse($response);
}
}
However, when the call is activated JS returns the error:
http://127.0.0.1:8000/omics_experiment/%7B%7Bpath('get_bio_control_sample')%7D%7D 404 (Not Found)
I'm accessing the Ajax call from omics_experiment/new (which is in the OmicsExperimentController) and using the route /bio_control/sample (as shown by the annotation), but it's not working. Can someone explain what I'm doing wrong?
I used this question as a template, the fact I'm using Symfony 3 might mean there are syntactic errors.
I just had to do this recently. I'm no expert on Symfony either, but since I just did this I may be able to help. Using Symfony is not really much different than doing it with a static URL. The main thing is to make sure that your controller and route are set up properly and working without AJAX, then you just need to use the path set in your route for the .post call.
And what makes it worse, is that it's really hard to test this type of interaction. Even your twig includes can cause it to fail if they are set up wrong.
Looking at your code again I think this may be the problem. Change this
$.post("{{path('get_bio_control_sample')}}", {sample_number:
to this
$.post("/bio_control/sample", {sample_number:
Because I think the way you have it is only good for twig templates, so if Symfony is not looking at your JQuery file like it does a twig template, then, it's not going to understand how to get the route.

Laravel - cannot get url GET parameters

I am having an issue trying to make a GET request to a route and process the parameters passed in via the URL. Here are two routes I created in routes.php:
$router->get('/', function() {
$test = \Input::get('id');
dd($test);
});
$router->get('test', function() {
$test = \Input::get('id');
dd($test);
});
When I go to the first URL/route ('/') and pass in some data, 123 prints to the screen:
http://domain.com/dev/?id=123
When I go to the second ('test') NULL prints to the screen (I've tried '/test' in the routes.php file as well).
http://domain.com/dev/test?id=123
A few things to note here:
This installation of Laravel is in a subfolder.
We are using Laravel 5.
Any idea why one would work and the other would not?
First thing - Laravel 5 is still under active development so you cannot rely on it too much at this moment.
Second thing is caching and routes. Are you sure you are running code from this routes?
Change this code into:
$router->get('/', function() {
$test = \Input::get('id');
var_dump($test);
echo "/ route";
});
$router->get('test', function() {
$test = \Input::get('id');
var_dump($test);
echo "test route";
});
to make sure messages also appear. This is because if you have annotations with the same verbs and urls they will be used and not the routes you showed here and you may dump something else. I've checked it in fresh Laravel 5 install and for me it works fine. In both cases I have id value displayed
You can use
Request::path()
to retrieve the Request URI or you can use
Request::url()
to get the current Request URL.You can check the details from Laravel 5 Documentation in here : http://laravel.com/docs/5.0/requests#other-request-information and when you did these process you can get the GET parameters and use with this function :
function getRequestGET($url){
$parts = parse_url($url);
parse_str($parts['query'], $query);
return $query;
}
For this function thanks to #ruel with this answer : https://stackoverflow.com/a/11480852/2246294
Try this:
Route::get('/{urlParameter}', function($urlParameter)
{
echo $urlParameter;
});
Go to the URL/route ('/ArtisanBay'):
Hope this is helpful.

Url Variables with %2f not handled by silex

I am very new to silex, but have experience with Java based MVC frameworks.
The problem I have seems to be how to accept certain special characters in URL arguments.
I have a controller defined as such:
$app->get('/editPage/{fileName}', function ($fileName) use ($app,$action) {
return $app['twig']->render('edit.twig.html',$action->editPage($fileName));
});
and this works great for urls like:
/myapp/editPage/file.html
/myapp/editPage/file-2.html
but if I pass an encodes "/" or %2F, the route is not picked up, and I get a 404.
1. /myapp/editPage/folder%2Ffile.html
The mod_rewrites rules should route any non-existent file paths to the index.php where silex is defined, so I am not sure what is happening.
I just need a way to capture values with "/" for this particular page. There are no conflicting childpages, so if there is a way to wildcard the path "/editPage/{.*|filename}/" or something obvious I am missing.
You can use assert to change the regex that is used to match the variable. If you want it to match anything, pass a very lenient regex.
eg.
$app = new \Silex\Application();
$app->get('/file/{filename}', function ($filename) {
die(var_dump($filename));
})->assert('filename', '.*');
$app->run();
These requests
GET /file/a%2fb%2fc.txt
GET /file/a/b/c.txt
both yield
string 'a/b/c.txt' (length=9)
It's not an issue with Silex but with Apache.
Apache rejects by design encoded slashes as part of the URI for security purposes. See this answer: https://stackoverflow.com/a/12993237/358813
As a workaround passing the value inside a query string is completely fine:
http://example.com/?file=%2Fpath%2Fto%2Ffile will work, provided you configure Silex accordingly.
In addition to #tacone answer's, here's how I configured Silex to make it work.
I guess it's not the prettiest solution however...
The URL called should be /get/?url=<url encoded>
$siController->get('/get/', function(Application $app, $url){
/** #var SocialIdentifier $si */
$si = $app['social_identifier.social_identifier'];
$result = $si->get($url);
return $app->json($result, 200);
})
->value('url', $_GET['url']);

Getting request parameters on Slim

I'm trying to get request parameter names and values dynamically, but the array is always empty. This is the get route:
$app->get('/get/profile/:id_user', function ($id_user) use ($app) {
print_r($app->request()->params());
});
And this is how im calling it from the browser:
http://localhost/get/profile/9492
This should return an array with id_user => 9492but it comes empty.
Any ideas why?
Notice: Please read update notes before trying out this code. The update note is my first comment in this answer.
Couldn't get to test it but please try the following:
$app->get('/get/profile/:id_user', function ($id_user) use ($app) {
$req = $app->request();
print_r($req->params());
});
Reference documentation: http://docs.slimframework.com/#Request-Method
Update: Okay after some digging figured the following, the params() method requires a parameter. If called without a parameter a Notice is raised. Checking the source revealed that this function called without a parameter returns null. See Http/Request.php line 199. Also for some reason currying does not seem to work either to retrieve parameters so you have to use the function parameter $id_user which has the expected value.
You can use following:
$app->get("/test.:format/:name",function() use ($app){
$router = $app->router();
print_r($router->getCurrentRoute()->getParams());
});
Also is a configuration problem。
try
try_files $uri $uri/ /index.php?$query_string;

Categories