CURL is not returning correct response when json data is passed through variable - php-curl

$data is the variable holding json string {"clientId":"MyClientID","clientSecret":"MyClientSecret","script":"<?php\n echo \"Welcome to GLB Coding Club\";\n?>\n","stdin":"","language":"php","versionIndex":"2"}.
as you can see in the first line below. I have encoded array into json using json_encode()
$data = json_encode(array("clientId"=>"MyClientID","clientSecret"=>"MyClientSecret","script"=> $this->input->post("script",true),"stdin"=>$this->input->post("stdin",true),"language"=>$this->input->post("language",true),"versionIndex"=>$this->input->post("versionIndex",true)));
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.jdoodle.com/v1/execute",
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,
CURLOPT_HTTPHEADER => array("cache-control: no-cache","content-type: application/json"),
CURLOPT_SSL_VERIFYPEER => false
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
}
else {
echo $response;
}
jdoodle is not returning correct $response instead returning the statements that were given to execute. But if I replace $data by actual json string {"clientId":"MyClientID","clientSecret":"MyClientSecret","script":"<?php\n echo \"Welcome to GLB Coding Club\";\n?>\n","stdin":"","language":"php","versionIndex":"2"} at CURLOPT_POSTFIELDS => $data then jdoodle is returning correct $response.

Then, simply
json_encode(array("clientId"=>"MyClientID","clientSecret"=>"MyClientSecret","script"=> $this->input->post("script",true),"stdin"=>$this->input->post("stdin",true),"language"=>$this->input->post("language",true),"versionIndex"=>$this->input->post("versionIndex",true)))
is not producing the $data string that you expect and that gives correct response:
'{"clientId":"MyClientID","clientSecret":"MyClientSecret","script":"<?php\n echo \"Welcome to GLB Coding Club\";\n?>\n","stdin":"","language":"php","versionIndex":"2"}'
Just
echo $data;
exit(0);
after the first line and check what is wrong when forming the $data string

I simply edited $this->input->post("script",true) to html_entity_decode($this->input->post("script",true)).

Related

How to sending many POST requests with cURL faster

I have code to active various gaming platforms for player, the code is working well but it runs very slowly. How can I make it better and run faster?
<?php
$_SESSION['username'] = "demo123";
$password = "pass123";
$prefix = "HAN";
$gmusername = $prefix.$_SESSION['username'];
$gmpassword = $password;
$apikey = "SEFOQVBJOjEyMzQ1Njc4";
/////// WM ///////
$params = ['username' => $gmusername];
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.gmaster8.com/WM/player/active",
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $params,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array(
"Authorization: Basic $apikey"
) ,
CURLOPT_USERPWD => "$gmusername:$gmpassword",
));
curl_exec($curl);
/////// EVOLUTION ///////
$params = ['username' => $gmusername];
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.gmaster8.com/EVOLUTION/player/active",
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $params,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array(
"Authorization: Basic $apikey"
) ,
CURLOPT_USERPWD => "$gmusername:$gmpassword",
));
curl_exec($curl);
/////// IBC ///////
$params = ['username' => $gmusername];
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.gmaster8.com/IBC/player/active",
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $params,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array(
"Authorization: Basic $apikey"
) ,
CURLOPT_USERPWD => "$gmusername:$gmpassword",
));
curl_exec($curl);
////// and there are more than 20 other platforms need to be actived like that
?>
Is there any solution better to active many platforms? My code above is running without error but it takes too much time loading for player when registering and activing permision to access among gaming platforms.

PHP cURL as DELETE using POSTFIELDS

In my case the user is logged in and would like to delete his account.
Therfore he triggers a POST form, revalidating the process with a confirmation of his password.
Now I would like to send a cURL DELETE to the api/server and at the same time deliver the confirmed password as well.
My approach is:
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => "https://www.myurl.com/v1/users",
CURLOPT_USERAGENT => $_SERVER['HTTP_USER_AGENT],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => json_encode(['cnfpwd' => $_POST['cnfpwd']]), //confirmed password
CURLOPT_HTTPHEADER => array('X-API-KEY: '$apiKey),
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "DELETE",
));
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response, true);
//For testing purposes only
print_r($response);
print_r($data);
If this approach is correct, how would I get the POSTFIELDS on the API/server side?
As this is a DELETE request, $_GET, $_POST, $_REQUEST are empty.
EDIT:
The api code for testing purposes:
<?php
if($_SERVER['REQUEST_METHOD'] == "DELETE"){
echo"POST: ";print_r($_POST);
}
?>
The result is:
POST: Array ( )
You should be able to get the body of the request with
$data = file_get_contents('php://input');
My final solution is:
$parameters = file_get_contents("php://input");
$parameters = json_decode($parameters, true);
#Paolos Solution is correct, I just needed to add the second line in order to access the parameters as an Array.

Coinimp http api withdraw

I'm trying to write the whole for coinimp a payout for the api v2.0. Unfortunately, I always get back only one empty issue.
maybe one of you can help me and tell you what the problem is here.
$fields = array(
"site-key" => 'c085da9be5ba47309d3805b3fe0e0e66adcda4f6f5041e8e6d21d6bd2abc60ce',
"user" => $this->user,
"amount" => $this->KontoExtern
);
$fields_string = '';
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, 'http://www.coinimp.com/api/v2/user/withdraw');
curl_setopt($ch,CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
$headers = array();
$headers[] = self::X_API_ID;
$headers[] = self::X_API_KEY;
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$ausgabe = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
echo 'Ausgabe:'.$ausgabe.'<br>';
curl_close ($ch);
$aus = json_decode($ausgabe);
return $aus;
can someone help me here and say where the problem lies?
the coinIMP API documentation realy is a mess i found this on stackoverflow and it works
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://www.coinimp.com/api/v2/user/balance?site-key=WEBSITE-ID&user=USER-ID",
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(
"cache-control: no-cache",
"x-api-id: PUBLIC-ID",
"x-api-key: SECRET-ID"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
?>
this code is easy to edit to make it work for you !!
change CURLOPT_URL value to: http://www.coinimp.com/api/v2/user/withdraw
change CURLOPT_CUSTOMREQUEST => "GET" to "POST"
Add CURLOPT_POST => 2 to the curl_setopt_array
Add CURLOPT_POSTFIELDS =>""site-key=value&user=value&amount=value
i know this isn't a direct answer to your qluestion but anyway it works :)
note: this will withdrawl Webchain, i haven't tryt Monero jet

Bigcommerce php api returning null on initial app install

I'm trying to do initial install of a BigCommerce draft app for oAuth access to api using the official Bigcommerce php library.
For some reason no matter what I do I get null back from a post to BigCommerce api. Can anyone see anything that could be causing this?
Thanks for any advice
<?php
require_once ('vendor/autoload.php');
use Bigcommerce\Api\Connection as Connection;
use Bigcommerce\Api\Client as Bigcommerce;
error_reporting(E_ALL);
ini_set('display_errors', 'on');
$client_id = "*******";
$client_secret = "*******";
if (count($_GET)) {
$code = $_GET['code'];
$context = $_GET['context'];
$scope = $_GET['scope'];
$url = "https://login.bigcommerce.com/oauth2/token";
$connection = new Connection();
$connection->useUrlencoded();
$connection->verifyPeer(false);
$response = $connection->post($url, array(
"client_id" => $client_id,
"client_secret" => $client_secret,
"redirect_uri" => "https://www.*******.com/bc-auth.php",
"grant_type" => "authorization_code",
"code" => $code,
"scope" => $scope,
"context" => $context));
if (is_null($response)) {
print "Last Error:\n";
print "<pre>";
print_r(Bigcommerce::getLastError());
print "</pre>";
exit();
}
$token = $response->access_token;
die($token); // this is just for testing
}
Try making your own POST request via cURL, papi..
// Prepare POST Data:
$postFields = array(
'client_id' => urlencode($client_id),
'client_secret' => urlencode($client_secret),
'code' => urlencode($code),
'scope' => urlencode($scope),
'grant_type' => urlencode('authorization_code'),
'redirect_uri' => urlencode("https://www.*******.com/bc-auth.php"),
'context' => urlencode($context)
);
// Format data for Post:
$fields_string = '';
foreach($postFields as $key=>$value) {
$fields_string .= $key.'='.$value.'&';
}
rtrim($fields_string, '&');
$postFields = $fields_string; // Single URL string of post fields
unset($fields_string);
// ** Curl Config **//
$ch = curl_init(); //open connection
curl_setopt($ch, CURLOPT_URL, "https://login.bigcommerce.com/oauth2/token");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = json_decode(curl_exec($ch)); // execute post! & assign response
curl_close($ch); // close connection
Removing and inserting it instead of this code:
$connection = new Connection();
$connection->useUrlencoded();
$connection->verifyPeer(false);
$response = $connection->post($url, array(
"client_id" => $client_id,
"client_secret" => $client_secret,
"redirect_uri" => "https://www.*******.com/bc-auth.php",
"grant_type" => "authorization_code",
"code" => $code,
"scope" => $scope,
"context" => $context));

Unsupported content with type: multipart/form-data in google plus api oauth2

I am trying to sign in with google plus Api in my web app.
I searched on it from https://developers.google.com/oauthplayground/https://developers.google.com/oauthplayground/
and I applied them.
When I request to https://www.googleapis.com/oauth2/v3/token , it returns
{ "error": "internal_failure", "error_description": "Unsupported content with type: multipart/form-data; boundary=----------------------------5dd1639f2986" }
I am putting my code snippets which are doing the request (as client id and secret as star)
I dont understand it, maybe you can help.
if(isset($_GET['code'])) {
// try to get an access token
$code = $_GET['code'];
$url = 'https://www.googleapis.com/oauth2/v3/token';
$params = array(
"code" => $code,
"client_id" => "************************",
"client_secret" => "************************",
"redirect_uri" => "http://localhost/googleplus/oauth2callback.php",
"grant_type" => "authorization_code"
);
$json=CallAPI('POST',$url,$params);
and my CALLAPI function
function CallAPI($method, $url, $data = false)
{
$curl = curl_init();
switch ($method)
{
case "POST":
curl_setopt($curl, CURLOPT_POST, 1);
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PUT":
curl_setopt($curl, CURLOPT_PUT, 1);
break;
default:
if ($data){
$url = sprintf("%s?%s", $url, http_build_query($data));
echo $url;
}
}
// Optional Authentication:
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "username:password");
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
You request is correct but missing something
the content type is not multipart/form-data should be application/x-www-form-urlencoded instead
I had very similar problem using OAuth2.0 to access Gmail from iOS app. Indeed Ahmad's suggestion is correct I'll expand it:
When you POST using HTTP there is a header field 'Content-Type:'. Looks like in your case it had default value of 'multipart/form-data' which is for binary data. For Google API OAuth2.0 make sure you set it to 'application/x-www-form-urlencoded'.
You can see this value in the example given here:
https://developers.google.com/identity/protocols/OAuth2InstalledApp#handlingtheresponse
You can read more about those two values for 'Content-Type' here:
application/x-www-form-urlencoded or multipart/form-data?
In my iOS framework I had to make a call to customize this HTTP header. Unfortunately I'm not familiar with PHP so hope that helps.
I had a very similar problem. I was finally able to resolve it by adding some elements to the HTTP header ("Content-Type" and "Content-Length") and manually constructing the url (so I can use 0 for "Content-Length").
$id_token = $_POST['id_token'];
$url = 'https://www.googleapis.com/oauth2/v3/tokeninfo?id_token='.$id_token;
$options = [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_HTTPHEADER => array( "Content-Length: 0", "Content-Type: application/x-www-form-urlencoded"),
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_SSL_VERIFYPEER => false,
];
$curlObj = curl_init();
curl_setopt_array($curlObj, $options);
$returnData = curl_exec($curlObj);
if (curl_errno($curlObj)) {
//error message
$returnData = curl_error($curlObj);
}
echo $returnData;
if(isset($_REQUEST['code'])){
$ch =curl_init();
$auth_url = "https://www.googleapis.com/oauth2/v4/token";
$post = array(
'code' =>$_REQUEST['code'],
'client_id' => '**************',
'client_secret' => '************',
'redirect_uri' => 'http://localhost/prakash/redirect.php',
'grant_type' => 'authorization_code'
);
$postText = http_build_query($post);
$options = array(
CURLOPT_URL =>$auth_url,
CURLOPT_POST => true,
CURLOPT_SSL_VERIFYPEER =>false,
CURLOPT_RETURNTRANSFER =>true,
CURLOPT_POSTFIELDS => $postText
);
//print_r($ch);
curl_setopt_array($ch, $options);
$returnData = curl_exec($ch);
print_r($returnData);
curl_close($ch);
exit;
}else{
print_r($_REQUEST);
exit;
}