Could not resolve host on cURL request PHP - php

I'm starting to build my first API, after succesful testing on localhost(Mac OS X El Capitan) I uploaded it to my digitalocean server running Ubuntu 16.04.
I've both tried to run the cURL request from my localhost and from the server where the API is stored and both of them return "Could not resolve host" error with error number 6. My code:
On API side just
echo "200";exit;
On client side
$token = 'this is the session token';
$url = "http://xx.xx.xx.xx/API/index.php";
$data = array('username'=>'username','password'=>'password');
$datajson = json_encode($data);
$message = $url . $datajson . 'PUT';
$publishThis = base64_encode(
hash_hmac('sha256', $message, 'secret key', true)
);
$len = 'Content-Length: ' . strlen($message);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, urlencode($url));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',$len, 'Authorization: ' . $publishThis));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS,$datajson);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
$response = curl_exec($ch);
help please!!
P.S: if I remove the urlencode function the request takes for about 20 mins and ends on a 400 bad request error

LATER EDIT:
$token = 'this is the session token';
$url = "http://xx.xx.xx.xx/API/index.php";
$data = array('username'=>'username','password'=>'password');
$datajson = json_encode($data);
$build_query = http_build_query($data);
$message = $url . $datajson . 'PUT';
$publishThis = base64_encode(
hash_hmac('sha256', $message, 'secret key', true)
);
$len = 'Content-Length: ' . strlen($build_query);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',$len, 'Authorization: ' . $publishThis));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS,$build_query);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
$response = curl_exec($ch);
if($errno = curl_errno($ch)) {
$error_message = curl_strerror($errno);
echo "cURL error ({$errno}):\n {$error_message}";
}
echo $response;
CHANGES:
$build_query = http_build_query($data);
$len = 'Content-Length: ' . strlen($build_query);
curl_setopt($ch, CURLOPT_POSTFIELDS,$build_query)
remove url encode from CURLOPT_URL

Related

How to get Google drive refresh token automatically

I am using php to upload files automatically to Google drive using API/Token, but I discovered that the Token expired after certain of time.
I always get new token from Oauth play ground Page
https://developers.google.com/oauthplayground/
So, how to refresh it automatically using Refresh Code Token
Here is the full code:-
global $GAPIS;
$GAPIS = 'https://www.googleapis.com/';
$name = $name;
$file = $zip_file_name;
$mime_type = 'application/zip';
$access_token = 'token';
$ch1 = curl_init();
curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch1, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch1, CURLOPT_URL, $GAPIS . 'upload/drive/v3/files?uploadType=media');
curl_setopt($ch1, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch1, CURLOPT_POST, 1);
curl_setopt($ch1, CURLOPT_POSTFIELDS, file_get_contents($file));
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch1, CURLOPT_HTTPHEADER, array('Content-Type: '.$mime_type, 'Content-Length: ' . filesize($file), 'Authorization: Bearer ' . $access_token) );
$response=curl_exec($ch1);
if($response === false){
$output = 'ERROR: '.curl_error($ch1);
} else{
$output = $response;
}
curl_close($ch1);
$this_response_arr = json_decode($response, true);
if(isset($this_response_arr['id'])){
$this_file_id = $this_response_arr['id'];
$ch2 = curl_init();
curl_setopt($ch2, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch2, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch2, CURLOPT_URL, $GAPIS . 'drive/v3/files/'.$this_file_id);
curl_setopt($ch2, CURLOPT_CUSTOMREQUEST, 'PATCH');
$post_fields = array();
$this_file_name = explode('.', $name);
$post_fields['name']=$this_file_name[0];
curl_setopt($ch2, CURLOPT_POSTFIELDS, json_encode($post_fields));
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch2, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: Bearer ' . $access_token) );
$response=curl_exec($ch2);
if($response === false){
$output = 'ERROR: '.curl_error($ch2);
} else{
$output = $response;
}
curl_close($ch2);
$print = json_decode($output, true);
if ($this_file_name[0] = $print['name']) {
echo "file uploaded successfully and ";
}
}
unlink ($file);die("Zip file removed");
return $output;
EDIT: Solution:-
Thanks a lot for Ronak Dhoot about his solution and here is the CURL code to get the refresh token automatically
$client_id = 'client_id';
$client_secret = 'client_secret';
$refresh_token = 'refresh_token';
$url = 'https://www.googleapis.com/oauth2/v4/token';
$fields = [
'client_id' => $client_id,
'client_secret' => $client_secret,
'refresh_token' => $refresh_token,
'grant_type' => 'refresh_token'
];
$fields_string = http_build_query($fields);
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$access_result = json_decode($result, true);
$access_token = $access_result['access_token'];
echo $access_token;
in Step 1 when Click “Authorize APIs” and allow access to your account when prompted. There will be a few warning prompts, just proceed.
When you get to step 2, check “Auto-refresh the token before it expires” and click “Exchange authorization code for tokens”.
When you get to step 3, click on step 2 again and you should see your refresh token.
Now, All you need to do is a post request like below :-
POST https://www.googleapis.com/oauth2/v4/token
Content-Type: application/json
{
"client_id": <client_id>,
"client_secret": <client_secret>,
"refresh_token": <refresh_token>,
"grant_type": "refresh_token"
}

php cuRL response "unable to transcode data stream audio/flac -> audio/x-float-array" - IBM Watson Speech to text API

I don't know much about how to use cURL.I am trying to convert Speech to Text using IBM Watson API. When I try to convert it without using parameters(Translate English
Audio File), I get a response without any error.
But when I add
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'model'=>'ja-JP_NarrowbandModel'
))
It returns
{ "code_description": "Bad Request", "code": 400, "error": "unable to
transcode data stream audio/flac -> audio/x-float-array " }
I am not sure if there is an issue in my Syntax or something else is going wrong there.
I read docs from : https://console.bluemix.net/docs/services/speech-to-text/http.html#http
<?php
$ch = curl_init();
$file = file_get_contents('audio-file.flac');
curl_setopt($ch, CURLOPT_URL, 'https://stream.watsonplatform.net/speech-to-text/api/v1/recognize');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $file);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_USERPWD, 'apikey' . ':' . 'MY_API_HERE');
$headers = array();
$headers[] = 'Content-Type: audio/flac';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'model'=>'ja-JP_NarrowbandModel'
));
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
print_r($result);
You are setting CURLOPT_POSTFIELDS twice, once with the content of your file and a second time with an array containing 'model'=>'ja-JP_NarrowbandModel'.
According to the documentation, you can pass the model as a query parameter.
Try something like this (not tested):
<?php
$file = file_get_contents('audio-file.flac');
$url = 'https://stream.watsonplatform.net/speech-to-text/api/v1/recognize';
$model = 'ja-JP_NarrowbandModel';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url . '?model=' . $model);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $file);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_USERPWD, 'apikey' . ':' . 'MY_API_HERE');
$headers = array();
$headers[] = 'Content-Type: audio/flac';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
print_r($result);

Zoho API-V2 Add Attactmetn URL

I am trying to add attachment url in crm. I am flowing this documentation . But i got error !
This is my code :
$zoho_url = "https://www.zohoapis.com/crm/v2/$module/$id/Attachments";
$post['attachmentUrl'] = $url;
$ch=curl_init();
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_URL,$zoho_url);
curl_setopt($ch,CURLOPT_POSTFIELDS,$post);
$headers = array();
$headers[] = "Authorization: ".$authtoken;
$headers[] = "Content-Type: multipart/form-data";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
$err = curl_errno($ch);
curl_close ($ch);
if ($err) {
$result = $err;
} else {
$result = $response;
}
print_r($result);
This is response :
{"code":"INVALID_REQUEST","details":{},"message":"unable to process your request. please verify whether you have entered proper method name, parameter and parameter values.","status":"error"}
I made this code for attach a file in a zoho record.
//Get the oauth Token
$accessToken=getCurrentAccessToken();
// files to upload
$tmpfile;
$filename;
$type;
foreach($files as $file){
$tmpfile = $file['tmp_name'];
$filename = basename($file['name']);
$type = $file['type'];
}
$cfile = new CURLFile(realpath($tmpfile),$type,$filename);
$post_data = array (
'file' => $cfile
);
$url = "https://www.zohoapis.com/crm/v2/$module/$id/Attachments";
$headers = array(
'Content-Type: multipart/form-data',
sprintf('Authorization: Zoho-oauthtoken %s', $accessToken)
);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$response = curl_exec($ch);
return $response;

PHP curl and outputting api responses

I am using cURL to interface with an API. What I wanting to do once I done what I need to with API is output the APIs response.
<?php
/*
* Server REST - user.login
*/
$input = file_get_contents("php://input");
$xml_input = simplexml_load_string($input);
$xml_arr = json_decode(json_encode($xml_input, TRUE));
// REST Server URL
$request_url = 'http://xxx.localhost:8888/api/v1/user/login.json';
// User data
$user_data = array(
'username' => $xml_arr->Username,
'password' => $xml_arr->Password,
);
// cURL
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $request_url);
curl_setopt($curl, CURLOPT_POST, 1); // Do a regular HTTP POST
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/json'));
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($user_data)); // Set POST data
curl_setopt($curl, CURLOPT_HEADER, FALSE); // Ask to not return Header
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_FAILONERROR, TRUE);
$response = curl_exec($curl);
$http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($http_code == 200) {
$logged_user = json_decode($response);
}
else {
$http_message = curl_error($curl);
return http_response_code(401);
}
$cookie_session = $logged_user->session_name . '=' . $logged_user->sessid;
if($xml_arr->Action == "Delete"){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://xxx.localhost:8888/api/v1/logic_melon/' . $xml_arr->JobReference);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/json', 'X-CSRF-Token: ' . $logged_user->token, 'Cookie: ' . $cookie_session));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
} elseif($xml_arr->Action == "Add") {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'http://xxx.localhost:8888/api/v1/logic_melon');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/json', 'X-CSRF-Token: ' . $logged_user->token, 'Cookie: ' . $cookie_session));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($xml_arr));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
}
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($http_code == 200)
{
// Convert json response as array
$response = json_decode($response);
echo $response;
}
else
{
// Get error msg
$http_message = curl_error($curl);
}
The api returns a response code and an message, how would I output this to my user? return $response doesn't seem to do the job.

Spotify Error Code 403 - This request requires user authentication

I want to add tracks to my PRIVATE Spotify playlist by php - but i don´t get it done. I´m always getting the error message
Error Code 403 - This request requires user authentication.
I'm not the good in the spotify api. Can someone help me out? This is my code:
<?php
error_reporting(E_ALL);
$url = 'https://accounts.spotify.com/api/token';
$method = 'POST';
$credentials = "Client ID:Client Secret";
$headers = array(
"Accept: */*",
"Content-Type: application/x-www-form-urlencoded",
"Authorization: Basic " . base64_encode($credentials));
$data = 'grant_type=client_credentials';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response_1 = curl_exec($ch);
curl_close($ch);
$response_1 = json_decode($response_1, true);
var_dump($response_1);
$token = $response_1['access_token'];
echo $token."<br>";
$headers_2 = array(
"Accept: application/json",
"Content-Type: application/x-www-form-urlencoded",
('Authorization: Bearer ' . $token));
$url_2 = 'https://api.spotify.com/v1/users/example/playlists/playlist_example_id/tracks';
$postargs = '?uris=spotify%3Atrack%3A4xwB7i0OMsmYlQGGbtJllv';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url_2);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers_2);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postargs);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response_2 = curl_exec($ch);
curl_close($ch);
$response_2 = json_decode($response_2, true);
var_dump($response_2);

Categories