1

I am learning PHP. I have two variable like this

$user_name = 'abc';
$pass = '12345';

I want use it inside curl string which originally require like this

CURLOPT_POSTFIELDS =>'{
    "username_or_email": "abc",
    "password": "12345"
    
}',

I am trying like below

CURLOPT_POSTFIELDS =>'{"username_or_email": '.'"$user_name"'.',"password":'.' "Freelance12"'.'}'

but its not working. Anyone can please help me for solve the issue? Thanks!

Riya Shah
  • 155
  • 1
  • 12
  • [This](https://stackoverflow.com/questions/5224790/curl-post-format-for-curlopt-postfields) would be a good starting point. You don't have to build it manually. – El_Vanja Dec 18 '20 at 12:52
  • 1
    `'{"username_or_email": "' . $user_name . '"'`. Or : `json_encode(["username_or_email" => $user_name, "password" => "Freelance12" ])` – Cid Dec 18 '20 at 12:52
  • 2
    If the post fields are supposed to be in json, then you should build up an array and use [json_encode](http://www.php.net/json_encode) to create a properly formatted json. – aynber Dec 18 '20 at 12:53
  • 2
    Does this answer your question? [curl POST format for CURLOPT\_POSTFIELDS](https://stackoverflow.com/questions/5224790/curl-post-format-for-curlopt-postfields) – phoenixstudio Dec 18 '20 at 13:11

2 Answers2

1

Try:

CURLOPT_POSTFIELDS =>'{"username_or_email": "'.$user_name.'","password": "Freelance12"}'

I dont know why you try to concat the main string with Freelance12; Freelance12 is a string, you can write directly.

MR Mark II
  • 433
  • 3
  • 13
1

I think this would probably be the approach I would recommend. Your POSTFIELDS looks like JSON so I would let PHP do the heavy lifting of turning it into a valid JSON object.

CURLOPT_POSTFIELDS => json_encode([
    'username_or_email' => $user_name, 
    'password' => $pass
])

All this does is create an associative array and then JSON encode it with the aptly named json_encode() function.

Were you to print the JSON string that is returned from this json_encode() call it would be...

'{"username_or_email": "abc", "password": "12345"}'
Daniel Morell
  • 2,308
  • 20
  • 34