Extra value 1 is appending with curl response - php

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);
}

Related

How NOT to display cURL response data in php?

I have the following code that makes an API call to a URL. The response is in json format.
When the response data is received, I want to further process the data using another function and NOT display the data in the console (I want to display only the final processed output). But currently, the response from the API call is being displayed in the console along with the final processed output.
The processed final data will be saved in $processedData variable.
<?php
function getDataFromApi(){
$url = 'https://www.myurl.com/data.json';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
function processData($data){
/**
* Do the processing and save processed data in $processedData variable.
*/
// Finally display the data
echo $processedData;
}
$result = getDataFromApi();
processData($result);
How do I NOT display the intermediate cURL resplonse but only the final response?
you are passing data variable but echoing the process data variable
function getDataFromApi(){
$url = 'https://www.myurl.com/data.json';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
curl_close($ch);
$processdata = processData($data);
return $processdata;
}
function processData($data){
/**
* Do the processing
*/
// Finally display the data
echo $data;
}
echo $getDataFromApi();
I found answer to my question myself so I am posting it here so that it can help others.
My code as stated in the question, by default executes the curl request and prints the output in the screen.
In the current form, the line $result = curl_exec($ch); will execute the cURL request and returns true or false based on whether the request was successful or not. So, the $result variable will NOT hold the response data (as opposed to what I assumed earlier), but either true or false.
In order not to display the response and save it in a variable (and pass it to another function), CURLOPT_RETURNTRANSFER option needs to be set to true as follows:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
This line instructs cURL to Return the response as a string instead of outputting it to the screen.
The final code would be as follows:
<?php
function getDataFromApi(){
$url = 'https://www.myurl.com/data.json';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
function processData($data){
/**
* Do the processing and save processed data in $processedData variable.
*/
// Finally display the data
echo $processedData;
}
$result = getDataFromApi();
processData($result);
Use below
function processData($data){
/** * Do the processing */
// Finally display the data echo $data;
}

Curl showing but not returning data

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);

PHP and Curl not Returning Output with Variable

Here is my index.php file...
<?php
// Defining the basic cURL function
function curl($url) {
$ch = curl_init(); // Initialising cURL
curl_setopt($ch, CURLOPT_URL, $url); // Setting cURL's URL option with the $url variable passed into the function
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); // Setting cURL's option to return the webpage data
$data = curl_exec($ch); // Executing the cURL request and assigning the returned data to the $data variable
curl_close($ch); // Closing cURL
return $data; // Returning the data from the function
}
$url1 = $_GET['link'];
$response = curl($url1);
$response = str_replace("./views","http://movietube.pm/views",$response);
$response = str_replace("./lib","http://movietube.pm/lib",$response);
$response = str_replace("./assets","http://movietube.pm/assets",$response);
echo $response;
?>
// Defining the basic cURL function
function curl($url) {
$ch = curl_init(); // Initialising cURL
curl_setopt($ch, CURLOPT_URL, $url); // Setting cURL's URL option with the $url variable passed into the function
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); // Setting cURL's option to return the webpage data
$data = curl_exec($ch); // Executing the cURL request and assigning the returned data to the $data variable
curl_close($ch); // Closing cURL
return $data; // Returning the data from the function
}
$url1 = $_GET['link'];
$response = curl($url1);
$response = str_replace("./views","http://movietube.pm/views",$response);
$response = str_replace("./lib","http://movietube.pm/lib",$response);
$response = str_replace("./assets","http://movietube.pm/assets",$response);
echo $response;
?>
Basically, what I want it to do is take an input
www.example.com?link=(link)
and return the HTML of the page, after executing the php...
On the output, it loads the page correctly, but it doesn't put in the tv show stuff, like the video player, the links, or the episode director...
What it does...
http://muchmovies.uphero.com/?link=http://www.tvstreaming.cc/watch.php?v=TGmi0OPy0Cc
What I want it to do...
http://www.tvstreaming.cc/watch.php?v=TGmi0OPy0Cc
Any help is appreciated!
Maybe you have a problem with php variable $_GET['link'] because you put this link:
http://muchmovies.uphero.com/?link=http://www.tvstreaming.cc/watch.php?v=TGmi0OPy0Cc
And note that your query string will be this:
?link=http://www.tvstreaming.cc/watch.php?v=TGmi0OPy0Cc
This query string must be encoding and you are not encoding it, so, variable $_GET['link'] will not have the value that you need to do the curl.
I recommend you 2 options:
Encode url params
Or, pass the url using base64 encode then on your
server use base decode
Please, tell me if this was the solution.

PHP Curl not storing json_encoded echoed data

Does anyone no if it is possible to store echoed results from a Curl script.
Example of script been submitted to:
\\some code to generate images using imagick and the post variables
$array = array(1,2,3,4,5,6,7,8,9);
$result = json_encode($array);
echo $result;
Example of Curl:
$id = 1;
$champ = array("product" => "1","id"=> $id,"occasion"=> $o,"field1" => "1991","field2" => "test","field3" =>"test1","field4" => "test2","field5" =>"test3","field6" =>"test4","field7" =>"test5","field8" =>"test6","test7");
foreach($champ as $key => $data){
$field_string .= $key."=".$data."&";
}
rtrim($field_string, "&");
$url = "http://www.test.com/website/script.php";
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST, count($champ));
curl_setopt($ch,CURLOPT_POSTFIELDS, $field_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, FALSE);
$result = curl_exec($ch);
$array = json_decode($result);
curl_close($ch);
var_dump($array);
If i var_dump($result) i get a bool(true) so i know that the script has executed correctly and the output shows on screen however i don't seem to be able to store the information into a variable to process.
Thank you in advance
As curl_exec documentation says:
curl_exec() 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.
In your case you turn CURLOPT_RETURNTRANSFER off.
Turn it on by
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
and check the $result again.
Note: building a request using foreach loop and rtrim() you may damage it if your data contains & character.
Just use http_build_query() with your $champ :
curl_setopt($ch,CURLOPT_POSTFIELDS, http_build_query($champ));

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));
}

Categories