cURL and PHP displaying "1" - php

I have a PHP script with which I want to read servers from database and connect to them with cURL. Servers responds with results from sql query. The problem is that script after each respond from server displays number 1. The ouput looks like this:
Server 1: some results
1Server 2: some results
1Server 3: some results
1
Here is the code that reads servers from database and connects to them:
<?php
$mysql_id = mysql_connect('localhost', 'ms', 'pass');
mysql_select_db('servers', $mysql_id);
mysql_query("SET NAMES utf8");
$query = "SELECT * FROM svr";
$result = mysql_query($query);
$num = mysql_num_rows($result);
while ($data = mysql_fetch_assoc($result))
{
$server[] = $data;
}
mysql_close($mysql_id);
$i = 0;
while($i < $num) {
$dealer = $server[$i]['dealer'];
echo $dealer . "<br />";
$data = "val=a"; //just for testing
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: text/html; charset=utf-8')
);
$result = curl_exec($ch);
echo $result;
$i++;
}
?>
I discovered that 1 is displayed with "echo $result;" and the code for creating response is this:
<?php
$mysql_id1 = mysql_connect('localhost', 'ms', 'pass');
mysql_select_db('servers', $mysql_id1);
mysql_query("SET NAMES utf8");
$query2 = "SELECT * FROM data";
$result2 = mysql_query($query2);
$num2 = mysql_num_rows($result2);
while ($data2 = mysql_fetch_assoc($result2))
{
$deli[] = $data2;
}
$i1 = 0;
$space = " ";
while ($i1 < $num2) {
echo $space . $deli[$i1]['id'] . " ";
echo $deli[$i1]['artikel'] . " ";
echo $deli[$i1]['znamka'] . " ";
echo $deli[$i1]['model'] . " ";
echo $deli[$i1]['letnik'] . " ";
echo $deli[$i1]['cena'] . " € ";
echo $deli[$i1]['zaloga'] . "<br />";
$i1++;
}
echo "<br />";
mysql_close($mysql_id1);
?>
Please help me

Use the CURLOPT_RETURNTRANSFER option. Otherwise cURL will automatically echo the data and just return true (which is converted to 1 by echo).
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
PHP.net says,
TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it directly.

You need to use CURLOPT_RETURNTRANSFE or curl_exec returns a statuscode and sends the response to stdout:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

CURLOPT_RETURNTRANSFER shoud be TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.read the full documentation php.net
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
or you can do
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

Use CURLOPT_RETURNTRANSFE or else it will return a status-code and sends the response to stdout:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

Man, if the user can change dealer field or $deli fields you have got stored XSS vulnerability here.
$dealer = $server[$i]['dealer'];
echo $dealer . "<br />";
echo $space . $deli[$i1]['id'] . " ";
...etc
use
htmlentities($your fields)
to solve this problem

Related

php is inserting empty data in mysql database automatically everyday

I have created an application where user can send notification to other devices with php as backend and fcm notification. On successfully sending the notification it store the details of notification and notification sender(user) on mysql database with table name 'notification' and 'sender_details'. However, new empty data are being stored in these two table everyday while the app is not even opened by anybody. Please Help
<?php
include('../conn.php');
$api_key="xxx";
$url="https://fcm.googleapis.com/fcm/send";
$fields=json_encode(array('to'=>$to,'notification'=>$data));
// Generated by curl-to-PHP: http://incarnate.github.io/curl-to-php/
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($fields));
$headers = array();
$headers[] = 'Authorization: key ='.$api_key;
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
}
//fetching data
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$date3 = date('Y-m-d');
$sqlm = "SELECT dateonly FROM user_details WHERE token='".$_POST['token']."' AND dateonly='$date3'";
$result3 = mysqli_query($conn, $sqlm);
if (mysqli_num_rows($result3) > 0) {
echo "alreadysend";
}else{
$sql = "SELECT * FROM data WHERE group='".$_POST['group']."'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$to=$row["token"];
//for sending email
$email=$row["email"];
$time2=date_default_timezone_set('Asia/Katmandu');
$date2 = date('Y-m-d h:i:s a', time());
$sql2 = "INSERT INTO user_details (name, phone, city)
VALUES ('".$_POST['name']."', '".$_POST['phone']."', '".$_POST['city']."')";
if ($conn->query($sql2) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql2 . "<br>" . $conn->error;
}
//end of second sql queries
// 2. for body of message
$body = $_POST["name"].' needs ' at '.$_POST["city"].', '.$_POST["hospital"].' hospital. Contact on the following number: '.$_POST["phone"].' (Message from them: '.$_POST["message"].')';
// 3. for title
$title = New Notification';
$data=array(
'title'=> $title,
'body'=>$body,
'image' => $img,
'vibrate' => 1
);
$time=date_default_timezone_set('Asia/Katmandu');
$date = date('Y-m-d h:i:s a', time());
$dateonly = date('Y-m-d');
$sql3 = "INSERT INTO notifications (title, body, time, dateonly)
VALUES ('$title', '$body', '$date', '$dateonly')";
if ($conn->query($sql3) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql3 . "<br>" . $conn->error;
}
//end of third sql queries
notify($to,$data);
}
} else {
echo "noresults";
}
}
mysqli_close($conn);
?>
All the post data are being received from the app

file_get_contents HTTP request failed error

So I have GetMessages.php, this script gets data out of an database(MongoDB). Then it makes a cURL POST to MyMessagesMDB.php. This is the code:
<?php
$FirstName = '';
$LastName = '';
$Email = '';
$Subject = '';
$Message = '';
GetFromDB();
echo $FirstName." ".$LastName;
echo "<br>";
echo $Email;
echo "<br>";
echo $Subject;
echo "<br>";
echo $Message;
echo "<br>";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://192.168.0.163/MyMessagesMDB.php");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS,
"FirstName=$FirstName&LastName=$LastName&Email=$Email&Subject=$Subject&TextMessage=$Message");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
curl_close($ch);
function GetFromDB(){
$client = new MongoDB\Driver\Manager('mongodb+srv://####:#########.tldyu.mongodb.net/Data');
$filter = [];
$options = [];
$query = new MongoDB\Driver\Query($filter, $options);
$cursor = $client->executeQuery('ContactMessages.ContactForm', $query);
foreach($cursor as $document){
$document = json_decode(json_encode($document),true);
global $FirstName, $LastName, $Email, $Subject, $Message;
$FirstName = $document['FirstName'];
$LastName = $document['LastName'];
$Email = $document['Email'];
$Subject = $document['Subject'];
$Message = $document['Message'];
}
}
?>
MyMessagesMDB.php is the script to get called first. It calls GetMessages.php and should then receive the information it has posted. Here is the code:
<?php
$FirstLoop = true;
if($FirstLoop == true){
file_get_contents('http://192.168.0.102/test/GetMessages.php');
$FirstLoop = false;
}
$FirstName = $_POST["FirstName"] ?? "";
$LastName = $_POST["LastName"] ?? "";
$Email = $_POST["Email"] ?? "";
$Subject = $_POST["Subject"] ?? "";
$Message = $_POST["TextMessage"] ?? "";
echo $FirstName." ".$LastName;
echo "<br>";
echo $Email;
echo "<br>";
echo $Subject;
echo "<br>";
echo $Message;
echo "<br>";
?>
But here starts my problem.
If I call MyMessagesMDB.php I get the error:
PHP Warning: file_get_contents(http://192.168.0.102/test/GetMessages.php): Failed to open stream: HTTP request failed!.
If I try to load the page manually I get no error and the data out of the database is printed on the screen.
When in MyMessagesMDB.php I comment the following line like this:
#file_get_contents('http://192.168.0.102/test/GetMessages.php');
I can load the page without any problem or error.
The Question
What do I have to do to call GetMessages.php from MyMessagesMDB.php and receive the information out of the database?
Note: I have tried
$curl_handle=curl_init();
curl_setopt($curl_handle,
CURLOPT_URL,'http://###.##.##.##/mp/get?
mpsrc=http://mybucket.s3.amazonaws.com/11111.mpg&mpaction=convert
format=flv');
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_handle, CURLOPT_USERAGENT, 'Your application
name');
$query = curl_exec($curl_handle);
curl_close($curl_handle);
After our comments back and forth, I think your implementation is way more complicated than it needs to be. Instead of MyMessagesMDB.php acting as both an initiator of the process and a recipient of data, it only needs to be an initiator.
In this implementation, mdb.php acts as the script that would sit with your database, it's whole job is to take everything from the ContactMessages.ContactForm query and output it as JSON.
<?php
$client = new MongoDB\Driver\Manager('mongodb+srv://####:#########.tldyu.mongodb.net/Data');
$filter = [];
$options = [];
$query = new MongoDB\Driver\Query($filter, $options);
$cursor = $client->executeQuery('ContactMessages.ContactForm', $query);
header('Content-Type: application/json');
echo json_encode($cursor);
Then you have get.php, which you have on the server at school, which uses file_get_contents to get the JSON, and then convert it back to a PHP array, which you can then output however you see fit.
<?php
$mdb_url = 'http://192.168.0.102/test/GetMessages.php';
$get = file_get_contents($mdb_url);
$decoded = json_decode($get, true);
foreach ($decoded as $document) {
echo $document['FirstName'] . '<br>' .
$document['LastName'] . '<br>' .
$document['Email'] . '<br>' .
$document['Subject'] . '<br>' .
$document['Message'] . '<br><hr>';
}

Stuck with arrays

Hi I am currently building a website where people can check the price of cyrptocurrencies. The coins I want to watch are in arrays, so it will read one by one and put it in the URL.
What I am now trying to do is to get all coins I want from the database and put it one by one in the URL. I already tried something by myself, but it is not working very well, and I am constantly getting errors or not the right result.
$array is the manual variable, and the ones above are the coins from the database
This is my code:
require_once('config.php');
$query = "SELECT * FROM targets";
$result = mysqli_query($mysqli, $query);
$datas = array();
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$datas[] = $row;
}
}
foreach ($datas as $data) {
$test = "'".$data['coin']."', ";
}
$array = array('vertcoin', 'spectrecoin', 'carvertical');
foreach ($array as $coins) {
$url = "https://api.coinmarketcap.com/v1/ticker/".$coins."/";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
$parsed_json = json_decode($data);
$name = $parsed_json['0']->name;
$symbol = $parsed_json['0']->symbol;
$price_usd = $parsed_json['0']->price_usd;
$price_btc = $parsed_json['0']->price_btc;
$percent_change_1h = $parsed_json['0']->percent_change_1h;
$percent_change_24h = $parsed_json['0']->percent_change_24h;
$percent_change_7d = $parsed_json['0']->percent_change_7d;
echo "<br><br>name: ". $name ."<br>";
echo "symbol: ". $symbol ."<br>";
echo "price_usd: ". $price_usd ."<br>";
echo "price_btc: ". $price_btc ."<br>";
echo "1h change: ". $percent_change_1h ."<br>";
echo "24h change: ". $percent_change_24h ."<br>";
echo "7d change: ". $percent_change_7d ."<br><br>";
}
Seems like you are overwritting the $test value each time.
I do not understant which variable is what, but If I am not wrong the following statement is where you try to concatenate your values:
foreach ($datas as $data) {
if($test){
//when $test is not null remember the value.
$test = $test."'".$data['coin']."', ";
}else{
//Otherwise set $test
$test = "'".$data['coin']."', ";
}
}
Assuming the following table:
CREATE TABLE `targets` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`coin` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
With this data:
INSERT INTO `targets` (`id`, `coin`) VALUES
(1, 'vertcoin'),
(2, 'spectrecoin'),
(3, 'carvertical');
This code:
require_once 'config.php';
$query = "SELECT * FROM targets";
$result = mysqli_query($mysqli, $query);
$coinList = array();
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$coinList[] = $row['coin'];
}
}
//print_r($datas);
foreach ($coinList as $coinItem) {
$url = "https://api.coinmarketcap.com/v1/ticker/".$coinItem."/";
echo sprintf('URL for coin '%s' is %s', $coinItem, $url);
// Rest of code goes here.
// curl etc.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
$parsed_json = json_decode($data);
$name = $parsed_json['0']->name;
$symbol = $parsed_json['0']->symbol;
$price_usd = $parsed_json['0']->price_usd;
$price_btc = $parsed_json['0']->price_btc;
$percent_change_1h = $parsed_json['0']->percent_change_1h;
$percent_change_24h = $parsed_json['0']->percent_change_24h;
$percent_change_7d = $parsed_json['0']->percent_change_7d;
echo "<br><br>name: ". $name ."<br>";
echo "symbol: ". $symbol ."<br>";
echo "price_usd: ". $price_usd ."<br>";
echo "price_btc: ". $price_btc ."<br>";
echo "1h change: ". $percent_change_1h ."<br>";
echo "24h change: ". $percent_change_24h ."<br>";
echo "7d change: ". $percent_change_7d ."<br><br>";
}
Produces this output:
URL for coin vertcoin is https://api.coinmarketcap.com/v1/ticker/vertcoin/
name: Vertcoin
symbol: VTC
price_usd: 4.53398
price_btc: 0.00040362
1h change: -0.11
24h change: -2.77
7d change: 6.88
URL for coin spectrecoin is https://api.coinmarketcap.com/v1/ticker/spectrecoin/
name: Spectrecoin
symbol: XSPEC
price_usd: 2.93546
price_btc: 0.00026103
1h change: 0.01
24h change: -3.42
7d change: 14.64
URL for coin carvertical is https://api.coinmarketcap.com/v1/ticker/carvertical/
name: carVertical
symbol: CV
price_usd: 0.011548
price_btc: 0.00000103
1h change: 3.75
24h change: -8.44
7d change:

Can not send data to server with post request

i have 2 file.
file one.php:
<?php
include 'config/dbconnect.php';
$query = mysql_query("select * from getgift_logs where status = 1") or die(mysql_error());
echo("<table border='1'>");
echo("<tr>");
echo("<td>User ID</td>");
echo("<td>Yes</td>");
echo("</tr>");
while ($row = mysql_fetch_array($query)) {
echo("<tr>");
echo("<td>".$row['user_id']."</td>");
echo "<td><button class='yes' gift_id = '".$row['id']."'>Yes</button></td>";
echo("</tr>");
}
echo("</table>");
?>
<div id='result'></div>
<script type = "text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$('.yes').click(function() {
var trans_id=$(this).attr("gift_id");
$.ajax({
url : "process.php?id="+trans_id,
type: "GET",
success: function(result) {
$('#result').html(result);
},
});
});
</script>
File one.php i send one get request to process.php file. And this is file process.php:
<?php
include("config/dbconnect.php");
date_default_timezone_set("UTC");
$id = $_POST['trans_id'];
$query = mysql_query("select * from getgift_logs where id = '".$id."'");
$row = mysql_fetch_array($query);
$topuplink = $row['topuplink'];
$trans_id = $row['trans_id'];
$clientsecret = $row['clientsecret'];
$accesstoken = $row['accesstoken'];
$lost_money = $row['lost_money'];
$status = $row['description'];
$time = date('Ymdhis',time());
$sign = md5($money."|".$trans_id."|".$time."|".$clientsecret);
$ch = curl_init();
$data = array(
'topup_money' => $lost_money,
'reference_trans_id' => $trans_id,
'description'=>$status,
'request_time'=> $time,
'sign'=>$sign
);
$postvars = '';
foreach($data as $key=>$value) {
$postvars .= $key . "=" . $value . "&";
}
$url = $topuplink."".$accesstoken;
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS,$postvars);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
print_r($response);
curl_close ($ch);
?>
In process.php file i send POST REQUEST but it not work(It not send data to server).
I don't know i wrong something? Please, help me! Thank all!
Try this one
$postvars = '';
foreach($data as $key=>$value) {
$postvars .= $key . "=" . $value . "&";
}
rtrim($postvars , '&'); // remove last &
$url = $topuplink."".$accesstoken;
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, count($data)); // count of total post fields
curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
print_r($response);
curl_close ($ch);

PHP Simple XML Parser, blank response

PHP Simple XML Parser, blank response.
The main problem with the code below is that without the parser it will work fine but as soon as the XML parser is added, so it can connect to the other server from the client, it will not return with the results, just a blank page?
Also this is a project, so before anyone ask's, why do you not have any SQLi protection. I have not as of yet implemented it yet.
Here is the code below:
Client side XML parser code: hinphp.php
<?php
$hin = $_GET["hin"];
$connection = curl_init();
curl_setopt($connection, CURLOPT_URL, "http://192.168.0.12/hinbuy.php?hin=");
curl_setopt($connection,CURLOPT_RETURNTRANSFER,1);
curl_setopt($connection,CURLOPT_HEADER, 0);
$response = curl_exec($connection);
$xml = simplexml_load_string($response);
for($index=0; $index < count($xml->songs); $index++)
{
echo $xml->songs[$index]->ID . "<br />";
echo $xml->songs[$index]->song . "<br />";
echo $xml->songs[$index]->artist . "<br />";
echo $xml->songs[$index]->year . "<br />";
echo $xml->songs[$index]->genre . "<br />";
echo $xml->songs[$index]->quantity . "<br />";
$ID = $xml->songs[$index]->ID;
echo "<a href='http://192.168.0.12/buyclihin.php?ID=$ID'>buy</a>";
}
curl_close($connection);
?>
Server side PHP select code: hinbuy.php
<?php
header("Content-type: text/xml");
echo "<?xml version='1.0' encoding='ISO-8859-1'?>";
echo "<hit>";
$hin = $_GET["hin"];
$conn = new PDO("mysql:host=localhost;dbname=xxxxx;","xxxxx","xxxxx");
$results = $conn->query("SELECT * FROM `ghit` WHERE `artist`='$hin'");
while($row=$results->fetch())
{
echo "<songs>";
echo "<id>$row[ID]</id>";
echo "<song>$row[song]</song>";
echo "<artist>$row[artist]</artist>";
echo "<year>$row[year]</year>";
echo "<genre>$row[genre]</genre>";
echo "<quantity>$row[quantity]</quantity>";
echo "</songs>";
}
echo "</hit>"
?>
Is it probably because you are not passing $hin to hibbuy.php?
Try:
$hin = $_GET["hin"];
$connection = curl_init();
curl_setopt($connection, CURLOPT_URL, "http://192.168.0.12/hinbuy.php?hin=" . $hin);

Categories