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));
Related
I want to send data from server 1 to server 2, first I select necessary data from the database, but how to send data with curl? I understand that I cannot send $result parameter just like in my code, but how should I do this?
My Code server 1:
public function setDivisions(){
$result = $this->conn->query("SELECT *FROM data_divisions");
$ch = curl_init('https://example.com/api.php?siteid='.$this->site_key.'');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $result);
curl_setopt($ch, CURLOPT_POST, 1);
$response = curl_exec($ch);
print_r($response);
}
Code on server 2:
$array = $_POST['result'];
//loop throw array and insert data into database
you can use it that way.
$ch = curl_init('https://upxxx.cod3fus1ontm.com/curl/json');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode((object)["records" => json_encode($result)]));
$response = curl_exec($ch);
var_dump($response);
on receipt, like this!
$json = file_get_contents("php://input");
$content = json_decode($json, true);
$records = json_decode($content['records'], true);
foreach($records as $record) {
echo $record['id'] . " - " . $record['text'] . "<br/>";
}
remember, that as you did to encode, you will have to do to decode
Come on, php://input returns all raw data after the request's HTTP headers, regardless of content type.
When we do this with file_get_contents (which reads the contents of a file and puts it into a variable of type string), we can read the content that was sent by curl.
Reviewing the code, you can optimize as follows, when sending to the server you placed, I suggested:
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode((object)["records" => json_encode($result)]));
you can replace it with:
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($result));
it's much simpler, but it's very important to put the query result inside a json_encode
finally, you can access the entire body of the message, through file_get_contents ("php://input") and put it inside a variable, which is nothing more than a JSON of the your query.
for you to understand how the parameters were passed, it is interesting to do the following:
$json = file_get_contents("php: // input");
var_dump($json); <- Here you see the thing as it is.
$records = json_decode($json, true); <- Here you generate an object with the content of json
var_dump($records);
With that, I think that solves the situation.
on server 1
$result = "result=".base64_encode($result)
curl_setopt($ch, CURLOPT_POSTFIELDS, $result);
...
on server 2
$array = base64_decode($_POST['result']);
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);
i have this code for read some data from a database, and call another php script (hostes on another server) for sending retrieved data. this is my code:
while ($rs = mysql_fetch_array($quary_result)) {
$fields = array(
'field1' => $rs['field1']
);
$postvars = http_build_query($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
$result = curl_exec($ch);
curl_close($ch);
}
but this code is executed only once. My query as about 200 results, while is executed only one time. What's wrong?
You have the impression that it is executed only once...
Your code says this:
while $rs = mysql_fetch_array($query_result) is true { do something }
Then the $result var will be overwritten at each entering in the while loop. Try converting the $result var into an array of result and then print the array to see if you have all your values like:
$result[] = curl_exec($ch);
echo '<pre>';
print_r($result);
echo '</pre>';
Also, you can use foreach() like:
$result = mysql_fetch_array($query_result);
foreach ($result as $res) { do something }
AND STOP USING MYSQL - this is deprecated. Use PDO instead like you are thought in this tutorial: PDO Tutorial.
I have script that calls at script via cURL. It looks like this,
Route::get('login-redirect', function() {
if (Input::has('error')) {
return Input::get('error_description');
}
if (Input::has('code')) {
$fields = array(
'grant_type' => 'password',
'username' => 'admin#local.com',
'password' => 'passwohrd',
'client_id' => 'testclient'
);
$fieldstring = http_build_query($fields, "\n");
$url = "http://apitest.local/api/v1/get-token";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fieldstring);
$result = curl_exec($ch);
$json = json_decode($result);
curl_close($ch);
$fields = array('access_token' => '3c1e6b099f172fc01304403939edf8e56904ab61');
$fieldstring = http_build_query($fields, "\n");
$url = "http://apitest.local/api/v1/me";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fieldstring);
$result = curl_exec($ch);
curl_close($ch);
dd($result);
}
The json returned looks like this, if I do dd($json)
{"content":null,"error":true,"error_description":"Invalid username and password combination"}int(1)
I feel like after running it through json_decode I should be able to just output $json->error but no.
The JSON gets made in the following class, but I cannot see anything odd here either, I am doing incorrect, or do I misunderstand json_decode?
<?php
namespace Shaunpersad\ApiFoundation\Http;
use App;
use Response;
class ErrorResponse
{
public static function make($message = '', $status = 200, array $headers = array(), $options = 0)
{
$response = App::make(
'api_response_array',
array(
'content' => null,
'error' => true,
'error_description' => $message
)
);
return Response::json($response, $status, $headers, $options);
}
}
First of all, you do not have CURLOPT_RETURNTRANSFER - your curl_exec returns output buffer directly to the screen.
Second of all, it looks like you have var_dump somewhere and I cannot see where :)
Third of all - you didn't asked any direct question.
Edit
Okay i've read it few time and answer below. The dd() function is truly a var_dump wrapper but it is dumping var_dump data into json format afaics.
What you've got as an output is not from dd($json):
// this part has been output by curl_exec():
{"content":null,"error":true,"error_description":"Invalid username and password combination"}
// only this part comes from dd($json):
int(1)
Here's why:
// no CURLOPT_RETURNTRANSFER, so curl_exec() outputs result and returns true:
$result = curl_exec($ch);
// thus $result = true;
// so here $json = 1, since this is what json_decode(true) will return
$json = json_decode($result);
// then you did dd($json), so it just appended var_dump(1) to the output:
{"content":null,"error":true,"error_description":"Invalid username and password combination"}int(1)
Update
As stated in the other answers, you're not actually receiving the output because you haven't set CURLOPT_RETURNTRANSFER. So curl_exec() will echo out the response to the DOM and return true (1) as your curl request ran successfully.
You'll be able to run the below stuff by setting this in your curl request somewhere:
curl_setop(CURLOPT_RETURNTRANSFER, true);
dd() is a laravel function and this is what the documentation says:
Dump the given variable and end execution of the script.
I'd presume it is just a wrapper function for a prettier looking var_dump() (As I don't use laravel, I wouldn't know its exact output.).
What you want is to decode the $result that is returned from your cUrl. Something like this should suffice:
$data = json_decode($result);
echo $data->error_description;
The successfully decoded object looks like this:
stdClass Object
(
[content] =>
[error] => 1
[error_description] => Invalid username and password combination
)
Example
You can even test your boolean error value like this now:
if($data->error) {
//....true
} else {
//....false
}
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);
}