How to receive push notifications from your website using php

On my website I have my resume, and a downloadable version in pdf. I wanted to get notified when someone downloaded the pdf version. So I needed a way to detect when the link was pressed and call my php script to sent the notification. After a while digging I found a similar solution in jQuery, in stackoverflow, which I modified to meet my needs.


 <a href="#" onclick="myfunction(); return false;">just a regular link</a>
 <div id="message"></div>

function myfunction(){
  $('#message').load('test.php');
}

The onclick event detects when the link is clicked and calls myfunction(), which just loads the php script. If the script has a return value or a message it is shown back to the frontend in the div with the id=”message”.

Push notifications were going to be sent from pushover. Its a “free” service where you can programmatically sent push notifications using their api. I used quotes because while its free to sign up and get your api key, in order to receive the notifications you have to buy their client after a five day free trial. They have clients for Andoid, iOS and Desktop through the browser. If you don’t buy the client, after the trial ends, you will simply stop receiving notifications in your device. You can however continue to sent push notifications to others.

Their service is super easy to use, and the documentation is excellent. There are many examples as well as complete code on how to call the api, in many programming languages. Have in mind that you need curl in order to call the api, which is not a big deal since most hosting providers (if not all) support it. Before start using it, you need to create an application first in pushover’s website. You just have to provide a name and a description for the application and receive your application api token which you will be needing. Below is an example in php, on how you would call the api to sent a push notification to your device.


curl_setopt_array($ch = curl_init(), array(
  CURLOPT_URL => "https://api.pushover.net/1/messages.json",
  CURLOPT_POSTFIELDS => array(
  "token" => "application_api_token",
  "user" => "your_api_key",
  "message" => "Hello, World!",
  "priority" => "0",
)));
curl_exec($ch);
curl_close($ch);

The server will respond, informing you of the success or failure of the operation.


{"status":1,"request":"e1fd56cd940fb0ad9d385620e1aefa53"}

BONUS:
You can use the code in my previous blog post, and include a user’s ip address and location in the message of your push notification. It’s not only nice to see real time visitors interacting with your website, it will be useful if bots try to submit your contact or registration form!

For the full source code please visit my github. If you have any questions or comments, please use the comment section below.

0 comments