Saturday, June 9, 2012

How to store image in MySql

There is two ways to achieve this  :
  • Storing the image as binary object
  • Storing the image as string
Screenshot


Method-1 : Storing image as binary object

       MySql supports BLOB data type.
       A blob (alternately known as a binary large object, basic large object, BLOB, or BLOb) is a collection of binary data stored as a single entity in a database management system. Blobs are typically images, audio or other multimedia objects, though sometimes binary executable code is stored as a blob. Database support for blobs is not universal. 

    Four types of BLOB supported by MySql:

  • TINYBLOB - 28 bytes
  • BLOB - 216 bytes
  • MEDIUMBLOB - 224 bytes
  • LONGBLOB - 232 bytes 
Create Table
CREATE TABLE `image` ( 
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(64) character SET utf8 NOT NULL,
  `type` varchar(20) NOT NULL,
  `data` mediumblob NOT NULL,
  PRIMARY KEY  (`id`) 
);
SET utf8 - allows you to store other than english
MEDIUMBLOB -  allows up to 16MB 
Storing image into database
<?php
//configuration details first
$db_host 'localhost';
$db_user 'root'$db_pwd 'root';
$database 'image';
$table 'image';
//connect to specific mysql
mysql_connect($db_host$db_user$db_pwd) or die(mysql_error());
//select a specific database
mysql_select_db($database) or die(mysql_error());
//insert into database
if(isset($_FILES['image']) && isset($_POST['imageTitle']))
{
    $type=mysql_real_escape_string($_FILES['image']['type']);
    $title=mysql_real_escape_string($_POST['imageTitle']);
    $data=mysql_real_escape_string(file_get_contents($_FILES['image']['tmp_name']));

    mysql_query("INSERT INTO {$table}
                    SET type='$type', title='$title',
                        data='$data'") or die(mysql_error());
}

//retrive from database
if(isset($_GET['id']))
{
    $results=mysql_query("SELECT type,data FROM {$table} WHERE id={$_GET['id']}") or die(mysql_error());
    if(@mysql_num_rows($results))
    {
        @list($type$data) = mysql_fetch_row($results);

        header("Content-Length: ".strlen($data));
        header("Content-type: {$type}");
        echo $data;
        mysql_close();
        exit;
    }
}

//display all the images
$results=mysql_query("SELECT * FROM {$table}") or die(mysql_error());

if(@mysql_num_rows($results))
{
    while(@list($id,$title,$type$data) = mysql_fetch_row($results))
    {
        echo "<a href=\"{$_SERVER['PHP_SELF']}?id=$id\"> <img src=\"http://{$_SERVER['HTTP_HOST']}{$_SERVER['PHP_SELF']}?id=$id\" width=\"150\" height=\"150\" title=\"{$title}\"/></a> &nbsp;";
    }
}
?>
 
<!--image uploader form-->
<div style="background: none repeat scroll 0pt 0pt rgb(245, 245, 245); border: 1px solid rgb(217, 217, 217); padding: 30px; font-size: 17px; width: 511px;">
<h2 style="text-align: center;">Image uploders</h2>
<form id="imageUploader" name="imageUploader" method="POST" action="<?php echo $_SERVER['PHP_SELF']; //refers current file ?>" enctype="multipart/form-data">
<p>ImageTitle: <input type="TEXT" style="font-size: 15px; border: 1px solid rgb(217, 217, 217); margin: 3px; padding: 3px; float: right;width:75%;" name="imageTitle"></p>
<p>Image: <input type="FILE" style="width:75%;font-size: 15px; border: 1px solid rgb(217, 217, 217); margin: 3px; padding: 3px; float: right;" name="image"></p>
<p style="text-align:right;"><input type="SUBMIT" value="SUBMIT" style="background-color: #4D90FE; color:#fff; border:1px solid #3079ED; font-weight:bold; text-align:center;"/></p>
</form>
</div>
Method-2 : Storing image as String

          For storing image as string , we can use our existing table with BLOB or we may create new table with MEDIUMTEXT instead of MEDIUMBLOB.Here i'm going to create a new table with MEDIUMTEXT.
CREATE TABLE `imageText` ( 
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(64) character SET utf8 NOT NULL,
  `type` varchar(20) ,
  `data` mediumtext NOT NULL,
  PRIMARY KEY  (`id`) 
);
Storing image into database
<?php

//configuration details first
$db_host 'localhost';
$db_user 'root'$db_pwd 'root';
$database 'image';
$table 'imagetext';

//connect to specific mysql
mysql_connect($db_host$db_user$db_pwd) or die(mysql_error());

//select a specific database
mysql_select_db($database) or die(mysql_error());

if(isset($_FILES['image']) && isset($_POST['imageTitle']))
{
    $type=mysql_real_escape_string($_FILES['image']['type']);
    $title=mysql_real_escape_string($_POST['imageTitle']);
    
    //read image file
    $handle=fopen("{$_FILES['image']['tmp_name']}""r");
    $img=fread($handlefilesize("{$_FILES['image']['tmp_name']}"));
    fclose($handle);

    $data=mysql_real_escape_string(base64_encode($img));

    mysql_query("INSERT INTO {$table}
                    SET type='$type', title='$title',
                        data='$data'") or die("INSERT ERROR : ".mysql_error());
}

//get image for display
if(isset($_GET['id']))
{
    $results=mysql_query("SELECT type,data FROM {$table} WHERE id={$_GET['id']}") or die(mysql_error());

    if(@mysql_num_rows($results))
    {
        @list($type$data) = mysql_fetch_row($results);

        header('Content-Length: '.strlen($data));
        header("Content-type: {$type}");
        echo base64_decode($data);
        mysql_close();
        exit;
    }
}

//display all the images
$results=mysql_query("SELECT * FROM {$table}") or die(mysql_error());
if(@mysql_num_rows($results))
{
    while(@list($id,$title,$type$data) = mysql_fetch_row($results))
    {
        echo "<a href=\"{$_SERVER['PHP_SELF']}?id=$id\"> <img src=\"http://{$_SERVER['HTTP_HOST']}{$_SERVER['PHP_SELF']}?id=$id\" width=\"150\" height=\"150\" alt=\"{$title}\"/></a> &nbsp;";;
    }
}
?>
<!--image uploder form-->
<div style="background: none repeat scroll 0pt 0pt rgb(245, 245, 245); border: 1px solid rgb(217, 217, 217); padding: 30px; font-size: 17px; width: 511px;">
<h2 style="text-align: center;">Image uploders</h2>
<form id="imageUploader" name="imageUploader" method="POST" action="<?php echo $_SERVER['PHP_SELF']; //refers current file ?>" enctype="multipart/form-data">
<p>ImageTitle: <input type="TEXT" style="font-size: 15px; border: 1px solid rgb(217, 217, 217); margin: 3px; padding: 3px; float: right;width:75%;" name="imageTitle"></p>
<p>Image: <input type="FILE" style="width:75%;font-size: 15px; border: 1px solid rgb(217, 217, 217); margin: 3px; padding: 3px; float: right;" name="image"></p>
<p style="text-align:right;"><input type="SUBMIT" value="SUBMIT" style="background-color: #4D90FE; color:#fff; border:1px solid #3079ED; font-weight:bold; text-align:center;"/></p>
</form>
</div>
base64_encode - Encodes data with MIME base64
base64_decode - Decodes data encoded with MIME base64

Disadvantage of BLOB is that it's not available on all database. 
Disadvantage  in storing as string is that it occupy more space.  Since Base64-encoded data takes about 33% more space than the original data.

Wednesday, June 6, 2012

Display a random "thirukkural" on your blog/website

To display a random thirukkural, copy and paste the HTML code below into your web page. :

<iframe src="http://justtrythis.co.in/demos/thirukkural/index.php" 
style="width: 100%; height: 120px; border: medium none;"></iframe>

Note:
  • You can see demo on top of this blog.
  • You can  customize width and height of iframe.If you want more customization inform me.
  • To create thirukkural database visit how-to-store-tamil-in-mysql

Download thirukkural : 
           download thirukkural.csv 
           download thirukkural.sql 
           download thirukkural.xml

How to store தமிழ்(Tamil) in MySql


      MySQL has Multi-Language support, Only think we have to do is create a database with charset UTF-8.

       UTF-8 (UCS Transformation Format — 8-bit) is a variable-width encoding that can represent every character in the Unicode character set.UTF-8 has become the dominant character encoding for the World-Wide Web, accounting for more than half of all Web pages. The Internet Engineering Task Force (IETF) requires all Internet protocols to identify the encoding used for character data, and the supported character encodings must include UTF-8.The Internet Mail Consortium (IMC) recommends that all e-mail programs be able to display and create mail using UTF-8. UTF-8 is also increasingly being used as the default character encoding in operating systems, programming languages, APIs, and software applications.


CREATE DATABASE WITH CHARSET UTF-8 :

CREATE TABLE thirukkural
(
 ID INTEGER NOT NULL AUTO_INCREMENT,
 ChapterName VARCHAR(50) NOT NULL DEFAULT '',
 SectionName VARCHAR(50) NOT NULL DEFAULT '',
 Verse TEXT,
 Translation TEXT,
 Explanation TEXT,
 PRIMARY KEY(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

On client side (browser) must add following code in header section : 

<META HTTP-EQUIV="Content-Type" CONTENT="text/html"; charset="utf-8" />

Note : 
            If the result shows like the ???? then prpoerly in your system (windows XP) need to install the extral language support tool by enabling the following options,

                   Control Panel -> Regional and Language Option -> Languages -> Install files for complex script and right-to-left languages (including Thai).

Sunday, June 3, 2012

combine form validation and way2sms class

        In this post I'm going to combine way2sms API with simple form validation. so it makes easy to send sms with nice look. 

Screenshots
sendSms.php
<?php

    session_start();

    if(isset($_POST['userName']) && isset($_POST['passWord']))

    {

        require_once('classSms.php');

        $_SESSION['userName']=$_POST['userName'];

        $_SESSION['passWord']=$_POST['passWord'];

        $smsObj=new way2sms($_POST['userName'],$_POST['passWord']);

        $result=$smsObj->sendSMSToMany($_POST['mobileNumber'],$_POST['msg']);

    }
?>
<html>

<head>

    <title>Consultation Form</title>

    <link rel="stylesheet" type="text/css" href="style.css"/>

    <link href="images/c12.ico" rel="shortcut icon" type="image/x-icon" />

    <script type="text/javascript" language="javascript">

    var regx_number=/^[0-9]{10}$/;

        window.onload = function()

        {

         //onload delegating event

            var inputTag=document.getElementsByTagName("input"),

                form=document.getElementById("getDetails");

            form.onsubmit=validate;

            document.getElementById("msg").onfocus=clearInfo;

            document.getElementById("msg").onblur=showInfo;

            for(var i=0;i<inputTag.length;i++)

            {

                inputTag[i].onfocus=clearInfo;

                inputTag[i].onblur=showInfo;

            }

        

        }

        function showInfo()

        {

            var info=document.getElementById("info");

            info.innerHTML="";

            switch(this.name)

            {

                case "userName":

                    if(!validNumber(this.value)) this.value="Your Mobile Number";

                    break;

                case "passWord":

                    if((this.value)=="") this.value="your password";

                    break;

                case "mobileNumber":

                    if((this.value)=="") this.value="Mobile Numbers";

                    break;

                case "msg":

                    if(this.value =="" ) this.value="Content Here";

                    break;

                default:

                    break;

            }

        }

        function clearInfo()

        {

            var info=document.getElementById("info");

            switch(this.value)

            {

                case "Your Mobile Number":

                    this.value="";

                    info.innerHTML="Enter your way2sms user name(mobile number).";

                    break;

                case "your password":

                    info.innerHTML="Enter your passWord.";

                    this.value="";

                    break;

                case "Mobile Numbers":

                    info.innerHTML="Enter recipient mobile numbers.<br>It should be seperated by comma(,).";

                    this.value="";

                    break;

                case "Content Here":

                    info.innerHTML="Enter message to send.";

                    this.value="";

                    break;

                default:

                    break;

            }

        }

        function validate()

        { 

            var uName=document.getElementById("userName").value,

                pass=document.getElementById("passWord").value,

                mnumber=document.getElementById("mobileNumber").value,

                msg=document.getElementById("msg").value;

            if(validNumber(uName) && (pass != "") && (mnumber != "") )

                return true;

            return false;

        }

        function validNumber(number)

        {

            return regx_number.test(number);

        }

    </script>

</head>

<body>

    <div id="container">

    <div style="margin-left: 80px;"><img alt="" src="images/fill_your_details.png"></div>

        <div id="info"><?php echo @implode("<br/>",$result); ?></div>

        <form name="getDetails" id="getDetails" method="POST" action="<?php echo $_SERVER['PHP_SELF'];?>">

            <input type="text" name="userName" id="userName" value="<?php if(isset($_SESSION['userName'])) echo $_SESSION['userName']; else { echo "Your Mobile Number"; } ?>"/>

            <input type="password" name="passWord" id="passWord" value="<?php if(isset($_SESSION['passWord'])) echo $_SESSION['passWord']; else { echo "your password"; } ?>"/>

            <input type="text" name="mobileNumber" id="mobileNumber" value="Mobile Numbers"/>

            <textarea name="msg" id="msg">Content Here</textarea>

            <button>send via way2sms</button>

        </form>

    </div>

</body>

</html>
click here for demo.
click here for classSms.php.
click here for simple effective form validation. 
 

Simple javascript regex tester

RegEx Tester

Regexp:

Subject string:

Replacement text:

Result:

source : http://www.regular-expressions.info/javascriptexample.html
For Java RegEx Tester : http://www.regexplanet.com/advanced/java/index.html


Regex syntax

flags
  • g - global match
  • i - ignore case
  • m - match over multiple lines
Escaping
  • \ - special characters to literal and literal characters to special
Quantifiers
  • ? - matches zero or one times
  • * - matches zero or more times
  • + - matches one or more times
  • {n} - matches n times
  • {n, m} - matches at least n times, but not more than m times
Anchors
  • ^ - matches at the start of the line
  • $ - matches at the end of the line
  • \b - matches at the beginning or the end of a word
delimiter
  • (?:x) - matches x not remember the match
  • x(?=y) - matches x only if x is followed by y
  • x(?!y) - matches x only if x is not followed by y
Character Escapes
  • \s - matches whitespace
  • \S - matches anything but a whitespace
  • \f - matches a form-feed
  • \n - matches a linefeed
  • \r - matches a carriage return
  • \t - matches a horizontal tab
  • \v - matches vertical tab
  • \d - matches any digit
  • \D - matches anything except digit
  • \w - matches any alphanumeric character including the underscore. Equivalent to [A-Za-z0-9_]
  • \W - matches any non-word character. Equivalent to [^A-Za-z0-9_]
Others
  • . - matches any character except a newline

Some predefined RegEx :

Positive Integers --- ^\d+$
Negative Integers --- ^-\d+$
Integer --- ^-{0,1}\d+$
Positive Number --- ^\d*\.{0,1}\d+$
Negative Number --- ^-\d*\.{0,1}\d+$
Positive Number or Negative Number - ^-{0,1}\d*\.{0,1}\d+$
Phone number --- ^\+?[\d\s]{3,}$
Phone with code --- ^\+?[\d\s]+\(?[\d\s]{10,}$
Year 1900-2099 --- ^(19|20)[\d]{2,2}$
Date (dd mm yyyy, d/m/yyyy, etc.) --- ^([1-9]|0[1-9]|[12][0-9]|3[01])\D([1-9]|0[1-9]|1[012])\D(19[0-9][0-9]|20[0-9][0-9])$
IP v4 --- ^(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]){3}$

Personal Name --- ^[\w\.\']{2,}([\s][\w\.\']{2,})+$ Username --- ^[\w\d\_\.]{4,}$ Password at least 6 symbols --- ^.{6,}$ Password or empty input --- ^.{6,}$|^$ email --- ^[\_]*([a-z0-9]+(\.|\_*)?)+@([a-z][a-z0-9\-]+(\.|\-*\.))+[a-z]{2,6}$ domain --- ^([a-z][a-z0-9\-]+(\.|\-*\.))+[a-z]{2,6}$
Match no input --- ^$ Match blank input --- ^[\s\t]*$ Match New line --- [\r\n]|$

Simple and effective form validation using Javascript

The following code uses:
FormValidation.html
<html>
<head>
<title>Consultation Form</title>
<script type=“text/javascript” language=“javascript”>
var regx_name=/^[A-Za-z]{2,30}$/,
 regx_number=/^[0-9]{10}$/,
 regx_mail=/^[a-zA-Z]+(([\'\,\.\- ][a-zA-Z ])?[a-zA-Z]*)*\s+&lt;(\w[-._\w]*\w@\w[-._\w]*\w\.\w{2,3})&gt;$|^(\w[-._\w]*\w@\w[-._\w]*\w\.\w{2,3})$/;
 window.onload = function()
 {
 //onload delegating event
  var inputTag=document.getElementsByTagName(“input”),
   form=document.getElementById(“getDetails”);
  form.onsubmit=validate;
  for(var i=0;i<inputTag.length;i++)
  {
   inputTag[i].onfocus=clearInfo;
   inputTag[i].onblur=showInfo;
  }
 }
 function showInfo()
 {
  var info=document.getElementById(“info”);
  info.innerHTML="";
  switch(this.name)
  {
   case “firstName”:
    if(!validName(this.value)) this.value=“First Name”;
    break;
   case “lastName”:
    if(!validName(this.value)) this.value=“Last Name”;
    break;
   case “countryCode”:
    break;
   case “mobileNumber”:
    if(!validNumber(this.value)) this.value=“Mobile Number”;
    break;
   case “mailId”:
    if(!validMail(this.value)) this.value=“Mail-ID”;
    break;
   default:
    break;
  }
 }
 function clearInfo()
 {
  var info=document.getElementById(“info”);
  switch(this.value)
  {
   case “First Name”:
   this.value="";
   info.innerHTML=“Enter your firstname.Only alphabets allowed.";
    break;
   case “Last Name”:
    info.innerHTML=“Enter your lastname.Only alphabets allowed.";
    this.value="";
    break;
   case “Mobile Number”:
    info.innerHTML=“Enter your mobile number.It should be 10-digits.";
    this.value="";
    break;
   case “Mail-ID”:
    info.innerHTML=“Enter a valid mail-id.";
    this.value="";
    break;
   default:
    break;
  }
 }

 function validate()
 { 
  var fname=document.getElementById(“firstName”).value,
   lname=document.getElementById(“lastName”).value,
   mnumber=document.getElementById(“mobileNumber”).value,
   mailID=document.getElementById(“mailId”).value;
  if(validName(fname) && validName(lname) && validNumber(mnumber) && validMail(mailID))
   return true;
  return false;
 }
 function validName(name)
 {
  return regx_name.test(name);
 }
 function validNumber(number)
 {
  return regx_number.test(number);
 }
 function validMail(mailID)
 {
  return regx_mail.test(mailID);
 }
</script>
</head>
<body>
<div id=“container”>
 <div id=“info”></div>
 <form name=“getDetails” id=“getDetails” method=“GET” action=“action_here”>
  <input type=“text” name=“firstName” id=“firstName” value=“First Name”/>
  <input type=“text” name=“lastName” id=“lastName” value=“Last Name”/>
  <input type=“text” name=“countryCode” id=“countryCode” disabled=“disabled” value="+91”/>
  <input type=“text” name=“mobileNumber” id=“mobileNumber” value=“Mobile Number”/>
  <input type=“text” name=“mailId” id=“mailId” value=“Mail-ID”/>
  <button>Get my FREE consultation!</button>
 </form>
</div>
</body>
</html>
Screen shot:




Click here for demo.
you can also download source.








 regex pattern   /^[A-Za-z]{2,30}$/ find valid name.
     ^              indicates begining of string
     [A-Za-z]  it matches only albhabets,A-Z indicates match all capital letters,a-z indicates match all small  letters
     {2,30}     indicates minimum string length 2 , maximum string length 30
     $              indicates end of string

 regex pattern /^[0-9]{10}$/ find valid mobile number.
      ^             indicates begining of string
     [0-9]        it matches only numberics,0-9 indicates match all numbers
     {10}        indicates string length should exactly 10
     $              indicates end of string

 regex pattern /^[a-zA-Z]+(([\'\,\.\- ][a-zA-Z ])?[a-zA-Z]*)*\s+<(\w[-._\w]*\w@\w[-._\w]*\w\.\w{2,3})>$|^(\w[-._\w]*\w@\w[-._\w]*\w\.\w{2,3})$/ find valid mail address.

  Anonymous function called window.onload=function(){}-it delegate clearInfo(),showInfo() to all input tag's onFocus,onblur respectively.
  "form.onsubmit=validate;" - it binds validate() with form's onsubmit event.

Friday, June 1, 2012

Way2Sms PHP CURL API [OUTDATED]

The following class help you to send sms via way2sms gateway.

Features of this class:
  • Can send sms to mutiple contacts at one shot , each contact should be seprated by comma (,)
  • Can send long sms (it automatically split text by 160 char/sms)
way2sms.php


<?php/*way2sms
 *used to send sms using web service
 *@ $uid       String:  username to authenticate the way2sms website
 *@ $pwd       String:  password for way2sms website
 *@ $phone     String:  phone numbers of recipients
 *@ $msg       String:  the message to be send
 */class way2sms{
    var $uid,$pwd,$phone,$msg;
    /*
    *@ constructor of way2sms class
    *
    *@ $id     String :  username to authenticate the way2sms website
    *@ $pass   String :  password for way2sms website
    *
    */
    function way2sms($id,$pass)
    {
        $this->uid=urlencode($id);
        $this->pwd=urlencode($pass);
    }
    /*
    *sendSMSToMany
    *@description : to send the sms
    *
    *@ $phone    String :  phone numbers of recipients
    *@ $msg      String :  the message to be send
    *
    *@return     array :  error message or success message
    */
    
    function sendSMS($phone$msg)
    {
        $curl curl_init();
        $timeout 30;
        $result = array();
        $autobalancer=rand(1,8);

        curl_setopt ($curlCURLOPT_URL"http://site".$autobalancer.".way2sms.com/Login1.action");
        curl_setopt ($curlCURLOPT_POST1);
        curl_setopt ($curlCURLOPT_POSTFIELDS"username=" $this->uid "&password=" $this->pwd);
        curl_setopt ($curlCURLOPT_COOKIESESSION1);
        curl_setopt ($curlCURLOPT_COOKIEFILE"cookie_way2sms");
        curl_setopt ($curlCURLOPT_FOLLOWLOCATION1);
        curl_setopt ($curlCURLOPT_MAXREDIRS20);
        curl_setopt ($curlCURLOPT_RETURNTRANSFER1);
        curl_setopt ($curlCURLOPT_USERAGENT"Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5");
        curl_setopt ($curlCURLOPT_CONNECTTIMEOUT$timeout);
        curl_setopt ($curlCURLOPT_REFERER"http://site".$autobalancer.".way2sms.com/");
        $text curl_exec($curl);
        
        preg_match_all('/<input[\s]*type="hidden"[\s]*name="Token"[\s]*id="Token"[\s]*value="?([^>]*)?"/si'$text$match);
        $token $match[1][0]; 

        // Check for proper login
        $pos stripos(curl_getinfo($curlCURLINFO_EFFECTIVE_URL), "main.action");

        if ($pos === "FALSE" || $pos == || $pos == "") return array("Login Faild");

        if (trim($msg) == "" || strlen($msg) == 0) return array("Invalid message");
        
        $msgs $this->split_for_sms($msg);
        
        //$pharr = explode(",",$phone);
        $p=$phone;
        $refurl curl_getinfo($curlCURLINFO_EFFECTIVE_URL);
        $refurl_instantsms=0;
        // foreach ($pharr as $p)
        // {
            if (strlen($p) != 10 || !is_numeric($p) || strpos($p".") != false)
            {
                array_push($result,"Invalid number : " $p ". ");
                //continue;
            }
            foreach($msgs as $msg)
            {
                curl_setopt ($curlCURLOPT_REFERER$refurl);
                curl_setopt ($curlCURLOPT_URL"http://site".$autobalancer.".way2sms.com/jsp/SingleSMS.jsp?Token=".$token);
                $text curl_exec($curl);
                
                preg_match_all('/rqMob=["\']([\d\w]+)["\'];/si'$text$match);
                $rqMob=$match[1][0];
                preg_match_all('/rqTok=["\']([\d\w]+)["\'];/si'$text$match);
                $rqTok=$match[1][0];
                //preg_match_all('/tkn=["\']?([\d\w\W]+)?["\'];/si', $text, $match);
                $Token=$token;
                /* preg_match_all('/<input[\s]*type="hidden"[\s]*name="cgnr"[\s]*id="cgnr"[\s]*value="?([^>]*)?"/si', $text, $match);
                $cgnr=$match[1][0];
                preg_match_all('/<input[\s]*type="hidden"[\s]*name="wasup"[\s]*id="wasup"[\s]*value="?([^>]*)?"/si', $text, $match); */
                preg_match_all('/[\s]*name=["\']wasup["\'][\s]*id=["\']wasup["\'][\s]*value=["\']?([^>]*)?["\']/si'$text$match);
                if(!isset($match[1][0]))
                    preg_match_all('/name=["\']wasup["\'][\s]*id=["\']wasup["\'][\s]*><option value=["\']?([^>]*)?["\']/si'$text$match);
                if(!isset($match[1][0]))
                    preg_match_all('/[\s]*name=["\']wasup["\'][\s]*id=["\']wasup["\'][\s]*>?([^>]*)?</si'$text$match);
                $wasup=$match[1][0];
                
                preg_match_all('/[\s]*name=["\']nrc["\'][\s]*id=["\']nrc["\'][\s]*value=["\']?([^>]*)?["\']/si'$text$match);
                if(!isset($match[1][0]))
                    preg_match_all('/name=["\']nrc["\'][\s]*id=["\']nrc["\'][\s]*><option value=["\']?([^>]*)?["\']/si'$text$match);
                if(!isset($match[1][0]))
                    preg_match_all('/[\s]*name=["\']nrc["\'][\s]*id=["\']nrc["\'][\s]*>?([^>]*)?</si'$text$match);
                $nrc=$match[1][0];
                preg_match_all('/[\s]*name=["\']HiddenAction["\'][\s]*value=["\']?([^>]*)?["\']/si'$text$match);
                if(!isset($match[1][0]))
                    preg_match_all('/name=["\']HiddenAction["\'].*><option value=["\']?([^>]*)?["\']/si'$text$match);
                $HiddenAction=$match[1][0];
                preg_match_all('/[\s]*name=["\']hud_pani["\'][\s]*id=["\']hud_pani["\'][\s]*value=["\']?([^>]*)?["\']/si'$text$match);
                if(!isset($match[1][0]))
                    preg_match_all('/name=["\']hud_pani["\'][\s]*id=["\']hud_pani["\'][\s]*><option value=["\']?([^>]*)?["\']/si'$text$match);
                if(!isset($match[1][0]))
                    preg_match_all('/[\s]*name=["\']hud_pani["\'].*id=["\']hud_pani["\'][\s]*>?([^>]*)?</si'$text$match);
                $hud_pani=$match[1][0];
                
                preg_match_all('/[\s]*name=["\']catnamedis["\'][\s]*id=["\']catnamedis["\'][\s]*value=["\']?([^>]*)?["\']/si'$text$match);
                $catnamedis $match[1][0];
                preg_match_all('/[\s]*id=["\']diffNo["\'][\s]*name=["\']diffNo["\'][\s]*value=["\']?([^>]*)?["\']/si'$text$match);
                $diffNo $match[1][0];
                
                /* preg_match_all('/<select[\s]*style="display: none;"[\s]*name="action"[\s]*id="action%>"[\s]*><option[\s]*value="?([^>]*)?"/si', $text, $match);
                $action = $match[1][0]; // get custid from the form fro the Action field in the post form                
                preg_match_all('/<textarea[\s]*style="display: none;"[\s]*name="Token"[\s]*id="Token">?([^>]*)?<\/textarea>/si', $text, $match);
                $Token = $match[1][0]; */
                
                $p urlencode($p);
                
                if($refurl_instantsms == 0)
                {
                    $refurl_instantsms=curl_getinfo($curlCURLINFO_EFFECTIVE_URL);
                }
            
            // Send SMS
            
                curl_setopt ($curlCURLOPT_URL"http://site".$autobalancer.".way2sms.com/jsp/stp2p.action");
                curl_setopt ($curlCURLOPT_REFERER$refurl_instantsms);
                curl_setopt ($curlCURLOPT_POST1);
                
                curl_setopt ($curlCURLOPT_POSTFIELDS"nrc=$nrc&wasup=$wasup&HiddenAction=$HiddenAction&hud_pani=$hud_pani&catnamedis=$catnamedis&$rqTok=$Token&$rqMob=$p&textArea=$msg&diffNo=$diffNo");
                curl_exec($curl);
                //var_dump(curl_getinfo($curl));
                @$sendError .= curl_error($curl);
            }
            array_push($result,"Message Sucessfully send to : " $p ". ");
        //}
        
        // Logout
        curl_setopt ($curlCURLOPT_URL"http://site".$autobalancer.".way2sms.com/jsp/logout.jsp");
        curl_setopt ($curlCURLOPT_REFERER$refurl);
        $text curl_exec($curl);    
        
        curl_close($curl);
        if (!empty($sendError)){
            return array($sendError);
        }
        return $result;
    }
    function split_for_sms($msg)
    {
        $length=strlen($msg);
        if($length <= 160)
        {
            return array(urlencode($msg));
        }
        else
        {
            preg_match_all("~.{0,153}(\s|$)~",$msg,$matches);
            $matches=array_filter($matches[0]);
            foreach($matches as $key=>$match)
                $matches[$key]=urlencode("PART-".($key+1).":".$matches[$key]);
            return $matches;
        }
    }
}
?>


Example usage of this class:
$obj=new way2sms('myusername','mypassword');
$result=$obj->sendSMS('mobile_number','message');
echo implode('<br >',$result);
click here for demo.