0

I got these two example.

Example1:

$data1 = "{'username':'myUserName','password':'myPassWord'}";

and Example2:

$username= "myUserName";
$password= "myPassWord";
$data2 = "{'username':'".$username."','password':'".$password."'}";

Which i send to cUrl post request in php. First example works while second does not. Why is that? I also tried setting variables in associative array, then using json_encode, then send it to cUrl. Nothing works except first example. I'm losing my mind here.

2 Answers 2

2

For valid JSON, you need to use double quotes, so change

$data2 = "{'username':'".$username."','password':'".$password."'}";

to

$data2 = '{"username":"' . $username . '", "password":"' . $password . '"}';

EDIT: a sharp remark by @LawrenceCherone, to ensure you don't run into trouble with usernames/passwords that carry " in them, always use json_encode() e.g.:

<?php
$username= "myUserName";
$password= 'my"PassWord'; // password containing "
$arr = ['username' => $username, 'password' => $password];
$result = json_encode($arr);

Output $result: Valid JSON

{"username":"myUserName","password":"my\"PassWord"}
Sign up to request clarification or add additional context in comments.

2 Comments

some usernames/passwords contain " which will break the JSON
Correct, and I sincerly invite @VeljkoStefanovic to accept your answer. Love the json_encode(compact(...))
1

Dont build your own json! Use json_encode() instead, and use compact() to make an array from global vars.

<?php
$username= "myUserName";
$password= "myPassWord";

$data2 = json_encode(compact('username', 'password'));

use $data2 for whatnot, which will contain:

{"username":"myUserName","password":"myPassWord"}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.