irwan

Send SMS from PHP (To almost every country)

Nov 15th, 2011
204
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 16.31 KB | None | 0 0
  1. // Include the class
  2. require 'class.swd_SMS.php';
  3.  
  4. // Create the object. (Parameters are optional if they're set in the class already)
  5. $SMS = new swd_SMS('username', 'password');
  6.  
  7. // Send SMS. First parameter is the cell phone number with country code. (Without leading 00)
  8. $SMS->send('34123456789', 'The message goes here');
  9.  
  10. // Let's send another just for fun
  11. $SMS->send('34987654321', 'The message goes here');
  12.  
  13. // All sent messages are stored in an array.
  14. echo '<pre>' . print_r($SMS->sent_messages, true) . '</pre>';
  15.  
  16.  
  17. // Each sent message has a unique message ID, which is in the array above as well. With this we can see the message status any time. Like this:
  18.  
  19. $status = $SMS->fetch_msg_status('MT0052355965-1');
  20.  
  21. echo '<pre>' . print_r($status, true) . '</pre>';
  22.  
  23.  
  24. <?php
  25.  
  26. class swd_SMS
  27. {
  28.  
  29.         /**
  30.         *       =========================================================================
  31.         *                                                        SMS Class
  32.         *       =========================================================================
  33.         *
  34.         *       @author:            Nicolas Oelgart
  35.         *       @copyright:         Nicolas Oelgart
  36.         *       @version:           Revision: 0.9
  37.         *       @date:              22nd April 2007
  38.         *       @last modified:     29th April 2007
  39.         *       @license            GPL
  40.         *
  41.         *       @website:           www.nicoswd.com
  42.         *       @email:             [email protected]
  43.         *
  44.         *       @requirements:      PHP 5
  45.         *
  46.         *       =========================================================================
  47.         *
  48.         *       Copyright (C) 2007  Nicolas Oelgart
  49.         *      
  50.         *       This program is free software; you can redistribute it and/or modify it
  51.         *       under the terms of the GNU General Public License as published by the
  52.         *       Free Software Foundation; either version 2 of the License, or (at your
  53.         *       option) any later version.
  54.         *      
  55.         *       This program is distributed in the hope that it will be useful, but
  56.         *       WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  57.         *       or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
  58.         *       for more details.
  59.         *      
  60.         *       You should have received a copy of the GNU General Public License along
  61.         *       with this program; if not, write to the Free Software Foundation, Inc.,
  62.         *       51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
  63.         *
  64.         *       =========================================================================
  65.         */
  66.  
  67.  
  68.         /**
  69.         *       Your TM4B username. If you don't have one yet, register here for free:
  70.         *       https://www.tm4b.com/register/
  71.         *
  72.         *       @type        string
  73.         */
  74.         private $username         =  'username';
  75.  
  76.         /**
  77.         *       Your TM4B login password.
  78.         *
  79.         *       @type        string
  80.         */
  81.         private $password         =  'password';
  82.  
  83.         /**
  84.         *       The SMS sender. Use your company name or whatever you want display
  85.         *       to the recipient
  86.         *
  87.         *       @type       string
  88.         */
  89.         private $from             =  'You';
  90.  
  91.         /**
  92.         *       Message route. Both Global I and Global II messaging routes are
  93.         *       identical with regards to reliability, delivery speed and support
  94.         *       for delivery states. More info here: http://www.tm4bhelp.com/kb/a-8.php#8
  95.         *
  96.         *       @type        string
  97.         */
  98.         public $msg_route         =  'GD02';
  99.  
  100.         /**
  101.         *       Minimum message length. Will set an error if the messags is shorter than
  102.         *       this value.
  103.         *
  104.         *       @type        integer
  105.         */      
  106.         public $msg_min_length    =  2;
  107.  
  108.         /**
  109.         *       Maximum message length. Will set an error if the messags is larger than
  110.         *       this value. If the message is larger than 160 chars, it will be split into
  111.         *       2 or more messages.
  112.         *
  113.         *       @type        integer
  114.         */      
  115.         public $msg_max_length    =  160;
  116.  
  117.         /**
  118.         *       Minimum number length. Will set an error if the number is shorter than
  119.         *       this value.
  120.         *
  121.         *       @type        integer
  122.         */      
  123.         public $min_num_length    =  8;
  124.  
  125.         /**
  126.         *       An array of errors that ocurred while any request.
  127.         *
  128.         *       @type        array
  129.         */      
  130.         public $errors            =  array();
  131.  
  132.         /**
  133.         *       An array with the details of the sent messages.
  134.         *
  135.         *       @type        array
  136.         */
  137.         public $sent_messages     =  array();
  138.  
  139.         /**
  140.         *       An array with all details of failed messages.
  141.         *
  142.         *       @type        array
  143.         */
  144.         public $failed_messages   =  array();
  145.  
  146.  
  147.        
  148.         /**
  149.         *       Class constructor. Takes 0 or 2 parameters. Parameter 1 being the username,
  150.         *       and parameter 2 being the password, for quick login.
  151.         *
  152.         *       @param       string        Login username
  153.         *       @param       string        Login password
  154.         *
  155.         *       @return      none
  156.         */
  157.         public function __construct()
  158.         {
  159.                 if (func_num_args() == 2)
  160.                 {
  161.                         list($this->username, $this->password) = func_get_args();
  162.                 }
  163.         }
  164.  
  165.  
  166.         /**
  167.         *       Sends the message out. The country code without the leading  00 must be
  168.         *       specified in the number.
  169.         *
  170.         *       @param       string        Recipient phone number.
  171.         *       @param       string        Message for recipient
  172.         *       @param       string        "From" header.
  173.         *       @param       string        Message route. Either GD01 or GD02
  174.         *
  175.         *       @return      boolean
  176.         */
  177.         public function send($number, $message, $from = false, $route = false)
  178.         {
  179.                 $number = preg_replace('/\D/', null, $number);
  180.  
  181.                 if (strlen($number) < $this->min_num_length)
  182.                 {
  183.                         self::set_error("Invalid number: {$number}");
  184.                         return false;
  185.                 }
  186.                
  187.                 // Convert message into a single line string.
  188.                 $message = preg_replace('/[\r\n\t]+/', ' ', trim(strval($message)));
  189.                 $message = preg_replace('/\s{2,}/', ' ', $message);
  190.                 $messagelength = strlen($message);
  191.  
  192.                 if ($messagelength < $this->msg_min_length)
  193.                 {
  194.                         self::set_error('Message too short.');
  195.                         return false;
  196.                 }
  197.                 else if ($messagelength > $this->msg_max_length)
  198.                 {
  199.                         self::set_error('Message too long.');
  200.                         return false;
  201.                 }
  202.  
  203.                 if ($from)
  204.                 {
  205.                         $this->from = $from;
  206.                 }
  207.                 if ($route AND in_array($route, array('GD01', 'GD02')))
  208.                 {
  209.                         $this->msg_route = $route;
  210.                 }
  211.  
  212.                 $request = array(
  213.                         'version' => '2.0',
  214.                         'type'    => 'broadcast',
  215.                         'msg'     => $message,
  216.                         'to'      => $number,
  217.                         'from'    => $this->from,
  218.                         'route'   => $this->msg_route
  219.                 );
  220.  
  221.                 $response = self::http_request($request);
  222.                 $request['delivertime'] = time();
  223.  
  224.                 if (self::is_error($response))
  225.                 {
  226.                         array_push($this->failed_messages, $request);
  227.                         return false;
  228.                 }
  229.                
  230.                 $request['messageid'] = $response;
  231.                 array_push($this->sent_messages, $request);
  232.                 return true;
  233.         }
  234.  
  235.        
  236.         /**
  237.         *       Receives the message status and returns an array with the status and deliver time.
  238.         *
  239.         *       @param       string        Message ID
  240.         *
  241.         *       @return      array         Deliver status/Deliver time
  242.         */
  243.         public function fetch_msg_status($messageid)
  244.         {
  245.                 $request = array('type' => 'check_status');
  246.  
  247.                 if (preg_match('/^MT[\d]{10}-\d$/', $messageid))
  248.                 {
  249.                         $request['id'] = $messageid;
  250.                 }
  251.                 else if (preg_match('/^[a-f0-9]{21}$/', $messageid))
  252.                 {
  253.                         $request['custom'] = $messageid;
  254.                 }
  255.                 else
  256.                 {
  257.                         self::set_error('Invalid Message ID.');
  258.                         return false;
  259.                 }
  260.  
  261.                 $response = self::http_request($request);
  262.  
  263.                 if (self::is_error($response))
  264.                 {
  265.                         return false;
  266.                 }
  267.  
  268.                 list($status, $delivertime) = explode('|', $response);
  269.                 list($year, $month, $day, $hour, $minute) = str_split($delivertime, 2);
  270.        
  271.                 return array(
  272.                         'delivered'   => ($status == 'DELIVRD'),
  273.                         'delivertime' => mktime($hour, $minute, 0, $month, $day, $year) // Don't we all prefer working with UNIX timestamps?
  274.                 );
  275.         }
  276.  
  277.  
  278.         /**
  279.         *       Gets the current balance of your account.
  280.         *
  281.         *       @return      mixed        Balance on success, false on failure.
  282.         */
  283.         public function fetch_balance()
  284.         {
  285.                 $request = array(
  286.                         'version' => '2.0',
  287.                         'type'    => 'check_balance'
  288.                 );
  289.  
  290.                 $response = self::http_request($request);
  291.  
  292.                 return self::is_error($response) ? false : $response;
  293.         }
  294.  
  295.  
  296.         /**
  297.         *       Checks if a specific destination is available on a message route
  298.         *
  299.         *       @param       string        Country code
  300.         *       @param       string        Message route
  301.         *
  302.         *       @return      array         Availability, country, and credits needed to send SMS to this country
  303.         */
  304.         public function check_destination($dest, $route = 'GD01')
  305.         {
  306.                 $request = array(
  307.                         'type'  => 'check_destination',
  308.                         'dest'  => $dest,
  309.                         'route' => $route
  310.                 );
  311.  
  312.                 $response = self::http_request($request);
  313.  
  314.                 if (self::is_error($response))
  315.                 {
  316.                         return false;
  317.                 }
  318.  
  319.                 @list($status, $country, $credits) = explode('|', $response);
  320.  
  321.                 return array(
  322.                         'status'  => ($status == 'Yes'),
  323.                         'country' => $country,
  324.                         'credits' => $credits
  325.                 );
  326.         }
  327.        
  328.        
  329.         /**
  330.         *       Sends the HTTP request to the server and receives the response.
  331.         *       Either the cURL library needs to be installed, or allow_url_fopen
  332.         *       needs to be enabled in php.ini
  333.         *
  334.         *       @param       array        request values
  335.         *
  336.         *       @return      string       Server response
  337.         */
  338.         private function http_request($request = array())
  339.         {
  340.                 // Should never exceed the time limit, but just in case.
  341.                 @set_time_limit(0);
  342.  
  343.                 $request['username'] = $this->username;
  344.                 $request['password'] = $this->password;
  345.  
  346.                 // Takes also care of the URL encoding.
  347.                 $request = http_build_query($request, '', '&');
  348.  
  349.                 if (function_exists('curl_init') AND $ch = @curl_init('https://www.tm4b.com/client/api/http.php'))
  350.                 {
  351.                         curl_setopt($ch, CURLOPT_POST, true);
  352.                         curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
  353.                         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  354.                         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  355.                
  356.                         $response = curl_exec($ch);
  357.                         curl_close($ch);
  358.                 }
  359.                 else if (ini_get('allow_url_fopen'))
  360.                 {
  361.                         if (!$fp = @fsockopen('ssl://tm4b.com', 443))
  362.                         {
  363.                                 self::set_error('Unable to connect to host. Try again later.');
  364.                                 return false;
  365.                         }
  366.  
  367.                         $header  = "POST /client/api/http.php HTTP/1.1\r\n";
  368.                         $header .= "Host: tm4b.com\r\n";
  369.                         $header .= "User-Agent: HTTP/1.1\r\n";
  370.                         $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
  371.                         $header .= "Content-Length: " . strlen($request) . "\r\n";
  372.                         $header .= "Connection: close\r\n\r\n";
  373.                         $header .= "{$request}\r\n";
  374.                        
  375.                         fputs($fp, $header);
  376.                         $result = array();
  377.  
  378.                         while(!feof($fp))
  379.                         {
  380.                                 $result[] = fgets($fp);
  381.                         }
  382.  
  383.                         fclose($fp);
  384.                         $response = $result[9];
  385.                 }
  386.                 else
  387.                 {
  388.                         trigger_error('Server does not support HTTP(S) requests.', E_USER_ERROR);
  389.                 }
  390.  
  391.                 return trim($response);
  392.         }
  393.  
  394.  
  395.         /**
  396.         *       Checks for errors in the API response and adds it to the array if there's one.
  397.         *
  398.         *       @param       string       API response
  399.         *
  400.         *       @return      boolean      True if error, false if not.
  401.         */
  402.         private function is_error($string)
  403.         {
  404.                 if (preg_match('/^error\(\d+\|([^\)]+)/', $string, $error))
  405.                 {
  406.                         self::set_error($error[1]);
  407.                         return true;
  408.                 }
  409.  
  410.                 return false;
  411.         }
  412.  
  413.  
  414.         /**
  415.         *       Sets the minumum and maximum message length
  416.         *
  417.         *       @param       integer        Minimum message length. Use false to keep default
  418.         *       @param       integer        Maximum message length.
  419.         *
  420.         *       @return      none
  421.         */
  422.         public function set_message_length($min, $max = false)
  423.         {
  424.                 if ($min !== false)
  425.                 {
  426.                         $this->msg_min_length = intval($min);
  427.                 }
  428.                 if ($max !== false)
  429.                 {
  430.                         $this->msg_max_length = intval($max);
  431.                 }
  432.         }
  433.        
  434.        
  435.         /**
  436.         *       Returns the number of sent messages.
  437.         *
  438.         *       @return       integer        Number of sent messages.
  439.         */
  440.         public function nr_sentmessages()
  441.         {
  442.                 return sizeof($this->sent_messages);
  443.         }
  444.  
  445.        
  446.         /**
  447.         *       Adds an error string to the error array
  448.         *
  449.         *       @param       string       Error string
  450.         *
  451.         *       @return      none
  452.         */
  453.         private function set_error($error)
  454.         {
  455.                 $this->errors[] = $error;
  456.         }
  457.  
  458.         /**
  459.         *       =========================================================================
  460.         *                                                        SMS Class end
  461.         *       =========================================================================
  462.         *       Copyright (C) 2007 by Nicolas Oelgart.
  463.         */
  464.        
  465. }
  466.  
  467. ?>
Advertisement
Add Comment
Please, Sign In to add comment