Curl api call return empty array - php

If I make this call with file_get_contents, it is returning the data, but with curl it show error true, code: 204, with all empty arrays, I m making post of single query string, I am just a novice in programming any help, thanks.
Array ( [error] => 1 [dname_avail] => [domname] => Array ( [tld_code] => )
<?php
$json = '';
if(isset($_POST['querystring'])){
$string_sanitised = $_POST['querystring'];
$query_var= str_replace(" ","",$string_sanitised);
// set HTTP header
$headers = array('Content-Type: application/json',);
// *** create the call to the API and pass parameters along
//apikey =xx67676876868686868686
$url = 'http://api.mydomain.com/domlook/domname/'.$query_var.'/apikey/xx67676876868686868686/';
// Open connection
$ch = curl_init();
// Set the url, number of GET vars, GET data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Execute request
$result = curl_exec($ch);
// Close connection
curl_close($ch);
// get the result and parse to JSON
$result_arr = json_decode($result, true);
print_r($result_arr);
}else{
echo "error";
}
?>

Related

PHP Curl Post and Get Response

I have a shell code as below."curl -X POST -F 'file=#textomate-api.pdf;type=text/plain' https://textomate.com/a/uploadMultiple"
This code send a file to the URL and get the response below.
{
"countedFiles": [
{
"wordsNumber": 340,
"charsNumber": 2908,
"charsNoSpacesNumber": 2506,
"wordsNumberNN": 312,
"charsNumberNN": 2755,
"charsNoSpacesNumberNN": 2353,
"md5": null,
"fileName": "textomate-api.pdf",
"error": null
}
],
"total": {
"wordsNumber": 340,
"charsNumber": 2908,
"charsNoSpacesNumber": 2506,
"wordsNumberNN": 312,
"charsNumberNN": 2755,
"charsNoSpacesNumberNN": 2353,
"md5": null
}
}
And I want to post a file via PHP and get this response or only value of "charsNoSpacesNumber".
Could you please help me with this?
Thanks a lot
You can do it as follows:
YET be sure to first check their T&C as I am not sure if they provide such a service for free.
Also be sure to include some error / exceptions handling.
<?php
//Initialise the cURL var
$ch = curl_init();
//Get the response from cURL
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//Set the Url
curl_setopt($ch, CURLOPT_URL, 'https://textomate.com/a/uploadMultiple');
$path = '/path/to/your/file.pdf';
$file = curl_file_create($path, 'application/pdf', 'file');
//Create a POST array with the file in it
$postData = array(
'file' => $file,
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
// Execute the request, decode the json into array
$response = json_decode(curl_exec($ch), true);
var_dump($response['total']['charsNoSpacesNumber']);
Thanks for your support Bartosz.
This is my code and I also shared an image of the code and results.
I hope there are enough information.
<?php
if(is_callable('curl_init')){
echo "curl is active";
} else {
echo "curl is passive";
}
//Initialise the cURL var
$ch = curl_init();
//Get the response from cURL
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//Set the Url
curl_setopt($ch, CURLOPT_URL, 'https://textomate.com/a/uploadMultiple');
$path = 'textomate-api.pdf';
$file = curl_file_create($path, 'application/pdf', 'file');
//Create a POST array with the file in it
$postData = array(
'file' => $file,
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
// Execute the request, decode the json into array
$response = json_decode(curl_exec($ch), true);
var_dump($response['total']['charsNoSpacesNumber']);
var_dump($response);
var_dump(file_exists($path));
?>
Updated code is below and you can see the results in the image.
I want to use this API on my website to be able to calculate character count of documents. I am using Wordpress and API provider gives us 3 options, Java, PHP (Wordpress) and Shell. They have something for Wordpress but I don't know how to use it.
You can reach all the files from here.
https://github.com/zentaly/textomate-api
If you take a look there, you can get more information and maybe you can find me a better solution.
And again thank you so much for your support, I appreciate it.
<?php
if(is_callable('curl_init')){
echo "curl is active";
} else {
echo "curl is passive";
}
//Initialise the cURL var
$ch = curl_init();
//Get the response from cURL
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//Set the Url
curl_setopt($ch, CURLOPT_URL, 'https://textomate.com/a/uploadMultiple');
curl_setopt($ch, CURLOPT_VERBOSE, 2);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_exec: var_dump(curl_errno($ch));
var_dump(curl_error($ch));
$path = 'textomate-api.pdf';
$file = curl_file_create($path, 'application/pdf', 'file');
//Create a POST array with the file in it
$postData = array(
'file' => $file,
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
// Execute the request, decode the json into array
$response = curl_exec($ch);
var_dump($response);
$response = json_decode($ch);
var_dump($response['total']['charsNoSpacesNumber']);
var_dump($response);
var_dump(file_exists($path));
var_dump($file);
?>

Getting data from JSON

Just wondering if anyone knew what I was doing wrong here?
I am trying to get data from an API for bitcoin via php. However, I am getting no results from my php page.
$url = "https://api.coinmarketcap.com/v1/ticker/bitcoin/?convert=EUR";
$json = file_get_contents($url);
$json_data = json_decode($json, true);
echo "ID: ". $json_data["id"];
However I am getting nothing show at all on the php page. If I use the code below, It works and dumps out the entire information. But, I would prefer to obtain the information separately, instead of one big dump.
$url = "https://api.coinmarketcap.com/v1/ticker/bitcoin/?convert=EUR";
$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);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);
var_dump(json_decode($result, true));
Anyone have any ideas why the first code block isn't working? Thanks! Very new to API and Json
Using cURL is much better
Updated code (needs error checking)
$url = "https://api.coinmarketcap.com/v1/ticker/bitcoin/?convert=EUR";
$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);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);
$json_data = json_decode($result, true);
foreach ($json_data as $item)
echo "ID: ". $item["id"];
I have printed the result it will produce following output
echo "<pre>";
print_r(json_decode($result, true));
Array
(
[0] => Array
(
[id] => bitcoin
[name] => Bitcoin
[symbol] => BTC
[rank] => 1
[price_usd] => 3821.37
[price_btc] => 1.0
[24h_volume_usd] => 2089880000.0
[market_cap_usd] => 63298556016.0
[available_supply] => 16564362.0
[total_supply] => 16564362.0
[percent_change_1h] => -1.72
[percent_change_24h] => -4.57
[percent_change_7d] => -15.76
[last_updated] => 1505359771
[price_eur] => 3214.536444
[24h_volume_eur] => 1758007056.0
[market_cap_eur] => 53246745321.0
)
)
so you can use foreach loop if your api contain multiple
$data=json_decode($result, true);
foreach($data as $key=>$val){
echo $val->id;
}
full code
<?php
$url = "https://api.coinmarketcap.com/v1/ticker/bitcoin/?convert=EUR";
$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);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);
$data=json_decode($result, true));
foreach($data as $key=>$val){
echo $val->id;
}
The setting you are looking for is allow_url_fopen.
You have two ways of getting around it without changing php.ini, one of them is to use fsockopen(), and the other is to use cURL.
I recommend using cURL over file_get_contents() anyways, since it was built for this.

Curl request response not getting

I am sending payment info to Virtual merchant payment gateway for payment system using curl. This is my code :
$Url= "https://www.myvirtualmerchant.com/VirtualMerchant/process.do";
// is cURL installed yet?
if (!function_exists('curl_init')){
die('Sorry cURL is not installed!');
}
// OK cool - then let's create a new cURL resource handle
$ch = curl_init();
// Now set some options (most are optional)
// Set URL to download
curl_setopt($ch, CURLOPT_URL, $Url);
// Include header in result? (0 = yes, 1 = no)
// curl_setopt($ch, CURLOPT_HEADER, 0);
// Should cURL return or print out the data? (true = return, false = print)
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Timeout in seconds
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$fields = array(
'ssl_card_number'=>urlencode($_POST['ssl_card_number']),
'ssl_exp_date'=>urlencode($_POST['ssl_exp_date']),
'ssl_cvv2cvc2'=>urlencode($_POST['ssl_cvv2cvc2']),
'ssl_avs_address'=>urlencode($_POST['ssl_avs_address']),
'ssl_avs_zip'=>urlencode($_POST['ssl_avs_zip']),
'ssl_merchant_id'=>urlencode($_POST['ssl_merchant_id']),
'ssl_user_id'=>urlencode($_POST['ssl_user_id']),
'ssl_pin'=>urlencode($_POST['ssl_pin']),
'ssl_transaction_type'=>urlencode($_POST['ssl_transaction_type']),
'ssl_amount'=>urlencode($_POST['ssl_amount']),
'ssl_show_form'=>urlencode($_POST['ssl_show_form']),
'TransactionType'=>urlencode($_POST['TransactionType'])
);
//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string,'&');
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
// Download the given URL, and return output
echo $output = curl_exec($ch);
// Close the cURL resource, and free system resources
curl_close($ch);
print_r($output);
But in $output i am getting nothing, not any error or message. Am i doing it wrong ? please tell me ?
First I'd check your mechant_id, pin, etc. Below is working code I created after working through a similar problem.
<html>
<body>
<p>--start--</p>
<?php
//if you have a live account don't use the "demo" post url it won't work
$post_url = 'https://www.myvirtualmerchant.com/VirtualMerchant/process.do';
//replace the xxx's with your proper merchant_id, etc.
//they will give you these when you activate your account
//I've set form to not show, and ssl_result_format =>ascii to get a string returned
$fields = array(
'ssl_merchant_id' =>'xxxxxx',
'ssl_user_id' =>'xxx',
'ssl_pin' =>'xxxxx',
'ssl_show_form' =>'false',
'ssl_result_format' =>'ascii',
'ssl_test_mode' =>'false',
'ssl_transaction_type' =>'ccsale',
'ssl_amount' =>'1.44',
'ssl_card_number' =>'5000300020003003',
'ssl_exp_date' =>'1214',
'ssl_avs_address' =>'Test 3',
'ssl_avs_zip' =>'123456',
'ssl_cvv2cvc2' =>'123',
);
//build the post string
$fields_string = '';
foreach($fields as $key=>$value) { $fields_string .=$key.'='.$value.'&'; }
rtrim($fields_string, "&");
//open curl session
// documentation on curl options at http://www.php.net/curl_setopt
$ch = curl_init();
//begin seting curl options
//set URL
curl_setopt($ch, CURLOPT_URL, $post_url);
//set method
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//set post data string
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
//these two options are frequently necessary to avoid SSL errors with PHP
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$result = curl_exec($ch);
if($result === FALSE) {
//post failed
die(curl_error($ch));
} else {
//got a response
//some people seem to get name/value pairs delimited with "&"
//but currently mine is \n
//support told me there's no way to change it..
$response_array = explode("\n",$result);
//make it nice and useful
foreach( $response_array as $k=>$v ){
$v=explode("=",$v);
$a[$v[0]]=$v[1];
}
//show the whole array
print_r($a);
//use a specific return value
//returns "APPROVAL" if it went through
echo('<h1>'. $a[ssl_result_message] . '</h1>');
}
?>
<p>--end--</p>
</body>
</html>
The code above should net you a screen like this:
--start--
Array ( [ssl_card_number] => 50**********3003 [ssl_exp_date] => 1214 [ssl_amount] => 1.44 [ssl_customer_code] => [ssl_salestax] => [ssl_invoice_number] => [ssl_description] => [ssl_departure_date] => [ssl_completion_date] => [ssl_company] => [ssl_first_name] => [ssl_last_name] => [ssl_avs_address] => Test 3 [ssl_address2] => [ssl_city] => [ssl_state] => [ssl_avs_zip] => 123456 [ssl_country] => [ssl_phone] => [ssl_email] => [ssl_result] => 0 [ssl_result_message] => APPROVAL [ssl_txn_id] => AA49315-1234567-F78F-468F-AF1A-F5C4ADCFFB1E [ssl_approval_code] => N53032 [ssl_cvv2_response] => [ssl_avs_response] => [ssl_account_balance] => 0.00 [ssl_txn_time] => 01/15/2014 11:53:15 AM )
APPROVAL
--end--
Make sure you delete all these test purchases when you finished testing. I'm told they will inhibit your real purchases from posting.
try this to find out the error
var_dump(curl_error($ch));
before and calling curl_exec($ch);
You are calling an HTTPS page. Please refer to following link
http://unitstep.net/blog/2009/05/05/using-curl-in-php-to-access-https-ssltls-protected-sites/
Try to find error give this code before curl close:--
echo "Curl Error :--" . curl_error($ch);
if no error found do like this:-
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
then
print_r($result);
exit;
Try this:
$output = curl_exec($ch);
$response = curl_getinfo($ch);
echo "<pre>";
print_r($response);
echo "</pre>";
Hope you get the response :)

Trying to use curl to do a GET, value being sent is allows null

I'm trying to use curl to do a simple GET with one parameter called redirect_uri. The php file that gets called prints out a empty string for $_GET["redirect_uri"] it shows red= and it seems like nothing is being sent.
code to do the get
//Get code from login and display it
$ch = curl_init();
$url = 'http://www.besttechsolutions.biz/projects/facebook/testget.php';
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_GET,1);
curl_setopt($ch,CURLOPT_GETFIELDS,"redirect_uri=my return url");
//execute post
print "new reply 2 <br>";
$result = curl_exec($ch);
print $result;
// print "<br> <br>";
// print $fields_string;
die("hello");
the testget.php file
<?php
print "red-";
print $_GET["redirect_uri"];
?>
This is how I usually do get requests, hopefully it will help you:
// create curl resource
$ch = curl_init();
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Follow redirects
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// Set maximum redirects
curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
// Allow a max of 5 seconds.
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
// set url
if( count($params) > 0 ) {
$query = http_build_query($params);
curl_setopt($ch, CURLOPT_URL, "$url?$query");
} else {
curl_setopt($ch, CURLOPT_URL, $url);
}
// $output contains the output string
$output = curl_exec($ch);
// Check for errors and such.
$info = curl_getinfo($ch);
$errno = curl_errno($ch);
if( $output === false || $errno != 0 ) {
// Do error checking
} else if($info['http_code'] != 200) {
// Got a non-200 error code.
// Do more error checking
}
// close curl resource to free up system resources
curl_close($ch);
return $output;
In this code, the $params could be an array where the key is the name, and the value is the value.

php curl help with google url shortner api

Im trying to shorten a url using ggole api's.Here is my php code .It gives a blank page when i load
<?php
define('GOOGLE_API_KEY', 'GoogleApiKey');
define('GOOGLE_ENDPOINT', 'https://www.googleapis.com/urlshortener/v1');
function shortenUrl($longUrl)
{
// initialize the cURL connection
$ch = curl_init(
sprintf('%s/url?key=%s', GOOGLE_ENDPOINT, GOOGLE_API_KEY)
);
// tell cURL to return the data rather than outputting it
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// create the data to be encoded into JSON
$requestData = array(
'longUrl' => $longUrl
);
// change the request type to POST
curl_setopt($ch, CURLOPT_POST, true);
// set the form content type for JSON data
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
// set the post body to encoded JSON data
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestData));
// perform the request
$result = curl_exec($ch);
curl_close($ch);
// decode and return the JSON response
return json_decode($result, true);
}
if (isset($_POST['url'])) {
$url = $_POST['url'];
$response = shortenUrl('$url');
echo sprintf(
$response['longUrl'],
$response['id']
);
}
?>
My html file:
<html>
<head>
<title>A BASIC HTML FORM</title>
</head>
<body>
<FORM NAME ="form1" METHOD =" " ACTION = "shortner.php">
<INPUT TYPE = "TEXT" VALUE ="Enter a url to shorten" name="url">
<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Shorten">
</FORM>
</body>
</html
I think I have found a solution to your problem. Since you are connecting to a URL that uses SSL, you will need to add some extra parameters to your code for CURL. Try the following instead:
<?php
define('GOOGLE_API_KEY', 'GoogleApiKey');
define('GOOGLE_ENDPOINT', 'https://www.googleapis.com/urlshortener/v1');
function shortenUrl($longUrl)
{
// initialize the cURL connection
$ch = curl_init(
sprintf('%s/url?key=%s', GOOGLE_ENDPOINT, GOOGLE_API_KEY)
);
// tell cURL to return the data rather than outputting it
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// create the data to be encoded into JSON
$requestData = array(
'longUrl' => $longUrl
);
// change the request type to POST
curl_setopt($ch, CURLOPT_POST, true);
// set the form content type for JSON data
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
// set the post body to encoded JSON data
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestData));
// extra parameters for working with SSL URL's; eypeon (stackoverflow)
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
// perform the request
$result = curl_exec($ch);
curl_close($ch);
// decode and return the JSON response
return json_decode($result, true);
}
if (isset($_POST['url'])) {
$url = $_POST['url'];
$response = shortenUrl('$url');
echo sprintf(
$response['longUrl'],
$response['id']
);
}
?>
I think it's coming form your html. You didn't put the form methode, so it send data by get.
And you show something only if you have post.
Try to do in the form method="post"
Edit
Bobby the main problem is that you don't have one problem but several in this code.
First if you don't do
<FORM NAME="form1" METHOD="POST" ACTION="shortner.php">
the if (isset($_POST['url'])) will never return true, because the variable send by the form will be GET (or do a if (isset($_GET['url']))).
Secondly you call the function with { $response = shortenUrl('$url'); }. Here you're not sending the url value but the string '$url'. So your variable $longUrl is always '$url'.
Thirdly you don't use sprintf like you should.
echo sprintf(
$response['longUrl'],
$response['id']
);
Sprintf need to take a string format:
echo sprintf("%s %s" // for example
$response['longUrl'],
$response['id']
);
But do you know that you can do directly
echo $response['longUrl'] . ' ' . $response['id'];
You can concatenate string directly with . in php
curl_exec() returns boolean false if something didn't go right with the request. You're not testing for that and assuming it worked. Change your code to:
$result = curl_exec($ch);
if ($result === FALSE) {
die("Curl error: " . curl_error($ch);
}
As well, you need to specify CURLOPT_RETURNTRANSFER - by default curl will write anything it receives to the PHP output. With this option set, it'll return the transfer to your $result variable, instead of writing it out.
You need to set CURLOPT_RETURNTRANSFER option in your code
function shortenUrl($longUrl)
{
// initialize the cURL connection
$ch = curl_init(
sprintf('%s/url?key=%s', GOOGLE_ENDPOINT, GOOGLE_API_KEY)
);
// tell cURL to return the data rather than outputting it
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// create the data to be encoded into JSON
$requestData = array(
'longUrl' => $longUrl
);
// change the request type to POST
curl_setopt($ch, CURLOPT_POST, true);
// set the form content type for JSON data
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
// set the post body to encoded JSON data
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
// perform the request
$result = curl_exec($ch);
curl_close($ch);
// decode and return the JSON response
return json_decode($result, true);
}
if (isset($_POST['url'])) {
$url = $_POST['url'];
$response = shortenUrl('$url');
echo sprintf(
$response['longUrl'],
$response['id']
);
}
// Create cURL
$apiURL = https://www.googleapis.com/urlshortener/v1/url?key=gfskdgsd
$ch = curl_init();
// If we're shortening a URL...
if($shorten) {
curl_setopt($ch,CURLOPT_URL,$apiURL);
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode(array("longUrl"=>$url)));
curl_setopt($ch,CURLOPT_HTTPHEADER,array("Content-Type: application/json"));
}
else {
curl_setopt($ch,CURLOPT_URL,$this->apiURL.'&shortUrl='.$url);
}
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
// Execute the post
$result = curl_exec($ch);
// Close the connection
curl_close($ch);
// Return the result
return json_decode($result,true);

Categories