PHP code run multiple time on single submit - php

Background: I have implemented the GCM enable android app which is use to received announcement and the announcement are send by a web site developed in php where we have created a html for m to enter the annoncement and button to submit.We submit this to php file which call the which get the all the registered user and run the code to send the message to all the user.
<?php
include_once 'db_functions.php';
include_once 'gcm.php';
$gcm = new GCM();
$db_functions = new DB_Functions();
$alluser = $db_functions->getAllUsers();
$message = array("price" => $message);
ob_start();
while ($row = mysqli_fetch_assoc($alluser)) {
echo "\n" . $row["name"] . "--";
$result = $gcm->send_notification(
array($row["gcm_regid"]),
$message);
echo $result;
}//End of while statement
?>
Issue: When I submit the form to send message to android app by using GCM call the same php webpage run for multiple time which is causing duplicate messages in client android app.
Could any one help me understand or provide me link which discuss this issue.
Possible Issue may be as the number of users have increase and it take a long time run this code for each use.
Any help in optimizing will be greatly appreciated.

I don't know what GCM library you use, but note that you can also call GCM with a list of ID's (up to 1000) to send the same message. So in that way you don't need to make 1000 calls if you have 1000 users. Unless of course your message is different for each user, but it doesn't look like it.
Besides that I don't think there is something wrong with your code. It can be that it takes a long time and people submit the form twice. Or you have some javascript on the button to submit the form which makes it to submit twice?

Thanks for your comment.
Basically i have found that this issue was due to the browser refresh in on the send message php page when network was week(lollipop network issue) so it cause the same message to be send for multiple no of time.
To solve the issue I have redesign the PHP page i.e. form to accept the message and send message by using the concept of request redirect get concept.
The link for the your reference.
https://en.wikipedia.org/wiki/Post/Redirect/Get
So that this issue does not happen due to refreshing.
Also thanks Jorgen for pointing out the concept of sending request to gcm server for all the gcm registration id it has improve the performance.

Related

CronJob Friendly PHP redirect

I'm struggling with a PHP script that is activated by a Cronjob and includes a redirect.
The script finds records in my database, sends an email as appropriate and then redirects to a compiled URL so the details of the records can be imported into an external system.
The email part works fine via a Cronjob, the redirect does not, I understand that this is because Cronjobs do not operate within the browser but I'm not sure what is the best alternative method of redirecting to the URL.
Simplified code below:
<?php
// Connect to DB
require_once($_SERVER['DOCUMENT_ROOT']."/admin/inc/dbconnect.php");
// Check DB for quotes that have not been sent to this client
$query_quotes = "SELECT * FROM quotes WHERE sent_client = 0 LIMIT 1";
$view_request = mysqli_query($GLOBALS['db_connect'], $query_quotes);
// Send to external system and email customer with quote
while ($quotes = mysqli_fetch_array($view_request)){
$Body = "Email Content";
// Send email via Swift Mailer
// Send quote information to third party system via URL redirect
header('Location: http://exampleurl/?FirstName='.rawurlencode($quotes['name']).'&businessName='.rawurlencode($quotes['company_name']).'.');
}
?>
It is as you said, you are not in a web-environment, so there is no browser to act on the Location: redirect. That doens't mean you can't pass information to a webpage - you just can't redirect to it - you call to it, and get information back - the info you get back might not be much - just 'OK, I got it' may well be more than enough. It might be as simple as
$url = "http://exampleurl/?FirstName=" .
rawurlencode($quotes['name']) . '&businessName=' .
rawurlencode($quotes['company_name'])
$response = file_get_contents($url);
And the response might be as simple as 200 OK (though if there is no response apart from just 'OK', officially according to the HTTP specs, you'd return 204 No Content, but that is a very small thing).
Better still would be to use a proper HTTP calling function that dcan deal with potential issues like redirections and make life a little easier - something like the Guzzle library for example, but again, if file_get_contents works for you with a URL, that may be enough, at least while you are testing the basics.

Mandrill - How do I retrieve the message content html that was just sent?

I'm using the Mandrill API with PHP.
I am sending a mail message:
$result = $mandrill->messages->sendTemplate($template_name, $template_content, $message);
$mandrill_return_data = current($result);
Since the message content is only saved for 24 hours, I would like to retrieve the html that was just sent and save it into my DB.
$message_content = $mandrill->messages->content($mandrill_return_data['_id'])['html'];
Unfortunately, this doesn't work and returns the following error:
A mandrill error occurred: Mandrill_Unknown_Message - No message
exists with the id '446740d7b61e4403b11379db4e1d45b0'
I did some googling and found this answer and it explains that it takes a few minutes to index the message in their system and I noticed this to be the case. Now I am trying to figure out a solution on how to retrieve the message content html and save it into my DB.
I suppose I could use a cron job to run every few hours or after it sends the message, or I could run an AJAX command to retrieve the message content html after a specified timeout, but both of those solutions seem hacky. I'm hoping for a more elegant solution that doesn't require a whole lot of additional code. Any ideas?

PHP + PayPal IPN + SQLite = a mysterious 503 error?

I have a simple php Paypal ipn listener which inserts the raw POST data into an SQLite (v2) database. It was working. Then...it stopped working. (I don't recall making any changes to it.) It uses a basic php sample that Paypal provides using CURL to communicate with Paypal (followed by the db insert). It just gives a 503 Service Unavailable error now.
It works (minus actually doing anything :)) if I comment out the final line, that simple contains "sqlite_exec(...)".
Alternatively, a MySQL insert works fine.Mailing results works as well.
The SQLite database appears normal. Another script reads & updates as normal.
Web host sees no issues on the server side.
Can anyone make sense of this?
Or maybe there is a way to send the POST data to another script so that it gets processed separately, on its own, instead of altogether as one page?
Update: What I'm trying to insert is the "raw post data" string...
$raw_post_data = file_get_contents('php://input');
...as seen on the top line here under php sample code: https://www.x.com/developers/PayPal/documentation-tools/code-sample/216623 . My script is the same except with an insert at the bottom, which basically looks like this:
$dbloc = "/db/ipn.sqlite";
if($db = sqlite_open("$dbloc", 0666, $sqlite_error)){}else{die ($sqlite_error);}
$datetime = date("Y-m-d H:i:s");
$data = $raw_post_data;
$sql="INSERT INTO Paypal (entrydate,verified,data) values ('$datetime',$verified,'$data')";
sqlite_exec($sql,$db);
From when are you getting this error ?
Paypal has done some IPN changes recently.
please check this links:
https://www.x.com/content/bulletin-ipn-and-pdt-scripts-and-http-1-1
http://www.tipsandtricks-hq.com/forum/topic/paypal-ipn-and-pdt-changes-effective-from-1st-february-2013
please let us know what you are trying to insert into the db.

Pusher App events not triggering

I'm testing out the Pusher library for handling websockets with a rather simple app using PHP and Javscript (jQuery) you can find it here: http://jsfiddle.net/JyVvr/1/
Tha backend ajax.php file contains this:
require 'lib/Pusher.php';
$message = $_POST['msg'];
$pusher = PusherInstance::get_pusher(); // My API key, secret, etc is directly set in the Pusher.php file
$pusher->trigger(
'test_channel',
'new_comment',
array('message' => $message)
);
echo json_encode(array('message' => $message));
Basically the app just takes a message and appends it to the ul element on form submit, the appending part works just fine but the new_comment event isn't triggering so the app isn't working as intended, I used an alert just to test if it showed but it just does nothing plus it doesn't throw any errors or anything. Can anyone tell me what am I doing wrong?
Thanks in advance!
If the events aren't reaching Pusher, make sure the Pusher server time and your server time match or are within 599s of each other. I've been trying to figure this out recently and this article was the first one to appear, so just mentioning this for others to save them some time and headache.
Take a look at the Pusher Debug Console for your app. If you don't see your event triggered in there then it's either not reaching or is not being accepted by the Pusher REST API.
There aren't any issued raised about this Pusher PHP library.

How would I go about writing a simple PHP bot?

How would I go about writing a simple PHP bot that could login in and recieve all the cookies sent by the server? ... and then send them back when required?
Any suggestions would be appreciated.
First of all, your question is too broad and lacking in detail to really answer effectively. That said, I'll give it a try.
Not knowing what exactly you mean by "log in", I assume you want the script to be able to post some data to another script via an HTTP request. The CURL Library is good for that. It is able to post data and handle cookies.
Edit: Got ninja'd by Zed. ;)
If for some reason you cannot use the curl extension on your server (extension not installed), you can use a class such as Snoopy which will still allow you to either use the curl binaries or use sockets to retrieve the information.
Snoopy handles cookies.
As for the writing the bot itself, it's just a question of sending the proper requests. Here is an example with Snoopy:
$snoopy = new Snoopy;
// The following needs to reflect the form configuration of the site
$login = array('usr' => 'hi', 'pwd' => 'hello');
if($snoopy->submit('http://example.com/login', $login) === false) {
// output the response code
die($snoopy->response_code . ':' . $snoopy->error);
}
//Request succeeded (doesn't mean we are logged in)
// output the results
echo $snoopy->results;
// Check the results to see if you are logged in and
// Continue using $snoopy.
// It will pass the proper cookies for the next requests.
With the help of the cURL library?

Categories