I need to send a POST request to Cloudflare API,
Their API example is:
curl -X POST "https://api.cloudflare.com/client/v4/zones/023e105f4ecef8ad9ca31a8372d0c353/purge_cache" \
-H "X-Auth-Email: user#example.com" \
-H "X-Auth-Key: c2547eb745079dac9320b638f5e225cf483cc5cfdda41" \
-H "Content-Type: application/json" \
--data '{"purge_everything":true}
I have been trying from my functions.php file to make a POST request. Here is my code:
$curl = curl_init();
curl_setopt( $curl, CURLOPT_URL, 'my_url' );
curl_setopt( $curl, CURLOPT_POST, true );
curl_setopt( $curl, CURLOPT_HTTPHEADER, array(
'X-Auth-Email' => 'my_email',
'X-Auth-Key' => 'cf_api_key',
'Content-Type' => 'application/json',
));
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode( '{"purge_everything":true}' ));
$result = curl_exec($curl);
curl_close($curl);
var_dump($result);
I am getting this response
'''{"success":false,"errors":[{"code":9106,"message":"Missing X-Auth-Key, X-Auth-Email or Authorization headers"}]} bool(true) '''
Where and how should I put my X-Auth-Key etc?
you have to use the array of httpheader as single values, separeted with doublepoint, not as key value pair:
please see this example:
$curl = curl_init();
curl_setopt( $curl, CURLOPT_URL, 'my_url' );
curl_setopt( $curl, CURLOPT_POST, true );
curl_setopt( $curl, CURLOPT_HTTPHEADER, array(
'X-Auth-Email: my_email',
'X-Auth-Key: cf_api_key',
'Content-Type: application/json',
));
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POSTFIELDS, ["purge_everything"=>true] );
$result = curl_exec($curl);
curl_close($curl);
var_dump($result);
Related
I am using codeigniter-3 ,inside controller i am hitting one external API it's giving 400 error but same curl request if i hit in postman it's working fine can you please help me did i miss anything ..?
CURL REQUEST in postman
curl --location --request POST 'http://armycalling.com/baligaz-api/api/userapi/login' \
--header 'x-api-key: ccccc' \
--header 'Authorization: Basic YWRtaW46YmFsaWdheiFAIyQ=' \
--header 'Content-Type: application/json' \
--header 'Cookie: ci_session=f3630b226e539f4aa079e980e23cc730609a1627' \
--data-raw '{
"email" : "dummy#gmail.com",
"password" : "dummy.srk"
}'
usercontroller.php
if(isset($_POST['login']))
{
//phpinfo();
$url = 'http://localhost/login';
$u_name = $this->input->post('username');
$password= $this->input->post('password');
$curl = curl_init($url);
$data = [
'email'=>$u_name,
'password'=>$password
];
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'x-api-key: ccccc',
'Authorization: Basic YWRtaW46YmFsaWdheiFAIyQ=',
'Content-Type: Application/json',
'Cookie: ci_session=6dc4b8f72e2953c590ff503bd47f52ecfa158c79'
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($curl);
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
return print($httpcode);
curl_close($curl);
Setting this request to use a cookie session and sending the username/password in a POST request yields a successful login.
function curl( $url=NULL, $options=NULL, $headers=false ){
$vbh = fopen('php://temp', 'w+');
session_write_close();
/* Initialise curl request object - these should be OK as-is */
$curl=curl_init();
/* Define standard options */
curl_setopt( $curl, CURLOPT_URL, trim( $url ) );
curl_setopt( $curl, CURLOPT_AUTOREFERER, true );
curl_setopt( $curl, CURLOPT_FOLLOWLOCATION, true );
curl_setopt( $curl, CURLOPT_FAILONERROR, true );
curl_setopt( $curl, CURLOPT_HEADER, false );
curl_setopt( $curl, CURLINFO_HEADER_OUT, false );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $curl, CURLOPT_BINARYTRANSFER, true );
curl_setopt( $curl, CURLOPT_CONNECTTIMEOUT, 20 );
curl_setopt( $curl, CURLOPT_TIMEOUT, 60 );
curl_setopt( $curl, CURLOPT_USERAGENT, 'Mozilla/5.0' );
curl_setopt( $curl, CURLOPT_MAXREDIRS, 10 );
curl_setopt( $curl, CURLOPT_ENCODING, '' );
/* enhanced debug */
curl_setopt( $curl, CURLOPT_VERBOSE, true );
curl_setopt( $curl, CURLOPT_NOPROGRESS, true );
curl_setopt( $curl, CURLOPT_STDERR, $vbh );
/* Assign runtime parameters as options to override defaults if needed. */
if( isset( $options ) && is_array( $options ) ){
foreach( $options as $param => $value ) curl_setopt( $curl, $param, $value );
}
/* send any headers with the request that are needed */
if( isset( $headers ) && is_array( $headers ) ){
curl_setopt( $curl, CURLOPT_HTTPHEADER, $headers );
}
/* Execute the request and store responses */
$res=(object)array(
'response' => curl_exec( $curl ),
'status' => curl_getinfo( $curl, CURLINFO_RESPONSE_CODE ),
'info' => (object)curl_getinfo( $curl ),
'errors' => curl_error( $curl )
);
rewind( $vbh );
$res->verbose=stream_get_contents( $vbh );
fclose( $vbh );
curl_close( $curl );
return $res;
}
# create a temporary file somewhere to store cookie data.
# Using the system temp directory should mean automatic
# deletion of these files in time.
$cookiestore=tempnam( sys_get_temp_dir(), '_cookiejar_' );
$url='http://armycalling.com/baligaz-api/api/userapi/login';
$headers=array(
'x-api-key: BALIGAZ#123',
'Authorization: Basic YWRtaW46YmFsaWdheiFAIyQ='
);
$args=array(
'email' => 'rasakumar.srk#gmail.com',
'password' => 'rasakumar.srk'
);
/*
Mark the request as a new Cookie session - subsequent requests
would have different options without CURLOPT_COOKIESESSION
*/
$options=array(
CURLOPT_COOKIESESSION => true,
CURLOPT_COOKIEFILE => $cookiestore,
CURLOPT_COOKIEJAR => $cookiestore,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $args
);
/*
Make the request with specified config options
*/
$res=curl( $url, $options, $headers );
/*
If the request is successful a 200 OK status code will be received
so we can then proceed to work with the response data.
If the request fails, using the returned info & verbose properties
of the response will show useful debug info.
*/
if( $res->status==200 ){
printf('<pre>%s</pre>',print_r( $res->response, true ) );
}
This yields:
{
"status": true,
"message": "User login successful.",
"data": {
"id": "22",
"user_id": "baligaz_595689",
"first_name": "Rasa",
"last_name": "Kumar",
"email": "rasakumar.srk#gmail.com",
"password": "529f263ebb230b4709003bb0f7457f90",
"phone": "73339190384",
"profile_img": "http://armycalling.com/baligaz-api/profile_image/baligaz_595689_app_one.png",
"role": "1",
"station_id": "HP Petrols",
"forgot_otp": "",
"created": "2022-06-24 04:47:13",
"created_by": null,
"modified": "2022-06-30 23:38:15",
"updated_by": "baligaz_595689",
"login_completed": null,
"status": "1"
}
}
I have the following php curl command:
// GET TOKEN
$ch = curl_init('https://api.meinbuero.de/openapi/auth/token');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_USERPWD, $wisoApiKey . ":" . $wisoSecretApiKey);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(array('ownershipId' => $wisoOwnershipId)) );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$response = json_decode(curl_exec($ch), true);
curl_close($ch);
$myToken = $response['token'];
// GET CUSTOMER
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json' , 'Authorization: Bearer '.$myToken));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_USERPWD, $wisoApiKey . ":" . $wisoSecretApiKey);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_URL, 'https://api.meinbuero.de/openapi/customer?'.http_build_query(
array(
'offset' => 0,
'limit' => 10,
'orderBy' => 'name',
'desc' => 'false',
'search' => ''
)));
$response = json_decode(curl_exec($ch),true);
curl_close($ch);
echo $response;
Now I need this curl commands (for testing) as a command which I can send via terminal.
TO get the toke I tried this successfully:
curl -X POST "https://api.meinbuero.de/openapi/auth/token" -H "accept: application/json" -H "Content-Type: application/json" -d "{\"ownershipId\":\"XYZ\"}" -u WISO_API_KEY:WISO_SECRET_API_KEY
But than I would like to get the customers:
curl -X GET "https://api.meinbuero.de/openapi/customer?offset=0&search=&limit=20&orderBy=title&desc=true" -H "accept: application/json" -H "Content-Type: application/json" -u WISO_API_KEY:WISO_SECRET_API_KEY -H "Authorization: Bearer MY_TOKEN"
I get the message:
Unauthorized%
I have a php script running with curl and reporting setup as such, but it stops executing on the line with the curl_exec() method, and there are no errors thrown:
$fields = array(
'auth' => array(
'cId' => 'DEADBEEF-8675309-8675309-123123-4321',
'sig' => 'Not really a signature',
'data' => array(
'field' => 'pat',
'value' => '12',
'id1' => 'lasagna',
'id2' => 'peperoni'
)
),
'item1' => 'QPFMgH1TnCTLrylGeNs8yzYVVXxUgR0RHwj9jNwgXJJEfxODdoOKDOJLv66CSU5XKRfu4KYtDJB5rAmngxNrRDFpWU69oHMTlZoHAewuy3ft',
'item2' => 'gMiGdw==',
'tokenList' => array(
"token", "list"
)
);
$postfields = json_encode($fields);
error_reporting(E_ALL);
ini_set('display_errors', true);
$curl = curl_init('http://localhost:8080/endpoint');
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postFields);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
//curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
//$result = curl_exec($curl);
echo "before curl_exec" . "\n\n";
$response = json_decode(curl_exec($curl));
echo "after curl_exec" . "\n\n";
print_r($response);
EDIT: forgot to include the line with json_encode for the $fields variable to pass to curl_setopt();
There are a couple of issues with your code:
you put the "post" data into $fields but then...
curl_setopt($curl, CURLOPT_POSTFIELDS, $postFields);
...you're passing $postFields to curl.
Assuming this is a typo, fixing with
curl_setopt($curl, CURLOPT_POSTFIELDS, $fields);
won't work.
If the parameter used for CURLOPT_POSTFIELDS is an array it must be an associative array where keys and values are strings (or values that can be casted/converted to strings).
In your case $fields is an array where some values are arrays. That won't work (and raises a warning "array to string conversion").
You set an header that specifies that the data sent with the request is in JSON format
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
If you want to send the data into $fields as JSON with a POST request you can do it this way:
$fields = array( /* ... */ );
$json_fields = json_encode( $fields );
$curl = curl_init( 'http://localhost:8080/endpoint' );
curl_setopt( $curl, CURLOPT_POST, true );
curl_setopt( $curl, CURLOPT_CUSTOMREQUEST, "POST" );
curl_setopt( $curl, CURLOPT_POSTFIELDS, $json_fields );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $curl, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json',
'Content-Length: ' . strlen($json_fields) ] );
curl_setopt( $curl, CURLOPT_FOLLOWLOCATION, true );
$response = curl_exec( $curl );
$response_data = json_decode( $response );
If still something needs to be fixed proceed with debugging by steps to isolate the problem:
// 1 - Check curl error
$errnum = curl_errno( $curl );
$errstr = curl_strerror( $errnum );
echo "Error: $errnum - $errstr\n";
// 2 - Check http status code of the response
$status = curl_getinfo( $curl, CURLINFO_HTTP_CODE );
echo "Status: $status\n";
// 3 - Inspect the response before coverting to JSON
echo "Response:\n";
var_export( $response );
echo "\n";
I'm struggling using cURL within PHP. I'm not sure what I need to do to "translate" this:
curl -X POST -u "{username}:{password}" --header "Content-Type: application/json" --data-binary #profile.json "https://gateway.watsonplatform.net/personality-insights/api/v3/profile?version=2016-10-20&consumption_preferences=true&raw_scores=true"
into PHP to execute it there.
This is all I've got so far, but I'm feeling like I'm not even close:
$url2 = 'https://watson-api-explorer.mybluemix.net/personality-insights/api/v3/profile?raw_scores=false&csv_headers=false&consumption_preferences=true&version=2017-02-01';
$request_headers = array();
$request_headers[] = 'Accept: application/json';
$request_headers[] = 'Content-Type: text/plain';
$request_headers[] = 'Content-Language: en';
$request_headers[] = 'Accept-Language: en';
$ch2 = curl_init( $url2 );
curl_setopt( $ch2, CURLOPT_POST, 1);
curl_setopt( $ch2, CURLOPT_POSTFIELDS, $myvars2);
curl_setopt( $ch2, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt( $ch2, CURLOPT_HEADER, $request_headers);
curl_setopt( $ch2, CURLOPT_RETURNTRANSFER, 1);
$response2 = curl_exec( $ch2 );
var_dump($response2);
It looks like you are just missing the authentication piece:
curl_setopt( $ch2, CURLOPT_USERPWD, "yourUsername:yourPassword");
Check out the manual. Also, you can do it this way, which can be a little easier:
curl_setopt_array( $ch2, array(
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $myvars2,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_HEADER => $request_headers,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_USERPWD => 'yourUsername:yourPassword'
);
I am trying to use cloudsight API (http://cloudsight.readme.io/v1.0/docs) that requires me to use both POST and GET. I've never used a REST API before but after doing some research found that to POST using PHP would work.
I found the following code in the api documentation but am not sure how to convert this command line curl to PHP. The response is in JSON.
curl -i -X POST \
-H "Authorization: CloudSight [key]" \
-F "image_request[image]=#Image.jpg" \
-F "image_request[locale]=en-US" \
https://api.cloudsightapi.com/image_requests
curl -i \
-H "Authorization: CloudSight [key]" \
https://api.cloudsightapi.com/image_responses/[token]
If you're still interesting by the answer :
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, "https://api.cloudsightapi.com/image_requests" );
$postFields = array(
'image_request' => array(
'remote_image_url' => $url,
'locale' => 'en-US'
)
);
$fields_string = http_build_query($postFields);
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $fields_string );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array( 'Authorization: CloudSight [key]', "Content-Type:multipart/form-data" ) );
curl_exec( $ch );
curl_close( $ch );
If using the php curl library, you can do this for the POST:
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, "https://api.cloudsightapi.com/image_requests" );
$postFields = array(
'image_request' => array(
'image' => '#/path/to/image.jpeg',
'locale' => 'en-US'
)
);
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $postFields );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array( 'Authorization: CloudSight [key]' ) );
curl_exec( $ch );
curl_close( $ch );
PHP>=5.5 also provides a CURLFile class (http://php.net/manual/en/class.curlfile.php) for working with files instead of passing the path, as in the example above.
For the GET, you can just remove these two lines and alter the url:
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $postFields );
Another option would be to use Guzzle if you use Composer in your project ( http://guzzle.readthedocs.org/en/latest/).