Cronjobs on Direct Admin is not working - php

I created a cronjobs on direct admin, and if that running it will check curl =>>> change values in mysql. But it's not working. Please help me ##. Thanks
This is my code:
<?php
class ControllerVemaybayCronJobapp
{
function index(){
$connect = $this->connect();
$query_routes_1 = $connect->query("SELECT * FROM **** where status = '0' GROUP BY routes ");
for ($result = array();
$row = $query_routes_1->fetch_assoc();
$result[array_shift($row)] = $row);
foreach ($result as $i => $aaa){
$routes = $aaa['routes'];
$detail_routes_2 = $connect->query("SELECT * FROM **** where routes = '" . $routes . "' AND status = '0' ");
for ($result2 = array();
$row2 = $detail_routes_2 ->fetch_assoc();
$result2[array_shift($row2)] = $row2);
foreach ($result2 as $t => $value1) {
$ngay = $value1['ngay'];
$thang = $value1['thang'];
$nam = $value1['nam'];
$min = $value1['minPrice'];
$max = $value1['maxPrice'];
$providers = $value1['providers'];
$startdate = $nam.$thang.'01';
$enddate = $nam.$thang.'31';
$bien = $this->getlist_ticketsofdate($routes,$startdate,$enddate);
foreach ($bien as $k => $value) {
$moi2 = array();
$moi = $value['c'];
$moi2 = $value['f'];
if($value['_id']['dim'] == $ngay ){
if($min <= $value['c'] && $value['c'] <= $max && strpos($providers, $value['p']) !== false){
$connect->query("UPDATE **** SET status='1' where customer_id = '" . $value1['customer_id'] . "' ");
break;
}else{
foreach ($moi2 as $key => $value2) {
if($min <= $value2['cp'] && $value2['cp'] <= $max && strpos($providers, $value2['p']) !== false){
$connect->query("UPDATE **** SET status='1' where customer_id = '" . $value1['customer_id'] . "' ") ;
break;
}
}
}
}
}
}
}
}
function connect(){
$servername = "****";
$username = "****";
$password = "****";
$databasename = "****";
$conn = new mysqli($servername, $username, $password,$databasename);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
return $conn;
}
function getlist_ticketsofdate($diadiem,$startDate,$endDate){
$url = '****';
$providers = array();
$providers[0] = '****';
$providers[1] = '****';
$providers[2] = '****';
$routes = array();
$routes[0] = $diadiem;
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Connection:keep-alive';
$param = array(
'startDate' => $startDate,
'endDate' => $endDate,
'minPrice' => '0',
'maxPrice' => '700000',
'providers' => $providers,
'routes' => $routes,
'type' => 'date',
);
$data_string = json_encode($param);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$result_tickets = json_decode($response,true);
return $result_tickets;
}
}
?>
This is my cronjobs

Cron job may not works directly on admin, cause it may required authentications for some process.
Sample php file name mail.php
<?php
// the message
$msg = "First line of text\nSecond line of text";
// use wordwrap() if lines are longer than 70 characters
$msg = wordwrap($msg,70);
// send email
mail("someone#example.com","My subject",$msg);
?>
Cron command:
For url
* * * * * wget http://example.com/mail.php &> /dev/null
For Path
* * * * * <BASE DIR>/mail.php
This cron job send mail every minute.

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

extending php execution time

Have tried to extend the execution time by these methods but the script keeps ending prematurely. It is basically cycling through a mysql database and doing something with each row. It should be lasting maybe five to ten minutes but stops consistently early at the same spot. I have tried the following:
set_time_limit(0);
curl_setopt($ch, CURLOPT_TIMEOUT, 2000000);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 200000);
None of them are working. Please help!
<?php
ini_set('max_execution_time', 500);
$user="5aabf73bdd2c7";
//$user = $_POST['user'];
$servername = "localhost";
$username = "placeprint_1";
$password = "JS313833";
$dbname = "placeprint_1";
// Create connection
$con = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
function file_get_contents_curl($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 2000000);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 200000);
curl_setopt($ch,CURLOPT_BINARYTRANSFER, true);
$data = curl_exec($ch);
curl_close ( $ch );
return $data;
}
$sql = "SELECT link, id, cookie FROM rawlinks WHERE cookie='$user' ORDER by ID desc ";
$result = $con->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$getimagefrom=$row["link"];
$id=$row["id"];
$cookie=$row["cookie"];
echo $getimagefrom;
echo "<br><br>ID:".$id."<br><br>";
$htmlaa = file_get_contents_curl($getimagefrom);
$docaa = new DOMDocument();
#$docaa->loadHTML($htmlaa);
$nodesaa = $docaa->getElementsByTagName('title');
$nodesxaa = $docaa->getElementsByTagName('img');
//get and display what you need:
$titlev = $nodesaa->item(0)->nodeValue;
$metasv = $docaa->getElementsByTagName('meta');
$asv = $docaa->getElementsByTagName('img');
for ($iv = 0; $iv < $metasv->length; $iv++)
{
$metav = $metasv->item($iv);
if($metav->getAttribute('name') == 'description')
$descriptionv = $metav->getAttribute('content');
if($metav->getAttribute('name') == 'keywords')
$keywordsv = $metav->getAttribute('content');
if($metav->getAttribute('property') == 'og:image');
$languagev = $metav->getAttribute('content');
}
for ($ivv = 0; $ivv < $asv->length; $ivv++)
{
$av = $asv->item($ivv);
echo $av->getAttribute('src');
echo "<br>";
$cvarv = $av->getAttribute('src');
echo " <img src='$cvarv' >";
$servername = "localhost";
$username = "placeprint_1";
$password = "JS313833";
$dbname = "placeprint_1";
// Create connection
$con = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
$getimagefrom = rtrim($getimagefrom, '/');
$cvarv = urlencode($cvarv);
$titlev = preg_replace('/[^\p{L}\p{N}\s]/u', '', $titlev);
$descriptionv = preg_replace('/[^\p{L}\p{N}\s]/u', '', $descriptionv);
}
}
}
$con->close();
echo "FINISHED!!!!";
?>
From php.ini try to increase the max_execution_time and restart apache server.
To locate where your php.ini is you can create a phpinfo.php file and insert the following:
<?php phpinfo();
More informarion here: https://mediatemple.net/community/products/dv/204643880/how-can-i-create-a-phpinfo.php-page
You can then get the location of the php.ini configuration file location when you visit the phpinfo.php on your browser.
From the code I can suggest that instead of doing an INSERT mysql request for every loop, you should prepare the insert values in the loop and then perform the actual mysql request only once after the loop is finished.
Another suggestion is to have curl_close ( $ch ); before the return in file_get_contents_curl()
I have updated your code in order to be able to work in chunks instead of doing all the execution at once. I have created a table import_progress where we will store the last imported/executed row and fetch 20 rows for every execution:
/**
* Get the last imported ID
*
* #param mysqli $con
*
* #return int
*/
function get_last_inserted_id( $con ) {
$sql = "SELECT imported_id
FROM import_progress
ORDER by ID desc
LIMIT 1";
$result = $con->query( $sql );
if ( $result->num_rows == 0 ) {
//Since you are fetching in descending order
//We need to return a very high number if we did not import anything yet
return 999999999999999999;
} else {
while ( $row = $result->fetch_assoc() ) {
return $row['imported_id'];
}
}
}
/**
* Get the last imported ID
*
* #param mysqli $con
* #param array $ids
*
* #return int
*/
function insert_imported_ids( $con, $ids ) {
$ids = array_unique( array_filter( $ids ) );
if ( empty( $ids ) ) {
return false;
}
$sql = "INSERT INTO import_progress (imported_id) VALUES";
//We now append the data to the mysql string
$insert = [];
foreach ( $ids as $id ) {
$insert[] = "($id)";
}
$sql .= implode( ',', $insert ) . ';';
return $con->query( $sql );
}
/**
* #param string $url
*
* #return mixed
*/
function file_get_contents_curl( $url ) {
$ch = curl_init();
curl_setopt( $ch, CURLOPT_HEADER, 0 );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt( $ch, CURLOPT_TIMEOUT, 2000000 );
curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, 200000 );
curl_setopt( $ch, CURLOPT_BINARYTRANSFER, true );
$data = curl_exec( $ch );
curl_close( $ch );
return $data;
}
$user = "5aabf73bdd2c7";
$servername = "db";
$username = "root";
$password = "root";
$dbname = "stack_overflow";
// Create connection
$con = new mysqli( $servername, $username, $password, $dbname );
// Check connection
if ( $con->connect_error ) {
die( "Connection failed: " . $con->connect_error );
}
$last_inserted_id = get_last_inserted_id( $con );
$sql = "SELECT link, id, cookie FROM rawlinks
WHERE cookie='$user'
AND ID < $last_inserted_id
ORDER by ID desc
LIMIT 20";
$result = $con->query( $sql );
if ( $result->num_rows > 0 ) {
$imported_ids = [];
// output data of each row
while ( $row = $result->fetch_assoc() ) {
$getimagefrom = $row["link"];
$id = $row["id"];
$cookie = $row["cookie"];
echo $getimagefrom;
echo "<br><br>ID:" . $id . "<br><br>";
$htmlaa = file_get_contents_curl( $getimagefrom );
$docaa = new DOMDocument();
#$docaa->loadHTML( $htmlaa );
$nodesaa = $docaa->getElementsByTagName( 'title' );
$nodesxaa = $docaa->getElementsByTagName( 'img' );
//get and display what you need:
$titlev = $nodesaa->item( 0 )->nodeValue;
$metasv = $docaa->getElementsByTagName( 'meta' );
$asv = $docaa->getElementsByTagName( 'img' );
for ( $iv = 0; $iv < $metasv->length; $iv ++ ) {
$metav = $metasv->item( $iv );
if ( $metav->getAttribute( 'name' ) == 'description' ) {
$descriptionv = $metav->getAttribute( 'content' );
}
if ( $metav->getAttribute( 'name' ) == 'keywords' ) {
$keywordsv = $metav->getAttribute( 'content' );
}
if ( $metav->getAttribute( 'property' ) == 'og:image' ) {
;
}
$languagev = $metav->getAttribute( 'content' );
}
for ( $ivv = 0; $ivv < $asv->length; $ivv ++ ) {
$av = $asv->item( $ivv );
echo $av->getAttribute( 'src' );
echo "<br>";
$cvarv = $av->getAttribute( 'src' );
echo " <img src='$cvarv' >";
$cvarv = urlencode( $cvarv );
$titlev = preg_replace( '/[^\p{L}\p{N}\s]/u', '', $titlev );
$descriptionv = preg_replace( '/[^\p{L}\p{N}\s]/u', '', $descriptionv );
}
$imported_ids[] = (int)$id;
}
insert_imported_ids($con, $imported_ids);
}
$con->close();
echo "FINISHED!!!!";
Curl doesn't make any difference. If set_time_limit doesn't work it means that a global configuration overrides it, try printing the following:
var_dump(ini_get('max_execution_time'));
One time before executing set_time_limit(0); and also after you've done it.
This could be editable by php.ini but also is typically a blocked feature in free or shared hosting providers to prevent users to over-load the shared server.
add
ini_set('max_execution_time', 500);
at the top of the page, here 500 is number of seconds.

convert data to JSON array

i am trying to use the push notification in google cloud messages and i am passing an array om registration ids, but for some reason i got the following error:
Field "data" must be a JSON array: You have just invited to play 'Soccer'
this is the part that i am trying to pass:
"registred_ids":["APA91bF9itasGCSK8NbD9u5GJWnEmbWCdS0sEn_xxRVbVpfI0_3FKkvxVBr5xtdE26VZgOO8rCBpf4CaAzHUbMj7PmmDxqpdbWO6VBrPB8dW4CPqPovJbnB_p1Ha_fuwyf8SnOqgOFajK8HEdiZO65qUljO2wCuuDQ"]
not the code of the gcm is :
<?php
class GCM {
function __construct() {
}
/**
* Sending Push Notification
*/
public function send_notification($registatoin_ids, $message) {
// include config
include_once 'connection.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_IPRESOLVE, CURL_IPRESOLVE_V4 );
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;
}
}
?>
and the code which passing the registration ids is:
<?php
include 'response_process.php';
include 'gcm.php';
class CreateEvent implements ResponseProcess {
public function dataProcess($dblink)
{
$output = array();
$sport = $_POST["sport_type"];
$date = date("Y-m-d",strtotime(str_replace('/','-',$_POST["date"])));
$s_time =$_POST["s_time"];
$e_time = $_POST["e_time"];
$lon = $_POST["lon"];
$lat = $_POST["lat"];
$event_type = $_POST["event_type"];
$max_p = $_POST["max_participants"];
$sched = $_POST["scheduled"];
$gen = $_POST["gender"];
$min_age = $_POST["minAge"];
$manager = $_POST["manager"];
$query = "SELECT * FROM event WHERE (event.longtitude = '$lon' AND event.latitude = '$lat')
AND event.event_date = '$date' And ((event.start_time BETWEEN '$s_time' AND '$e_time') OR (event.end_time BETWEEN '$s_time' AND '$e_time'))";
//AND (event.start_time = '$s_time' AND event.end_time = '$e_time')
//check time and place of the event
$result_q = mysqli_query($dblink,$query) or die (mysqli_error($dblink));
if(!$result_q)
{
$output["flag"]= "select failed";
$output["msg"] = $result_q;
return json_encode($output);
}
//case date and time are available
else {
$no_of_rows = mysqli_num_rows($result_q);
if ($no_of_rows < 1) {
$output["flag"] = "success";
$output["msg"] = "insert event";
$result = mysqli_query($dblink, "INSERT into event(manager_id,kind_of_sport,event_date,start_time,end_time,longtitude,latitude,private,gender,min_age,max_participants,current_participants,scheduled,event_status)
VALUES ('$manager','$sport','$date','$s_time','$e_time','$lon','$lat','$event_type','$gen','$min_age','$max_p','1','$sched','1')") or die (mysqli_error($dblink));
if (!$result) {
$output["flag"] = "failed to create event";
// return (json_encode($output));
}
else{
if(isset($_POST["invitedUsers"])){
$query_id = "SELECT id From event WHERE event.event_date = '$date' and event.start_time = '$s_time' and event.end_time = '$e_time'";
$event_s_res = mysqli_query($dblink,$query_id) or die (mysqli_error($dblink));
if(!$event_s_res)
{
$output["flag"] = "failed";
$output["msg"] = "Event id not found";
}
else{
$row = mysqli_fetch_assoc($event_s_res);
$no_of_rows = mysqli_num_rows($event_s_res);
if($no_of_rows > 1 || $no_of_rows == 0)
{
$output["flag"] = "failed";
$output["msg"] = "Event id not found";
}
else{
$event_id = $row["id"];
$json = $_POST["jsoninvited"];
$json = json_decode($json);
$output["size_invited"] = count($json);
$query_users = "SELECT id,gcm_id From users WHERE ";
$i=0;
$size_of_param = (count($json));
foreach($json as $user) {
if ($i < $size_of_param - 1)
// add a space at end of this string
$query_users .= "users.mobile = '".$user."' or ";
else {
// and this one too
$query_users .= "users.mobile = '".$user."' ";
$output["users"][] = $user['mobile'];
}
$i++;
$output["index"]=$i;
}
$output["user_query"]= $query_users;
$event_user_s_res = mysqli_query($dblink,$query_users) or die (mysqli_error($dblink));
if(!$event_user_s_res)
{
$output["flag"] = "failed";
$output["msg"] = "user id not found";
}
$insert_query = "INSERT into attending (event_id,user_id,status) VALUES ";
$i=0;
$status = "deny";
$registration_ids = array();
while($row_user = mysqli_fetch_assoc($event_user_s_res))
{
$registration_ids[$i]=$row_user["gcm_id"];
if($i<$size_of_param - 1)
$insert_query .= "('" .$event_id. "','" .$row_user["id"]. "','" .$status. "'), ";
else
$insert_query .= "('".$event_id."','".$row_user["id"]."','".$status."') ";
$i++;
}
$insert_query_res = mysqli_query($dblink,$insert_query) or die (mysqli_error($dblink));
if(!$insert_query_res)
{
$output["flag"] = "failed";
$output["msg"] = "failed to insert to attending table";
}else{
$output["id_query"]= $insert_query;
$output["registred_ids"] = $registration_ids;
$output["msg"] = "success to insert into attending";
$gcm = new GCM();
$message = "You have just invited to play '".$sport."'";
$output["gcm_message"]=$message;
$gcm_res = $gcm->send_notification($registration_ids,$message);
$output["gcm_res"] = $gcm_res;
} //els of $insert_query_res
} //else of $no_of_rows > 1 || $no_of_rows == 0
} // else of $event_s_res
} //if isset($_POST["invitedUsers"]
} // if $result
} // if $no_of_rows < 1
else {
$output["flag"] = "failed";
$output["msg"] = "Place is already occupied in this time";
}
}
return json_encode($output);
}
}
Use this-
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => array("message" => $message),
);
It says the data field needs to be an array, but you are setting it to $message, which is a string, not an array.
Field "data" must be a JSON array: You have just invited to play 'Soccer'
This means the value passed in data node is not a json.
Encoding $message into json will fix the error.

setcookie() can't set a cookie

This is script.php which I run which directs the user to callback.php
<?php
session_start();
require_once 'OAuth.php';
require_once 'OAuthCurl.php';
$callback_url = "http://something/bio/callback.html";
$consumer_key = "<code>";
$consumer_secret = "<code>";
$oauth_request_token = "http://api.twitter.com/oauth/request_token";
$oauth_authorize = "http://api.twitter.com/oauth/authorize";
$oauth_access_token = "http://api.twitter.com/oauth/access_token";
$sig_method = new OAuthSignatureMethod_HMAC_SHA1();
$test_consumer = new OAuthConsumer($consumer_key, $consumer_secret, $callback_url);
$req_req = OAuthRequest::from_consumer_and_token($test_consumer, NULL, "GET", $oauth_request_token);
$req_req->sign_request($sig_method, $test_consumer, NULL);
$oc = new OAuthCurl();
$reqData = $oc->fetchData($req_req->to_url());
parse_str($reqData['content'], $reqOAuthData);
$req_token = new OAuthConsumer($reqOAuthData['oauth_token'], $reqOAuthData['oauth_token_secret'], 1);
$acc_req = OAuthRequest::from_consumer_and_token($test_consumer, $req_token, "GET", $oauth_authorize);
$acc_req->sign_request($sig_method, $test_consumer, $req_token);
$_SESSION['oauth_token'] = $reqOAuthData['oauth_token'];
$_SESSION['oauth_token_secret'] = $reqOAuthData['oauth_token_secret'];
Header("Location: $acc_req");
?>
This is the callback.php
I'm trying to set a cookie on callback.php but the cookie is not getting set.
I can't seem to understand why?
<?php
session_start();
$_SESSION['oauth_token'];
$_SESSION['oauth_token_secret'];
require_once 'OAuth.php';
require_once 'OAuthCurl.php';
require_once __DIR__ . '/TwitterOAuth/TwitterOAuth.php';
require_once __DIR__ . '/TwitterOAuth/Exception/TwitterException.php';
use TwitterOAuth\TwitterOAuth;
date_default_timezone_set('Asia/Calcutta');
$callback_url = "http://something/bio/callback.php";
$consumer_key = "<code>";
$consumer_secret = "<code>";
$oauth_request_token = "http://api.twitter.com/oauth/request_token";
$oauth_authorize = "http://api.twitter.com/oauth/authorize";
$oauth_access_token = "http://api.twitter.com/oauth/access_token";
//$authenticate_token = "https://api.twitter.com/1.1/account/verify_credentials.json";
//echo($authenticate_token);
//exit();
$sig_method = new OAuthSignatureMethod_HMAC_SHA1();
$test_consumer = new OAuthConsumer($consumer_key, $consumer_secret, $callback_url);
$params = array();
$acc_token = new OAuthConsumer($_SESSION['oauth_token'],$_SESSION['oauth_token_secret'], 1);
$acc_req = OAuthRequest::from_consumer_and_token($test_consumer, $acc_token, "GET", $oauth_access_token);
$acc_req->sign_request($sig_method, $test_consumer, $acc_token);
$oc = new OAuthCurl();
$reqData = $oc->fetchData("{$acc_req}&oauth_verifier=".$_GET['oauth_verifier']."");
parse_str($reqData['content'], $accOAuthData);
//$username = $accOAuthData[screen_name];
$_SESSION['username'] = $accOAuthData['screen_name'];
$_SESSION['final_oauth_token'] = $accOAuthData['oauth_token'];
$_SESSION['final_oauth_token_secret'] = $accOAuthData['oauth_token_secret'];
$final_oauth_token = $_SESSION['final_oauth_token'];
$final_oauth_token_secret = $_SESSION['final_oauth_token_secret'];
$username = $_SESSION['username'];
/**
* Array with the OAuth tokens provided by Twitter when you create application
*
* output_format - Optional - Values: text|json|array|object - Default: object
*/
$config = array(
'consumer_key' => '<code>',
'consumer_secret' => '<code>',
'oauth_token' => $final_oauth_token,
'oauth_token_secret' => $final_oauth_token_secret,
'output_format' => 'object'
);
/**
* Instantiate TwitterOAuth class with set tokens
*/
$tw = new TwitterOAuth($config);
$params = array(
'screen_name' => $username,
'count' => 5,
'exclude_replies' => true
);
/**
* Send a GET call with set parameters
*/
$response = $tw->get('users/show', $params);
$id =($response-> id);
$description=($response-> description);
$screen_name = ($response-> screen_name);
setcookie("test1", $screen_name, time()+3600*30);
/*Connection String*/
$hostname = 'something';
$database = 'twitter';
$username = '';
$password = '';
$conn = mysql_connect($hostname,$username,$password);
if(!$conn)
{
die("Unable to Connect localhost!".mysql_error());
}
mysql_select_db($database) or die("Unable to select database!".mysql_error());
$query = mysql_query("SELECT id FROM twitter_tbl WHERE id = '". $id ."'");
if (mysql_num_rows($query) > 0)
{
}
else
{
$sql='INSERT INTO twitter_tbl(description,screen_name,id,final_oauth_token,final_oauth_token_secret,timestamp) VALUES("'.$description.'","'.$screen_name.'","'.$id.'","'.$final_oauth_token.'","'.$final_oauth_token_secret.'",'.strval(time()).')';
if(!mysql_query($sql,$conn))
{
die('Error: ' . mysql_error());
}
$bio_archives1 = 'INSERT INTO bio_archives(bio,screen_name,id,timestamp) VALUES("'.$description.'","'.$screen_name.'","'.$id.'",'.strval(time()).')';
if(!mysql_query($bio_archives1,$conn))
{
die('Error: ' . mysql_error());
}
}
if( strlen($description) < 80)
{
$newtext="is now ".'"'.$description.'"'." 'http://www.biostories.net/user.php?screen_name=".$screen_name."'";
$b = explode( "#tweeted", $newtext );
$txt = trim( $b[0] );
$url = trim( $b[1] );
$txt = substr( $txt, 0, 139 - strlen( $url ) );
$output = $txt . " " . $url;
}
else
{
$description1 = substr($description, 0, 50);
$newtext="is now ".'"'.$description1.'...."'." 'http://www.biostories.net/user.php?screen_name=".$screen_name."'";
$b = explode( "#tweeted", $newtext );
$txt = trim( $b[0] );
$url = trim( $b[1] );
$txt = substr( $txt, 0, 139 - strlen( $url ) );
$output = $txt . " " . $url;
}
$tw = new TwitterOAuth($config);
try{
$tw->post('statuses/update',array('status' =>$output));
}
catch(Exception $e) {
($e->getMessage());
}
$result = mysql_query('SELECT * FROM twitter_tbl WHERE id = "'.$id.'"');
while($row = mysql_fetch_array($result))
{
$desc = $row['description'];
}
if($desc === $description)
{
}
else
{
$query_update = mysql_query("SELECT id FROM twitter_up_tbl WHERE id = '". $id ."'");
if (mysql_num_rows($query_update) > 0)
{
$query1 ="Update twitter_up_tbl SET description='".$description."' WHERE id=".$id."";
$sql1 = mysql_query($query1);
}
else
{
$update_sql = 'INSERT INTO twitter_up_tbl(description,screen_name,id,final_oauth_token,final_oauth_token_secret,lastupdate) VALUES("'.$description.'","'.$screen_name.'","'.$id.'","'.$final_oauth_token.'","'.$final_oauth_token_secret.'",'.strval(time()).')';
if(!mysql_query($update_sql,$conn))
{
die('Error: ' . mysql_error());
}
}
$query ="Update twitter_tbl SET description='".$description."' WHERE id=".$id."";
$sql = mysql_query($query);
$bio_archives = 'INSERT INTO bio_archives(bio,screen_name,id,timestamp) VALUES("'.$description.'","'.$screen_name.'","'.$id.'",'.strval(time()).')';
if(!mysql_query($bio_archives,$conn))
{
die('Error: ' . mysql_error());
}
}
?>

Syntax for PHP while($row =mysql_fetch_row...?

I am trying to send SMS to multiple recipients. The code I am trying to achieve this is like this:
The problem I am facing is the message is being delivered to only the first record in the table.
Need some help, what & where I am going wrong?
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$result = mysql_query("SELECT name,mobile FROM members");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
while($row = mysql_fetch_row($result)) {
$mobile=$row[1];
$name=$row[0];
$request = "";
$param['mobileno'] = "91". $mobile;
$param['message'] = "Dear $name (organisation name) wishes you a very very Happy Birthday";
$param['username'] = "username";
$param['password'] = "password";
$param['sendername'] = "sender";
foreach ($param as $key => $val ){$request .= $key . "=" . urlencode($val);
$request .= "&";}$request = substr( $request, 0, strlen( $request ) - 1 );
$url = "http://smsapi" . $request;
$ch = curl_init($url);curl_setopt($ch, CURLOPT_URL, $url );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
$result = curl_exec($ch);
var_dump($result);exit;
curl_close( $ch );
}
You need to stick to Joomla coding standards. Don't go using mysql_* functions as they are deprecated and pose security threats.
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('*')
->from('members');
$db->setQuery($query);
$rows = $db->loadObjectList();
while($rows){
foreach ( $rows as $row ) {
$mobile = $row->mobile;
$name = $row->name;
}
//rest of code
}

Categories