Solved

SMS

Posted on 2004-08-10
34
859 Views
Last Modified: 2010-06-30
I want to add the SMS feature in my website, so ppl can send sms directly to my phone from the website. Anyone know how can I achieve this in php?

I registered on

http://www.clickatell.com


what next?


Moiz
0
Comment
Question by:Moizsaif123
  • 11
  • 8
  • 7
  • +4
34 Comments
 
LVL 25

Accepted Solution

by:
Squinky earned 80 total points
Comment Utility
Clickatell have some basic PHP that works:

http://www.clickatell.com/downloads/Clickatell_sample_code.pdf

I've written a huge clickatell PHP class for a company system (so I can't post it), but clickatell's documentation and support is really pretty good, have a rummage around their site.
0
 
LVL 9

Assisted Solution

by:waygood
waygood earned 80 total points
Comment Utility
Many thanks guys I am in the middle of sorting this sort of thing out and expected to pay much more than the price listed on clickatell (but the company i was going to use did faxes too)
0
 
LVL 25

Expert Comment

by:Squinky
Comment Utility
Clickatell is not only a good deal, they are about the only provider I have encountered that actually offers a professional service at all, despite having attempted to contact around 20 other providers who were just plain not interested. Forget trying to get any response directly from the networks - they're just not interested in your business, and yet they dare complain about how they're having trouble paying for their 3G licenses... I find it quite ironic that I have to go to a different hemisphere to send a message to a person sitting next to me... Only complaint I have is that they don't allow + prefixes for sender numbers, so you can't use international reply numbers unless you happen to know what country the recipient is in at the time. Duh! It's apparently a limitation imposed on them by their networks.

For higher-end stuff (short codes, reverse billing etc), http://www.quios.com/ were quite helpful, but I've not actually used them.
0
 
LVL 4

Author Comment

by:Moizsaif123
Comment Utility
Squinky,

First of all I need to mention im a beginner in php and secondly I tried your code from the pdf file, I dont understand the code and I need steps on how to proceed with this...Is this free by the way, because I registered with clickatell and i dint pay any money..


Moiz
0
 
LVL 25

Expert Comment

by:Squinky
Comment Utility
After you register, you'll need to buy some credits - they might give you 10 free ones or something.

They allow you to set up different access codes to access their system in different ways, e.g. you can have different setups for XML, PHP and Java. They refer to them as APIs, so you need to go set one up - read their instructions. It will involve you doing things like specifying the IP address of your server (an API is tied to a fixed IP), and probably a name and password which you then need to insert in the PHP script they supply in order to use your API from PHP. Essentially you need to build a query string and then open it as a URL, using file_get_contents, fopen or CURL functions in PHP.
It has some nice features for callbacks so you can send a message and it will notify you later that it's arrived or been opened by calling one of your own scripts, and again, that's something to set up in your PHP API.

As well as their sample code, read their general documentation carefully - I'm not about to reproduce or paraphrase it here!
0
 
LVL 9

Assisted Solution

by:_GeG_
_GeG_ earned 40 total points
Comment Utility
Hi Moiz,

I did a Clickatell class fo my site, but it costs a little money, you can check out the docs on http://www.have2.com/sms/
It's very easy to use, for example to send a single sms, you need only three lines:
<?php
require_once('Clickatell_SMS.php');
$sms=new Clickatell_SMS('username', 'password', 'api_id'); // you will get those values from Clickatell at registration
$result=$sms->SendMsg(476583677637, 'SMS Text here'); // first is telephone number, then the SMS text
if ($result) echo 'ok';
else echo 'Error: '.$sms->lastErrorMessage();
?>
0
 
LVL 25

Expert Comment

by:Squinky
Comment Utility
Nice class.
0
 
LVL 9

Expert Comment

by:waygood
Comment Utility
Took the code from Squinky and wrote this class during my lunch. Is this similar to the one you want people to pay for??

<?php

class Cls_clickatell
{
      function Cls_clickatell($user, $password)
      {
            $this->user=$user;
            $this->password=$password;
            $this->api_id="";
            $this->base_url="";

            $this->error="";
            $this->sess_id=0;
      }

      function set($variable, $value)
      {
            if(isset($this->$variable))
            {
                  $this->$variable=$value;
                  return TRUE;
            }
            return FALSE;
      }
      function set_baseurl($url)
      {
            if(!trim($url)=="")
            {
                  if(!ereg("^http://", $url))
                  {
                        $url="http://".$url;
                  }
                  return $this->set('base_url', $url);
            }
            return FALSE;
      }
      function set_api($api)
      {
            if(!trim($api)=="")
            {
                  return $this->set('api_id', $api);
            }
            return FALSE;      
      }


      function send_msg($telephone, $message)
      {
            $telephone=ereg_replace("^[0-9]","",$telephone);
            $message=urlencode($message);

            if(!$this->establish_session())
            {
                  return FALSE;
            }
            if(!$this->establish_session())
            {
                  return FALSE;
            }
            return TRUE;
      }

      function establish_session()
      {
            $url=$this->base_url . "/http/auth?user=" . $this->user . "&password=" . $this->password . "&api_id=" . $this->api_id;

            $request = file($url);
            if( (is_array($request)) && (sizeof($request)>0) )
            {
                  // split our response. return string is on first line of the data returned
                  $sess = split(":",$request[0]);
                  if($sess[0] == "OK")
                  {
                        $this->sess_id = trim($sess[1]); // remove any whitespace
                        return TRUE;
                  }
                  else
                  {
                        $this->error="Authentication failure: ".$request[0];
                        return FALSE;
                  }
            }
            else
            {
                  $this->error="Unable to start session.";
                  return FALSE;
            }
      }

      function send_message($telephone, $message)
      {
            $url = $this->base_url . "/http/sendmsg?session_id=" . $this->sess_id . "&to=" . $telephone . "&text=" . $message;

            $request = file($url);
            if( (is_array($request)) && (sizeof($request)>0) )
            {
                  // split our response. return string is on first line of the data returned
                  $send = split(":",$request[0]);
                  if($send[0] == "ID")
                  {
                        $this->message_id = trim($send[1]); // remove any whitespace
                        return TRUE;
                  }
                  else
                  {
                        $this->error="Authentication failure on current session: ". $request[0];
                        return FALSE;
                  }
            }
            else
            {
                  $this->error="Unable to send message on current session.";
                  return FALSE;
            }
      }

      function get_error()
      {
            return $this->error;
      }
      function get_message_id()
      {
            return $this->message_id;
      }
}

$user = "user";
$password = "password";
$api_id = "xxxx";
$baseurl ="http://api.clickatell.com";
$text = "This is an example message";
$to = "0123456789";

$send_sms=new Cls_clickatell($user, $password);
$good=TRUE;
$good=$send_sms->set_baseurl($baseurl);
if($good)
{
      $good==$send_sms->set_api($api_id);
      if($good)
      {
            $good=$send_sms->send_msg($to, $text);
      }
}
if($good)
{
      echo "complete: message id is ".$send_sms->get_message_id();
}
else
{
      echo $send_sms->get_error();
}

?>
0
 
LVL 9

Expert Comment

by:waygood
Comment Utility
Fair play theres a lot more functionality to the class GEG mentioned.

Nice seeing the documentation to tantalise us, but you didnt tell us where to get it.
0
 
LVL 9

Expert Comment

by:_GeG_
Comment Utility
lol
your lunch class has still some flaws, but if you invest some more lunches, it should work fine for single messages, but you will have problems sending to a larger amount of recipients ;)
(@waygood: just prove of concept why it wouldn't work yet: send_msg() calls twice establish_session() instead of doing real work ;))

As I mentioned before I used it for my own site. Until now I didn't think about selling it.
What would you say is a fair price for it?
It is optimized for sending bulk messages (no per recipient connections to the clickatell server that slow down the service, no maximum amount of recipients as there would be with GET requests and some other improvements).
0
 
LVL 9

Expert Comment

by:waygood
Comment Utility
Your right, the second one was supposed to be send_message, must have been reaching the end of my chicken curry and chips when I did that bit.

QUOTE " did a Clickatell class fo my site, but it costs a little money, you can check out the docs on"
_________________________________________^

Thats why I asked about where to get it and what price.
0
 
LVL 9

Expert Comment

by:_GeG_
Comment Utility
:D ok, you can buy it now!
0
 
LVL 5

Expert Comment

by:basiclife
Comment Utility
Ok, I use sms2email.com but despite the name, they provide everything I need to SMS from my php scripts. Here's my script:

<?php

$un="my UN";
$pw="my PW";
$authnumber="my Mobile Number (in int format w/o the +. ie 447095...";
$lowwater=30;
$array_servers = array("gw1.sms2email.com","gw11.sms2email.com", "gw2.sms2email.com","gw22.sms2email.com");

function formatNumber($number) {
      if (substr($number, 0, 2) == "07") {
          $number="44" . substr($number, 1, strlen($number)-1);
      }
      if (substr($number, 0, 1) == "+") {
          $number=substr($number, 1, strlen($number)-2);
      }
    return $number;
}

function getCredit() {
      $username=$GLOBALS["un"];
      $password=$GLOBALS["pw"];
      foreach($GLOBALS["array_servers"] as $server) { //this line sets the server we wish to connect to
            $connecturl = fopen("http://$server/sms/postmsg.php?cmd=credit&username=$username&password=$password","r");
        if($connecturl) {
                  stream_set_timeout($connecturl, 30);
              $CreditsPage='';
              while (!feof($connecturl)) {
                $CreditsPage .= fread($connecturl, 8192);
              }
              fclose($connecturl);
              $tempCredit = explode ("=", $CreditsPage);
              return $tempCredit[1];
            break;
          }
    }

    return "Error";
}

function sendSMS($number, $message, $from) {
      $message = substr(urlencode($message), 0, 160);
    $number = formatNumber($number);

      $username=$GLOBALS["un"];
      $password=$GLOBALS["pw"];

      $resultType = array (
                      "AQSMS-NOAUTHDETAILS" =>
                              array (0, "No Authorisation Details Supplied"),
                      "AQSMS-AUTHERROR" =>
                              array (0, "Authorisation Failed"),
                      "AQSMS-NOCREDIT" =>
                              array (0, "No Message Credits Available"),
                      "AQSMS-OK" =>
                              array (1, "Ok"),
                      "AQSMS-NOMSG" =>
                              array (0, "Insufficient Information"),
                      "AQSMS-INVALID_DESTINATION" =>
                              array (0, "Invalid Number ($number)")
      );


    if (getCredit() <=$GLOBALS["lowwater"] && $number != $GLOBALS["authnumber"]) { //Die if less than $lowwater credits and not going to my phone
             return array (0, "Credit below low-water mark");
      }

      foreach($GLOBALS["array_servers"] as $server) { //this line sets the server we wish to connect to
            $connecturl = @fopen("http://$server/sms/postmsg.php?to_num=$number&orig=$from&username=$username&password=$password&message=$message","r");
            //print "http://$server/sms/postmsg.php?to_num=$number&orig=$from&username=$username&password=$password&message=$message";
        if($connecturl) {
                  stream_set_timeout($connecturl, 30);
              $ResultPage='';
              while (!feof($connecturl)) {
                $ResultPage .= fread($connecturl, 8192);
              }
              fclose($connecturl);
              $ResultPage=trim($ResultPage);
              return $resultType[$ResultPage];
            break;
          }
    }

    return array (0, "Unable to connect to any SMS server (attempted " . count($GLOBALS["array_servers"]) . ")");
}

?>



What this does it: Provide a function getCredit() to check how many SMS I have bought and sendSMS() to actually send one. It won't send to anyone other than me if I I have < 30 credits. Also has a formatNumber() function which converts numbers into a UK format
0
 
LVL 4

Author Comment

by:Moizsaif123
Comment Utility


_GeG_

I used yur code for sending a sms but i get an error, saying tht

Fatal error: Cannot instantiate non-existent class: clickatell_sms in /usr/home/moizsaif/public_html/server.php on line 68



Moiz
0
 

Expert Comment

by:evanatmtd
Comment Utility
Hi, is this just to SMS YOUR phone? if so, who is your service provider and I will whip somthing up based on that.
0
 
LVL 5

Expert Comment

by:basiclife
Comment Utility
If that was aimed at me, no it's to SMS anyone's phone but if there is no number supplied it defaults to mine. You needto visit www.sms2email.com and sign up for an account. They give you access to a php script, which you send the information to. It returns a code (listed in the array in my example) with the outcome of the SMS
0
 
LVL 9

Expert Comment

by:waygood
Comment Utility
(I am using it for something a little different so I am sending an email instead)
With the clickatell example I gave earlier, your could:-

$user = "user";
$password = "password";
$api_id = "xxxx";
$baseurl ="http://api.clickatell.com";
$text = "This is an example message";
$to = "0123456789";
$alt = "44444444";  // added this

$send_sms=new Cls_clickatell($user, $password);
$good=TRUE;
$good=$send_sms->set_baseurl($baseurl);
if($good)
{
     $good==$send_sms->set_api($api_id);
     if($good)
     {
          $good=$send_sms->send_msg($to, $text);
     }
}
if($good)
{
     echo "complete: message id is ".$send_sms->get_message_id();
}
else
{
     echo $send_sms->get_error();
     $good=$send_sms->send_msg($alt, $text);  // added this - send message to you on error
}

0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 4

Author Comment

by:Moizsaif123
Comment Utility


I added the above code in my php script and I get this error...

Fatal error: Cannot instantiate non-existent class: cls_clickatell in /usr/home/moizsaif/public_html/server.php on line 91



Moiz
0
 
LVL 25

Expert Comment

by:Squinky
Comment Utility
So did you forget to include/require the cls_clickatell class file?
0
 
LVL 9

Expert Comment

by:waygood
Comment Utility
Cls_clickatell not cls_clickatell
0
 
LVL 4

Author Comment

by:Moizsaif123
Comment Utility
I paste only this in a new page

and I get this error....

Fatal error: Cannot instantiate non-existent class: cls_clickatell in /usr/home/moizsaif/public_html/sms.php on line 11



<?php

$user = "moizsaif";
$password = "g1zix0gj";
$api_id = "SMA995";
$baseurl ="http://api.clickatell.com";
$text = "This is an example message";
$to = "12013100991";
$alt = "12013100991";  // added this

$send_sms=new Cls_clickatell($user, $password);
$good=TRUE;
$good=$send_sms->set_baseurl($baseurl);
if($good)
{
     $good==$send_sms->set_api($api_id);
     if($good)
     {
          $good=$send_sms->send_msg($to, $text);
     }
}
if($good)
{
     echo "complete: message id is ".$send_sms->get_message_id();
}
else
{
     echo $send_sms->get_error();
     $good=$send_sms->send_msg($alt, $text);  // added this - send message to you on error
}


?>



0
 
LVL 25

Expert Comment

by:Squinky
Comment Utility
So where's your include?
0
 
LVL 4

Author Comment

by:Moizsaif123
Comment Utility
maybe thats what I am missing...or not maybe im sure thts what im missing...

where do I put the include and how do I define it...



Moiz
0
 
LVL 25

Expert Comment

by:Squinky
Comment Utility
Before you create an instance of Cls_clickatell, you need to include/require the source file that the class definition is stored in, otherwise PHP doesn't know how to create a Cls_clickatell type object, hence the error you're seeing. I don't know where you've put it. I'd usually do something like:

require_once 'Cls_clickatell.class.php';
0
 
LVL 4

Author Comment

by:Moizsaif123
Comment Utility
I have included the whole class (Cls_clickatell). Now I dont get any errors

 but im still unable to send any sms messages accross to my phone....

12013100991

is it maybe my phone number.... ?



<?php

class Cls_clickatell
{
     function Cls_clickatell($user, $password)
     {
          $this->user=$user;
          $this->password=$password;
          $this->api_id="SMA995";
          $this->base_url="http://api.clickatell.com";

          $this->error="";
          $this->sess_id=0;
     }

     function set($variable, $value)
     {
          if(isset($this->$variable))
          {
               $this->$variable=$value;
               return TRUE;
          }
          return FALSE;
     }
     function set_baseurl($url)
     {
          if(!trim($url)=="http://api.clickatell.com")
          {
               if(!ereg("^http://", $url))
               {
                    $url="http://".$url;
               }
               return $this->set('base_url', $url);
          }
          return FALSE;
     }
     function set_api($api)
     {
          if(!trim($api)=="SMA995")
          {
               return $this->set('api_id', $api);
          }
          return FALSE;    
     }


     function send_msg($telephone, $message)
     {
          $telephone=ereg_replace("^[0-9]","",$telephone);
          $message=urlencode($message);

          if(!$this->establish_session())
          {
               return FALSE;
          }
          if(!$this->establish_session())
          {
               return FALSE;
          }
          return TRUE;
     }

     function establish_session()
     {
          $url=$this->base_url . "/http/auth?user=" . $this->user . "&password=" . $this->password . "&api_id=" . $this->api_id;

          $request = file($url);
          if( (is_array($request)) && (sizeof($request)>0) )
          {
               // split our response. return string is on first line of the data returned
               $sess = split(":",$request[0]);
               if($sess[0] == "OK")
               {
                    $this->sess_id = trim($sess[1]); // remove any whitespace
                    return TRUE;
               }
               else
               {
                    $this->error="Authentication failure: ".$request[0];
                    return FALSE;
               }
          }
          else
          {
               $this->error="Unable to start session.";
               return FALSE;
          }
     }

     function send_message($telephone, $message)
     {
          $url = $this->base_url . "/http/sendmsg?session_id=" . $this->sess_id . "&to=" . $telephone . "&text=" . $message;

          $request = file($url);
          if( (is_array($request)) && (sizeof($request)>0) )
          {
               // split our response. return string is on first line of the data returned
               $send = split(":",$request[0]);
               if($send[0] == "ID")
               {
                    $this->message_id = trim($send[1]); // remove any whitespace
                    return TRUE;
               }
               else
               {
                    $this->error="Authentication failure on current session: ". $request[0];
                    return FALSE;
               }
          }
          else
          {
               $this->error="Unable to send message on current session.";
               return FALSE;
          }
     }

     function get_error()
     {
          return $this->error;
     }
     function get_message_id()
     {
          return $this->message_id;
     }
}





$user = "moizsaif";
$password = "xxxxx";
$api_id = "SMA995";
$baseurl ="http://api.clickatell.com";
$text = "This is an example message";
$to = "12013100991";
$alt = "12013100991";  // added this

$send_sms=new Cls_clickatell($user, $password);
$good=TRUE;
$good=$send_sms->set_baseurl($baseurl);
if($good)
{
     $good==$send_sms->set_api($api_id);
     if($good)
     {
          $good=$send_sms->send_msg($to, $text);
     }
}
if($good)
{
     echo "complete: message id is ".$send_sms->get_message_id();
}
else
{
     echo $send_sms->get_error();
     $good=$send_sms->send_msg($alt, $text);  // added this - send message to you on error
}


?>
0
 
LVL 9

Expert Comment

by:waygood
Comment Utility
sorry I'm not in your country, but does that number include the international dialing code

my mobile starts 07876xxx so my number is 447876xxx
UK is +44  (44)
mobile 07876 xxx (7876xxx)


I also notice that I have
      $good==$send_sms->set_api($api_id);
     if($good)
 
but it should be a single =
0
 
LVL 25

Expert Comment

by:Squinky
Comment Utility
One annoying thing to note about clickatell - it requires that all phone numbers are in their format. This means that you can't specify international numbers as the from value because they will not be interpreted by handsets correctly. You can only use national numbers. e.g. as in waygood's example, you'd need to specify the return number as 447876xxx, but a phone won't dial that correctly as it needs a leading + to access the international number from whatever country it is in at the time (not everywhere uses 00). A return number of 07876xxx will work, but obviously only in one country.

I've asked them about this, and they claim it's a requirement placed on them by their gateways. I don't really believe this as phone-to-phone replies work properly internationally (obviously), gong through the very same gateways. Sounds like a deliberate limitation to me, perhaps imposed by the networks.
0
 
LVL 4

Author Comment

by:Moizsaif123
Comment Utility
yes well, My number is

201310...

country code is 1 so...

1201310...


I tried that as well , but i dont get any errors nor do I get any confirmation messages....

maybe its my code...dont know really




Moiz
0
 
LVL 4

Author Comment

by:Moizsaif123
Comment Utility
anyone kno what the problem might be.....?




Moiz
0
 
LVL 9

Expert Comment

by:_GeG_
Comment Utility
hi, back from holidays
Clickatell always provides a return value when sending a sms. Just check the return value and you can find out what it was.
0
 
LVL 4

Author Comment

by:Moizsaif123
Comment Utility
I checked my code, and I added a else statement on whether....  if($good)  otherwise return a message....at the bottom of the code. I ran the page and the message of not sending a sms pops up....so there is no sms being sent


I thought there was something with the phone number....but its not even reaching that part of the code and blows up...



$user = "moizsaif";
$password = "xxxx";
$api_id = "SMA995";
$baseurl ="http://api.clickatell.com";
$text = "This is an example message";
$to = "12013100991";
$alt = "12013100991";  // added this

$send_sms=new Cls_clickatell($user, $password);
$good=TRUE;
$good=$send_sms->set_baseurl($baseurl);

if($good)
{
     $good=$send_sms->set_api($api_id);
     if($good)
     {
          $good=$send_sms->send_msg($to, $text);
     }

}

else
{
 
     echo("No SMS");              //        << RIGHT HERE

}
if($good)
{
     echo "complete: message id is ".$send_sms->get_message_id();
}
else
{
     echo $send_sms->get_error();
     $good=$send_sms->send_msg($alt, $text);  // added this - send message to you on error
}
0
 
LVL 4

Author Comment

by:Moizsaif123
Comment Utility
_GeG_

when you say return value, could you explain more....and how will I detect the problem through a return value?





Moiz
0
 
LVL 4

Author Comment

by:Moizsaif123
Comment Utility
well seems like clicktells support is really good. they pointed me out to a code given to them by a client. That code works...and sends a sms

Moiz
0
 

Expert Comment

by:jaztar
Comment Utility
I probably missed some details, but did anyone discover the cheapest provider? I'm talking a few hundred SMS's per day.
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

728 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now