how to convert command line curl to php curl - php

I need to convert this command line cURL into a php cURL and echo the result
curl -H "Content-Type: application/json" -d '{ "code":"<code>", "client_id": "<client_id>", "client_secret": "<client_secret>"}' https://www.example.com/oauth/access_token
how can this be done?

Try this simple approach:
$data = array("code"=>"123", "client_id"=> "123", "client_secret"=> "123");
$data_string = json_encode($data);
$ch = curl_init('https://www.example.com/oauth/access_token');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
Replace 123 with your values. Here is the manual for curl_setopt()

Something like this should work, assuming you need to POST the data to the URL:
<?php
// URL that the data will be POSTed to
$curl_url = 'https://www.example.com/oauth/access_token';
// Convert the data into an array
$curl_data_arr = array('{ "code":"<code>", "client_id": "<client_id>", "client_secret": "<client_secret>"}');
// Prepare to post as an array
$curl_post_fields = array();
foreach ($curl_data_arr as $key => $value) {
// Assuming you need the values url encoded, this is an easy way
$curl_post_fields[] = $key . '=' . urlencode($value);
}
$curl_header = array('Content-Type: application/json');
$curl_array = array(
CURLOPT_URL => $curl_url,
CURLOPT_HTTPHEADER => $curl_header,
CURLOPT_POSTFIELDS => implode('&', $curl_post_fields),
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
);
// Initialize cURL
$curl = curl_init();
// Tell cURL to use the array of options we just set up
curl_setopt_array($curl, $curl_array);
// Assign the result to $data
$data = curl_exec($curl);
// Empty variable (at first) to avoid errors being displayed
$result = '';
// Check for errors
if ($error = curl_error($curl)) {
// If there's an error, assign its value to $result
$result = $error;
}
curl_close($curl);
// If there's no errors...
if (empty($error)) {
// ... instead assign the value of $data to $result
$result = $data;
}
echo $result;

Related

Shopify GraphQL Error "Parse error on \":\" (COLON) at [2, 35]" With PHP

Greetings I have a problem with my GraphQL I don't know how to pass data to my GraphQL without getting
Error Message: "Parse error on ":" (COLON) at [2, 35]"
here is what I'm trying to pass product variant id data and get some response here is the example of what I'm trying to do and my function for graphql
$variantId = (isset($data->variantId) && !empty($data->variantId)) ? strip_tags($data->variantId) : "";
if(empty($variantId)){
$result['error'] = "Product id not specified!";
}
$query = array("query" => '{
productVariant(id: '. ($variantId) .') {
availableForSale
}
}');
$variants = shopify_gql_call($_SESSION['access_token'], $_SESSION['shop_name'], $query);
if( isset($variants['response']) && !empty($variants['response']) ){
$result[] = $variants['response'];
}else{
$result['error'] = "Variants not found!";
}
function shopify_gql_call($token, $shop, $query = array()) {
// Build URL
$url = "https://" . $shop . ".myshopify.com" . "/admin/api/".getenv('API_DATE')."/graphql.json";
// Configure cURL
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, TRUE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($curl, CURLOPT_MAXREDIRS, 3);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
// curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 3);
// curl_setopt($curl, CURLOPT_SSLVERSION, 3);
curl_setopt($curl, CURLOPT_USERAGENT, 'My New Shopify App v.1');
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
// Setup headers
$request_headers[] = "";
$request_headers[] = "Content-Type: application/json";
if (!is_null($token)) $request_headers[] = "X-Shopify-Access-Token: " . $token;
curl_setopt($curl, CURLOPT_HTTPHEADER, $request_headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($query));
curl_setopt($curl, CURLOPT_POST, true);
// Send request to Shopify and capture any errors
$response = curl_exec($curl);
$error_number = curl_errno($curl);
$error_message = curl_error($curl);
// Close cURL to be nice
curl_close($curl);
// Return an error is cURL has a problem
if ($error_number) {
return $error_message;
} else {
// No error, return Shopify's response by parsing out the body and the headers
$response = preg_split("/\r\n\r\n|\n\n|\r\r/", $response, 2);
// Convert headers into an array
$headers = array();
$header_data = explode("\n",$response[0]);
$headers['status'] = $header_data[0]; // Does not contain a key, have to explicitly set
array_shift($header_data); // Remove status, we've already set it above
foreach($header_data as $part) {
$h = explode(":", $part, 2);
$headers[trim($h[0])] = trim($h[1]);
}
// Return headers and Shopify's response
return array('headers' => $headers, 'response' => $response[1]);
}
}
I strongly suggest the use of https://packagist.org/packages/shopify/shopify-api instead of implementing your own function/http requests.
Your query should be something like this
query anynamehere($id: ID!){
productVariant(id:$id){
availableForSale
}
}
and then you submit the ID as part of another entry of the array, check the example below:
$query = [
"query" =>
'query anynamehere($id: ID!){
productVariant(id:$id){
availableForSale
}
}',
"variables" => [
'id' => $variantId
]
];
You should never concatenate the values as part of the query string (unless you want to deal with a lot of injection issues). Check more info about variables here https://graphql.org/learn/queries/

JSON write out with PHP [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 3 years ago.
I have a JSON message, and I dont know How can I write out a part of json.
I tried:
{{$data[0]->items[0]}}
{{$data[0]->name}}
{{$data->items[0]-name}}
{{$data[0]->items}}
ect...
JSON message:
{
"items":[
{
"name":"Knight",
"id":26000000,
"maxLevel":13,
"iconUrls":{
"medium":"https:\/\/api-assets.clashroyale.com\/cards\/300\/jAj1Q5rclXxU9kVImGqSJxa4wEMfEhvwNQ_4jiGUuqg.png"
}
},
{
"name":"Archers",
"id":26000001,
"maxLevel":13,
"iconUrls":{
"medium":"https:\/\/api-assets.clashroyale.com\/cards\/300\/W4Hmp8MTSdXANN8KdblbtHwtsbt0o749BbxNqmJYfA8.png"
}
}
]
}
EDIT:
This is the Controller
As you see $data array is decoded
It looks like your post is mostly code; please add some more details. omg
$token = "token";
$url = "https://api.clashroyale.com/v1/cards";
$ch = curl_init($url);
$headr = array();
$headr[] = "Accept: application/json";
$headr[] = "Authorization: Bearer ".$token;
curl_setopt($ch, CURLOPT_HTTPHEADER, $headr);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$res = curl_exec($ch);
$data = json_decode($res, true);
curl_close($ch);
return view('clash', ['data' => $data]);
First you have to decode your JSON-String to a PHP-Array and then you can access it easily this way:
$json = '{
"items":[
{
"name":"Knight",
"id":26000000,
"maxLevel":13,
"iconUrls":{
"medium":"https:\/\/api-assets.clashroyale.com\/cards\/300\/jAj1Q5rclXxU9kVImGqSJxa4wEMfEhvwNQ_4jiGUuqg.png"
}
},
{
"name":"Archers",
"id":26000001,
"maxLevel":13,
"iconUrls":{
"medium":"https:\/\/api-assets.clashroyale.com\/cards\/300\/W4Hmp8MTSdXANN8KdblbtHwtsbt0o749BbxNqmJYfA8.png"
}
},
{
"name":"Goblins",
"id":26000002,
"maxLevel":13,
"iconUrls":{
"medium":"https:\/\/api-assets.clashroyale.com\/cards\/300\/X_DQUye_OaS3QN6VC9CPw05Fit7wvSm3XegXIXKP--0.png"
}
},
{
"name":"Giant",
"id":26000003,
"maxLevel":11,
"iconUrls":{
"medium":"https:\/\/api-assets.clashroyale.com\/cards\/300\/Axr4ox5_b7edmLsoHxBX3vmgijAIibuF6RImTbqLlXE.png"
}
}
]
}';
$array = json_decode( $json, true ); // we receive an associative array because the second parameter is true
echo $array['items'][0]['name'];
echo $array['items'][1]['id'];
Usage in for example:
$token = "token";
$url = "https://api.clashroyale.com/v1/cards";
$ch = curl_init($url);
$headr = array();
$headr[] = "Accept: application/json";
$headr[] = "Authorization: Bearer ".$token;
curl_setopt($ch, CURLOPT_HTTPHEADER, $headr);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$res = curl_exec($ch);
$data = json_decode($res, true);
curl_close($ch);
echo $data['items'][0]['name']; // echo the value of the key 'name' of the first element in items
echo $data['items'][1]['id']; // echo the value of the key 'id' of the second element in items
// you can also store them or do whatever you want
return view('clash', ['data' => $data]);
Or access the data in your view like this:
{{ $data['items'][0]['name'] }}
{{ $data['items'][0]['id'] }}

pushcrew - send notification with PHP curl

This is the code:
$title = 'Du hast neue Nachricht';
$message = 'Besuch meine Website';
$url = 'https://www.bla.com';
$subscriberId = 'xxx51a002dec08a1690fcbe6e';
$apiToken = 'xxxe0b282d9c886456de0e294ad';
$curlUrl = 'https://pushcrew.com/api/v1/send/individual/';
//set POST variables
$fields = array(
'title' => $title,
'message' => $message,
'url' => $url,
'subscriber_id' => $subscriberId
);
$httpHeadersArray = Array();
$httpHeadersArray[] = 'Authorization: key='.$apiToken;
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $curlUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
curl_setopt($ch, CURLOPT_HTTPSHEADER, $httpHeadersArray);
//execute post
$result = curl_exec($ch);
$resultArray = json_decode($result, true);
if($resultArray['status'] == 'success') {
echo $resultArray['request_id']; //ID of Notification Request
}
else if($resultArray['status'] == 'failure')
{
echo 'fail';
}
else
{
echo 'dono';
}
echo '<pre>';
var_dump($result);
echo '</pre>';
And I get:
dono
string(36) "{"message":"You are not authorized"}"
And nothing in the console and no other errors. The apitoken is 100% correct. What could be the trouble here? Do I have to wait till pushcrew decide to allow my website or something?
Ignore this: I must add some more text to ask this question..
There is typo here:
curl_setopt($ch, CURLOPT_HTTPSHEADER, $httpHeadersArray);
Correct is with
CURLOPT_HTTPHEADER
(without the S)

Curl request with array values as input for query (GET) params

I have output from an array I would like to use as input in a PHP Curl request. Do I store them as another array and loop through the array with the Curl request?
Here is the output from the array:
foreach ($threadsarray['threads'] as $thread) {
print $thread['id']."<br />";
}
These are values I would like to use as input for Curl (obviously these values are different every time depending on the output for each loop above):
178369845
291476958
224408290
270960091
270715888
270513013
229639500
229630641
215503057
214314923
I want to execute a curl request for each of those thread id's...
Here is how I am building the Curl request:
$url2 = 'https://api.website.com/endpoint';
$data2 = array (
'specialkey' => '123abcd789xyz',
'anotherparam' => 'Brown',
'locale' => 'en-US',
'thread_id' => array (
$thread['id']
)
);
//build the query string because this is a get request
$params2 = '';
foreach($data2 as $key2=>$value2)
$params2 .= $key2.'='.$value2.'&';
$params2 = trim($params2, '&');
// Excecute the curl request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url2.'?'.$params2 );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 'false');
$mycurlresult = curl_exec($ch);
echo '<pre>';
$resultarray = json_decode($mycurlrequest, TRUE);
print_r($resultarray);
echo '</pre>';
if (FALSE === $mycurlrequest)
throw new Exception(curl_error($ch), curl_errno($ch));
I can't seem to build the request string correctly...what am I missing?
I can't really test this, but I'd suggest something like this. First, set up your curl, and create an array with an empty placeholder for thread_id.
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 'false');
$url2 = 'https://api.website.com/endpoint';
$data2 = array(
'specialkey' => '123abcd789xyz',
'anotherparam' => 'Brown',
'locale' => 'en-US',
'thread_id' => ''
);
Then loop over your array. For each item, replace the thread_id key in the $data2 parameters array with that item's id, build the query using http_build_query and execute the request.
foreach ($threadsarray['threads'] as $thread) {
$data2['thread_id'] = $thread['id']; // add the current id
$params2 = http_build_query($data2); // build the new query
curl_setopt($ch, CURLOPT_URL, $url2.'?'.$params2 );
$mycurlresult = curl_exec($ch);
echo '<pre>';
$resultarray = json_decode($mycurlrequest, TRUE);
print_r($resultarray);
echo '</pre>';
if (FALSE === $mycurlrequest)
throw new Exception(curl_error($ch), curl_errno($ch));
}

cURL not making requests in sequence

I have a custom function that uses cURL to make a request and then handle the response. I use it in a loop and the function itself works fine. But, when used inside of a loop, the function that is supposed to be executed first often doesn't. Seems like the sequence in which the posts are supposed to occur are totally neglected.
function InitializeCurl($url, $post, $post_data, $token, $form, $request) {
if($post) {
if($form) {
$default = array('Content-Type: multipart/form-data;');
} else {
$default = array('Content-Type: application/x-www-form-urlencoded; charset=utf-8');
}
} else {
$default = array('Content-Type: application/json; charset=utf-8');
}
// Add the authorization in the header if needed
if($token) {
$push = 'Authorization: Bearer '.$token;
array_push($default, $push);
}
$headers = array_merge($GLOBALS['basics'], $default);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.test.com/'.$url);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0);
if($request) {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $request);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if($post) {
if($form === false) {
$post_data = http_build_query($post_data);
}
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
}
$response = curl_exec($ch);
return $response;
}
// Define the token
$token = "sample_token";
$msg = array('msg_1', 'msg_2', 'msg_3', 'msg_4', 'msg_5', 'msg_6', 'msg_7', 'msg_8', 'msg_9', 'msg_10');
for($i=0;$i<count($msg);$i++) {
$post_data = array("content_type" => "text",
"body" => $msg[$i]);
$info = InitializeCurl("send_message/", true, $post_data, $token, false, false);
$decode = #json_decode($info, true);
}
The loop should make it so that each message is posted after one another in order. But, it's totally not. Would adding CURLOPT_TIMEOUT fix this?
Seems you are missing some code, but anyway, you would probably be better off using this CURL class, or rather classes:
http://semlabs.co.uk/journal/multi-threaded-stack-class-for-php
See examples. You will be returned a result with all the URLs. You can loop through to get details of the URL etc. like this:
$urls = array(
1 => 'http://seobook.com/',
2 => 'http://semlabs.co.uk/',
64 => 'http://yahoo.com/',
3 => 'http://usereffect.com/',
4 => 'http://seobythesea.com/',
5 => 'http://darkseoprogramming.com/',
6 => 'http://visitwales.co.uk/',
77 => 'http://saints-alive.co.uk/',
7 => 'http://iluvsa.blogspot.com/',
8 => 'http://sitelogic.co.uk/',
9 => 'http://tidybag.co.uk/',
10 => 'http://felaproject.net/',
99 => 'http://billhicks.com/'
);
$opts = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true
);
$hs = new CURLRequest();
$res = $hs->getThreaded( $urls, $opts, 5 );
foreach( $res as $r )
{
print_r( $r['info'] ); # prints out verbose info and data of URL etc.
print_r( $r['content'] ); # prints out the HTML response
}
But the result will be returned in sequence, so you can also identify the response by index.

Categories