I have a table where I want to run a PHP script during the maintenance.
I have the following code.
$sql = "SELECT `id`, `url` FROM `log_requests` WHERE `is_sent` = '0'";
$e = $conn->execute($sql);
My url array after fetching the table from DB.
Array
(
[0] => https://www.smsgatewaycenter.com/library/send_sms_2.php?UserName=username&Password=password&Type=Individual&To=9999999999&Mask=Senderid&Message=Hello+World+1
[1] => https://www.smsgatewaycenter.com/library/send_sms_2.php?UserName=username&Password=password&Type=Individual&To=9999999999&Mask=Senderid&Message=Hello+World+2
[2] => https://www.smsgatewaycenter.com/library/send_sms_2.php?UserName=username&Password=password&Type=Individual&To=9999999999&Mask=Senderid&Message=Hello+World+3
[3] => https://www.smsgatewaycenter.com/library/send_sms_2.php?UserName=username&Password=password&Type=Individual&To=9999999999&Mask=Senderid&Message=Hello+World+4
)
Then I run while loop
$ch = curl_init();
while($row = $e->FetchRow() ){
curl_setopt($ch, CURLOPT_URL, $row['url']);
curl_setopt($ch, CURLOPT_HEADER, 0);
$q = "UPDATE `log_requests` SET `is_sent` = '1' WHERE `id` = '".$row['id']."'";
$conn->execute($q);
}
curl_close($ch);
Issue is only one URL is executed using CURL and in my table only one row gets updated as 1 in is_sent column.
Why is it running single url in my while loop. What mistakes am I making here?
************************* EDIT ********************
Okay, now I came out with following and running successfully now. I just want to know whether am doing right or not.
$set = array();
while ($row = $executequery2->FetchRow()) {
$set[$row['url']][] = $row;
}
$curl_handles = array();
foreach($set as $url => $rows) {
$curl_handles[$url] = curl_init();
curl_setopt($curl_handles[$url], CURLOPT_URL, $url);
foreach($rows as $row) {
$query3 = "UPDATE `log_requests` SET `is_sent` = '1' WHERE `id` = '" . $row['id'] . "'";
$conn->Execute($query3);
}
}
$curl_multi_handle = curl_multi_init();
$i = 0;
$block = array();
foreach($curl_handles as $a_curl_handle) {
$i++;
curl_multi_add_handle($curl_multi_handle, $a_curl_handle);
$block[] = $a_curl_handle;
if (($i % 5 == 0) or ($i == count($curl_handles))) {
$running = NULL;
do {
$running_before = $running;
curl_multi_exec($curl_multi_handle, $running);
if ($running != $running_before) {
echo ("Waiting for $running sites to finish...<br />");
}
}
while ($running > 0);
foreach($block as $handle) {
$code = curl_getinfo($handle, CURLINFO_HTTP_CODE);
$curl_errno = curl_errno($handle);
$curl_error = curl_error($handle);
if ($curl_error) {
echo (" *** cURL error: ($curl_errno) $curl_error\n");
}
curl_multi_remove_handle($curl_multi_handle, $handle);
}
$block = array();
}
}
curl_multi_close($curl_multi_handle);
Updating the table column is the right way?
I had faced same issue and got this solution online. Just separate curl code from the loop and then try.
Something like this:
while($row = $e->FetchRow()) {
$result = call_curl($row['url']);
if($result === FALSE) {
die("Error");
}
else
{
$q = "UPDATE `log_requests` SET `is_sent` = '1' WHERE `id` = '".$row['id']."'";
}
}
function call_curl($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
$result = curl_exec ($ch);
curl_close($ch);
return $result;
}
Hope this helps you as well.
Related
I am posting data to a URL to send a Thank You Message. The details am picking are from a table called readtextfilejson. From where I am sending Thank you messages to users.
I am however not able to select details of the only users who haven't received their text message. My code is selecting all the data and posting to all the users again and again in a loop. Thus sending multiple ThankYouMessages to users.
I have added a new column called ThankyouMessage that is by default = 'not sent'.
So that when my script runs, it updates the ThankYouMessage column to = 'SENT', so that my script can Only select details of users who haven't yet received their thankyoumessage.
Thus i don't keep re-sending the same message again and again. Kindly take a look at my script below and assist how i might resolve this.
My table structure:
<?php
$data = (string) file_get_contents($file);
//echo $data;
$data = str_replace('//Confirmation Respose', '', $data);
$data = str_replace('// Validation Response', '', $data);
$data = str_replace(' ', '', $data);
$data = preg_replace('/\s+/S', " ", $data);
$data = trim($data);
$pattern = '/\s*/m';
$replace = '';
$testString = $data;
$removedWhitespace = preg_replace( $pattern, $replace,$testString );
$removedWhitespace2 = str_replace (' ', '', $testString);
$getAllData = explode('}{', $removedWhitespace2);
foreach ($getAllData as $row) {
$row = str_replace('{', '', $row);
$rowData = explode(',"', $row);
$rowData = explode(',"', $row);
$columnValues = array();
$chkTransId = '';
foreach ($rowData as $value) {
$newVal = explode(':', $value);
$key = str_replace('"', '', $newVal[0]);
$val = str_replace('"', '', $newVal[1]);
$val = trim($val);
$columnValues[] = ($val) ? "'$val'": "''";
if($key == 'TransID'){
$chkTransId = $val;
}
}
if($chkTransId == ''){
continue;
}
////THIS IS THE SECTION AM HAVING PROBLEMS WITH - I WANT TO
////SELECT ONLY THE DATA WHERE THE COLUMN WHERE thankyoumessage =
///// 'NOT SENT'
$chkSql = "select * from `readtextfilejson`where TransID='$chkTransId'";
$getResult = mysqli_query($con, $chkSql);
$getCount = mysqli_num_rows($getResult);
$row = mysqli_fetch_object($getResult);
$text = "Dear ". $row->FirstName ." Your Payment of ". $row->TransAmount ." to XXXXX was Received Succesfully. Confirmation Code: ". $row->TransID ."";
$destination = array("messageId"=>"$product_id","to"=>"$row->MSISDN");
$product_id=uniqid();
$notifyUrl = "URL";
$notifyContentType = "application/json";
$callbackData = 'eHostOnlineCodeCheck125690';
$username = "USERNAME";
$password = "PASSWORD";
$postUrl = "POSTURL";
$message = array("from" => "USERNAME",
"destinations" => $destination,
"text" => $text,
"bulkId" => "",
"notifyUrl" => $notifyUrl,
"flash" => "false",
"notifyContentType" => $notifyContentType,
"callbackData" => $callbackData);
$postData = array("messages" => array($message));
$postDataJson = json_encode($postData);
//Submit all data to SMS server
$ch = curl_init();
$header = array("Content-Type:application/json", "Accept:application/json");
curl_setopt($ch, CURLOPT_URL, $postUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_MAXREDIRS, 2);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postDataJson);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// response of the POST request
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$responseBody = json_decode($response);
curl_close($ch);
echo "<pre>";
print_r($row);
print_r($responseBody);
echo "</pre>";
$Sql = "UPDATE readtextfilejson SET thankyoumessage = 'SENT' WHERE thankyoumessage = 'not sent'";
mysqli_query($con, $Sql) or die(mysqli_error($con));
if($getCount > 0){
continue;
}
$columnValues = implode(',', $columnValues);
$sql = "INSERT INTO `readtextfilejson`(`TransactionType`, `TransID`, `TransTime`, `TransAmount`, `BusinessShortCode`, `BillRefNumber`, `InvoiceNumber`, `OrgAccountBalance`, `ThirdPartyTransID`, `MSISDN`, `FirstName`, `MiddleName`, `LastName`) VALUES (".$columnValues.")";
mysqli_query($con, $sql) or die(mysqli_error($con));
}
echo 'Data inserted successfully';
?>
2 possible issues.
1) You are selecting the transaction regardless of what thankyoumessage is set to. You may need to add a condition to that first SQL's where clause
SELECT * FROM `readtextfilejson`
WHERE TransID = '$chkTransId' AND thankyoumessage = 'not sent'
2) When you update the transaction thankyoumessage to "SENT" you are setting all transactions, because your update statement is missing the transaction id. You may need to add it.
UPDATE readtextfilejson
SET thankyoumessage = 'SENT'
WHERE thankyoumessage = 'not sent' AND TransID = '$chkTransId'
And since you want to set it to SENT regardless of what it was before, you may not need the thankyoumessage check either.
UPDATE readtextfilejson
SET thankyoumessage = 'SENT'
WHERE TransID = '$chkTransId'
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);
i have php script it keep downloading feeds from the internet.
but unfortunately it keep duplicate the image feed into the database.
part from the image, the script working fine on other feed like description,link, title.
php script
<?php
require 'database.php';
$url = "http://www.albaldnews.com/rss.php?cat=24";
$rss = simplexml_load_file($url);
if($rss)
{
echo '<h1>'.$rss->channel->title.'</h1>';
echo '<li>'.$rss->channel->pubDate.'</li>';
$items = $rss->channel->item;
foreach($items as $item)
{
$enclosure = $item->enclosure[0]['url'];
$ch = curl_init ("$enclosure");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
$rawdata=curl_exec ($ch);
curl_close ($ch);
$img=mysqli_real_escape_string($conn,$rawdata);
$query = "SELECT image from feedtable where link = '$img'";
$result= mysqli_query($conn, $query);
$num_rows = mysqli_num_rows($result);
if ($num_rows == 0)
{
$query1 = "INSERT INTO feedtable (image)VALUES ('$img')";
$result1= mysqli_query($conn, $query1);
echo "image added\n";
}
else
{
echo "duplicate entry\n";
}
}
}
?>
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;
}
}
?>
I have three filed in my mysql table they are: id, url, status
How to check all urls from the column url and write either 1 (available) or 0 (unavailable) to the status column?
To just check urls manualy in php w/o mysql I could use this:
<?php
function Visit($url){
$agent = "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)";
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL,$url );
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch,CURLOPT_VERBOSE,false);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
$page=curl_exec($ch);
//echo curl_error($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if($httpcode >= 200 && $httpcode < 300){
return true;
}
else {
return false;
}
}
if(Visit("http://www.google.com")){//maybe make it a variable from a result of a mysql select, but how to process it one by one?
echo "Website OK"; //maybe somesql here to wtite '1'
}
else{
echo "Website DOWN";//maybe somesql here to wtite '0'
}
?>
This is bad in terms of performance as doing queries in a loop is bad design, you should instead build a batch update and run the query in the end, but I've not enough time now to elaborate that. This is just to get you started:
$sql = "SELECT id,url FROM mytable";
$res = mysql_query($sql) or die(mysql_error());
if($res)
{
while($row = mysql_fetch_assoc($res))
{
$status = visit($row['url']) ? '1' : '0';
$id = $row['id'];
$update = "UPDATE mytable SET status = $status WHERE id = $id";
$res = mysql_query($update) or die(mysql_error());
}
}
echo mysql_num_rows($result) ? '1' : '0';
You can use sql queries for example:
select id, url from urltable;
update urltable set status=1 where id=99;
So, how about use this code with your Visit function:
$link = mysql_connect('localhost', 'test', 'pppppp');
$db_selected = mysql_select_db('test', $link);
$query = "select id, url from urltable";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
$visitid = $row['id'];
$visiturl = $row['url'];
$visitstatus = Visit($visiturl)? 1: 0;
$upquery = sprintf("update urltable set status=%d where id=%d", $visitstatus, $visitid);
$upresult = mysql_query($upquery);
}