How to send SMS messages using PHP and my.fastsms

The function below creates a new PHP class called SMS and has two functions available. One that will check the number of credits remaining in your fastsms.co.uk account. Each SMS send counts as a credit.


<?php

class SMS {

    function __construct() {
    }

    function SendSMS($telephoneNumber, $message)
    {
         // include config
        include_once './config.php';

         // Create Parameter Array
        unset($Parameters);
        $Parameters['Action']="Send";
        $Parameters['DestinationAddress']=$telephoneNumber ;
        $Parameters['SourceAddress']="Test SMS";
        $Parameters['Body']=$message;
        $Parameters['ValidityPeriod']="86400";

        // Call api_connect() function
        $resultcode= $this->api_connect(SMS_TOKEN, $Parameters);

        if ($resultcode>0)
        {
            //get remaining credits

            return "Message ID is: ".$resultcode . "n" . $this->GetCreditLevel();
        }
            else
        {
            return "An error occurred. ID: ".$resultcode;
        }

    }
    function GetCreditLevel()
    {
         // include config
        include_once './config.php';
        // Create Parameter Array
    unset($Parameters);
    $Parameters['Action']="CheckCredits";
    // Call api_connect() function
    $resultcode=$this->api_connect(SMS_TOKEN, $Parameters);
    if (is_numeric($resultcode) && $resultcode<0)
    {
        return "An error occurred. ID: ".$resultcode;
    }
        else
    {
        return "Current SMS Credits: ".$resultcode;
    }

    }

// api connect function
function api_connect($Token, $ParameterArray)
{
    // Create the URL to send the message.
    // The variables are set using the input from an HTML form

    $err = array();
    $url = "my.fastsms.co.uk";
    $headers = "POST /api HTTP/1.0rn";
    $headers .= "Host: ".$url."rn";

    // Create post string
    // Username and Password
    $poststring = "Token=".$Token;

    // Turn the parameter array into the variables

    while (list($Key, $Value)=@each($ParameterArray))
    {
        $poststring .= "&".$Key."=".urlencode($Value);
    }

    // Finish off the headers
    $headers .= "Content-Length: ".strlen($poststring)."rn";
    $headers .= "Content-Type: application/x-www-form-urlencodedrn";

    // Open a socket
    $http = fsockopen ($url, 80, $err[0], $err[1]);
    if (!$http)
    {
        echo "Connection to ".$url.":80 failed: ".$err[0]." (".$err[1].")";
        exit();
    }

    // Socket was open successfully, post the data.
    fwrite ($http, $headers."rn".$poststring."rn");

    // Read the results from the post
    $result = "";
    while (!feof($http))
    {
        $result .= fread($http, 8192);
    }

    // Close the connection
    fclose ($http);

    // Strip the headers from the result
    list($resultheaders, $resultcode)=preg_split("/rnrn/", $result, 2);

    return $resultcode;
}

}

?>

 

Advertisements