Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slim PHP and GET Parameters

Tags:

rest

php

slim

I'm playing with Slim PHP as a framework for a RESTful API, and so far it's great. Super easy to work with, but I do have one question I can't find the answer to. How do I grab GET params from the URL in Slim PHP?

For example, if I wanted to use the following:

http://api.example.com/dataset/schools?zip=99999&radius=5

A case of the Mondays? Am I overthinking it? Thanks in advance!

like image 820
Eric Arenson Avatar asked Nov 14 '11 16:11

Eric Arenson


4 Answers

You can do this very easily within the Slim framework, you can use:

$paramValue = $app->request()->params('paramName');

$app here is a Slim instance.

Or if you want to be more specific

//GET parameter

$paramValue = $app->request()->get('paramName');

//POST parameter

$paramValue = $app->request()->post('paramName');

You would use it like so in a specific route

$app->get('/route',  function () use ($app) {
          $paramValue = $app->request()->params('paramName');
});

You can read the documentation on the request object http://docs.slimframework.com/request/variables/

As of Slim v3:

$app->get('/route', function ($request, $response, $args) {
    $paramValue = $request->params(''); // equal to $_REQUEST
    $paramValue = $request->post(''); // equal to $_POST
    $paramValue = $request->get(''); // equal to $_GET

    // ...

    return $response;
});
like image 149
Martijn Avatar answered Nov 14 '22 06:11

Martijn


For Slim 3/4 you need to use the method getQueryParams() on the PSR 7 Request object.

Citing Slim 3 / Slim 4 documentation:

You can get the query parameters as an associative array on the Request object using getQueryParams().

like image 22
vlp Avatar answered Nov 14 '22 05:11

vlp


I fixed my api to receive a json body OR url parameter like this.

$data = json_decode($request->getBody()) ?: $request->params();

This might not suit everyone but it worked for me.

like image 4
Mulhoon Avatar answered Nov 14 '22 05:11

Mulhoon


Slim 3

$request->getQueryParam('page')

or

$app->request->getQueryParam('page')
like image 3
Smith Avatar answered Nov 14 '22 07:11

Smith