not sending messages from script - php

I know i might gonna so many down vote but please help me through this as i nearly there. I have below code.
<?php
exec("mode COM1 BAUD=9600 PARITY=N data=8 stop=1 xon=off");
$fp = fopen ("\\.\com1", "r+");
//$fp = dio_open('COM5:', O_RDWR | O_NOCTTY | O_NONBLOCK);
if (!$fp)
{
echo "Uh-oh. Port not opened.";
}
else
{
$string = "AT+CMGF=1";
$string = $string."OK";
$string = $string."AT+CMGS='+44XXXXX'";
$string = $string."> Hello World?<Ctrl>+<Z>";
$string = $string."+CMGS: 44";
$string = $string."OK";
fputs ($fp, $string );
echo $string."\n";
fclose ($fp);
}
?>
above code is outputting AT+CMGF=1OKAT+CMGS='+44XXXX'> Hello World?++CMGS: 44OK but not actually sending any message to that number.
I have device is attached with PC which has SIM card in it.
How can I do this?

From what I know of AT commands, is that it is a dialogue. You have to send AT+CMGF=1 then wait for the modem to send OK, send the next command etcetera.
You are now sending everything, including the modem's responses in one string.
More information (as always) on Wikipedia: http://en.wikipedia.org/wiki/Hayes_command_set
The code should be along the lines of (off the top of my head, not tested):
$string = "AT+CMGF=1";
fputs($fp, $string);
$r = fgets($fp);
if ($r == "OK") {
$string = "AT+CMGS='+44XXXXX'";
fputs($fp, $string);
$r = $fgets($fp);
... etc ...
}

Related

PHP - TCP/IP fsockopen

I was wondering if anyone has had any experience with this before. I'm trying to write a simple script that will continously read data from the TCP/IP stream but for some reason or another the script reads in a bunch of data, writes it out and then just stops.
$fp = fsockopen("xxxx", 3000, $errno, $errstr, 5);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
while (!feof($fp)) {
echo fgets($fp, 128)."\n";
fflush($fp);
}
fclose($fp);
}
I'd like it to have a constant flow to it, rather then echo out a bunch of data then wait 30 seconds and output a bunch more data. Anyone have any ideas?
---- EDIT ----
ZMQ Code
include 'zmsg.php';
$context = new ZMQContext();
$client = new ZMQSocket($context, ZMQ::SOCKET_DEALER);
// Generate printable identity for the client
$identity = sprintf ("%04X", rand(0, 0x10000));
$client->setSockOpt(ZMQ::SOCKOPT_IDENTITY, $identity);
$client->connect("tcp://xxxx:3000");
$read = $write = array();
$poll = new ZMQPoll();
$poll->add($client, ZMQ::POLL_IN);
$request_nbr = 0;
while (true) {
// Tick once per second, pulling in arriving messages
for ($centitick = 0; $centitick < 100; $centitick++) {
$events = $poll->poll($read, $write, 1000);
$zmsg = new Zmsg($client);
if ($events) {
$zmsg->recv();
echo $zmsg->body()."\n";
//printf ("%s: %s%s", $identity, $zmsg->body(), PHP_EOL);
}
}
$zmsg = new Zmsg($client);
//$zmsg->body_fmt("request #%d", ++$request_nbr)->send();
}
Here is how you connect to a server (as a client) if your goal is ONLY to PULL data (read).
<?php
$context = new ZMQContext();
$sock = new ZMQSocket($context, ZMQ::SOCKET_PULL);
$sock->connect("tcp://ADDRESS:3000");
while (true)
{
$request = $sock->recv(); # recv is blocking by default, no need to put timers.
printf ("Received: %s;%s", $request, PHP_EOL);
}
?>
if you want to reply, you'll need to use a pair socket (ZMQ::SOCKET_PAIR), then you can use:
$sock->send("data to send");
Also, if instead of you connecting to clients, clients connects to you, use the bind method instead of connect.
EDIT: use the PUSH socket type on the other side if you use the pull here, else, use the pair socket on both sides.

How to use fgets as stream_get_line alternative?

I am using stream_get_line to store some php output in a variable, while I'm running a telnet session via fsockopen.
However, my second server does not run PHP5, which is disabled the ability to use stream_get_line. Is there any alternative for PHP 4.3?
I heard that fgets is almost the same, but I don't seem to get it to work exactly like stream_get_line.
Code:
...
# opening connection
$fp = #fsockopen($ip, 23, $errno, $errstr, 8);
# loggin in
fputs($fp, "$user\r");
usleep(250000);
fputs($fp, "$password\r");
# getting information
fputs($fp, "show info\n");
usleep(250000);
fputs($fp, "show info 2\n");
usleep(250000);
fputs($fp, "show info 3\n");
usleep(250000);
fputs($fp, "show info 4\n");
usleep(250000);
fputs($fp, "?\n");
$content = stream_get_line($fp, 0, "?");
$contentvalues = array(
1 => substr($content, 130, 3),
2 => substr($content, 180, 3)
);
fclose($fp);
...
(I am storing specific parts of my output in the $contentvalues variable.)
From the docs:
This function is nearly identical to fgets() except in that it allows
end of line delimiters other than the standard \n, \r, and \r\n, and
does not return the delimiter itself.
From the comments:
when fgets reads some bytes from socket, where EOF is reached, it
returns bool(false) same as stream_get_line
BUT if remote client drops connection, and server script will try to
read some data with function fgets, function will return bool(false),
and stream_get_line will return string(0) ""
so you can detect remote client disconnection with stream_get_line,
and cannot with fgets
There's also some dithering about which function is faster, but it seems to be dependant on the version of PHP, the day of the week, and what the commenter had for dinner the previous night.
edit
Judging by your response to Steffen's answer you're hung up on the fact that fgets() does not take a third parameter as a delimiter. Applying a basic input loop and checking the string will get you there. Also, in Steffen's defense, you were never quite clear on in your question, stating only that it doesn't "work exactly like stream_get_line".
<?php
$delim = '?';
$buf = 4096;
$fp = #fsockopen($ip, 23, $errno, $errstr, 8);
// ... yadda yadda yadda ... //
$content = '';
while( $part = fgets($fp, $buf) ) {
$ind = strpos($part, $delim);
if( $ind !== false ) {
$content .= substr($part, 0, $ind);
break;
}
$content .= $part;
}
Also, even with stream_get_line() you should be using a loop to get the input as a length parameter or 0 does not mean "unlimited", but rather will use one of PHP's defaults which is 8192 bytes.
You can use fgets() (string fgets ( resource $handle [, int $length ] )) instead.
http://www.php.net/manual/de/function.fgets.php

SSH2 change a user password

I've been playing around with SSH and now I need to change a user's password via the PHP's ssh2,
Here's my code:
$stream = ssh2_exec($ssh, 'passwd test1234');
stream_set_blocking($stream, true);
$data = '';
while($buffer = fread($stream, 4096)) {
$data .= $buffer;
}
fclose($stream);
echo $data."<hr/>";
$stream = ssh2_exec($ssh, 'saulius123');
stream_set_blocking($stream, true);
$data = '';
while($buffer = fread($stream, 4096)) {
$data .= $buffer;
}
echo $data."<hr/>";
$stream = ssh2_exec($ssh, 'saulius123');
stream_set_blocking($stream, true);
$data = '';
while($buffer = fread($stream, 4096)) {
$data .= $buffer;
}
echo $data."<hr/>";
However this just make's my PHP script hang, any ideas?
ssh2_exec invokes the command; to send input, you'll need to write to the stream.
That is, $stream gives you access to standard input and standard output. So you'll need to write the password you wish to set using fwrite on $stream before trying to read back the output.
Since you've put the stream in blocking mode, passwd is awaiting your input (the password) at the same time your script is waiting for passwd. As a result, the script hangs.
Personally, I'd use phpseclib, a pure PHP SSH implementation. Example:
<?php
include('Net/SSH2.php');
$key = new Crypt_RSA();
//$key->setPassword('whatever');
$key->loadKey(file_get_contents('privatekey'));
$ssh = new Net_SSH2('www.domain.tld');
if (!$ssh->login('username', $key)) {
exit('Login Failed');
}
echo $ssh->read('username#username:~$');
$ssh->write("ls -la\n");
echo $ssh->read('username#username:~$');
?>
The biggest advantage of it over libssh2 is portability. We use Amazon Web Services were I work and sometimes we move over to new prod servers or dev servers and the most difficult part in setting them up is installing all the PECL extensions and what not.
phpseclib, in contrast, doesn't have any requirements.

Using PHP to read a web page with fsockopen(), but fgets is not working

Im using this code here: http://www.digiways.com/articles/php/httpredirects/
public function ReadHttpFile($strUrl, $iHttpRedirectMaxRecursiveCalls = 5)
{
// parsing the url getting web server name/IP, path and port.
$url = parse_url($strUrl);
// setting path to '/' if not present in $strUrl
if (isset($url['path']) === false)
$url['path'] = '/';
// setting port to default HTTP server port 80
if (isset($url['port']) === false)
$url['port'] = 80;
// connecting to the server]
// reseting class data
$this->success = false;
unset($this->strFile);
unset($this->aHeaderLines);
$this->strLocation = $strUrl;
$fp = fsockopen ($url['host'], $url['port'], $errno, $errstr, 30);
// Return if the socket was not open $this->success is set to false.
if (!$fp)
return;
$header = 'GET / HTTP/1.1\r\n';
$header .= 'Host: '.$url['host'].$url['path'];
if (isset($url['query']))
$header .= '?'.$url['query'];
$header .= '\r\n';
$header .= 'Connection: Close\r\n\r\n';
// sending the request to the server
echo "Header is: <br />".str_replace('\n', '\n<br />', $header)."<br />";
$length = strlen($header);
if($length != fwrite($fp, $header, $length))
{
echo 'error writing to header, exiting<br />';
return;
}
// $bHeader is set to true while we receive the HTTP header
// and after the empty line (end of HTTP header) it's set to false.
$bHeader = true;
// continuing untill there's no more text to read from the socket
while (!feof($fp))
{
echo "in loop";
// reading a line of text from the socket
// not more than 8192 symbols.
$good = $strLine = fgets($fp, 128);
if(!$good)
{
echo 'bad';
return;
}
// removing trailing \n and \r characters.
$strLine = ereg_replace('[\r\n]', '', $strLine);
if ($bHeader == false)
$this->strFile .= $strLine.'\n';
else
$this->aHeaderLines[] = trim($strLine);
if (strlen($strLine) == 0)
$bHeader = false;
echo "read: $strLine<br />";
return;
}
echo "<br />after loop<br />";
fclose ($fp);
}
This is all I get:
Header is:
GET / HTTP/1.1\r\n
Host: www.google.com/\r\n
Connection: Close\r\n\r\n
in loopbad
So it fails the fgets($fp, 128);
Is there a reason you aren't using PHP's built-in, enabled-by-default ability to fetch remote files using fopen?
$remote_page = file_get_contents('http://www.google.com/'); // <- Works!
There are also plenty of high-quality third-party libraries, if you need to do something like fetch headers without thinking too hard. Try Zend_Http_Client on for size.
The flaw is here:
$good = $strLine = fgets($fp, 128);
if(!$good)
{
echo 'bad';
return;
}
fgets() returns either a string on success, or FALSE on failure. However, if there was no more data to be returned, fgets() will return the empty string (''). So, both $good and $strLine are set to the empty string, which PHP will happily cast to FALSE in the if() test. You should rewrite as follows:
$strLine = fgets($fp, 128);
if ($strLine === FALSE) { // strict comparison - types and values must match
echo 'bad';
return;
}
There's no need for the double assignment, as you can test $strLine directly.

Are sockets so slow in PHP?

I'm using this code for sockets. Console says that the page is processed for a very small amount of time, but Chrome says that page is loading for ~1 second!
$this->serv_sock = socket_create(AF_INET, SOCK_STREAM, 0);
socket_bind($this->serv_sock, $this->serv, $this->port) or die("Could not bind to address\n");
socket_listen($this->serv_sock);
while (1) {
echo "Waiting...\n";
$client = socket_accept($this->serv_sock);
$start_mtime = microtime(true);
echo "Accepted at ".$start_mtime.".\n";
$input = '';
$len = 0;
do {
//echo "Reading.\n";
$inp = socket_read($client, 1024);
$input .= $inp;
if (strpos($input, "\n\n") === false && strpos($input, "\r\n\r\n") === false)
continue;
if (!$len) {
if (!preg_match("/Content-Length: (\d+)/", $input, $matches)) {
break;
}
$len = $matches[1];
if (!$len)
break;
echo "We want $len bytes.\n";
}
if (strpos($input, "\n\n") !== false)
list($headers, $content) = explode("\n\n", $input);
else
list($headers, $content) = explode("\r\n\r\n", $input);
if (strlen($content) >= $len)
break;
} while ($inp);
echo "Calling callback as ".microtime(true).".\n";
if (strpos($input, "\n\n") !== false)
list($headers, $content) = explode("\n\n", $input);
else
list($headers, $content) = explode("\r\n\r\n", $input);
$output = $this->translate($callback, $headers, $content); // nothing slow here
$time_end = microtime(true);
echo "Sending output at ".$time_end." (total ".($time_end - $start_mtime).")\n\n";
$output = "HTTP/1.0 Ok\n".
"Content-Type: text/html; charset=utf-8\n".
"Content-Length: ".strlen($output)."\n".
"Connection: close\n\n".
$output;
socket_write($client, $output);
socket_close($client);
}
If I understand what you're saying. As far as I know there is a difference between server processing time and client processing time.
The time it actually takes to process the information on the server will always be less. Once the server finishes processing the information the data still has to be sent to the browser and has to be rendered. The time for the data to get there and for the browser to render is what I'm suspecting the reason is as to why Chrome is telling you it's taking ~1 second.

Categories