tags:

views:

130

answers:

3

I made a PHP class that dramatically simplifies sending text messages with PHP. I know this isn't really a "help me out!" type question per se, but I would like to share the code because I have found it to be tremendously useful. You're free to do whatever you'd like with the code . You can even go around telling people you made it. Just don't accuse me if anything goes wrong.

Without further ado:

<?php

// Carrier email suffixes
define('ATT',                 'txt.att.net');
define('SPRINT',              'messaging.sprintpcs.com');
define('TMOBILE',             'tmomail.net');
define('US_CELLULAR',         'email.uscc.net');
define('VERIZON',             'vtext.com');
define('VIRGIN_MOBILE',       'vmobl.com');

// Message parameters
define('MAX_SMS_LENGTH',       140);
define('DEFAULT_CELL_SENDER',  '[email protected]');

class Cell
{
    public static function send($pNumber, $pCarrier, $pMessage)
    {
        // Keep a notifier of whether the message was sent or not
        $Success = true;

        // Define the recipient address
        $Recipient = $pNumber . '@' . $pCarrier;

        // Find out how many message will have to be sent
        $MessageCount = ceil(strlen($pMessage) / MAX_SMS_LENGTH);

        for ($i = 0; $i < $MessageCount; $i++)
        {
            // Calculate the subset of the entire message that can be sent at once
            $StartIndex = $i * MAX_SMS_LENGTH;
            $Message = stripslashes(substr($pMessage, $StartIndex, MAX_SMS_LENGTH));

            // Display page numbers on messages that span multiple iterations
            if ($MessageCount > 1)
            {
                $Message .= ' (' . ($i + 1) . '/' . $MessageCount . ')';
            }

            // Send the message
            $Success &= mail($Recipient, null, $Message, 'From: ' . DEFAULT_CELL_SENDER);
        }

        return $Success;        
    }
}

?>

It automatically handles paging across multiple text messages. Also, I know text messages are generally restricted to 160 characters, not 140. I reduced the limit by 20 characters to leave room for the email address.

I hope this helps someone out there. Cheers!

+6  A: 

So if your question is, where to share this code, I would prefer Github, or Google Code. Good luck ;)

Nort
+3  A: 

Well, to address your comment on your question, there are four major "flaws" that I can see:

  1. Doesn't allow to send Unicode SMS.
  2. Doesn't support sending concatenated SMS, it's really ugly to see (n/m).
  3. When (n/m) is added you're not calculating the message length correctly.
  4. You could do a lot better with a foreach (str_split($sms, 140) as $sms_part).
Alix Axel
+1  A: 

The main problem I see with this is that it only works on US carriers. If you really want to send SMS's via code, maybe you should use something like Twilio

Jani Hartikainen