CURL using PHP not displaying response - php

I'm trying to run a CURL command in my PHP file, but I'm not able to see the output. The following is modified slightly without the real usernames/passwords/URLs.
The reason I'm trying to see the output is to make sure the CURL command is working as expected (I've run it in bash so I know the expected result).
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com');
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT , 'Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0');
$headers = array();
$headers[] = 'Accept: application/json';
$headers[] = 'Content-Type: text/plain;charset=utf-8';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_USERPWD, '$username:$password');
curl_setopt($ch, CURLOPT_POSTFIELDS, '$data');
// grab URL and pass it to the browser
curl_exec($ch);
I've run the following to make sure CURL is installed with my PHP server, and that is the case:
function _is_curl_installed() {
if (in_array ('curl', get_loaded_extensions())) {
return true;
}
else {
return false;
}
}
// Ouput text to user based on test
if (_is_curl_installed()) {
echo "cURL is <span style=\"color:blue\">installed</span> on this server";
} else {
echo "cURL is NOT <span style=\"color:red\">installed</span> on this server";
}
Is there something I'm doing wrong? I've run the curl command on my bash, and I'm able to see a response fine:
curl -X POST --user $username:$password --header "Content-Type: text/plain;charset=utf-8" --header "Accept: application/json" --data-binary #Test.txt "http://www.example.com"

Try this example:
<?php
// SEND CURL POST DATA
$jsonData = array(
'user' => 'Username',
'pass' => 'Password'
);
//Encode the array into JSON.
$jsonDataEncoded = json_encode($jsonData);
//API Url
$url = 'http://fxstar.eu/JSON/api.php';
//Initiate cURL.
$ch = curl_init($url);
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
//Set the content type to application/json
//curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_HTTPHEADER, array(Content-Type: text/plain;charset=utf-8);
//Execute the request
echo $result = curl_exec($ch);
?>
Get json from js:
<?php
// GET JSON CONTENT FROM JS api.php
$jsonStr = file_get_contents("php://input"); //read the HTTP body.
$json = json_decode($jsonStr);
?>

Related

How to declare CURL body for CoinBase API call in php

I want use php curl to interact with coinbase api. Simple API calls that does not require data to be passed are successful. What I want to do is create address.
CLI curl works. The command line curl command sample is below:
curl https://api.coinbase.com/v2/accounts/82de7fcd-db72-5085-8ceb-bee19303080b/addresses \
-X POST \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer abd90df5f27a7b170cd775abf89d632b350b7c1c9d53e08b340cd9832ce52c2c' \
-d '{"name": "New receive address"}'
}
My php code excerpt
$apiurl = "https://api.coinbase.com";
$secret = "coinbase api secret";
$method = "POST";
$requestPath = "/v2/accounts/actualAccountID/addresses";
$body = "";
$url = $apiurl.$requestPath;
$data["name"] = "curl smj6 ary";
$body=json_encode($data);
$string = $timestamp.$method.$requestPath.$body;
$sig = hash_hmac('sha256', $string, $secret);
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
// Set the url
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_VERBOSE, true);
if($method == "POST"){
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
}
$headers = [
"CB-ACCESS-KEY: xxx",
"CB-ACCESS-SIGN:$sig",
"CB-ACCESS-TIMESTAMP: $timestamp",
"CB-VERSION: 2018-03-21",
"accept: application/json;charset=utf-8"
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Execute
$result_json = curl_exec($ch);
It returns
{"errors":[{"id":"authentication_error","message":"invalid signature"}]}
Since it works with listing user. I guess th error occurs the way iam passing post data to curl.
Similar Questions that I found on SO but none solves my issue. Please help!
Invalid Signature Coinbase
CoinBase "invalid signature" PHP Buy API Request
How to declare CURL body for CoinBase API call
Api key authentication for coinbase
UPDATE:
$apiurl = "https://api.coinbase.com/v2/";
$requestPath = "accounts/$accountid/addresses";
returns same error
There are sites that convert the command line cURL syntax to PHP, like https://incarnate.github.io/curl-to-php/
I just pasted your command and:
// Generated by curl-to-PHP: http://incarnate.github.io/curl-to-php/
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.coinbase.com/v2/accounts/82de7fcd-db72-5085-8ceb-bee19303080b/addresses");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"name\": \"New receive address\"}");
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array();
$headers[] = "Content-Type: application/json";
$headers[] = "Authorization: Bearer abd90df5f27a7b170cd775abf89d632b350b7c1c9d53e08b340cd9832ce52c2c";
$headers[] = "CB-ACCESS-KEY: <your api key>";
$headers[] = "CB-ACCESS-SIGN: <the user generated message signature>";
$headers[] = "CB-ACCESS-TIMESTAMP: <a timestamp for your request>";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close ($ch);

Post the data with header in curl not working in php?

I'm trying to create the box app users using PHP. The curl for create user as follows, and it is working on terminal
curl https://api.box.com/2.0/users \
-H "Authorization: Bearer <Access token>" \
-d '{"name": "New User", "is_platform_access_only": true}' \
-X POST
Same thing I have tried with php But it is giving the following error
{"type":"error","status":400,"code":"invalid_request_parameters","help_url":"http:\/\/developers.box.com\/docs\/#errors","message":"Invalid input parameters in request","request_id":"6688622675982fb5339a37"}
The following one I have tried
$developer_token = "TOKEN" ;
$access_token_url = "https://api.box.com/2.0/users";
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $access_token_url);
//Adding Parameters
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'name'=>'NEW USER',
'is_platform_access_only'=>'true',
));
//Adding Header
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer '.$developer_token
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response1 = curl_exec($ch);
If I remove the Post parameters, and run with only headers it is give the result of users. But with post it is throws error.
I have rise the same question in Perl tag with Perl code. There I got answer by user #melpomene.
We should encode the data as JSON. It is working,
Then the final code is
$data = array(name=>SOMENAME,is_platform_access_only=>true);
$data = json_encode($data);
$header = array("Authorization: Bearer <TOKEN>");
$ch = curl_init("https://api.box.com/2.0/users/");
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response1 = curl_exec($ch);
curl_close($ch);

curl POST -F to php cUrl

I'm attempting to POST a local file to an API, it works if I use command line curl but not when I try using php cURL. I set up some variables for the headers and body
$headers = array();
$headers[] = 'Authorization: Passcode '.$passcode;
$headers[] = 'FileType: STD';
$api_url = 'https://url.com';
$field_json = json_encode($field).';type=application/json'
$filepath = realpath('path/file.csv');
$file = new CURLFile($filepath,'text/csv');
curl based on the API's specifications works if I set it as a string and use exec
$cmd = "curl -X POST -H \"$headers[0]\" -H \"$headers[1]\" -F \"field=$field_json\" -F \"filename=#$filepath\" $api_url";
exec($cmd,$result); //This works successfully
but when I attempt to send the POST using the following code with PHP cURL, I get a vague error response 'Unexpected error'
$body = array(
'field' => $field_json,
'filename' => $file
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $api_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
//curl_setopt($ch, CURLOPT_SAFE_UPLOAD, FALSE);
$result = curl_exec($ch);
curl_close($ch);
echo json_encode($result);
I'm using PHP 5.5.9 and have tried it using the old way with # and the filepath.

Using PHP to get JSON data using curl

I am trying to use PHP to get JSON data using curl, however I am getting error 302, and am not getting data returned.
I can execute the curl at the command line using:
curl -X GET --header "Accept: application/json" "https://api.lootbox.eu/pc/us/Hydropotamus-1777/profile"
The following is the PHP script that is currently not working:
<?php
// Get cURL resource
$url = 'https://api.lootbox.eu/pc/eu/Hydropotamus-1777/profile';
$curl = curl_init($url);
echo "A";
// Set some options - we are passing in a useragent too here
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Accept: application/json'
));
echo "B";
$resp = curl_exec($curl);
echo "C";
echo $resp;
// Close request to clear up some resources
curl_close($curl);
?>
Below are a few environment details that may be helpful:
Windows 10
PHP 5.6.24
Chrome browser
Well I tried the following and it worked for me, getting the response:
<?php
// Get cURL resource
$url = 'https://api.lootbox.eu/pc/eu/Hydropotamus-1777/profile';
// Initiate curl
$ch = curl_init();
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Accept: application/json'
));
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);
// Will dump a beauty json :3
var_dump(json_decode($result, true));
?>
Seems you need to disable ssl verification.
A great tool to use is the RESTRequest class in PHP, https://gist.github.com/therealklanni/3440166 and then you can do:
<?php
session_start();
ini_set('display_errors', 'On');
error_reporting(E_ALL | E_STRICT);
include_once("RestRequest.php");
$url = 'https://api.lootbox.eu/pc/eu/Hydropotamus-1777/profile';
$getDataRequest = new RestRequest($dataurl, 'GET');
$getDataRequest->execute();
$data = json_decode($getDataRequest->responseBody);
echo(json_encode($data));
?>

How to use PHP CURL function to do the same request?

Here is my curl commaad line .
curl -u 'username:password' -X GET -H 'Accept: application/json' -H 'Content-Type: application/xml' -d '<request><layout>1</layout><filtermode>category</filtermode><filtervalue>115399046</filtervalue><limit>1</limit><start></start><sortfield></sortfield><sortdir></sortdir></request>' https://example.com/contacts
I use curl command line. It works for me. Now, I need do it in PHP.
The hard part is: The server accept GET request, but need a xml string in request body. I have tried to change GET to POST, the server did NOT return the correct message.
<?php
$ch = curl_init();
$credentials = "user:pass";
$data = 'xml string';
$page = "/contacts";
$headers = array( "GET ".$page." HTTP/1.0", "Content-type: application/xml", "Accept: application/json", "Authorization: Basic " . base64_encode($credentials) );
curl_setopt($ch, CURLOPT_URL, 'example.com/contacts');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$ret = curl_exec($ch);
?>
You can't put the GET line in $header, that causes an invalid header to be sent. The PHP equivalent of -X GET is:
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");

Categories