Send sms through d-link GSM modem in PHP - php

I am trying to send sms via D-Link GSM modem. I am new on this. My code shows Unable to setup COM port I did not add any additional file, library or any modification in php.ini file in xampp. just installed software provided by modem. My operating system is windows 10. I am mentioning my code, though I got it from internet.
$mobile_number=$_POST['mobile_number'];
$messages=$_POST['messages'];
$gsm_send_sms = new gsm_send_sms();
$gsm_send_sms->debug = false;
$gsm_send_sms->port = 'COM3';
$gsm_send_sms->baud = 115200;
$gsm_send_sms->init();
$status = $gsm_send_sms->send($mobile_number,$messages);
if ($status) {
echo "<body bgcolor='lightgreen'>";
echo "<br><br><br>";
echo "<h3 align='center'>Message Successfully Send... </h3>\n";
echo "</body>";
} else {
echo "<body bgcolor='lightgreen'>";
echo "<br><br><br>";
echo "<h3 align='center'>Message not sent Successfully... </h3>\n";
echo "</body>";
}
$gsm_send_sms->close();
//Send SMS via serial SMS modem
class gsm_send_sms {
public $port = 'COM3';
public $baud = 115200;
public $debug = false;
private $fp;
private $buffer;
//Setup COM port
public function init() {
$this->debugmsg("Setting up port: \"{$this->port} # \"{$this->baud}\" baud");
exec("MODE {$this->port}: BAUD={$this->baud} PARITY=N DATA=8 STOP=1", $output, $retval);
if ($retval != 0) {
throw new Exception('Unable to setup COM port, check it is correct');
}
$this->debugmsg(implode("\n", $output));
$this->debugmsg("Opening port");
//Open COM port
$this->fp = fopen($this->port . ':', 'r+');
//Check port opened
if (!$this->fp) {
throw new Exception("Unable to open port \"{$this->port}\"");
}
$this->debugmsg("Port opened");
$this->debugmsg("Checking for response from modem");
//Check modem connected
fputs($this->fp, "AT\r");
//Wait for ok
$status = $this->wait_reply("OK\r\n", 5);
if (!$status) {
throw new Exception('Did not receive responce from modem');
}
$this->debugmsg('Modem connected');
//Set modem to SMS text mode
$this->debugmsg('Setting text mode');
fputs($this->fp, "AT+CMGF=1\r");
$status = $this->wait_reply("OK\r\n", 5);
if (!$status) {
throw new Exception('Unable to set text mode');
}
$this->debugmsg('Text mode set');
}
//Wait for reply from modem
private function wait_reply($expected_result, $timeout) {
$this->debugmsg("Waiting {$timeout} seconds for expected result");
//Clear buffer
$this->buffer = '';
//Set timeout
$timeoutat = time() + $timeout;
//Loop until timeout reached (or expected result found)
do {
$this->debugmsg('Now: ' . time() . ", Timeout at: {$timeoutat}");
$buffer = fread($this->fp, 1024);
$this->buffer .= $buffer;
usleep(200000);//0.2 sec
$this->debugmsg("Received: {$buffer}");
//Check if received expected responce
if (preg_match('/'.preg_quote($expected_result, '/').'$/', $this->buffer)) {
$this->debugmsg('Found match');
return true;
//break;
} else if (preg_match('/\+CMS ERROR\:\ \d{1,3}\r\n$/', $this->buffer)) {
return false;
}
} while ($timeoutat > time());
$this->debugmsg('Timed out');
return false;
}
//Print debug messages
private function debugmsg($message) {
if ($this->debug == true) {
$message = preg_replace("%[^\040-\176\n\t]%", '', $message);
echo $message . "\n";
}
}
//Close port
public function close() {
$this->debugmsg('Closing port');
fclose($this->fp);
}
//Send message
public function send($tel, $message) {
//Filter tel
$tel = preg_replace("%[^0-9\+]%", '', $tel);
//Filter message text
$message = preg_replace("%[^\040-\176\r\n\t]%", '', $message);
$this->debugmsg("Sending message \"{$message}\" to \"{$tel}\"");
//Start sending of message
fputs($this->fp, "AT+CMGS=\"{$tel}\"\r");
//Wait for confirmation
$status = $this->wait_reply("\r\n> ", 5);
if (!$status) {
//throw new Exception('Did not receive confirmation from modem');
$this->debugmsg('Did not receive confirmation from modem');
return false;
}
//Send message text
fputs($this->fp, $message);
//Send message finished indicator
fputs($this->fp, chr(26));
//Wait for confirmation
$status = $this->wait_reply("OK\r\n", 180);
if (!$status) {
//throw new Exception('Did not receive confirmation of message sent');
$this->debugmsg('Did not receive confirmation of message sent');
return false;
}
$this->debugmsg("Message Send Successfully...");
return true;
}
}

It's Look like You are using a D-Link USB GSM Modem.
in this case Modem COM port doesn't show in Device Manager Automatically.
First you must start D-Link Connection Manager SoftWare and then you can find your modem under MODEM category in Device Manager.
R-Click on it and Open Properties window.
You can find COM port on it!

Related

connect multiple device android to the same php socket

My problem is when I try to connect the Android application with Java socket identified by an IP and a port 4444 with a PHP service, identified by the same port, and keep this connection open to accept multiple connections via the Android app.
So with a second Android device if we connect to PHP we will have the same communication channel as the one device and we cannot identify which device is connected via PHP.
Is there a possibility to differentiate these two connections via the PHP file or instantiate two different PHP service for the two devices.
The Android code:
public String connect() {
Socket socket = null;
try {
socket = new Socket();
// This limits the time allowed to establish a connection in the case
// that the connection is refused or server doesn't exist.
socket.connect(new InetSocketAddress(dstAddress, dstPort), context.getResources().getInteger(R.integer.time_out));
// This stops the request from dragging on after connection succeeds.
socket.setSoTimeout(context.getResources().getInteger(R.integer.time_out));
// socket = new Socket();
// socket.connect(new InetSocketAddress(dstAddress, dstPort), 2000);
if (!socket.isConnected())
throw new SocketException("Could not connect to Socket");
DataInputStream DIStream = new DataInputStream(socket.getInputStream());
DataOutputStream DOStream = new DataOutputStream(socket.getOutputStream());
DOStream.write(numCmd.getBytes(), 0, numCmd.getBytes().length);
DOStream.flush();
response = DIStream.readLine();
DOStream.close();
DIStream.close();
socket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "{\"Error_no\":5000}";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "{\"Error_no\":5000}";
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "{\"Error_no\":5000}";
} finally {
if (socket != null) {
try {
socket.close();
if(response == null){
response = "{\"Error_no\":5000}";
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "{\"Error_no\":5000}";
}
}
}
// Log.i("resp",response);
return response;
}
The PHP code:
<?php
echo "service php started \n";
$version = '2.2.0';
$address = '10.164.2.1';
$port = 4444;
$timeout= 2;
$cmd = explode("*", str_replace(array("/"), "*",
str_replace(" ","",shell_exec("netstat -tulpn | grep :".$port))));
echo "pid ".$cmd[1];
$cmd[1] = substr_replace($cmd[1], '', 0, 6);
echo "pid ".$cmd[1];
exec("kill -9 $cmd[1]");
sleep(1);
$socketPath = 'unix:///home/root/sockets/local_iapp_socket';
// Create WebSocket.
$server = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($server, SOL_SOCKET, SO_REUSEADDR, 1);
if(socket_bind($server, $address, $port)){
echo "Connected with tcp socket \n";
}else{
echo "connection with tc socket error \n";
}
socket_listen($server);
echo "server is listning \n";
$socket_fd = connect_socket_local();
echo "connected to unix socket \n";
while ($client = socket_accept($server)) {
$num_cmd = socket_read($client, 5000);
echo "Client Message : ".$num_cmd ."\n";
if($socket_fd != false){
$id=24;
$len= strlen($num_cmd);
$fwrite1 = fwrite($socket_fd, pack("L", $len),4);
if($fwrite1 === false){
$content = '{"Error_no":5000}';
echo "fwrite1 a échoué : raison : " . socket_strerror(socket_last_error()) . "\n";
exit;
}
$fwrite2 = fwrite($socket_fd,pack("L", $id),4);
if($fwrite2 === false){
$content = '{"Error_no":5000}';
echo "fwrite2 a échoué : raison : " . socket_strerror(socket_last_error()) . "\n";
exit;
}
$fwrite3 = fwrite($socket_fd,$num_cmd,strlen($num_cmd));
if($fwrite3 === false){
$content = '{"Error_no":5000}';
echo "fwrite3 a échoué : raison : " . socket_strerror(socket_last_error()) . "\n";
exit;
}
$content = fread($socket_fd, 5000) ;
if( $content == null){
echo "impossible d'atteindre la socket locale" . socket_strerror(socket_last_error()) . "\n";
$content = '{"Error_no":5000}';
}
}else{
$content = '{"Error_no":5000}';
echo "problème de connexion" . socket_strerror(socket_last_error()) . "\n";
}
$json_resp = $content;
echo "json_resp" . $json_resp."\n\r";
socket_write($client, $json_resp,strlen($json_resp));
socket_close($client);
}
socket_close($server);
function connect_socket_local()
{
global $socketPath , $timeout;
if (($socket_fd= stream_socket_client($socketPath , $errorno, $errorstr, $timeout)) === false) {
echo "stream_socket_client a échoué : raison : " . socket_strerror(socket_last_error()) . "\n";
}
return $socket_fd;
}
?>
You can run a separate server process for each client. Each server process needs to have an unique IP address or TCP port. Each client needs to be configured to connect to the correct server address and port. This is difficult to manage and doesn't scale.
At the server side, you can get the peer address, that is the IP address and port of the client. In PHP, you can use socket_getpeername() for this. However, depending on the network setup, this might not be the IP address of the client itself. It can be the IP address of an intermediate gateway or other network device. Also, the client IP address might be dynamic.
The best solution is to send some identification from the client to the server when the clients connects to the server. This can be a name or some other unique identification. You have to change the protocol between the client and server to support this. The client needs to know when and how to send the identification. The server needs to know when and how to receive the identification.

Unable to setup COM port, check it is correct

I am sending sms using Nokia usb Device and PHP script but getting error
many answer are there on stack but no answer has solution of this problem
Fatal error: Uncaught Exception: Unable to setup COM port, check it is correct in C:\xampp\htdocs\sms-prac\send-sms.php:103
Stack trace:
#0 C:\xampp\htdocs\sms-prac\send-sms.php(36): gsm_send_sms->init()
#1 {main}
thrown in C:\xampp\htdocs\sms-prac\send-sms.php on line 103
My gsm_send_sms Class Code
//Send SMS via serial SMS modem
class gsm_send_sms {
public $port = 'COM1';
public $baud = 115200;
public $debug = false;
private $fp;
private $buffer;
//Setup COM port
public function init() {
$this->debugmsg("Setting up port: \"{$this->port} # \"{$this->baud}\" baud");
exec("MODE {$this->port}: BAUD={$this->baud} PARITY=N DATA=8 STOP=1", $output, $retval);
if ($retval != 0) {
throw new Exception('Unable to setup COM port, check it is correct');
}
$this->debugmsg(implode("\n", $output));
$this->debugmsg("Opening port");
//Open COM port
$this->fp = fopen($this->port . ':', 'r+');
//Check port opened
if (!$this->fp) {
throw new Exception("Unable to open port \"{$this->port}\"");
}
$this->debugmsg("Port opened");
$this->debugmsg("Checking for responce from modem");
//Check modem connected
fputs($this->fp, "AT\r");
//Wait for ok
$status = $this->wait_reply("OK\r\n", 5);
if (!$status) {
throw new Exception('Did not receive responce from modem');
}
$this->debugmsg('Modem connected');
//Set modem to SMS text mode
$this->debugmsg('Setting text mode');
fputs($this->fp, "AT+CMGF=1\r");
$status = $this->wait_reply("OK\r\n", 5);
if (!$status) {
throw new Exception('Unable to set text mode');
}
$this->debugmsg('Text mode set');
}
//Wait for reply from modem
private function wait_reply($expected_result, $timeout) {
$this->debugmsg("Waiting {$timeout} seconds for expected result");
//Clear buffer
$this->buffer = '';
//Set timeout
$timeoutat = time() + $timeout;
//Loop until timeout reached (or expected result found)
do {
$this->debugmsg('Now: ' . time() . ", Timeout at: {$timeoutat}");
$buffer = fread($this->fp, 1024);
$this->buffer .= $buffer;
usleep(200000);//0.2 sec
$this->debugmsg("Received: {$buffer}");
//Check if received expected responce
if (preg_match('/'.preg_quote($expected_result, '/').'$/', $this->buffer)) {
$this->debugmsg('Found match');
return true;
//break;
} else if (preg_match('/\+CMS ERROR\:\ \d{1,3}\r\n$/', $this->buffer)) {
return false;
}
} while ($timeoutat > time());
$this->debugmsg('Timed out');
return false;
}
//Print debug messages
private function debugmsg($message) {
if ($this->debug == true) {
$message = preg_replace("%[^\040-\176\n\t]%", '', $message);
echo $message . "\n";
}
}
//Close port
public function close() {
$this->debugmsg('Closing port');
fclose($this->fp);
}
//Send message
public function send($tel, $message) {
//Filter tel
$tel = preg_replace("%[^0-9\+]%", '', $tel);
//Filter message text
$message = preg_replace("%[^\040-\176\r\n\t]%", '', $message);
$this->debugmsg("Sending message \"{$message}\" to \"{$tel}\"");
//Start sending of message
fputs($this->fp, "AT+CMGS=\"{$tel}\"\r");
//Wait for confirmation
$status = $this->wait_reply("\r\n> ", 5);
if (!$status) {
//throw new Exception('Did not receive confirmation from modem');
$this->debugmsg('Did not receive confirmation from modem');
return false;
}
//Send message text
fputs($this->fp, $message);
//Send message finished indicator
fputs($this->fp, chr(26));
//Wait for confirmation
$status = $this->wait_reply("OK\r\n", 180);
if (!$status) {
//throw new Exception('Did not receive confirmation of messgage sent');
$this->debugmsg('Did not receive confirmation of messgage sent');
return false;
}
$this->debugmsg("Message sent");
return true;
}
}
My PHP Code which i am using to send SMS
<?php
//SMS via GSM Modem - A PHP class to send SMS messages via a GSM modem attached to the computers serial port.
//Windows only (tested on XP with PHP 5.2.6)
//Tested with the EZ863 (Telit GE863) GSM modem
//Requires that PHP has permission to access "COM" system device, and system "mode" command
ini_set('max_execution_time', 300);
error_reporting(E_ALL);
//Example
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "MembersManagmentSystem";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Member.memberId, Member.memberContactMobileNumber, SMSRecipient.smsRecipientReceiverId, SMSRecipient.smsInfoId, SMSInfo.smsInfoText, SMSInfo.`smsInfoSaveDateTime` FROM Member, SMSRecipient,SMSInfo WHERE SMSRecipient.`smsRecipientReceiverId` = Member.`memberId` AND SMSRecipient.`smsInfoId`= SMSInfo.`smsInfoId` AND SMSRecipient.smsRecipientSentDateTime IS NULL AND Member.`memberContactMobileNumber` IS NOT NULL AND SMSInfo.`smsInfoSaveDateTime` > DATE_SUB(NOW(), INTERVAL 1 DAY)";
$result = $conn->query($sql);
echo "<pre>";
$gsm_send_sms = new gsm_send_sms();
$gsm_send_sms->debug = false;
$gsm_send_sms->port = 'COM3';
$gsm_send_sms->baud = 115200;
$gsm_send_sms->init();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
print_r($row);
$status = $gsm_send_sms->send($row['memberContactMobileNumber'], $row['smsInfoText']);
if ($status) {
$sql = "UPDATE SMSRecipient SET smsRecipientSentDateTime = now() WHERE smsInfoId = ".$row['smsInfoId']." and smsRecipientReceiverId = ".$row['memberId'];
if ($conn->query($sql) === TRUE) {
echo "Message sent\n";
}
} else {
echo "Message not sent\n";
}
}
//exit();
} else {
echo "0 results";
}
$gsm_send_sms->close();
$conn->close();
?>
on change $gsm_send_sms->debug = false; to true, get
Array
(
[0] =>
[1] => Status for device COM3:
[2] => -----------------------
[3] => Baud: 115200
[4] => Parity: None
[5] => Data Bits: 8
[6] => Stop Bits: 1
[7] => Timeout: OFF
[8] => XON/XOFF: OFF
[9] => CTS handshaking: OFF
[10] => DSR handshaking: OFF
[11] => DSR sensitivity: OFF
[12] => DTR circuit: ON
[13] => RTS circuit: ON
[14] =>
)
After Debug above Code I found that when i first time connect my device and run it php executing this line as like as infinity loop and before this line all debugmsg and other code running fine please help me
$buffer = fread($this->fp, 8192);

Can't monitor STDOUT of a C program in parallel with web sockets, by using stream select in PHP

I m writing a websocket based client server in PHP.Server is listeninig for clients which get connected from a browser, when client write something its echoed
back to the client. Client input and new connection from the client are monitored by using stream select.
In my previous work I used stream select to get output of the C program and display it on the browser now I want that when a client
send some message I execute a C program using proc open. C program outputs "hello" message in a loop after certain time, I want that when ever there
is output on the C program I send it to the client browser.
Client browser successful gets connected, when client sends data the server echo it back, the C program gets executed on server but I cant monitor its STDOUT by using same stream select that is monitoring my sockets.
I am not able to monitor my child process STDOUT using stream select. By using select How can I monitor the new process STDOUT that I started using proc open
,It looks that some how I lost the STDOUT descriptor that is usually accessible after starting the C program by using proc open.
hello.c
#include<stdio.h>
#include<stdint.h>
void main(void)
{
uint8_t i = 0;
uint8_t count = 10;
for(i = 0; i < count; i++)
{
printf("hello world\n");
sleep(1);
}
}
server.php
execute_prog('unbuffer /var/www/html/test/./hello3');//unbuffer stdout
function execute_prog($exe)
{
echo "[+execute_prog]";
$host = 'localhost'; //host
$port = '9000'; //port
$null = NULL; //null var
$read_socks;
$new_client;
$server = stream_socket_server("tcp://0.0.0.0:9000", $errno, $errorMessage);
if ($server === false)
{
throw new UnexpectedValueException("Could not bind to socket: $errorMessage");
}
set_time_limit(1800);
$exe_command = escapeshellcmd($exe);
$descriptorspec = array(
0 => array("pipe", "r"), // stdin -> for execution
1 => array("pipe", "w"), // stdout -> for execution
2 => array("pipe", "w") // stderr
);
{
$client_socks = array();
$read_socks = array($server);
$changed = array();
$stdout = NULL;
while(1)
{
//prepare readable sockets
$write = NULL;
$err = NULL;
$except = NULL;
$changed = $read_socks;//by refrence
if (false === ($num_changed_streams = stream_select($changed, $write, $except, 0)))
{
/* Error handling */
echo "Errors\n";
}
else if ($num_changed_streams > 0)
{
/* At least on one of the streams something interesting happened */
echo "Data on ".$num_changed_streams." descriptor\n";
if(in_array($stdout[0], $changed))
{
echo "Data on child process STDOUT\n";
$s = fgets($stdout[0]);
if( $s === false )
{
// Hello program has finished.
echo 'Finished', PHP_EOL;
$s = NULL;
ob_flush();
flush();
// Close all descriptors and return...
// break;
}
else
{
echo $s."</br>";
//fwrite($new_client,$s,strlen($s));//commented temporarily
$s = NULL;
ob_flush();
flush();
}
}
else if(in_array($server, $changed))
{
//new client
echo "New Connection\n";
$new_client = stream_socket_accept($server);
if ($new_client)
{
//print remote client information, ip and port number
echo 'Connection accepted from ' . stream_socket_get_name($new_client, true) . "n";
$read_socks[] = $new_client;
echo "Now there are total ". count($read_socks) . " clients.n";
}
$header = fread($new_client, 1024);//read data sent by the socket
perform_handshaking($header, $new_client, $host, $port); //perform websocket handshake
$ip = stream_socket_get_name($new_client, true);
$response = mask(json_encode(array('type'=>'system', 'message'=>$ip.' connected'))); //prepare json data
fwrite($new_client,$response,strlen($response));
//delete the server socket from the read sockets
unset($changed[ array_search($server, $changed) ]);
}
else if($write)
{
echo "Data on child process STDIN\n";
}
else if($err)
{
echo "Data on child process STDERR\n";
}
else
{
echo "Message from the client \n";
//message from existing client
foreach($changed as $sock)
{
$data = fread($sock, 128);
//echo "Data read:".$data." From sock:".$sock."\n";
if(!$data)
{
unset($client_socks[ array_search($sock, $client_socks) ]);
#fclose($sock);
echo "A client disconnected. Now there are total ". count($client_socks) . " clients.n";
continue;
}
else
{
$received_text = unmask($data); //unmask data
$tst_msg = json_decode($received_text); //json decode
$user_name = $tst_msg->name; //sender name
$user_message = $tst_msg->message; //message text
$user_color = $tst_msg->color; //color
// echo "name:".$user_name." user mesg:".$user_message."\n";
//prepare data to be sent to client
$response_text = mask(json_encode(array('type'=>'usermsg', 'name'=>$user_name, 'message'=>$user_message, 'color'=>$user_color)));
fwrite($sock, $response_text, strlen($response_text));
//..................................................................................................................
echo "Executing a process\n";
$process = proc_open($exe_command, $descriptorspec, $pipes);//creating child process
if (is_resource($process))
{
echo "Process Created";
}
$read_sock[] = $pipes[1];//add a descriptor
$stdout = array($pipes[1]);//save stdout in a variable defined above
print_r ($stdout);
}
}
}
$num_changed_streams = 0;
}
}
// close the listening socket
fclose($server);
fclose($pipes[0]);
fclose($pipes[1]);
fclose($pipes[2]);
echo "exitcode: ".proc_close($process)."\n";
}
echo "[-execute_prog]";
// return $ret;
}
Output Of server.php
[+execute_prog]Data on 1 descriptor
New Connection
Connection accepted from 127.0.0.1:49875nNow there are total 2 clients.nData on 1 descriptor
Message from the client
Executing a process
Process Created Array
(
[0] => Resource id #12
)
As can be seen from output that it never show message "Data on child process STDOUT" even the C program was created
Other utility functions unmask, mask etc can be provided if required.
Thankyou
i was saving the stdout in read_sock instead of read_socks array, now its resolved

PHP Serial Port Access

I am trying to implement this code below, I have a wavecom gsm modem connected to COM6 http://imgur.com/QwkwfMc it works on 3rd party sms gateway software but it is very expensive.
I am getting these errors
Fatal error: Uncaught exception 'Exception' with message 'Unable to setup COM port, check it is correct' in C:\wamp\www\sms\index.php on line 53
( ! ) Exception: Unable to setup COM port, check it is correct in C:\wamp\www\sms\index.php on line 53
What do i need to do to make this work?
<?php
//SMS via GSM Modem - A PHP class to send SMS messages via a GSM modem attached to the computers serial port.
//Windows only (tested on XP with PHP 5.2.6)
//Tested with the EZ863 (Telit GE863) GSM modem
//Requires that PHP has permission to access "COM" system device, and system "mode" command
error_reporting(E_ALL);
//Example
$gsm_send_sms = new gsm_send_sms();
$gsm_send_sms->debug = false;
$gsm_send_sms->port = 'COM6';
$gsm_send_sms->baud = 9600;
$gsm_send_sms->init();
$status = $gsm_send_sms->send('+642102844012', 'testing 123');
if ($status) {
echo "Message sent\n";
} else {
echo "Message not sent\n";
}
$gsm_send_sms->close();
//Send SMS via serial SMS modem
class gsm_send_sms {
public $port = 'COM6';
public $baud = 9600;
public $debug = false;
private $fp;
private $buffer;
//Setup COM port
public function init() {
$this->debugmsg("Setting up port: \"{$this->port} # \"{$this->baud}\" baud");
exec("MODE {$this->port}: BAUD={$this->baud} PARITY=N DATA=8 STOP=1", $output, $retval);
if ($retval != 0) {
throw new Exception('Unable to setup COM port, check it is correct');
}
$this->debugmsg(implode("\n", $output));
$this->debugmsg("Opening port");
//Open COM port
$this->fp = fopen($this->port . ':', 'r+');
//Check port opened
if (!$this->fp) {
throw new Exception("Unable to open port \"{$this->port}\"");
}
$this->debugmsg("Port opened");
$this->debugmsg("Checking for responce from modem");
//Check modem connected
fputs($this->fp, "AT\r");
//Wait for ok
$status = $this->wait_reply("OK\r\n", 5);
if (!$status) {
throw new Exception('Did not receive responce from modem');
}
$this->debugmsg('Modem connected');
//Set modem to SMS text mode
$this->debugmsg('Setting text mode');
fputs($this->fp, "AT+CMGF=1\r");
$status = $this->wait_reply("OK\r\n", 5);
if (!$status) {
throw new Exception('Unable to set text mode');
}
$this->debugmsg('Text mode set');
}
//Wait for reply from modem
private function wait_reply($expected_result, $timeout) {
$this->debugmsg("Waiting {$timeout} seconds for expected result");
//Clear buffer
$this->buffer = '';
//Set timeout
$timeoutat = time() + $timeout;
//Loop until timeout reached (or expected result found)
do {
$this->debugmsg('Now: ' . time() . ", Timeout at: {$timeoutat}");
$buffer = fread($this->fp, 1024);
$this->buffer .= $buffer;
usleep(200000);//0.2 sec
$this->debugmsg("Received: {$buffer}");
//Check if received expected responce
if (preg_match('/'.preg_quote($expected_result, '/').'$/', $this->buffer)) {
$this->debugmsg('Found match');
return true;
//break;
} else if (preg_match('/\+CMS ERROR\:\ \d{1,3}\r\n$/', $this->buffer)) {
return false;
}
} while ($timeoutat > time());
$this->debugmsg('Timed out');
return false;
}
//Print debug messages
private function debugmsg($message) {
if ($this->debug == true) {
$message = preg_replace("%[^\040-\176\n\t]%", '', $message);
echo $message . "\n";
}
}
//Close port
public function close() {
$this->debugmsg('Closing port');
fclose($this->fp);
}
//Send message
public function send($tel, $message) {
//Filter tel
$tel = preg_replace("%[^0-9\+]%", '', $tel);
//Filter message text
$message = preg_replace("%[^\040-\176\r\n\t]%", '', $message);
$this->debugmsg("Sending message \"{$message}\" to \"{$tel}\"");
//Start sending of message
fputs($this->fp, "AT+CMGS=\"{$tel}\"\r");
//Wait for confirmation
$status = $this->wait_reply("\r\n> ", 5);
if (!$status) {
//throw new Exception('Did not receive confirmation from modem');
$this->debugmsg('Did not receive confirmation from modem');
return false;
}
//Send message text
fputs($this->fp, $message);
//Send message finished indicator
fputs($this->fp, chr(26));
//Wait for confirmation
$status = $this->wait_reply("OK\r\n", 180);
if (!$status) {
//throw new Exception('Did not receive confirmation of messgage sent');
$this->debugmsg('Did not receive confirmation of messgage sent');
return false;
}
$this->debugmsg("Message sent");
return true;
}
}
?>
Try this below code hope it helps,
Note : uses php_serial.class.php
Code :
<?php
require("php_serial.class.php");
$serial = new phpSerial;
// First we must specify the device. This works on both linux and windows (if
// your linux serial device is /dev/ttyS0 for COM1, etc)
$serial->deviceSet("/dev/ttyS0");
// We can change the baud rate, parity, length, stop bits, flow control
$serial->confBaudRate(9600);
$serial->confParity("none");
$serial->confCharacterLength(8);
$serial->confStopBits(1);
$serial->confFlowControl("none");
// Then we need to open it
$serial->deviceOpen();
// To write into
$serial->sendMessage("AT+CMGF=1\n\r");
$serial->sendMessage("AT+cmgs=\"+912709345x23\"\n\r");
$serial->sendMessage("Hi, This is the sms that I sent to you using PHP script with serial Port communication with my phone as serial device!! GN - VKSALIAN \n\r");
$serial->sendMessage(chr(26));
//wait for modem to send message
sleep(7);
// Or to read from
$read = $serial->readPort();
echo $read;
// If you want to change the configuration, the device must be closed
$serial->deviceClose();
?>

Send SMS using GSM modem in PHP

I would like to send SMS from my GSM modem. I tried to implement this using this link as reference. But my modem will not produce any response.Any help..Thanks in advance....
Here is my code snippet..
$gsm_send_sms = new gsm_send_sms();
$gsm_send_sms->init();
$status = $gsm_send_sms->my_send_message_function("+09524566775", "raja");
$gsm_send_sms->close();
//Send SMS via serial SMS modem
class gsm_send_sms {
public $port = 'COM7';
public $baud = "9600";
public $debug = true;
private $fp;
private $buffer;
//Setup COM port
public function init() {
$this->debugmsg("Setting up port: \"{$this->port} # \"{$this->baud}\" baud");
exec("MODE {$this->port}: BAUD={$this->baud} PARITY=N DATA=8 STOP=1", $output, $retval);
if ($retval != 0) {
throw new Exception('Unable to setup COM port, check it is correct');
}
$this->debugmsg(implode("\n", $output));
$this->debugmsg("Opening port");
//Open COM port
$this->fp = fopen($this->port . ':', 'r+');
//Check port opened
if (!$this->fp) {
throw new Exception("Unable to open port \"{$this->port}\"");
}
$this->debugmsg("Port opened");
$this->debugmsg("Checking for responce from modem");
//Check modem connected
fputs($this->fp, "AT\r");
//Wait for ok
$status = $this->wait_reply("OK\r\n", 5);
if (!$status) {
throw new Exception('Did not receive responce from modem');
}

Categories