Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
642 views
in Technique[技术] by (71.8m points)

json - How to write output php variable in curl request in Postfields

I am creating plugin and I need to get data using curl request. Here is my code

$userName = 'admin';
$password = '123456';

$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_URL => "https://apis.tcscourier.com/production/v1/cod/create-order",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 60,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "
{"userName":"<?php $userName ?>","password":"<?php $password ?>","costCenterCode":"2705","consigneeName":"Nabeel Khan"}
",
CURLOPT_HTTPHEADER => [
"X-IBM-Client-Id: 9b9fc7fa5fc4",
"accept: application/json",
"content-type: application/json"
],
]);

$response = curl_exec($curl);
$err = curl_error($curl);

But the $username and $password variable in CURLOPT_POSTFIELDS is not working or output. So I want to know how to output variables in CURLOPT_POSTFIELDS ?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just pass an array to curl and it does the dirty work for you:

CURLOPT_POSTFIELDS => ['userName' => $username, 'password' => $password, ...],

Edit: I just noticed that you try to send a JSON payload, then you have to encode the data first:

CURLOPT_POSTFIELDS => json_encode(['userName' => $username, 'password' => $password, ...]),

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...