Curl showing but not returning data - php

I'm trying to write a simple curl function that queries the freegeoip.net site with the IP address of a site visitor. This is usually done by typing "https://freegeoip.net/csv/{IP Address}" in the browser address line. The site then processes the request and returns a csv file that can be opened or saved. I'm trying to access the csv data directly so that I can parse and use it. This is the code that I am using:
<?php
$ip=$_SERVER["REMOTE_ADDR"];
$geturl = "http://freegeoip.net/csv/".$ip;
$data = curl_get_contents($geturl);
echo ("<br>Data = '".$data."'<br>");
function curl_get_contents($url)
{
$ch = curl_init($url);
if($ch)
{
$tmp = curl_exec($ch);
curl_close($ch);
return $tmp;
}
else
{
echo "Curl not loaded!<br>";
}
}
?>
This is what I am getting back:
...,US,United States,ST,State,City,?????,America/New_York,.*****,-.****,***
Data = '1'
As you can see, my function is accessing and showing the csv data but not returning it to the $data variable. Apparently, the data is being shown when the "curl_exec($ch);" command is being executed. I want to parse and use the returned data but can't until the data is returned. What am I doing wrong?

The documentation of curl_exec() says:
Return Values
Returns TRUE on success or FALSE on failure. However, if the CURLOPT_RETURNTRANSFER option is set, it will return the result on success, FALSE on failure.
What it doesn't say is explained in the documentation page of curl_setopt(), on the CURLOPT_RETURNTRANSFER option:
Option: CURLOPT_RETURNTRANSFER
Set value to: TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.
That is, by default, curl_exec() outputs the body of the response it gets. In order to make it return the value and not output it, you have to use curl_setopt():
$ch = curl_init($url);
curl_exec($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);

you need to add following line before curl_exec other wise the result will output instead of returning it to $tmp variable.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

You aren't telling Curl that you want the data to be returned rather than output:
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);
curl_setopt($ch, CURLOPT_URL, "http://freegeoip.net/csv/".$ip);
$csv=curl_exec($ch);
But this is rather verbose when, depending on your config, you can:
$csv=file_get_contents("http://freegeoip.net/csv/".$ip);

Related

PHP Curl, Request data accept in a variable

Hello I am having a very weird problem. I am writing this code to get the data from the koncat api
$url = 'https://api.kontakt.io/beacon/?device';
$privKey = 'key here';
$cURL = curl_init();
curl_setopt($cURL, CURLOPT_URL, $url);
curl_setopt($cURL, CURLOPT_HTTPGET, true);
curl_setopt($cURL, CURLOPT_HTTPHEADER, array("Api-Key: ".$privKey,
"Accept: application/vnd.com.kontakt+json;version=5",
"Content-Type: application/x-www-form-urlencoded"));
$result = curl_exec($cURL);
The problem is Data is successfully printing on the screen but I don't know which variable here is printing out the data. I didn't use echo command in my code. If I print out the result variable it prints out only '1' meaning success.
The php documentation about curl_exec says that it will return true or fail on failure. curl_exec will also print the result directly into the output.
If you don't want that, you need to set the curl option CURLOPT_RETURNTRANSFER to 1. This will tell curl_exec to return the result on sucess.
Documentation about CURLOPT_RETURNTRANSFER:
CURLOPT_RETURNTRANSFER TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.
More information:
http://php.net/curl_exec
http://php.net/curl_setopt

Extra value 1 is appending with curl response

From following two files I am getting output (2000)1 but It should only (2000)
After getting value using curl extra 1 is appending, but why?
balance.php
<?php
$url = "http://localhost/sms/app/user_balance.php";
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, 2);
curl_setopt($ch,CURLOPT_POSTFIELDS, "id=2&status=Y");
$result = curl_exec($ch);
curl_close($ch);
echo $result;
?>
user_balance.php
<?php
$conn = mysql_connect("localhost","root","");
mysql_select_db("sms",$conn);
$user_id = $_REQUEST["id"];
$sql = "SELECT * FROM user_sms WHERE user_id='$user_id'";
$rec = mysql_query($sql);
if($row = mysql_fetch_array($rec)) {
$balance = $row["user_sms_balance"];
}
echo "(".$balance.")";
?>
From the PHP manual documentation for curl_setopt():
CURLOPT_RETURNTRANSFER - Set value to TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.
If you don't set CURLOPT_RETURNTRANSFER option to TRUE , then the return value from curl_exec() will be the boolean value of the operation -- 1 or 0. To avoid it, you can set CURLOPT_RETURNTRANSFER to TRUE, like below:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
I can see that last response to this question was made back in 2017....
I have bashed my head around for past day and I finally got the results that I wanted. I had the same problem as the author of this question.
Maybe my solution will help others and if do help please vote it I would appreciate it.
So in my case I have build the plugin and using shortcode and cURL API get I am feeding API data into the shortcode output.
Anyway I had this working but also printing the Extra value , which is the true value from the CURLOPT_RETURNTRANSFER.
I have solved this by passing ob_start() and ob_get_clean() inside of my shortcode function. This has cleaned and return the response that I wanted without the Extra value 1 appending at the end of my data response.
My shortcode function looks like this
function shortcode_init(){
ob_start();
include PLUGIN_URL . 'templates/shortcode.php';
return ob_get_clean();
}
As you can see I am including the additional php where my cURL API call is defined.
In case someone needs this..here you go.
$ch = curl_init();
$url = YOUR API END POINT URL HERE;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$err = curl_error($ch);
curl_close($ch);
if ($err) {
echo $err;
} else {
// this returns the array from object
// then we can easily iterate thought arrays and echo values that we need,
$decoded = json_decode($response, true);
}

How to stop Resource from showing up in curl_exec result

Hi I'm trying to use this script to return a value from another php script on my site without leaving the page, but I am getting the number 1 after the string (I'm assuming that the 1 is the resource number) This is the script:
<?php
// 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
$result = curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
echo $result;
?>
Output is somthing like this:
"<?php include \\\\localfolder\\blabla\script.php ?>1"
and the 1 at the end is what I don't want showing up.
Thanks,
Robert
You need to set the CURLOPT_RETURNTRANSFER option to true:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
From the documentation:
CURLOPT_RETURNTRANSFER
TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.

Post and get result with PHP

From a PHP page, I'm trying to POST some data to another PHP page and get data back.
Here is what I currently have:
<?php
// Initialize cURL session
$ch = curl_init('postpage.php');
// Set some options on the session
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('field1' => 'Andrew'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute post
$result = curl_exec($ch);
var_dump($result);
// Close the session
curl_close($ch);
?>
and in postpage.php:
<?php
echo 'Receipt of post request. field1:'.$_POST["field1"];
?>
All the var_dump gives me is this:
string(0) ""
Why am I not getting the text back?
Thanks!
The curl executed from your php script is not aware of the current environment, that is, you cannot use relative urls. The url you supply to curl_init must be absolute (i.e. including http://)
If this is indeed the actual initialization you're doing, the error may lie in the arguments of curl_init() which expects a fully qualified URL.
Also, you might want to employ some error diagnostics. curl_exec returns FALSE on failure. The reason why can be determined with curl_error():
$ch = curl_init( ... );
// ... some curl_setopt()
$result = curl_exec($ch);
if ($result === FALSE)
{
die("cURL error: " . curl_error($ch));
}

Why are the Twitter api calls so slow?

When I execute the following code it takes between 10-12 seconds to respond.
Is the problem with Twitter or with our server?
I really need to know as this is part of the code to display tweets on our website and a 12 second load time is just not acceptable!
function get_latest_tweets($username)
{
print "<font color=red>**". time()."**</font><br>";
$path = 'http://api.twitter.com/1/statuses/user_timeline/' . $username.'.json?include_rts=true&count=2';
$jason = file_get_contents($path);
print "<font color=red>**". time()."**</font><br>";
}
Thanks
When you put the URL into your browser (http://api.twitter.com/1/statuses/user_timeline/username.json?include_rts=true&count=2) how long does it take for the page to appear? If it's quick then you need to start the search at your server.
use curl instead of file_get_contents() to request, so that response will be compressed. Here is the curl function which iam using.
function curl_file_get_contents($url)
{
$curl = curl_init();
curl_setopt($curl,CURLOPT_URL,$url); //The URL to fetch. This can also be set when initializing a session with curl_init().
curl_setopt($curl,CURLOPT_RETURNTRANSFER,TRUE); //TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.
curl_setopt($curl,CURLOPT_ENCODING , "gzip");
curl_setopt($curl, CURLOPT_FAILONERROR, TRUE); //To fail silently if the HTTP code returned is greater than or equal to 400.
curl_setopt($curl,CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE);
$contents = curl_exec($curl);
curl_close($curl);
return $contents;
}

Categories