My Webservices not working PHP/MYSQL/JSON - php

I have created web services but it is not working using cURL.
When I am using file_get_contents($request) it is working.
I want to call it using cURL
Server Input Code
<?php
require_once('config.php');
$posts = array();
/* require the user as the parameter */
if(isset($_GET['roll']) and isset($_GET['name']))
{
/* soak in the passed variable or set our own */
$roll = $_GET['roll']; //no default
$name = $_GET['name']; //no default
/* grab the posts from the db */
if($roll!="" and $name!="")
{
$query = "INSERT INTO STUDENT VALUES('$roll','$name')";
if(mysql_query($query,$dblink))
{
$posts[] = array('status'=>'Data Inserted');
}
else
{
$posts[] = array('status'=>'Not Inserted');
}
}
else
{
$posts[] = array('status'=>'Null Value sent');
}
/* disconnect from the db */
#mysql_close($db);
}
else
{
$posts[] = array('status'=>'Please check the arguments');
}
/* output in necessary format */
header('Content-type: application/json');
echo json_encode(array('posts'=>$posts));
?>
Server Output Code is
<?php
require_once('config.php');
/* require the user as the parameter */
$posts = array();
if(isset($_REQUEST['roll']))
{
$posts = array();
/* soak in the passed variable or set our own */
$roll = $_REQUEST['roll']; //no default
/* grab the posts from the db */
if($roll!="")
{
if($roll=="All")
{
$query = "SELECT * FROM STUDENT";
}
else
{
$query = "SELECT * FROM `STUDENT` WHERE roll = '$roll'";
}
$result = mysql_query($query,$dblink) or die('Errant query: '.$query);
if(!$result)
{
$posts[] = array('status'=>'Roll Not Found');
}
else
{
/* create one master array of the records */
if(mysql_num_rows($result))
{
while($post = mysql_fetch_assoc($result))
{
$posts[] = array('student'=>$post);
}
}
else
{
$posts[] = array('status'=>'Roll not Found');
}
}
}
else
{
$posts[] = array('status'=>'Roll Should Not be Null');
}
/* disconnect from the db */
#mysql_close($db);
}
else
{
$posts[] = array('status'=>'Please send Valid Argument');
}
/* output in necessary format */
header('Content-type: application/json');
echo json_encode(array('posts'=>$posts));
?>
Call Using file_get_contents($request) Its working
<?php
$request="https://returns.jabong.com/tracking/WebServices/server_output.php?roll=12MCA02";
//$request="https://returns.jabong.com/tracking/WebServices/server_input.php?roll=12MCA02&name=Aneesh Khan";
$response = file_get_contents($request);
print_r($response);
?>
Call using cURL - Its not working
$sUrl = "https://returns.jabong.com/tracking/WebServices/server_input.php";
$sData = 'roll=12MCA05&name=Aneesh A Khan';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $sUrl);
curl_setopt($ch, CURLOPT_POSTFIELDS, $sData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
$vRes = curl_exec($ch);
curl_close($ch);
header('Content-Type: text/json');
echo $vRes;
?>
Call is not working using cURL , Please help me soon ?

Your code was quite mixed up - you are requiring $_GET parameters in some places, $_REQUEST parameters in others and the curl function looks like it's attempting to send via POST - but there are options missing to force curl to send via POST. Using a simple GET request via curl with the parameters appended to the url the data gets inserted.
<?php
$sUrl = "https://returns.jabong.com/tracking/WebServices/server_input.php";
$sData = 'roll='.uniqid().'&name='.uniqid('user_',true);
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $sUrl . '?' . $sData );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );
$vRes = curl_exec($ch);
curl_close($ch);
echo $vRes;
?>
Which method is it you want to use? And, as #Marc pointed out this code is open to sql injection.

Related

Parse error: syntax error, unexpected '(', expecting '{' in C:\wamp\www\NewFirebase\Firebase.php on line 3

sent push notification using Firebase via PHP API.Parameter pass from the android and data get to push notification sent to android. Announcement get data from the database and its pass data in Firebase class and its sent to notification in android.in line 3 whats error i don't Know.
Announcement.php
<?php
if($_SERVER['REQUEST_METHOD']=='GET'){
// $full_name = $_POST['full_name'];
// $contact_number = $_POST['contact_number'];
require_once __DIR__ . '/firebase.php';
require_once __DIR__ . '/push.php';
$firebase = new Firebase();
$push = new Push();
$reg = $_GET['reg'];
$fdate = $_GET['fdate'];
$tdate = date('Y-m-d G:i:s');
//$tdate = date("2018-01-20");
print_r($tdate);
$date2 = strtotime("+1 day", strtotime($fdate));
$fdate1 = date("Y-m-d", $date2);
//print_r($fdate1);
require_once('Demo.php');
$sql = "select max(AnnounceDate) as announcedate from AnnouncementTable";
$stmt1 = sqlsrv_query($conn,$sql);
$result = array();
$result["announcement"] = array();
$result["success"] = 1;
$row = sqlsrv_fetch_array($stmt1,SQLSRV_FETCH_ASSOC);
$date1 = $row["announcedate"]->format('Y-m-d');
$marks = array();
$marks["announcedate"] = $row["announcedate"]->format('Y-m-d');
array_push($result["announcement"], $marks);
echo json_encode($result);
print_r($date1);
if ($date1 != $fdate){
$check = "select * from
AnnouncementTable
where
AnnounceDate between '$fdate1' and '$tdate';select token from Std_Reg where RegNo='$reg'";
$stmt = sqlsrv_query($conn,$check);
if(sqlsrv_has_rows($stmt) > 0){
while ($row = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC)){
$notiTitle = "Eurasian Infotech";
$clickEvent ="Announcement";
$notiMessage = $row["Title"];
$notiDescription = $row["Description"];
$regId = $row['token'];
$push->setTitle($notiTitle);
$push->setMessage($notiMessage);
$push->setClickevent($clickEvent);
$push->setAnnounce($notiDescription);
$json = '';
$response = '';
$json = $push->getPush();
$response = $firebase->send($regId,$json);
//sendNotification($notiTitle, $notiMessage,$reg,$date1);
echo "sucessfully added";
}
}else{
echo "error in sending request";
}
}else{
echo "Sent Notification";
}
}else{
echo 'error';
}
?>
Firebase.php
<?php
class Firebase(){
public function send($to,$message){
$fields = array(
'to' => $to,
'data' => $message,
);
return $this->sendPushNotification($fields);
}
private function sendPushNotification($fields) {
require_once __DIR__ . '/config.php';
// Set POST variables
$url = 'https://fcm.googleapis.com/fcm/send';
$headers = array(
'Authorization: key=' . FIREBASE_API_KEY,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Disabling SSL Certificate support temporarly
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// Execute post
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
// Close connection
curl_close($ch);
return $result;
}
}
?>
push.php
<?php
class Push{
private $title;
private $message;
private $date;
private $announce;
private $clickevent;
function _construct(){
}
public function setTitle($title){
}
public function setMessage($message){
}
public function setDate($date){
}
public function setAnnounce($announce){
}
public function setClickevent($clickevent){
}
public function getPush(){
$res = array();
$res['data']['title'] = $this->title;
$res['data']['message'] = $this->message;
$res['data']['date'] = $this->date('Y-m-d');
$res['data']['announce'] = $this->announce;
$res['data']['clickevent'] = $this->clickevent;
$res['data']['timestamp'] = date('Y-m-d G:i:s');
return $res;
}
}
?>

PHP curl automatically sending two requests

Im Using PHP curl for saving website name page name on which user has just clicked and ip address in my database, but the problem curl send 2 requests automatically one with correct data and in other one just changed the page name to index.php, i want to abort the second request just, means when curl executes one time then no request by curl untill an other click on the same page, hope my discription will help you to find out my error for me, here is my code.
**This IS My Curl Code**
$wb_nm = $_SERVER[HTTP_HOST];
$pg_nm = $_SERVER[PHP_SELF];
$usr_ip = $_SERVER[REMOTE_ADDR];
$pg_nm_ultr = trim($pg_nm , '/');
$n_url = "localhost/curl/new_page.php";
$data = array(
"varhost" => $wb_nm,
"varpage" => $pg_nm_ultr,
"varip" => $usr_ip
);
$post = curl_init();
curl_setopt($post, CURLOPT_URL, $n_url);
curl_setopt($post, CURLOPT_POSTFIELDS, $data);
curl_setopt($post, CURLOPT_RETURNTRANSFER, false);
$result = curl_exec($post);
curl_close($post);
?>
**And This Is new_page.php**
if(isset($_POST['varhost']) && isset($_POST['varpage']) && isset($_POST['varip']))
{
$web_name = $_POST['varhost'];
$page_name_ulter = $_POST['varpage'];
$user_ip = $_POST['varip'];
define("DB_HOSTNAME", "localhost");
define("DB_USER", "root");
define("DB_PASS", "");
define("DB_DB", "pan");
$connection = mysqli_connect(DB_HOSTNAME, DB_USER, DB_PASS, DB_DB);
if(isset($connection)){
$query = "SELECT * FROM tbl_agencies WHERE weblink = '".$web_name."'";
$result = mysqli_query($connection , $query);
if($result){
while($row = mysqli_fetch_array($result)){
if(isset($row))
{
$D_id = $row['domain_id'];
$D_name = $row['website'];
if($D_id == 0)
{
return false;
}
}
else
{
}
break;
}
}
}
$date_date = date('Y-m-d');
$time_stamp = date("H:i:s");
$query_Code = "INSERT INTO user_details (website_domain_id , website_domain_name , page_clicked , user_IP , access_date , access_time) VALUES ('".$D_id."','".$D_name."' , '".$page_name_ulter."' , '".$user_ip."' , '".$date_date."' , '".$time_stamp."')";
$result_Code = mysqli_query($connection , $query_Code);
if($result_Code)
{
mysqli_close($connection);
}
}
?>
In curl_setopt($post, CURLOPT_POSTFIELDS, $fields);, you can send fields as an associative array. So this code:
$fields = '';
foreach($data as $key => $value) {
$fields .= $key . '=' . $value . '&';
}
rtrim($fields, '&');
is actually not needed such that curl_setopt($post, CURLOPT_POSTFIELDS, $fields); becomes
curl_setopt($post, CURLOPT_POSTFIELDS, $data);

Gcm message not sent to more that 1000 users

Gcm message not sent to more that 1000 users , gcm has its own limit of sending message to 1000 users so the idea is to divide the users in batch of 1000 each i tried that but the gcm message is received by first 1000 users only how can we send the message in batches of 1000 each, in a total of say 5000 users, so that all users get the message i am new to php please explain the working
<?php
require 'connect.php';
function sendPushNotification($registration_ids, $message) {
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registration_ids,
'data' => $message,
);
define('GOOGLE_API_KEY', 'xxxxxxxxxxxxxxxxxxxxxxxxx');
$headers = array(
'Authorization:key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
//echo json_encode($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if($result === false)
die('Curl failed ' . curl_error());
curl_close($ch);
return $result;
}
$pushStatus = '';
function getGCMCount(){
$total = "";
$query = "SELECT count(gcm_regId) as total FROM gcm_users";
while($query_row = mysql_fetch_assoc($query_run)) {
$total = $query_row['total'] / 1000;
}
return $total;
}
if(!empty($_GET['push'])) {
$query = "SELECT gcm_regId FROM gcm_users";
if($query_run = mysql_query($query)) {
$gcmRegIds = array();
$i = 0;
while($query_row = mysql_fetch_assoc($query_run)) {
$i++;
$gcmRegIds[floor($i/1000)][] = $query_row['gcm_regId'];
//echo $i . "</br>" ;
}
}
$pushMessage = $_POST['message'];
if(isset($gcmRegIds) && isset($pushMessage)) {
$pushStatus = array();
//echo "</br> counnt of messages send is". count($pushStatus);
foreach($gcmRegIds as $key=>$val)
{
$message = array('price' => $pushMessage);
//$message1 = array($key=>$val);
//$c = (array_merge($message ,$message1 ));
$pushStatus[] = sendPushNotification($val, $message);
//echo $key;
}
}
}
?>
<html>
<head>
<title>Google Cloud Messaging (GCM) Server in PHP</title>
</head>
<body>
<h1>Google Cloud Messaging (GCM) Server in PHP</h1>
<form method = 'POST' action = 'send_all.php/?push=1'>
<div>
<textarea rows = 2 name = "message" cols = 23 placeholder = 'Messages to Transmit via GCM'></textarea>
</div>
<div>
<input type = 'submit' value = 'Send Push Notification via GCM'>
</div>
<p><h3><?php //echo $pushStatus . "<br>"?></h3></p>
</form>
</body>
</html>
Refer this snippet for sending messages to more than 1000 users
<?php
//Sample for sending notification to more than 1000 users
$mPushNotification = $push->getMessage();
$stmt = $this->con->prepare("SELECT gcm_regid FROM gcm_users");
$stmt->execute();
$result = $stmt->get_result();
$tokens = array();
while ($token = $result->fetch_assoc()) {
array_push($tokens, $token['gcm_regid']);
}
$firebase = new Firebase();
$total = count($tokens);
$groups = ceil($total/800);
$currentval=ceil($total/$groups);
$firebase = new Firebase();
for ($i=0; $i <$groups; $i++) {
$val=($i*$currentval)+1;
$total = ($i+1)*$currentval;
$resToken = getSpecificToken($val,$total);
$result1 = $firebase->send($resToken, $mPushNotification);
}
function getSpecificToken($upper,$lower)
{
$stmt = $this->con->prepare("SELECT * FROM gcm_users LIMIT $upper,$lower");
$stmt->execute();
$result = $stmt->get_result();
$tokens = array();
while ($token = $result->fetch_assoc()) {
array_push($tokens, $token['gcm_regid']);
}
return $tokens;
}
function getMessage() {
$res = array();
$res['data']['id'] = 1;
$res['data']['title'] = "TestTitle";
$res['data']['message'] = "TestMessage : Hello";
return $res;
}
?>
//Firebase File
<?php
class Firebase {
public function send($registration_ids, $message) {
$fields = array(
'registration_ids' => $registration_ids,
'data' => $message,
);
return $this->sendPushNotification($fields);
}
/*
* This function will make the actual curl request to firebase server
* and then the message is sent
*/
private function sendPushNotification($fields) {
//importing the constant files
require_once 'Config.php';
//firebase server url to send the curl request
$url = 'https://fcm.googleapis.com/fcm/send';
//building headers for the request
$headers = array(
'Authorization: key=' . FIREBASE_API_KEY,
'Content-Type: application/json'
);
//Initializing curl to open a connection
$ch = curl_init();
//Setting the curl url
curl_setopt($ch, CURLOPT_URL, $url);
//setting the method as post
curl_setopt($ch, CURLOPT_POST, true);
//adding headers
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//disabling ssl support
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//adding the fields in json format
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
//finally executing the curl request
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
//Now close the connection
curl_close($ch);
//and return the result
return $result;
}
}
?>

GCM send message to all devices [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have a problem with GCM, I can't send a message to all devices.
This isn't the original code, but is my own version!
send_message.php:
<?php
if (isset($_POST["regId"]) && isset($_POST["message"])) {
//$regId = $_POST["regId"];
$message = $_POST["message"];
include './GCM.php';
$gcm = new GCM();
//$registatoin_ids = array($regId);
$message = array("price" => $message);
include_once 'db_functions.php';
$db = new DB_Functions();
$users = $db->getAllUsers();
if($users != false){
$no_of_users = mysql_num_rows($users);
}else{
$no_of_users = 0;
}
$i = 0;
while ($row = mysql_fetch_array($users)) {
$ids[$i] = $row["gcm_regid"];
$i++;
foreach ($ids as $value){
echo $value;
$registatoin_ids = $value;
json_encode($registatoin_ids);
$result = $gcm->send_notification($registatoin_ids, $message);
echo $result;
}
}
echo $value;
echo $registatoin_ids;
}
?>
GCM.php:
<?php
class GCM {
//put your code here
// constructor
function __construct() {
}
/**
* Sending Push Notification
*/
public function send_notification($registatoin_ids, $message) {
// include config
include_once './config.php';
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message,
);
$headers = array(
'Authorization: key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Disabling SSL Certificate support temporarly
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// Execute post
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
// Close connection
curl_close($ch);
echo $result;
}
}
?>
db_functions.php:
<?php
class DB_Functions {
private $db;
//put your code here
// constructor
function __construct() {
include_once './db_connect.php';
// connecting to database
$this->db = new DB_Connect();
$this->db->connect();
}
// destructor
function __destruct() {
}
/**
* Storing new user
* returns user details
*/
public function storeUser($name, $email, $gcm_regid) {
// insert user into database
$result = mysql_query("INSERT INTO gcm_users(name, email, gcm_regid, created_at) VALUES('$name', '$email', '$gcm_regid', NOW())");
// check for successful store
if ($result) {
// get user details
$id = mysql_insert_id(); // last inserted id
$result = mysql_query("SELECT * FROM gcm_users WHERE id = $id") or die(mysql_error());
// return user details
if (mysql_num_rows($result) > 0) {
return mysql_fetch_array($result);
} else {
return false;
}
} else {
return false;
}
}
/**
* Get user by email and password
*/
public function getUserByEmail($email) {
$result = mysql_query("SELECT * FROM gcm_users WHERE email = '$email' LIMIT 1");
return $result;
}
/**
* Getting all users
*/
public function getAllUsers() {
$result = mysql_query("select * FROM gcm_users");
return $result;
}
/**
* Check user is existed or not
*/
public function isUserExisted($email) {
$result = mysql_query("SELECT email from gcm_users WHERE email = '$email'");
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
// user existed
return true;
} else {
// user not existed
return false;
}
}
}
?>
The original code is from Ravi Tamada.
change send_message.php to the bellow code :
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
include_once 'db_functions.php';
if (isset($_GET["message"]) && isset($_GET["Number"])) {
$message = $_GET["message"];
$db = new DB_Functions();
$users = $db->getAllUsers();
$regIds = array();
while($row = mysql_fetch_array($users)) {
array_push($regIds,$row['gcm_regid']);
}
echo isset($users);
if ($users != false)
$no_of_users = mysql_num_rows($users);
else
$no_of_users = 0;
include_once './GCM.php';
$gcm = new GCM();
$message = array("message" => $message);
$result = $gcm->send_notification($regIds, $message);
echo $result;
}
?>

Get User ID from username Instagram

I am trying to find out how can I get a user ID from a username using Instagram API but I have no luck..
My code so far is:
$username = 'some user name';
$username = strtolower($username); // sanitization
$token = "ACCESS_TOKEN_HERE";
$url = "https://api.instagram.com/v1/users/search?q=".$username."&access_token=".$token;
$get = file_get_contents($url);
$json = json_decode($get);
foreach($json->data as $user)
{
if($user->username == $username)
{
return $user->id;
}
}
Using the suggestions from the comments, I was able to get the userid from username using this code. Please let me know as I am not the greatest PHP developer and there might be a more concise way of doing this.
$user = USER_NAME;
$count = NUMBER_TO_RETURN;
$token = ACCESS_TOKEN_HERE;
$query = http_build_query(
array(
'q'=>$user,
'count'=>$count,
'access_token'=>$token
)
);
$url = "https://api.instagram.com/v1/users/search?{$query}";
// Gets our data
function fetchData($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
// Pulls and parses data.
$result = fetchData($url);
$result = json_decode($result);
$userid = $result->data[0]->id;
echo $userid;
Put username in "", for example:
https://api.instagram.com/v1/users/search?q=%22bordeux1%22&access_token=TOKEN
For me works fine.

Categories