Send Push Notification using PHP and OneSignal

Here is a sample code using PHP to send a push notification to your mobile application using the OneSignal API. Create a free account on https://onesignal.com/ and get your OneSignal AppID and OneSignal RestID keys.

I use the below PHP code in a web app to send OneSignal push notifications to Xamarin Forms apps using the OneSignal Nuget https://www.nuget.org/packages/Com.OneSignal/
You can use this code in any PHP page for use in web form post, cron job, web api, etc…

See my C# example here

function OneSignalSender($userid, $message)
{

$onesignalappid = 'your-onesignalappid';
$onesignalrestapikey = 'your-onesignalrestapikey';

//if using filters to a tag with a userid
$filters = array(
array("field" => "tag", "key" => "userid", "relation" => "=", "value" => $userid)
);

$subtitle = array(
"en" => 'the title'; //Title for ios 10 or higher
);

$headings = array(
"en" => 'title';// Title'
);

$content = array(
"en" => $message//this is the message
);

$fields = array(
'app_id' => $onesignalappid,
//'included_segments' => array('All'), //uncomment if using segments
//'filters' => $filters, //uncomment if using filters
'large_icon' => "ic_launcher_round.png",
'contents' => $content,
'headings' => $headings,
'subtitle' => $subtitle
);

$fields = json_encode($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
curl_setopt($ch, CURLOPT_HTTPHEADER,
array
(
'Content-Type: application/json; charset=utf-8',
'Authorization: Basic ' . $onesignalrestapikey
)
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

$response = curl_exec($ch);
curl_close($ch);

return $response;
}