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.
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 have the following data I pulled from an API using PHP's file_get_contents($url), I would like to parse this data and put each comma separated value into a variable whilst looping to the next set (there are thousands of row, I simply extracted the first two), I have tried parsing methods however most have an element consisting of the datalabel:data, any assistance would be gladly appreciated.
[[1610223840000,"3.63410000","3.65100000","3.62900000","3.64150000","14194.01000000",1610223899999,"51684.84892800",195,"7619.89000000","27756.15839400","0"],[1610223900000,"3.64610000","3.65090000","3.63410000","3.65000000","2219.73000000",1610223959999,"8090.68646600",46,"1176.75000000","4290.44934900","0"]]
Ok figured this out today, for anyone who needs it
$ch = curl_init();
$url = "https://api.blahblahblah";
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
curl_close($ch);
$obj = json_decode($result, true);
foreach ($obj as $key => $value) {
echo $value[0] . "<br>";
echo $value[1] . "<br>";
}
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);
}
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));
I want to make use of an API but it print alot of info and i don't know how i can get a few key values of the array.
<?php
$query = "SELECT * FROM kvk WHERE adres='Wit-geellaan 158'";
$host = "http://api.openkvk.nl/php/";
$url = $host ."/". rawurlencode($query);
$curl = curl_init();
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_exec($curl);
curl_close($curl);
?>
Is my php script and it shows
array(array("RESULT"=>array("TYPES"=>array("int","bigint","varchar","varchar","varchar","varchar","varchar","int","int","smallint","smallint","int"),"HEADER"=>array("id","kvk","bedrijfsnaam","adres","postcode","plaats","type","kvks","sub","bedrijfsnaam_size","adres_size","verhuisd"),"ROWS"=>array(array("1303095","271242250000","Schoonmaakbedrijf Regio","Wit-geellaan 158","2718CK","Zoetermeer","Hoofdvestiging","27124225","0","23","16","0")))))
Thanks in advance
Greetings,
Vierri
//Use the cURL setting to put the result into a variable rather than printing it
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
//store the result rather than print (as we set CURLOPT_RETURNTRANSFER)
$result = curl_exec($curl);
if ( $result === false ){
//something went wrong, handle the error
}
//evaluate the array result and store it. (Please don't use this line in production code)
//as the $result string is from a untrusted source
eval('$array = '.$result.';');
//then you can, for example, get a list of the types
$types = $array[0]['RESULT']['TYPES'];
//or some keys
$keys = array_keys($array[0]['RESULT']);
The above code is dangerous and probably shouldn't be used as it is. They could put anything nasty in the response and you would evaluate it (the eval line) which could do bad things to your server. I would check if they have a better API that doesn't send responses in that format. (json or XML would be better)
If not you may want to considerer manually parsing the response array rather than using eval
To get all keys and values:
$server_output = curl_exec($curl);
var_dump($server_output);
To just get a list of keys:
$server_output = curl_exec($curl);
ksort($server_output);
foreach ( $server_output AS $key => $val ) {
echo "$key\n";
}