JSON body in a CURL POST request in PHP - php

Working on a CURL Post to a restful backend service. Using RESTClient extension in Firefox I get my intended response.
So I have my Authorization, Accept, and Content-Type Headers set in CURL
$ch = curl_init();
curl_setopt_array(
$ch,
array(
CURLOPT_HTTPHEADER => array('User-Agent: Mozilla Firefox', 'Accept: application/json', 'Authorization: Basic v3iYdNlAcGxlKASocYkadkCSCIDpsdkFDJ='),
CURLOPT_URL => 'http://myurl.com/restfulservice/',
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $jsonpoststring,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPAUTH => CURLAUTH_BASIC | CURLAUTH_ANY,
CURLOPT_USERPWD => sprintf('%s;%s', 'foo#bar.com', 'somepassword'),
CURLOPT_SSL_VERIFYPEER => false
)
);
$output = curl_exec($ch);
curl_close($ch);
In RESTClient I have this JSON in the Body
{"authentication":{"identification":{"identstring":"foo#bar.com","identId":1},"security":{"securestring":"Password1", "secureId":3}},"externIdent":{"externAuth":{"hashauth":"K3DvhinSb7H","district":"iad"}}}
My question is: How to include that body in the PHP Curl request.

Pass it in postfields
jsonpoststring='{"authentication":{"identification":{"identstring":"foo#bar.com","identId":1},"security":{"securestring":"Password1", "secureId":3}},"externIdent":{"externAuth":{"hashauth":"K3DvhinSb7H","district":"iad"}}}
';
$ch = curl_init();
curl_setopt_array(
$ch,
array(
CURLOPT_HTTPHEADER => array('User-Agent: Mozilla Firefox', 'Accept: application/json', 'Authorization: Basic v3iYdNlAcGxlKASocYkadkCSCIDpsdkFDJ='),
CURLOPT_URL => 'http://myurl.com/restfulservice/',
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $jsonpoststring,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPAUTH => CURLAUTH_BASIC | CURLAUTH_ANY,
CURLOPT_USERPWD => sprintf('%s;%s', 'foo#bar.com', 'somepassword'),
CURLOPT_SSL_VERIFYPEER => false
)
);
$output = curl_exec($ch);
curl_close($ch);

This should do the trick
$data = json_decode('{"authentication":{"identification":{"identstring":"foo#bar.com","identId":1},"security":{"securestring":"Password1", "secureId":3}},"externIdent":{"externAuth":{"hashauth":"K3DvhinSb7H","district":"iad"}}}');
$ch = curl_init();
curl_setopt_array(
$ch,
array(
CURLOPT_HTTPHEADER => array('User-Agent: Mozilla Firefox', 'Accept: application/json', 'Authorization: Basic v3iYdNlAcGxlKASocYkadkCSCIDpsdkFDJ='),
CURLOPT_URL => 'http://myurl.com/restfulservice/',
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $data,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPAUTH => CURLAUTH_BASIC | CURLAUTH_ANY,
CURLOPT_USERPWD => sprintf('%s;%s', 'foo#bar.com', 'somepassword'),
CURLOPT_SSL_VERIFYPEER => false
)
);
$output = curl_exec

Related

How to get OAuth 2.0 using PHP curl with client credentials as grant_type?

What I have been trying:
$header = array(
"Authorization :Basic $authorization",
"Content-Type: application/json"
);
//option 1
$param='{
"grant_type" : "client_credentials"
}';
//option 2
$param = array("Grant_type: client_credentials",);
//option 3
$param = "grant_type=client_credentials";
//option 4
$a = array(
'grant_type' => 'client_credentials');
$param = http_build_query($a);
$ch = curl_init( $url );
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_POSTFIELDS,$param);
curl_setopt($ch,CURLOPT_VERBOSE, true);
curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,120);
curl_setopt($ch,CURLOPT_TIMEOUT,120);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_HTTPHEADER,$header);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);
$content = curl_exec( $ch );
$err = curl_error($ch);
curl_close( $ch );
I already tried all the option above, but keep getting error like this:
response_type or grant_type is required
How to pass grant_type in curl concept? Or is it me who using it wrongly?
Found answer from this link https://auth0.com/docs/api-auth/tutorials/client-credentials
Need to add this following line tho:
CURLOPT_SSL_VERIFYHOST =>false,
CURLOPT_SSL_VERIFYPEER => false,
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://xxy",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYHOST =>false,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET",
CURLOPT_HTTPHEADER => array(
"content-type: application/x-www-form-urlencoded"
),
));

How to correctly output specific cURL response from POST request

I'm running a cURL post request that is appearing to hit the url and return a response. However, I'm led to believe that I'm not handling the request output properly and it's throwing an error that I don't understand. I'm extremely new to cURL and if anyone could point me in the right direction, I'd appreciate it.
$curl = curl_init();
$headers = array(
'Content-Type: application/json',
'X-Requested-With: XMLHttpRequest',
);
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'XXX',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => [
client_id => 'XXX',
client_secret => 'XXX',
member_id => 'XXX'
],
CURLOPT_HTTPHEADER => $headers,
CURLOPT_HTTPAUTH => CURLAUTH_BASIC
]);
$resp = curl_exec($curl);
curl_close($curl);
var_dump(json_decode($resp, true));
This results in the errors that follows:
{"errors":{"":["Input string '--------------------------cec6101ba64bcb7f' is not a valid number. Path '', line 1, position 42."]},"title":"One or more validation errors occurred.","status":400,"traceId":"80031695-0002-ef00-b63f-84710c7967bb"}
$curl = curl_init();
$headers = array(
'Content-Type: application/json',
'X-Requested-With: XMLHttpRequest',
);
//////
Adding this and using json_encode allowed for the request to be properly sent with the required id's and secret tokens.
//////
$data = array(
"ClientId" => "$api_clientId" ,
"ClientSecret" => "$api_clientSecret",
"MemberId" => "$api_memberId"
);
$data_string = json_encode($data);
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://cors-anywhere.herokuapp.com/https://staging.micromerchantsystems.com/authenticationservice/api/GateKeeper/createtoken',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $data_string,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_HTTPAUTH => CURLAUTH_BASIC
]);
$resp = curl_exec($curl);
curl_close($curl);
var_dump(json_decode($resp, true));

Get all cookies from a page using cURL PHP

I'm trying to access a page using PHP's cURL, this page is to return 2 cookies in the "Response Headers", but in the cURL header only returns the first one.
Does anyone know if there might be some block on the page, and how to work around this problem?
This cookie is generated on a "Status Code: 302"
I've already tried to get "file_get_contents" and also tried to do the
"CURLOPT_HEADERFUNCTION" function and I also know success
OBS: The function to break the google captcha is already working.
$url = 'https://pje.trt15.jus.br/captcha/login_post.php';
$post = [
'g-recaptcha-response' => $g_response,
'referer' => '/consultaprocessual/pages/consultas/ConsultaProcessual.seam',
'random' => $g_captcha_random,
'entrar' => $g_captcha_entrar
];
if( $g_captcha_enviar != null )
$post[$g_captcha_enviar] = 'Enviar';
if( $g_captcha_entrar != null )
$post['entrar'] = $g_captcha_entrar;
$post_http = http_build_query($post);
$headers = [
':authority: pje.trt15.jus.br',
':method: POST',
':path: /captcha/login_post.php',
':scheme: https',
'accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
//'accept-encoding: gzip, deflate, br',
'accept-language: pt-BR,pt;q=0.9,en-US;q=0.8,en;q=0.7',
'cache-control: no-cache',
'content-length: ' . strlen($post_http),
'content-type: application/x-www-form-urlencoded',
'cookie: '.$cookie_captchasess.' _ga=GA1.3.1830456077.1560269951; _gid=GA1.3.249690674.1560269951',
'origin: https://pje.trt15.jus.br',
'referer: https://pje.trt15.jus.br/consultaprocessual/pages/consultas/ConsultaProcessual.seam',
'upgrade-insecure-requests: 1'
];
$options = [
CURLOPT_COOKIESESSION => true,
CURLOPT_HEADER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $post_http,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_COOKIE => $cookie_captchasess,
CURLOPT_FRESH_CONNECT => true,
CURLOPT_VERBOSE => true,
CURLOPT_REDIR_PROTOCOLS => CURLPROTO_HTTPS,
CURLOPT_ENCODING => 'gzip, deflate',
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_AUTOREFERER => true,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_TIMEOUT => 40,
CURLOPT_USERAGENT => $user_agent,
];
$ch = curl_init();
curl_setopt_array($ch, $options);
$resp = curl_exec($ch);
curl_close($ch);
echo "<pre>";
echo $resp;

add basic authorization to php curl script

How do I add basic authorization to my below php script? I am trying to send data to an API
$ch = curl_init();
$token = 'eyJpZCI6MTExOCwiZW52IXXXXXXXXJzaWQiOjYsImFsZyI6IkhTMjU2In0.eyJzdWIiOiJhZG1pbkBtaW5leDXXXXXXXTAsImV4cCI6MTU0ODk0ODgxMH0.owTm-ItzXnpqVSFbXXXXXXXXXX';
$authorization = "Authorization: Bearer ".$token; // Prepare the authorisation token
$curlConfig = array(
CURLOPT_URL => "https://api.endpoint.com",
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => array(
'From' => 'HI',
'To' => '024XXXXXXX',
'Content' => 'hello there'
)
);
curl_setopt_array($ch, $curlConfig);
$result = curl_exec($ch);
curl_close($ch);
echo $result
I guess this will work (I'm not sure, as I never used Authorization)...
$ch = curl_init();
$token = 'eyJpZCI6MTExOCwiZW52IXXXXXXXXJzaWQiOjYsImFsZyI6IkhTMjU2In0.eyJzdWIiOiJhZG1pbkBtaW5leDXXXXXXXTAsImV4cCI6MTU0ODk0ODgxMH0.owTm-ItzXnpqVSFbXXXXXXXXXX';
$curlConfig = array(
CURLOPT_URL => "https://api.endpoint.com",
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => array(
'From' => 'HI',
'To' => '024XXXXXXX',
'Content' => 'hello there'
)
);
curl_setopt_array($ch, $curlConfig);
$result = curl_exec($ch);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Authorization: Bearer ".$token
));
curl_close($ch);
echo $result
That's it?

how to get cookie value from curl response in php

I am calling this API by curl:
$url = '/api/auth/login';
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "{\"fbUserID\": \"$fbID\", \"fbAccessToken\": \"$Token\"}",
CURLOPT_HTTPHEADER => array(
"accept: application/json",
"cache-control: no-cache",
"content-type: application/json"
),
));
$response = curl_exec($curl);
$jsonresult = json_decode($response);
$err = curl_error($curl);
My question is how can I get the cookie value in response header, I am testing call in POSTMAN API so I am getting cookie value.
Can you please help?
Add this code segment
$cookie=dirname(__FILE__)."/cookie.txt";
curl_setopt ($curl, CURLOPT_COOKIEJAR, $cookie);
curl_setopt ($curl, CURLOPT_COOKIEFILE, $cookie);
It will look like this finally
$cookie=dirname(__FILE__)."/cookie.txt";
$url = '/api/auth/login';
$curl = curl_init();
curl_setopt_array($curl,
array( CURLOPT_URL => $url
, CURLOPT_COOKIEJAR => $cookie
, CURLOPT_COOKIEFILE => $cookie
, CURLOPT_RETURNTRANSFER => true
, CURLOPT_ENCODING => ""
, CURLOPT_MAXREDIRS => 10
, CURLOPT_TIMEOUT => 30
, CURLOPT_CUSTOMREQUEST => "POST"
, CURLOPT_POSTFIELDS => "{\"fbUserID\": \"$fbID\", \"fbAccessToken\": \"$Token\"}"
,CURLOPT_HTTPHEADER => array(
"accept: application/json",
"cache-control: no-cache",
"content-type: application/json"
),
));
$response = curl_exec($curl);
$jsonresult = json_decode($response);
$err = curl_error($curl);

Categories