I am building my first ever project from scratch on a lamp stack. I decided to try out the slim api framework. Below you can see i start building a helper function for my api. However I am getting this
error: undefined constant CURLOPT_GET - assumed 'CURLOPT_GET'
and then this
error: curl_setopt() expects parameter 2 to be long, string given
// Main Gospel Blocks API Call Function
Function gbCall($gbRoute) {
// JSON Headers
$gblCallHeaders[] = "Content-Type: application/json;charset=utf-8";
// Call the API
$gblCall = curl_init();
curl_setopt($gblCall, CURLOPT_URL, $GLOBALS['gbApiUrl'] . $gbRoute);
curl_setopt($gblCall, CURLOPT_GET, TRUE);
curl_setopt($gblCall, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($gblCall, CURLOPT_HTTPHEADER, $gblCallHeaders);
// Get the response
$response = curl_exec($gblCall);
// Close cURL connection
curl_close($gblCall);
// Decode the response (Transform it to an Array)
$response = json_decode($response, true);
// Return response
return $response;
}
The api I am hitting is just json encoded objects, not quite sure why this isn't returning the json...
Try using CURLOPT_HTTPGET though I am not sure if it serves your purpose.
More detail can be found here
It happens when phpxxx-curl was not installed in your machine
There is nothing like CURLOPT_GET in the options for cURL that's why that error occured. Take a look at CURL options
For the GET Request in the Curl
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "URL");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
$headers = array();
$headers[] = "Key: Value";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close ($ch);
Related
Im using 2ba its API to receive product information which I later on want to store inside my database. I am trying to create a post request for receiving the data I need. This is the request I want to get to working. And this is my code:
postApiData.php
<?php
/**
* Posts API data based on given parameters at index.php.
*/
// Base url for all api calls.
$baseURL = 'https://api.2ba.nl';
// Version number and protocol.
$versionAndProtocol = '/1/json/';
// All parts together.
$url = $baseURL . $versionAndProtocol . $endPoint;
// Init session for CURL.
$ch = curl_init();
// Init headers. Security for acces data.
$headers = array();
$headers[] = "Authorization: Bearer " . $token->access_token;
// Options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($parameters));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
// Execute request.
$data = curl_exec($ch);
// If there is an error. Show whats wrong.
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
echo "<br>";
echo "Error location: postApiData";
exit();
}
// Ends the CURL session, frees all resources that belongs to the curl (ch).
curl_close($ch);
// String to array.
$data = json_decode($data);
?>
index.php
// Specified url endpoint. This comes after the baseUrl.
$endPoint = 'Product/forGLNAndProductcodes';
// Parameters that are required or/and optional for the endPoint its request.
$parameters = [
'gln' => '2220000075756',
'productcodes' => ['84622270']
];
// Get Supplier info
include("postApiData.php");
print_r($data);
exit();
My API key does for sure work since I have done alot of different GET requests already, also im not getting an access denied error.
The error I get with this code is: The requested URL returned error: 500 Internal Server Error
I also receive a "Bad request" 400 error when I remove the curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($parameters)); part
Is there anyone who knows what im doing wrong?
PS: It's not really possible to try this code yourself unless you have a 2ba account with working key's etc.
Okey I fixed it already...
I had to add some extra headers and change the $parameters values like this:
postApiData.php
// Added this above the authorization.
$headers[] = "Connection: close";
$headers[] = "Accept-Encoding: gzip,deflate";
$headers[] = "Content-Type: application/json";
// Removed the http_build_query part.
curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
index.php
// Encoded in a json way as asked by 2ba request.
$parameters = json_encode($parameters);
I am struggling to understand this error when i am trying to post the data the the 3rd party api database.
I have the $data here which i want to post with the curl and it is in json format.
<?php
$url = 'https://www.yourdomain.com/uploadproducts';
$api_key = 'nMUiKg/oj7xtq40';
$sec_key = 'Nf+NQ2/WyjohqXOF1';
$data = '{"product_sku":"FLAFFA000","product_category":"Fifth Avenue","product_subcategory":"0","product_name":"Love Print Flats","product_url":"http://love-print-flats-857","product_description":"Solid Candy Color Cartoon Printed Big","price":"1850","age_group":"0","product_img":"media/catalog/product/f/l/flaffa0001pin38.jpg,media/catalog/product/f/l/flaffa0001pin38_a.jpg,media/catalog/product/f/l/flaffa0001pin38_b.jpg","product_stock":[{"38":"1.0000"}],"product_discount":"100","discount_start_date":"0","discount_end_date":"0","product_tags":["0"]}';
//var_dump($data);
$data_string ='scapi_key='.urlencode($api_key).'&scsecret_key='.urlencode($sec_key)."&products=".urlencode($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if(curl_errno($ch))
{
echo 'Curl error: ' . curl_error($ch);
}
curl_close($ch);
$arr = json_decode($response, true);
echo "<pre>$response</pre>";
echo $arr;
?>
When i m trying to execute this file with the url www.yourdomain.com/test.php i m getting the following error.
{"msg":"200 OK","success":"Successfully added 0","updated":"Successfully updated 0","error":"Errors found 14"}
Array
Then i have tried using the
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
to my code above, and i m getting the following error
{"msg":"API key is missing","success":"Successfully added 0","updated":"Successfully updated 0"}
Array
I have also dumped the json data and have validated the json format,
string(943) "{"product_sku":"FLAFFA000","product_category":"Fifth Avenue","product_subcategory":"0","product_name":"Love Print Flats","product_url":"http://love-print-flats-857","product_description":"Solid Candy Color Cartoon Printed Big","price":"1850","age_group":"0","product_img":"media/catalog/product/f/l/flaffa0001pin38.jpg,media/catalog/product/f/l/flaffa0001pin38_a.jpg,media/catalog/product/f/l/flaffa0001pin38_b.jpg","product_stock":[{"38":"1.0000"}],"product_discount":"100","discount_start_date":"0","discount_end_date":"0","product_tags":["0"]}";
On researching more on this issue, i have gone through the document of curl codes and it say that Error 14 is CURLE_FTP_WEIRD_227_FORMAT (14)
FTP servers return a 227-line as a response to a PASV command. If libcurl fails to parse that line, this return code is passed back.
So as per the error shown, is there any possible solution with the curl error 14 or is there error in the code ? What can be the issue with FTP?
Any little help or hint would help me out.
I need to make one API request to AWS Route53 to create a reusable delegation set. You can't do this through the console web interface, it has to be through the API.
Here is the documentation for making this API request: http://docs.aws.amazon.com/Route53/latest/APIReference/api-create-reusable-delegation-set.html
<?php
$baseurl = "route53.amazonaws.com/2013-04-01/delegationset";
$body = '<?xml version="1.0" encoding="UTF-8"?>
<CreateReusableDelegationSetRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
<CallerReference>whitelabel DNS</CallerReference>
</CreateReusableDelegationSetRequest>';
$ch = curl_init();
// Set query data here with the URL
curl_setopt($ch, CURLOPT_URL, $baseurl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_POSTFIELDS, $body );
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Host: route53.amazonaws.com','X-Amzn-Authorization: '));
curl_setopt($ch, CURLOPT_TIMEOUT, '3');
$rest = curl_exec($ch);
if ($rest === false)
{
// throw new Exception('Curl error: ' . curl_error($crl));
print_r('Curl error: ' . curl_error($ch));
}
curl_close($ch);
print_r($rest);
?>
I know the request isn't signed/authenticated, but I'm not even able to connect to the server. I would at least like to get an error message that says I'm not authenticated before I continue. Instead all I get is "connection refused".
I'm sure I'm doing something completely wrong here. But Google has been of no use.
scrowler was right. I changed:
$baseurl = "route53.amazonaws.com/2013-04-01/delegationset";
to
$baseurl = "https://route53.amazonaws.com/2013-04-01/delegationset";
I got the error message I was expecting and now I can work on the next step.
I am using the HttpRequest class in my php script, but when I uploaded this script to my hosting provider's server, I get a fatal error when executing it:
Fatal error: Class 'HttpRequest' not found in ... on line 87
I believe the reason is because my hosting provider's php.ini configuration doesnt include the extension that supports HttpRequest. When i contacted them they said that we cannot install the following extentions on shared hosting.
So i want the alternative for httpRequest which i make like this:
$url= http://ip:8080/folder/SuspendSubscriber?subscriberId=5
$data_string="";
$request = new HTTPRequest($url, HTTP_METH_POST);
$request->setRawPostData($data_string);
$request->send();
$response = $request->getResponseBody();
$response= json_decode($response, true);
return $response;
Or How can i use this request in curl as it is not working for empty datastring?
You can use CURL in php like this:
$ch = curl_init( $url );
$data_string = " ";
curl_setopt( $ch, CURLOPT_POSTFIELDS, $data_string );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
$result = curl_exec($ch);
curl_close($ch);
return $result;
and empty data string doesn't make sense in post request, but i've checked it with empty data string and it works quiet well.
you can use a framework like zend do this. framework usually have multiple adapters (curl,socket,proxy).
here is a sample with ZF2:
$request = new \Zend\Http\Request();
$request->setUri('[url]');
$request->setMethod(\Zend\Http\Request::METHOD_POST);
$request->getPost()->set('key', $value);
$client = new \Zend\Http\Client();
$client->setEncType('application/x-www-form-urlencoded');
$response = false;
try {
/* #var $response \Zend\Http\Response */
$response = $client->dispatch($request);
} catch (Exception $e) {
//handle error
}
if ($response && $response->isSuccess()) {
$result = $response->getBody();
} else {
$error = $response->getBody();
}
you don't have to use the entire framework just include (or autoload) the classes that you need.
Use the cURL in php
<?php
// A very simple PHP example that sends a HTTP POST to a remote site
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://example.com/feed.rss");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,"postvar1=value1&postvar2=value2");
// in real life you should use something like:
// curl_setopt($ch, CURLOPT_POSTFIELDS,
// http_build_query(array('postvar1' => 'value1')));
// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);
// further processing ....
if ($server_output == "OK") { ... } else { ... }
?>
for more see this PHP Difference between Curl and HttpRequest
a slight variaton on the curl methods proposed, i decode the json that is returned, like in this snippet
I have a frontend code
$ch = curl_init();
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
//curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
curl_setopt($ch, CURLOPT_URL, $url);
//make the request
$responseJSON = curl_exec($ch);
$response_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($response_status == 200) { // success
// remove any "problematic" characters from the json string and then decode
if (debug) {
echo "----finish API of getAPI inside basic_function with status==200---";
echo "<br>";
echo "-------the json response is-------" ; //.$responseJSON;
var_dump($responseJSON);
//print_r($responseJSON);
echo "<br>";
}
return json_decode( preg_replace( '/[\x00-\x1F\x80-\xFF]/', '', $responseJSON ) );
}
and I have a backend code which executed when cURL fired its operation with its URL. The backend code would therefore activated. So, I know cURL is operating.
$output=array (
'status'=>'OK',
'data'=>'12345'
)
$output=json_encode($output)
echo $output;
and $output shown on browser as {"status":"OK","data":"12345"}
However, I gone back to the frontend code and did echo $responseJSON, I got nothing. I thought the output of {"status":"OK","data":"12345"} would gone to the $responseJSON. any idea?
Here's output on Browser, something is very odd! the response_status got 200 which is success even before the parsing of API by the backend code. I expect status =200 and json response after the {"status":"OK","data":"12345"}
=========================================================================================
inside the get API of the basic functions
-------url of cURL is -----http://localhost/test/api/session/login/?device_duid=website&UserName=joe&Password=1234&Submit=Submit
----finish API of getAPI inside basic_function with status==200---
-------the json response is-------string(1153)
"************inside Backend API.php******************
---command of api is--/session/login/
---first element of api is--UserName=joe
--second element of api is---Password=1234
---third element of api is----Submit=Submit
----fourth element of api is---
-------inside session login of api-------------
{"status":"OK","data":"12345"}
Have you tried with curl_setopt($ch, CURLOPT_TIMEOUT, 10); commented?
See what happends if you comment that line.
Also try with the a basic code, if that works, smthing you added later is wrong:
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, false);
// grab URL and pass it to the browser
curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
Try var_dump($responseJSON)
If it returns false try
curl_error ( $ch )
Returns a clear text error message for the last cURL operation.
Are you sure your $url is correct?