Marth
Marth

Reputation: 55

Building a URL with JSON data as a query string parameter value

I have this data

$data = array('username' => 'myname',
              'password' => 'mypass'
           );
$json = json_encode($data);

How can i pass the json as a variable to a url that looks like this

'http://example.com/login/?data='

this is what i have tried and get '400: data not passed' error

$data = array('username' => 'myname',
          'password' => 'mypass'
       );

$data_string = json_encode($data);
$curl = curl_init();
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($curl, CURLOPT_URL, 'http://example.com/login/?data='); //also 'http://example.com/login/'
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Accept: application/json',
            'Content-Length: ' . strlen($data_string)
        ));
curl_setopt($curl, CURLOPT_HEADER, TRUE);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);

// Exec
$response = curl_exec($curl);
$info = curl_getinfo($curl);
curl_close($curl);

Upvotes: 1

Views: 2152

Answers (2)

Charles Bryant
Charles Bryant

Reputation: 1015

This is possible to do this, you are pretty much there.

$data = array('username' => 'myname',
              'password' => 'mypass'
           );
$json = json_encode($data);

$url = 'http://example.com/login/?data=' . urlencode($json);

This will be a safe url that can do what ever you want with it.

Upvotes: 0

Brad
Brad

Reputation: 163234

Any data used in the query string should be URL-encoded.

$url = 'http://example.com/login/' . http_build_query([
    'data' => json_encode([
        'username' => 'myname',
        'password' => 'mypass'
    ])
]);

http_build_query() will take an associative array of parameters, and apply all the proper encodings, building the whole query string for you.

The URL returned:

http://example.com/login/data=%7B%22username%22%3A%22myname%22%2C%22password%22%3A%22mypass%22%7D

Upvotes: 3

Related Questions