Using PHP CURL to Post Data from While Loop in JSON API - php

The data I want to post into the json api body below is from a while loop. So I want to Select from the database and send multiple students data from the database. I can post individually but I'm unable to do it from a loop. How please? Thanks.
{
"students":[
{
"admissionNumber": "2010",
"class":"js one"
},
{
"admissionNumber": "2020",
"class":"ss one"
}
],
"appDomain":"www.example.com"
}
Here's my code:
if(isset($_POST['submit'])){
$sql = "SELECT * FROM students";
while($row = mysqli_fetch_array($sql){
$admissionNumber = $row['admNo'];
$class = $row['class'];
$data = array('students' => array(['admissionNumber' => $admNo, 'class' => $class]),
'appDomain' => "http://example.com",
);
echo $data;
$url = 'https://the-end-point';
$params = $data;
$data_string = json_encode($data);
$curl = curl_init();
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $data_string,
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"content-type: application/json",
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
}
echo "<script>
alert(' Student Created Successfully!');
window.location = '.../students.php';
</script>";
}
}
}

Related

Cant Extract data from PHP curl response

I learning to use API from: https://rapidapi.com/lambda/api/face-recognition-and-face-detection/endpoints
I want to save or echo albumkey to variable and store in database. I have tried $response->albumkey and didn't work.
here my response below:
{
album: "amanda11",
msg: "Please put this in a safe place and remember it, you'll need it!",
albumkey: "c00bc5d3b1bf64a1ba68f690d4dabee494a2c6fbf48cf8f09c6d41fbece45b7b"
}
And here my code:
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://lambda-face-recognition.p.rapidapi.com/album",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "album=amanda11",
CURLOPT_HTTPHEADER => [
"content-type: application/x-www-form-urlencoded",
"x-rapidapi-host: lambda-face-recognition.p.rapidapi.com",
"x-rapidapi-key: 932571abf0msh45cf0f3cef74aacp19e151jsn33e9949a1974"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
if ($err) {
echo $err;
} else {
echo $response;
}
You need to parse the JSON before you can access its values. In PHP you do that with json_decode():
$response = curl_exec($curl);
$err = curl_error($curl);
if ($err) {
echo $err;
} else {
$json = json_decode($response);
echo $json->albumkey ;
}
Here's a basic example:
$response = '{
"album": "amanda11",
"msg": "Please put this in a safe place and remember it, you\'ll need it!",
"albumkey": "c00bc5d3b1bf64a1ba68f690d4dabee494a2c6fbf48cf8f09c6d41fbece45b7b"
}';
$json = json_decode($response);
echo $json->albumkey;
Demo

Error creating natural language classifier with api using PHP, returns data too small error but works in Postman

The cURL request works in Postman with the following:
curl -i -u "apikey:12345" \
-F training_data=#rtcu.csv \
-F training_metadata="{\"language\":\"en\",\"name\":\"RTCU\"}" \
"https://gateway.watsonplatform.net/natural-language-classifier/api/v1/classifiers/v1/classifiers"
Postman's generated cURL code for PHP returns { "code" : 400, "error" : "Data too small", "description" : "The number of training entries received = 0, which is smaller than the required minimum of 5" }
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://gateway.watsonplatform.net/natural-language-classifier/api/v1/classifiers",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"training_data\"; filename=\"rtcu.csv\"\r\nContent-Type: text/csv\r\n\r\n\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"training_metadata\"\r\n\r\n{\"language\":\"en\",\"name\":\"RTCU\"}\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--",
CURLOPT_HTTPHEADER => array(
"Authorization: Basic 12345",
"cache-control: no-cache",
"content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
I've tried adding the "#" in front of the filename like suggested in other posts with no success. I haven't had this problem with other IBM Watson services and their cURL calls. What could be the issue?
Using CURLFile worked for me
$uploadFilePath = 'rtcu.csv';
$name = "RTCU";
$lang = "en";
$uploadFileMimeType = "text/csv";
$uploadFilePostKey = 'training_data';
$metaPostKey = "training_metadata";
$uploadFile = new CURLFile(
$uploadFilePath,
$uploadFileMimeType,
$uploadFilePostKey
);
$curlHandler = curl_init();
curl_setopt_array( $curlHandler, [
CURLOPT_URL => 'https://gateway.watsonplatform.net/natural-language-classifier/api/v1/classifiers',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => array(
"Authorization: Basic 12345",
"cache-control: no-cache"
),
CURLOPT_POSTFIELDS => [
$uploadFilePostKey => $uploadFile,
$metaPostKey => "{\"language\":\"{$lang}\",\"name\":\"{$name}\"}"
],
] );
$response = curl_exec( $curlHandler );
$err = curl_error( curlHandler );
curl_close( curlHandler );
if ( $err ) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
}

Redirect to specific page after form success

I'm a total beginner and I don't know how to redirect to specific page after from success :
if ( !empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
}
else{
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.sendinblue.com/v3/contacts",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => '{"email":"'.$email.'", "updateEnabled":true, "listIds":[8], "attributes" : {"NOM":"'.$nom.'", "NIVEAU":"'.$niveau.'", "OPT-IN_METHOD":"FORMULAIRE"}}',
CURLOPT_HTTPHEADER => array(
"accept: application/json",
"api-key: KEY ",
"content-type: application/json"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
}
$data['success'] = true;
$data['message'] = 'Success!';
}
echo json_encode($data);
}
I tried many solutions but I'm totally lost.
Thanks for your help

How to add php variable in json?

I want to send email using Sendinblue API in php.
I added some php variable in the email code, but the script is not working!
<?php
$email = "12345#gmail.com";
$username = "12345";
$html = "<h1>Hi!</h1>";
$subject = "Hello";
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.sendinblue.com/v3/smtp/email",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "{\"sender\":{\"name\":\"ABC\",\"email\":\"abc#abc.com\"},\"to\":[{\"email\":\".$email.\",\"name\":\".$username.\"}],\"bcc\":[{\"email\":\"admin#abc.com\",\"name\":\"Admin\"}],\"htmlContent\":\".$html.\",\"subject\":\".$subject.\"\"replyTo\":{\"email\":\"support#abc.com\",\"name\":\"Support\"}}",
CURLOPT_HTTPHEADER => array(
"accept: application/json",
"api-key: API-KEY", //hidden because of privacy reason
"content-type: application/json"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
?>
However, I receive this error message:
{"error":{"status":400,"message":"Input must be a valid JSON object","code":"bad_request"}}
Update
$email = "12345#gmail.com";
$username = "12345";
$html = "<h1>Hi!</h1>";
$subject = "Hello";
with
$arr = [
'email'=>"12345#gmail.com",
'username'=>"12345",
'html'=>"<h1>Hi!</h1>",
'subject'=>"Hello",
];
$postData = json_encode( $arr );
Put encode string in curl
CURLOPT_POSTFIELDS => $postData

ALM SaaS REST API 12.50 not working in PHP

I have tried below code in PHP to get the defect details from ALM but its not showing any response in browser. But the same is working in POSTMAN . Can someone help me here
Here is the document of REST API USAGE REST DOCUMENT FROM ALM
I have already tried existing posts from Stackoverflow
HP ALM REST API login using PHP CURL
ALM REST API v12.50 error 401
Nothing is helping so posted a new question
Note : Due to security purpose header value is kept as encoded value
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://hostname/qcbin/api/domains/domainname/projects/projectname/defects/?limit=10",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"authorization: Basic encoded value",
"cache-control: no-cache",
"postman-token: a8a2398d-7a0a-0ebd-a586-58a40e524a9a"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
?>
I have finally found the solution and below is the approach
First we need get to LWSSO_COOKIE_KEY,QCSession,ALM_USER,XSRF_TOKEN values from the ALM Authentication link then we should use the values for subsequent calls
Below is the complete working code to get the list of defects by entering ALM Credentials
<?php
$curl = curl_init();
Header('Content-type: application/json');
$credentials = "username:password";
curl_setopt_array($curl, array(
CURLOPT_URL => "https://host:port/qcbin/api/authentication/sign-in",
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HEADER => 1,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"authorization: Basic " . base64_encode($credentials) ,
"cache-control: no-cache"
) ,
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err)
{
echo "cURL Error #:" . $err;
}
else
{
// If there is no error then get the response to form the array of headers to get the different values required
$array_start = explode(';', $response);
foreach ($array_start as $key => $value) {
$remove_from_string = ['HTTP/1.1 200 OK','Path=/','HTTPOnly','HttpOnly','Content-Length',': 0'];
$replace_array = ['','','','','',''];
$value = str_replace($remove_from_string,$replace_array,$value);
$value = trim(preg_replace(('/Expires: [a-zA-Z]+, [0-9]+ [a-zA-Z]+ [0-9]+ [0-9]+:[0-9]+:[0-9]+ [a-zA-Z]+/'), '', $value));
$value = trim(preg_replace(('/Server: [a-zA-Z0-9.\(\)]+/'),'',$value));
if (!empty($value)) {
$almheaders[trim(explode('=',$value)[0])] = explode('=',$value)[1];
}
}
$LWSSO_COOKIE_KEY = $almheaders['Set-Cookie: LWSSO_COOKIE_KEY'];
$QCSession = $almheaders['Set-Cookie: QCSession'];
$ALM_USER = $almheaders['Set-Cookie: ALM_USER'];
$XSRF_TOKEN = $almheaders['Set-Cookie: XSRF-TOKEN'];
// Now form the Cookie value from the above values.
$cookie = "Cookie: JSESSIONID=33eyr1y736486zcnl0vtmo12;XSRF-TOKEN=$XSRF_TOKEN;QCSession=$QCSession;ALM_USER=$ALM_USER;LWSSO_COOKIE_KEY=$LWSSO_COOKIE_KEY";
// echo $cookie;
$curl = curl_init();
Header('Content-type: application/json');
curl_setopt_array($curl, array(
CURLOPT_URL => "https://host:port/qcbin/api/domains/CET_NTD/projects/BILLING_OPERATIONS/defects",
// CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HEADER => 0,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"authorization: Basic " . base64_encode($credentials) ,
"cache-control: no-cache",
"Accept: application/json",
$cookie
) ,
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err)
{
echo "cURL Error #:" . $err;
}
else
{
echo $response;
}
}
?>

Categories