Rana
Rana

Reputation: 6154

Pass URL as parameter in silex controller

I want to pass a url as parameter to a controller as like below:

$api->get('/getfile/{fileurl}', function(Request $request, $fileurl){
              //do something
}

Here {fileurl} can be a valid http url. However, the above mapping isn't working and resulting 404(may be because of the slashes in the {fileurl} part?) . How to solve it to accept the $url in $fileurl variable?

Upvotes: 0

Views: 1243

Answers (3)

videomonkey43
videomonkey43

Reputation: 1

why not?

$app->get("/getfile/{fileurl}", function ($fileurl) use ($app) {
  $decoded_fileurl = urldecode($fileurl);
  // ..
});

urldecode() was meant for exactly this purpose, you just need to make sure to encode the url before creating the link in twig it's as simple as {{ myvar|e('url') }} or in php urlencode($myvar) I was just trying to pass around email addresses in urls and ran into the same problem. I post it here for posterity.

Upvotes: 0

Ralf Hertsch
Ralf Hertsch

Reputation: 1287

Use base64_encode() before passing the $fileurl

$fileurl = base64_encode(YOUR_URL);

and decode $fileurl in your controller:

$app->get("/getfile/{fileurl}", function ($fileurl) use ($app) {
  $decoded_fileurl = base64_decode($fileurl);
  // ..
});

Upvotes: 1

Maerlyn
Maerlyn

Reputation: 34107

You need to check the regex matching the fileurl part match slashes, as it does not do that by default.

Simply do an assert("fileurl", ".*") call on your route like this:

$app->get("/getfile/{fileurl}", function ($fileurl) use ($app) {
    // ...
})->assert("fileurl", ".*");

Make sure it's your last parameter, as it'll swallow everything.

Upvotes: 2

Related Questions