Pass whole incoming data to curl - Laravel - php

I wanted to pass the whole incoming data (that is, $request) to the curl not wanted to post to a particular field in the endpoint as subjectId=>1 as am running this curl request for different endPoint everytime. The below curl request will work if CURLOPT_URL => $url . $subjectId, was given. As my input changes for every end point, i've to pass everything that comes in the input to the curl , i can't pass it as an arary $subjectId. Is there any way to do this?
Currently, dd($Response); returns null
Am giving a postman input like this:
{
"subjectId":"1"
}
Curl
public function getContentqApiPost(Request $request)
{
$token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.ey";
$headers = [
"Accept: application/json",
"Authorization: Bearer " . $token
];
$url="http://127.0.0.1:9000/api/courses/course-per-subject";
$subjectId = "?subjectId=$request->subjectId";
$ch = curl_init();
$curlConfig = array(
// CURLOPT_URL => $url . $subjectId,
CURLOPT_URL => $url . $request,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $headers,
);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt_array($ch, $curlConfig);
$result = trim(curl_exec($ch));
$Response = json_decode($result, true);
if (curl_errno($ch)) {
$error_msg = curl_error($ch);
echo $error_msg;
}
curl_close($ch);
return $Response;
}

If you would like to pass all params of $request to curl:
$queryParams = '';
$delimeter = '?';
foreach($request->all() as $k => $v){
$queryParams .= "$delimeter$k=$v";
$delimeter = '&';
}
Also You can only pass the params you want:
foreach($request->only(['subjectId']) as $k => $v){
// code here
}
Finally you have:
CURLOPT_URL => $url . $queryParams,

Answer
Assuming you want to pass the entire GET query string as-is:
$query_string = str_replace($request->url(), "", $request->fullUrl());
$url = "http://localhost:9000/api/courses/course-per-subject" . $query_string;
This works because $request->url() returns the URL without the query string parameters, while $request->fullUrl() returns the URL with all the query string parameters, so we can use str_replace with an empty replacement to remove the non-query part. Note that $query_string will already start with a ? so there is no need to add that yourself.
Other suggestions
Unless your Laravel API is a 1:1 copy of the backend API, I strongly suggest writing a class that interfaces with the backend API, then provide it to your Laravel controllers using dependency injection. E.g.
class CourseCatalogApi {
public function getSubjectsInCourse(String $course){
... // your curl code here
}
}
Finally, since you are already using Laravel, there is no need to write such low level code using curl to make HTTP requests. Consider using guzzlehttp, which is already a dependency of Laravel.

Related

Coinmarketcap API Call with PHP

I tried my first API call but something is still wrong. I added my API-Key, choose the symbol and tried to echo the price. But it is still not valid. But my echo is still 0. Maybe someone show me what i did wrong. Thank you!
<?php
$coinfeed_coingecko_json = file_get_contents('https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?symbol=ETH');
$parameters = [
'start' => '1',
'limit' => '2000',
'convert' => 'USD'
];
$headers = [
'Accepts: application/json',
'X-CMC_PRO_API_KEY: XXX'
];
$qs = http_build_query($parameters); // query string encode the parameters
$request = "{$url}?{$qs}"; // create the request URL
$curl = curl_init(); // Get cURL resource
// Set cURL options
curl_setopt_array($curl, array(
CURLOPT_URL => $request, // set the request URL
CURLOPT_HTTPHEADER => $headers, // set the headers
CURLOPT_RETURNTRANSFER => 1 // ask for raw response instead of bool
));
$response = curl_exec($curl); // Send the request, save the response
print_r(json_decode($response)); // print json decoded response
curl_close($curl); // Close request
$coinfeed_json = json_decode($coinfeed_coingecko_json, false);
$coinfeedprice_current_price = $coinfeed_json->data->{'1'}->quote->USD->price;
?>
<?php echo $coinfeedde = number_format($coinfeedprice_current_price, 2, '.', ''); ?>
API Doc: https://coinmarketcap.com/api/v1/#operation/getV1CryptocurrencyListingsLatest
There is a lot going on in your code.
First of all $url was not defined
Second of all you made two requests, one of which I have removed
Third; you can access the json object by $json->data[0]->quote->USD->price
Fourth; I removed the invalid request params
I have changed a few things to make it work:
$url = "https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest";
$headers = [
'Accepts: application/json',
'X-CMC_PRO_API_KEY: ___YOUR_API_KEY_HERE___'
];
$request = "{$url}"; // create the request URL
$curl = curl_init(); // Get cURL resource
// Set cURL options
curl_setopt_array($curl, array(
CURLOPT_URL => $request, // set the request URL
CURLOPT_HTTPHEADER => $headers, // set the headers
CURLOPT_RETURNTRANSFER => 1 // ask for raw response instead of bool
));
$response = curl_exec($curl); // Send the request, save the response
$json = json_decode($response);
curl_close($curl); // Close request
var_dump($json->data[0]->quote->USD->price);
var_dump($json->data[1]->quote->USD->price);

Consuming cURL in restful codeigniter

In native PHP, I have a consuming restful server like this:
$url = "http://localhost/pln/api/json?rayon=$rayon&id_pel=$id_pel&nama=$nama";
$client = curl_init($url);
curl_setopt($client,CURLOPT_RETURNTRANSFER,true);
$respone = curl_exec($client);
$result = json_decode($respone);
How can I access cURL like this when using CodeIgniter?
There's no active cURL library around for CodeIgniter 3.x. There were one for CI 2.x which is no longer maintained.
Consider using Guzzle which is very popular and considered as a de-facto HTTP interfacing library for PHP. Here's an usage example from the docs:
$client = new GuzzleHttp\Client();
$res = $client->request('GET', 'https://api.github.com/user', [
'auth' => ['user', 'pass']
]);
echo $res->getStatusCode();
// "200"
echo $res->getHeader('content-type');
// 'application/json; charset=utf8'
echo $res->getBody();
// {"type":"User"...'
I also recommend using Requests which is inspired by Python Requests module and is way more easier than Guzzle to get started with:
$headers = array('Accept' => 'application/json');
$options = array('auth' => array('user', 'pass'));
$request = Requests::get('https://api.github.com/gists', $headers, $options);
var_dump($request->status_code);
// int(200)
var_dump($request->headers['content-type']);
// string(31) "application/json; charset=utf-8"
var_dump($request->body);
// string(26891) "[...]"
As CodeIgniter 3.x has support for Composer packages out of the box, you can easily install one of these packages through composer and start using it right away.
I stongly recommend you to not to go down the "Download Script" way as suggested in Manthan Dave's answer. Composer provides PHP with a sophisticated dependency management ecosystem; Utilize that! "Download This Script" dog days are over for good.
I used the following function in codeigniter for curl url and works fine, try it out:
function request($auth, $url, $http_method = NULL, $data = NULL) {
//check to see if we have curl installed on the server
if (!extension_loaded('curl')) {
//no curl
throw new Exception('The cURL extension is required', 0);
}
//init the curl request
//via endpoint to curl
$req = curl_init($url);
//set request headers
curl_setopt($req, CURLOPT_HTTPHEADER, array(
'Authorization: Basic ' . $auth,
'Accept: application/xml',
'Content-Type: application/x-www-form-urlencoded',
));
//set other curl options
curl_setopt($req, CURLOPT_RETURNTRANSFER, true);
curl_setopt($req, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($req, CURLOPT_TIMEOUT, 30);
//set http method
//default to GET if data is null
//default to POST if data is not null
if (is_null($http_method)) {
if (is_null($data)) {
$http_method = 'GET';
} else {
$http_method = 'POST';
}
}
//set http method in curl
curl_setopt($req, CURLOPT_CUSTOMREQUEST, $http_method);
//make sure incoming payload is good to go, set it
if (!is_null($data)) {
if (is_array($data)) {
$raw = http_build_query($data);
} else {
//Incase of raw xml
$raw = $data;
}
curl_setopt($req, CURLOPT_POSTFIELDS, $raw);
}
//execute curl request
$raw = curl_exec($req);
if (false === $raw) { //make sure we got something back
throw new Exception(curl_error($req) . $url, -curl_errno($req));
}
//decode the result
$res = json_decode($raw);
if (is_null($res)) { //make sure the result is good to go
throw new Exception('Unexpected response format' . $url, 0);
}
return $res;
}
You could use default Curl library of codeigniter:
$this->load->library('curl');
$result = $this->curl->simple_get('http://example.com/');
var_dump($result);
For more details refer this link :
https://www.formget.com/curl-library-codeigniter/
Adding to #sepehr answer. Requests library can be configured in a very easy way in codeigniter as described here
https://stackoverflow.com/a/46062566/2472685

YQL : Getting unsupported http protocol error

When i'm trying to invoke the YQL via cURL i'm getting the following error.
HTTP Version Not Supported
Description: The web server "engine1.yql.vip.bf1.yahoo.com" is using an unsupported version of the HTTP protocol.
Following is the code used
// URL
$URL = "https://query.yahooapis.com/v1/public/yql?q=select * from html where url=\"http://www.infibeam.com/Books/search?q=9788179917558\" and xpath=\"//span[#class='infiPrice amount price']/text()\"&format=json";
// set url
curl_setopt($ch, CURLOPT_URL, $URL);
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
echo $output;
?>
Invoking the same URL from thr browser works fine
https://query.yahooapis.com/v1/public/yql?q=select * from html where
url="http://www.infibeam.com/Books/search?q=9788179917558" and
xpath="//span[#class='infiPrice amount price']/text()"&format=json
Can someone please point me what is wrong in the code?
The problem is probably caused because the url you feed to cURL is not valid. You need to prepare / encode the individual values of the query strings for use in a url.
You can do that using urlencode():
$q = urlencode("select * from html where url=\"http://www.infibeam.com/Books/search?q=9788179917558\" and xpath=\"//span[#class='infiPrice amount price']/text()\"");
$URL = "https://query.yahooapis.com/v1/public/yql?q={$q}&format=json";
In this case I have only encoded the value of q as the format does not contain characters that you cannot use in a url, but normally you'd do that for any value you don't know or control.
Okay I gottacha .. The problem was with the https. Used the following snippet for debug
if (false === ($data = curl_exec($ch))) {
die("Eek! Curl error! " . curl_error($ch));
}
Added below code to accept SSL certificates by default.
$options = array(CURLOPT_URL => $URL,
CURLOPT_HEADER => "Content-Type:text/xml",
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_RETURNTRANSFER => TRUE
);
Complete code is here
<?php
// create curl resource
$ch = curl_init();
// URL
$q = urlencode("select * from html where url=\"http://www.infibeam.com/Books/search?q=9788179917558\" and xpath=\"//span[#class='infiPrice amount price']/text()\"");
$URL = "https://query.yahooapis.com/v1/public/yql?q={$q}&format=json";
echo "URL is ".$URL;
$ch = curl_init();
//Define curl options in an array
$options = array(CURLOPT_URL => $URL,
CURLOPT_HEADER => "Content-Type:text/xml",
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_RETURNTRANSFER => TRUE
);
//Set options against curl object
curl_setopt_array($ch, $options);
//Assign execution of curl object to a variable
$data = curl_exec($ch);
echo($data);
//Pass results to the SimpleXMLElement function
//$xml = new SimpleXMLElement($data);
echo($data);
if (false === ($data = curl_exec($ch))) {
die("Eek! Curl error! " . curl_error($ch));
}
if (200 !== (int)curl_getinfo($ch, CURLINFO_HTTP_CODE)) {
die("Oh dear, no 200 OK?!");
}
//Close curl object
curl_close($ch);
?>

Send AJAX-like post request using PHP only

I'm currently working on some automatization script in PHP (No HTML!).
I have two PHP files. One is executing the script, and another one receive $_POST data and returns information.
The question is how from one PHP script to send POST to another PHP script, get return variables and continue working on that first script without HTML form and no redirects.
I need to make requests a couple of times from first PHP file to another under different conditions and return different type of data, depending on request.
I have something like this:
<?php // action.php (first PHP script)
/*
doing some stuff
*/
$data = sendPost('get_info');// send POST to getinfo.php with attribute ['get_info'] and return data from another file
$mysqli->query("INSERT INTO domains (id, name, address, email)
VALUES('".$data['id']."', '".$data['name']."', '".$data['address']."', '".$data['email']."')") or die(mysqli_error($mysqli));
/*
continue doing some stuff
*/
$data2 = sendPost('what_is_the_time');// send POST to getinfo.php with attribute ['what_is_the_time'] and return time data from another file
sendPost('get_info' or 'what_is_the_time'){
//do post with desired attribute
return $data; }
?>
I think i need some function that will be called with an attribute, sending post request and returning data based on request.
And the second PHP file:
<?php // getinfo.php (another PHP script)
if($_POST['get_info']){
//do some actions
$data = anotherFunction();
return $data;
}
if($_POST['what_is_the_time']){
$time = time();
return $time;
}
function anotherFunction(){
//do some stuff
return $result;
}
?>
Thanks in advance guys.
Update: OK. the curl method is fetching the output of php file. How to just return a $data variable instead of whole output?
You should use curl. your function will be like this:
function sendPost($data) {
$ch = curl_init();
// you should put here url of your getinfo.php script
curl_setopt($ch, CURLOPT_URL, "getinfo.php");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec ($ch);
curl_close ($ch);
return $result;
}
Then you should call it this way:
$data = sendPost( array('get_info'=>1) );
I will give you some example class , In the below example you can use this as a get and also post call as well. I hope this will help you.!
/*
for your reference . Please provide argument like this,
$requestBody = array(
'action' => $_POST['action'],
'method'=> $_POST['method'],
'amount'=> $_POST['amount'],
'description'=> $_POST['description']
);
$http = "http://localhost/test-folder/source/signup.php";
$resp = Curl::postAuth($http,$requestBody);
*/
class Curl {
// without header
public static function post($http,$requestBody){
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $http ,
CURLOPT_USERAGENT => 'From Front End',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $requestBody
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
return $resp;
}
// with authorization header
public static function postAuth($http,$requestBody,$token){
if(!isset($token)){
$resposne = new stdClass();
$resposne->code = 400;
$resposne-> message = "auth not found";
return json_encode($resposne);
}
$curl = curl_init();
$headers = array(
'auth-token: '.$token,
);
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_HTTPHEADER => $headers ,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $http ,
CURLOPT_USERAGENT => 'From Front End',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $requestBody
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
return $resp;
}
}

Getting JSON response with PHP

I'm trying to connect an API that uses 0AUTH2 via PHP. The original plan was to use client-side JS, but that isn't possible with 0AUTH2.
I'm simply trying get a share count from the API's endpoint which is here:
https://api.bufferapp.com/1/links/shares.json?url=[your-url-here]&access_token=[your-access-key-here]
I do have a proper access_token that I am using to access the json file, that is working fine.
This is the code I have currently written, but I'm not even sure I'm on the right track.
// 0AUTH2 ACCESS TOKEN FOR AUTHENTICATION
$key = '[my-access-key-here]';
// JSON URL TO BE REQUESTED
$json_url = 'https://api.bufferapp.com/1/links/shares.json?url=http://bufferapp.com&access_token=' . $key;
// GET THE SHARE COUNT FROM THE REQUEST
$json_string = '[shares]';
// INITIALIZE CURL
$ch = curl_init( $json_url );
// CONFIG CURL OPTIONS
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array('Content-type: application/json') ,
CURLOPT_POSTFIELDS => $json_string
);
// SETTING CURL AOPTIONS
curl_setopt_array( $ch, $options );
// GET THE RESULTS
$result = curl_exec($ch); // Getting jSON result string
Like I said, I don't know if this is the best method - so I'm open to any suggestions.
I'm just trying to retrieve the share count with this PHP script, then with JS, spit out the share count where I need it on the page.
My apologies for wasting anyone's time. I have since been able to work this out. All the code is essentially the same - to test to see if you're getting the correct response, just print it to the page. Again, sorry to have wasted anyones time.
<?php
// 0AUTH2 ACCESS TOKEN FOR AUTHENTICATION
$key = '[your_access_key_here]';
// URL TO RETRIEVE SHARE COUNT FROM
$url = '[your_url_here]';
// JSON URL TO BE REQUESTED - API ENDPOINT
$json_url = 'https://api.bufferapp.com/1/links/shares.json?url=' . $url . ' &access_token=' . $key;
// GET THE SHARE COUNT FROM THE REQUEST
$json_string = '[shares]';
// INITIALIZE CURL
$ch = curl_init( $json_url );
// CONFIG CURL OPTIONS
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array('Content-type: application/json') ,
CURLOPT_POSTFIELDS => $json_string
);
// SETTING CURL AOPTIONS
curl_setopt_array( $ch, $options );
// GET THE RESULTS
$result = curl_exec($ch); // Getting jSON result string
print $result;
?>

Categories