Learn from your fellow PHP developers with our PHP blogs, or help share the knowledge you've gained by writing your own.
;extension=sockets
extension=sockets
server.php
file$host = 'localhost';
$port = '9000';
$null = NULL;
function send_message($msg)
{
global $clients;
foreach($clients as $changed_socket)
{
@socket_write($changed_socket,$msg,strlen($msg));
}
return true;
}
function unmask($text) {
$length = ord($text[1]) & 127;
if($length == 126) {
$masks = substr($text, 4, 4);
$data = substr($text, 8);
}
elseif($length == 127) {
$masks = substr($text, 10, 4);
$data = substr($text, 14);
}
else {
$masks = substr($text, 2, 4);
$data = substr($text, 6);
}
$text = "";
for ($i = 0; $i < strlen($data); ++$i) {
$text .= $data[$i] ^ $masks[$i%4];
}
return $text;
}
function mask($text)
{
$b1 = 0x80 | (0x1 & 0x0f);
$length = strlen($text);
if($length <= 125)
$header = pack('CC', $b1, $length);
elseif($length > 125 && $length < 65536)
$header = pack('CCn', $b1, 126, $length);
elseif($length >= 65536)
$header = pack('CCNN', $b1, 127, $length);
return $header.$text;
}
function perform_handshaking($receved_header,$client_conn, $host, $port)
{
$headers = array();
$lines = preg_split("/
/", $receved_header);
foreach($lines as $line)
{
$line = chop($line);
if(preg_match('/\A(\S+): (.*)\z/', $line, $matches))
{
$headers[$matches[1]] = $matches[2];
}
}
$secKey = $headers['Sec-WebSocket-Key'];
$secAccept = base64_encode(pack('H*', sha1($secKey . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
$upgrade = "HTTP/1.1 101 Web Socket Protocol Handshake
" .
"Upgrade: websocket
" .
"Connection: Upgrade
" .
"WebSocket-Origin: $host
" .
"WebSocket-Location: ws://$host:$port/php-ws/chat-daemon.php
".
"Sec-WebSocket-Accept:$secAccept
";
socket_write($client_conn,$upgrade,strlen($upgrade));
}
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($socket, 0, $port);
socket_listen($socket);
$clients = array($socket);
while (true) {
$changed = $clients;
socket_select($changed, $null, $null, 0, 10);
if (in_array($socket, $changed)) {
$socket_new = socket_accept($socket); $clients[] = $socket_new;
$header = socket_read($socket_new, 1024); perform_handshaking($header, $socket_new, $host, $port);
socket_getpeername($socket_new, $ip); $response = mask(json_encode(array('type'=>'system', 'message'=>$ip.' connected'))); send_message($response);
$found_socket = array_search($socket, $changed);
unset($changed[$found_socket]);
}
foreach ($changed as $changed_socket) {
while(socket_recv($changed_socket, $buf, 1024, 0) >= 1)
{
$received_text = unmask($buf); $tst_msg = json_decode($received_text, true); $user_name = $tst_msg['name']; $user_message = $tst_msg['message']; $user_color = $tst_msg['color'];
$response_text = mask(json_encode(array('type'=>'usermsg', 'name'=>$user_name, 'message'=>$user_message, 'color'=>$user_color)));
send_message($response_text); break 2; }
$buf = @socket_read($changed_socket, 1024, PHP_NORMAL_READ);
if ($buf === false) { $found_socket = array_search($changed_socket, $clients);
socket_getpeername($changed_socket, $ip);
unset($clients[$found_socket]);
$response = mask(json_encode(array('type'=>'system', 'message'=>$ip.' disconnected')));
send_message($response);
}
}
}
socket_close($socket);
$host = 'localhost';
$port = '9000';
$subfolder = "php_ws/";
$colors = array('#007AFF','#FF7000','#FF7000','#15E25F','#CFC700','#CFC700','#CF1100','#CF00BE','#F00');
$color_pick = array_rand($colors);
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class="chat-wrapper">
<div id="message-box"></div>
<div class="user-panel">
<input type="text" name="name" id="name" placeholder="Your Name" maxlength="15" />
<input type="text" name="message" id="message" placeholder="Type your message here..." maxlength="100" />
<button id="send-message">Send</button>
</div>
</div>
</body>
</html>
<style type="text/css">
.chat-wrapper {
font: bold 11px/normal 'lucida grande', tahoma, verdana, arial, sans-serif;
background: #00a6bb;
padding: 20px;
margin: 20px auto;
box-shadow: 2px 2px 2px 0px #00000017;
max-width:700px;
min-width:500px;
}
#message-box {
width: 97%;
display: inline-block;
height: 300px;
background: #fff;
box-shadow: inset 0px 0px 2px #00000017;
overflow: auto;
padding: 10px;
}
.user-panel{
margin-top: 10px;
}
input[type=text]{
border: none;
padding: 5px 5px;
box-shadow: 2px 2px 2px #0000001c;
}
input[type=text]#name{
width:20%;
}
input[type=text]#message{
width:60%;
}
button#send-message {
border: none;
padding: 5px 15px;
background: #11e0fb;
box-shadow: 2px 2px 2px #0000001c;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
var msgBox = $('#message-box');
var wsUri = "ws://".$host.":".$port."/php-ws/server.php";
websocket = new WebSocket(wsUri);
websocket.onopen = function(ev) { msgBox.append('<div class="system_msg" style="color:#bbbbbb">Welcome to my "Chat box"!</div>'); }
websocket.onmessage = function(ev) {
var response = JSON.parse(ev.data);
var res_type = response.type; var user_message = response.message; var user_name = response.name; var user_color = response.color; switch(res_type){
case 'usermsg':
msgBox.append('<div><span class="user_name" style="color:' + user_color + '">' + user_name + '</span> : <span class="user_message">' + user_message + '</span></div>');
break;
case 'system':
msgBox.append('<div style="color:#bbbbbb">' + user_message + '</div>');
break;
}
msgBox[0].scrollTop = msgBox[0].scrollHeight; };
websocket.onerror = function(ev){ msgBox.append('<div class="system_error">Error Occurred - ' + ev.data + '</div>'); };
websocket.onclose = function(ev){ msgBox.append('<div class="system_msg">Connection Closed</div>'); };
$('#send-message').click(function(){
send_message();
});
$( "#message" ).on( "keydown", function( event ) {
if(event.which==13){
send_message();
}
});
function send_message(){
var message_input = $('#message'); var name_input = $('#name');
if(message_input.val() == ""){ alert("Enter your Name please!");
return;
}
if(message_input.val() == ""){ alert("Enter Some message Please!");
return;
}
var msg = {
message: message_input.val(),
name: name_input.val(),
color : '<?php echo $colors[$color_pick]; ?>'
};
websocket.send(JSON.stringify(msg));
message_input.val(''); }
</script>
php -q c:\xampp\htdocs\php-ws\server.php
$ php -i
phpinfo()
PHP Version => 7.2.10-0ubuntu1
System => Linux awesome 4.18.0-10-generic #11-Ubuntu SMP Thu Oct 11 15:13:55 UTC 2018 x86_64
Build Date => Sep 13 2018 13:38:55
Server API => Command Line Interface
Virtual Directory Support => disabled
...
less
command in order to get pagination and search: php -i | less
. Type Q
to exit the less
shell. Some distros might lack less
, in that case you may try php -i | more
, which doesn't give you search but still has pagination.$ php -m
[PHP Modules]
calendar
Core
ctype
date
dom
ds
exif
...
$ php --re ds
Extension [ <persistent> extension #46 ds version 1.2.6 ] {
- Dependencies {
Dependency [ json (Required) ]
Dependency [ spl (Required) ]
}
- Classes [11] {
Interface [ <internal:ds> interface Ds\Hashable ] {
- Constants [0] {
}
- Static properties [0] {
}
...
$ php --rc Ds\Vector
Class [ <internal:ds> <iterateable> final class Ds\Vector implements Ds\Sequence, Traversable, Countable, JsonSerializable, Ds\Collection ] {
- Constants [1] {
Constant [ public integer MIN_CAPACITY ] { 8 }
}
- Static properties [0] {
}
...
$ php --rf fopen
Function [ <internal:standard> function fopen ] {
- Parameters [4] {
Parameter #0 [ <required> $filename ]
Parameter #1 [ <required> $mode ]
Parameter #2 [ <optional> $use_include_path ]
Parameter #3 [ <optional> $context ]
}
}
-a
switch might be what you're looking for:$ php -a
Interactive mode enabled
php > var_dump(join(", ", [1, 2, 3]));
php shell code:1:
string(7) "1, 2, 3"
php >
readline
support (most distros have that anyway).$ php -l test.php
PHP Parse error: syntax error, unexpected 'array_shift' (T_STRING) in test.php on line 4
Errors parsing test.php
$ cd /my_application/document_root
$ php -S localhost:8000
umask(0);
$pid = pcntl_fork();
if ($pid < 0) {
print('fork failed');
exit 1;
}
if ($pid > 0) { echo "daemon process started
";
exit;
}
$sid = posix_setsid();
if ($sid < 0) {
exit 2;
}
chdir('/');
file_put_contents($pidFilename, getmypid() );
run_process();
ob_start();
var_dump($some_object);
$content = ob_get_clean();
fwrite($fd_log, $content);
ini_set('error_log', $logDir.'/error.log');
fclose(STDIN);
fclose(STDOUT);
fclose(STDERR);
$STDIN = fopen('/dev/null', 'r');
$STDOUT = fopen($logDir.'/application.log', 'ab');
$STDERR = fopen($logDir.'/application.error.log', 'ab');
function sig_handler($signo)
{
global $fd_log;
switch ($signo) {
case SIGTERM:
fclose($fd_log); unlink($pidfile); exit;
break;
case SIGHUP:
init_data(); break;
default:
}
}
pcntl_signal(SIGTERM, "sig_handler");
pcntl_signal(SIGHUP, "sig_handler");
$base = event_base_new();
$event = event_new();
$errno = 0;
$errstr = '';
$socket = stream_socket_server("tcp://$IP:$port", $errno, $errstr);
stream_set_blocking($socket, 0);
event_set($event, $socket, EV_READ | EV_PERSIST, 'onAccept', $base);
function onRead($buffer, $id)
{
while($read = event_buffer_read($buffer, 256)) {
var_dump($read);
}
}
function onError($buffer, $error, $id)
{
global $id, $buffers, $ctx_connections;
event_buffer_disable($buffers[$id], EV_READ | EV_WRITE);
event_buffer_free($buffers[$id]);
fclose($ctx_connections[$id]);
unset($buffers[$id], $ctx_connections[$id]);
}
$event2 = event_new();
$tmpfile = tmpfile();
event_set($event2, $tmpfile, 0, 'onTimer', $interval);
$res = event_base_set($event2, $base);
event_add($event2, 1000000 * $interval);
function onTimer($tmpfile, $flag, $interval)
{
$global $base, $event2;
if ($event2) {
event_delete($event2);
event_free($event2);
}
call_user_function(‘process_data’,$args);
$event2 = event_new();
event_set($event2, $tmpfile, 0, 'onTimer', $interval);
$res = event_base_set($event2, $base);
event_add($event2, 1000000 * $interval);
}
event_delete($event);
event_free($event);
event_base_free($base);
event_base_set($event, $base);
event_add($event);
function onAccept($socket, $flag, $base) {
global $id, $buffers, $ctx_connections;
$id++;
$connection = stream_socket_accept($socket);
stream_set_blocking($connection, 0);
$buffer = event_buffer_new($connection, 'onRead', NULL, 'onError', $id);
event_buffer_base_set($buffer, $base);
event_buffer_timeout_set($buffer, 30, 30);
event_buffer_watermark_set($buffer, EV_READ, 0, 0xffffff); event_buffer_priority_set($buffer, 10); event_buffer_enable($buffer, EV_READ | EV_PERSIST); $ctx_connections[$id] = $connection;
$buffers[$id] = $buffer;
}
#! /bin/sh
#
$appdir = /usr/share/myapp/app.php
$parms = --master –proc=8 --daemon
export $appdir
export $parms
if [ ! -x appdir ]; then
exit 1
fi
if [ -x /etc/rc.d/init.d/functions ]; then
. /etc/rc.d/init.d/functions
fi
RETVAL=0
start () {
echo "Starting app"
daemon /usr/bin/php $appdir $parms
RETVAL=$?
[ $RETVAL -eq 0 ] && touch /var/lock/subsys/mydaemon
echo
return $RETVAL
}
stop () {
echo -n "Stopping $prog: "
killproc /usr/bin/fetchmail
RETVAL=$?
[ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/mydaemon
echo
return $RETVAL
}
case in
start)
start
;;
stop)
stop
;;
restart)
stop
start
;;
status)
status /usr/bin/mydaemon
;;
*)
echo "Usage:
php {start|stop|restart|status}"
;;
RETVAL=$?
exit $RETVAL
#php app.phar
myDaemon version 0.1 Debug
usage:
--daemon – run as daemon
--debug – run in debug mode
--settings – print settings
--nofork – not run child processes
--check – check dependency modules
--master – run as master
--proc=[8] – run child processes
$key = ftok(__FILE__, 'A');
$queue = msg_get_queue($key);
msg_send($queue, 1, 'message, type 1');
msg_send($queue, 2, 'message, type 2');
msg_send($queue, 3, 'message, type 3');
msg_send($queue, 1, 'message, type 1');
echo "send 4 messages
";
queue-receive.php$key = ftok('queue-send.php', 'A');
$queue = msg_get_queue($key);
for ($i = 1; $i <= 3; $i++) {
echo "type: {$i}
";
while ( msg_receive($queue, $i, $msgtype, 4096, $message, false, MSG_IPC_NOWAIT) ) {
echo "type: {$i}, msgtype: {$msgtype}, message: {$message}
";
}
}
u% php queue-send.php
send 4 messages
u% php queue-receive.php
type: 1
type: 1, msgtype: 1, message: s:15:"message, type 1";
type: 1, msgtype: 1, message: s:15:"message, type 1";
type: 2
type: 2, msgtype: 2, message: s:15:"message, type 2";
type: 3
type: 3, msgtype: 3, message: s:15:"message, type 3";
while (msg_receive($queue, $i, $msgtype, 4096, $message, false, MSG_IPC_NOWAIT)) {
$key = ftok('queue-send.php', 'A');
$queue = msg_get_queue($key);
while ( msg_receive($queue, 0, $msgtype, 4096, $message) ) {
echo "msgtype: {$msgtype}, message: {$message}
";
}
$pid = pcntl_fork();
$key = ftok('queue-send.php', 'A');
$queue = msg_get_queue($key);
if ($pid == -1) {
exit;
} elseif ($pid) {
exit;
} else {
while ( msg_receive($queue, 0, $msgtype, 4096, $message) ) {
echo "msgtype: {$msgtype}, message: {$message}
";
}
}
posix_setsid();
$id = ftok(__FILE__, 'A');
$shmId = shm_attach($id);
$var = 1;
if (shm_has_var($shmId, $var)) {
$data = (array) shm_get_var($shmId, $var);
} else {
$data = array();
}
$data[time()] = file_get_contents(__FILE__);
shm_put_var($shmId, $var, $data);
$id = ftok(__DIR__ . '/shared-memory-write-base.php', 'A');
$shmId = shm_attach($id);
$var = 1;
if (shm_has_var($shmId, $var)) {
$data = (array) shm_get_var($shmId, $var);
} else {
$data = array();
}
foreach ($data as $key => $value) {
$path = "/tmp/$key.php";
file_put_contents($path, $value);
echo $path . PHP_EOL;
}
$id = ftok(__FILE__, 'A');
$semId = sem_get($id);
sem_acquire($semId);
$data = file_get_contents(__DIR__.'/06050396.JPG', FILE_BINARY);
$shmId = shm_attach($id, strlen($data)+4096);
$var = 1;
if (shm_has_var($shmId, $var)) {
$data = shm_get_var($shmId, $var);
$filename = '/tmp/' . time();
file_put_contents($filename, $data, FILE_BINARY);
shm_remove($shmId);
} else {
shm_put_var($shmId, $var, $data);
}
sem_release($semId);
$users = [new User(), new User()];
I see a lost opportunity to use Iterator.public function getUsers(): array
{
return $userArray;
}
public function setUsersToActiveState()
{
$users = $this->getUsers();
foreach ($users as $user) {
if(!$user->getActiveStatus()) {
$user->setActiveStatus(true);
}
}
}
There immediately two problems occurred.
class UsersCollection implements \IteratorAggregate
{
private $users = [];
public function getIterator() : UserIterator
{
return new UserIterator($this);
}
public function getUser($position)
{
if (isset($this->users[$position])) {
return $this->users[$position];
}
return null;
}
public function count() : int
{
return count($this->users);
}
public function addUser(User $users)
{
$this->users[] = $users;
}
}
class UserIterator implements \Iterator
{
private $position = 0;
private $userCollection;
public function __construct(UsersCollection $userCollection)
{
$this->userCollection = $userCollection;
}
public function current() : User
{
return $this->userCollection->getUser($this->position);
}
public function next()
{
$this->position++;
}
public function key() : int
{
return $this->position;
}
public function valid() : bool
{
return !is_null($this->userCollection->getUser($this->position));
}
public function rewind()
{
$this->position = 0;
}
}
class UsersCollectionTest extends TestCase
{
public function testUsersCollectionShouldReturnNullForNotExistingUserPosition()
{
$usersCollection = new UsersCollection();
$this->assertEquals(null, $usersCollection->getUser(1));
}
public function testEmptyUsersCollection()
{
$usersCollection = new UsersCollection();
$this->assertEquals(new UserIterator($usersCollection), $usersCollection->getIterator());
$this->assertEquals(0, $usersCollection->count());
}
public function testUsersCollectionWithUserElements()
{
$usersCollection = new UsersCollection();
$usersCollection->addUser($this->getUserMock());
$usersCollection->addUser($this->getUserMock());
$this->assertEquals(new UserIterator($usersCollection), $usersCollection->getIterator());
$this->assertEquals($this->getUserMock(), $usersCollection->getUser(1));
$this->assertEquals(2, $usersCollection->count());
}
private function getUserMock()
{
}
}
class UserIteratorTest extends MockClass
{
public function testCurrent()
{
$iterator = $this->getIterator();
$current = $iterator->current();
$this->assertEquals($this->getUserMock(), $current);
}
public function testNext()
{
$iterator = $this->getIterator();
$iterator->next();
$this->assertEquals(1, $iterator->key());
}
public function testKey()
{
$iterator = $this->getIterator();
$iterator->next();
$iterator->next();
$this->assertEquals(2, $iterator->key());
}
public function testValidIfItemInvalid()
{
$iterator = $this->getIterator();
$iterator->next();
$iterator->next();
$iterator->next();
$this->assertEquals(false, $iterator->valid());
}
public function testValidIfItemIsValid()
{
$iterator = $this->getIterator();
$iterator->next();
$this->assertEquals(true, $iterator->valid());
}
public function testRewind()
{
$iterator = $this->getIterator();
$iterator->rewind();
$this->assertEquals(0, $iterator->key());
}
private function getIterator() : UserIterator
{
return new UserIterator($this->getCollection());
}
private function getCollection() : UsersCollection
{
$userItems[] = $this->getUserMock();
$userItems[] = $this->getUserMock();
$usersCollection = new UsersCollection();
foreach ($userItems as $user) {
$usersCollection->addUser($user);
}
return $usersCollection;
}
private function getUserMock()
{
}
}
public function getUsers(): UsersCollection
{
$userCollection = new UsersCollection();
foreach ($whatIGetFromDatabase as $user) {
$userCollection->addUser($user);
}
return $userCollection;
}
public fucntion setUsersToActiveState()
{
$users = $this->getUsers();
foreach ($users as $user) {
if(!$user->getActiveStatus()) {
$user->setActiveStatus(true);
}
}
}
As you can see setUsersToActiveState remains the same, we only do not need to specify for our IDE or collagues what type $users variable is. public function addUser(User $users)
{
if ($user->getAge() > 18) {
$this->users[] = $users;
}
}
public function addUsers(array $users)
{
foreach($users as $user) {
$this->addUser(User $users);
}
}