SlideShare a Scribd company logo
SessionServer :: Maintaining state between several servers Stephan Schmidt 1&1 Internet AG
Agenda The need for a session server ext/sockets and ext/pcntl Using Net_Server Designing a protocol Architecture of HTTP_SessionServer Building a client Integrating the built-in session functions The future
Why Sessions? HTTP is stateless Requests operate in a sandbox Two requests of the same user may be handled by different apache processes Modern applications require a state Authentication Shopping carts User tracking
PHP sessions Built-in functions since PHP4 Data associated with a user is stored on the server Unique Session-Id for each active user, passed between requests Stores data on the filesystem (other containers are possible) Shared Memory Database
Disadvantages Data is stored on the web server only accessible via PHP only accessible from this server applications must run on this server no clusters size may be limited (size of /tmp or shared memory segment)
The Solution Store session data in one central location accessible from any server accessible by any application accessible by any programming language no overhead (like when using a RDBMS or web service) access must be simple
Session Server Stores key value pairs for sessions Daemon that is awaiting connections may be accessed using fsockopen(), fwrite() and fread() very simple protocol Store data on the filesystem, just like PHP's session functions, but need  not  be on the webserver
Building a server with PHP ext/sockets allows you to create daemons: $fd  = socket_create( AF_INET, SOCK_STREAM, SOL_TCP ); if(!is_resource($fd)) { die('Could not create socket.'); } socket_bind( $fd, 'localhost', 9090 ); socket_listen( $fd, 10 ); $newFd = socket_accept( $fd ); $text = "Hello world!\n"; socket_write( $newFd, $text, strlen( $text ) ); socket_close($newFd); socket_close($fd);
Building a server with PHP (2) run this script in with PHP-CLI $ php myServer.php open a new terminal and execute $ telnet localhost 9090 schst@rot3:schst> telnet localhost 9090 Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. Hello world! Connection closed by foreign host. schst@rot3:schst>
Building a server with PHP (3) ext/sockets provides more functions receive data from client using socket_read() set options get information about the client socket_accept() halts script execution Limited to one connection at a time May keep more than one connection open using socket_select() but still sequential
Making use of ext/pcntl Implements the Unix style of process creation signal handling process termination That means current process can be copied at runtime parent-process may stop children Not available on Windows
Making use of ext/pcntl (2) $children = 5; for ($i=1; $i<=$children; $i++) { $pid = pcntl_fork(); if ($pid === -1) { exit('Could not fork child.'); } elseif ($pid) { continue; } else { printf(&quot;new process created: %s\n&quot;,getmypid()); break; } } // do not exit while(true) { sleep(5); }
Making use of ext/pcntl (3) pcntl_fork() forks process and returns new process id If pcntl_fork() returns '0' (zero), current process is the child If master-process is stopped, all children are stopped as well Child-Processes may be stopped without stopping the parent
Making use of ext/pcntl (4) run this script in with PHP-CLI $ php myFork.php schst@rot3:schst> php5 myFork.php new process created: 30923 new process created: 30924 new process created: 30925 new process created: 30926 new process created: 30927
Making use of ext/pcntl (5) Take a look at the processes $ ps fax | grep myFork schst@rot3:schst> ps fax | grep myFork 30922 pts/0  S+  0:00  |  \_ php5 myFork.php 30923 pts/0  S+  0:00  |  \_ php5 myFork.php 30924 pts/0  S+  0:00  |  \_ php5 myFork.php 30925 pts/0  S+  0:00  |  \_ php5 myFork.php 30926 pts/0  S+  0:00  |  \_ php5 myFork.php 30927 pts/0  S+  0:00  |  \_ php5 myFork.php Kill one process $ kill 30923
Confused by low-level code? Use PEAR::Net_Server! Provides generic server class. Has support for pcntl_fork() Triggers callbacks on events New client connects Client sends data Client disconnects …
Using Net_Server class Net_Server_Handler_Talkback extends Net_Server_Handler { function onConnect($clientId = 0) { $this->_server->sendData($clientId,&quot;Welcome to my server\n&quot;); } function onReceiveData($clientId = 0, $data = '') { $this->_server->sendData($clientId, &quot;You said: $data&quot;); } } $server  = &Net_Server::create('Fork', 'localhost', 9090); $handler = &new Net_Server_Handler_Talkback; $server->setCallbackObject($handler); $server->start();
Using Net_Server (2) run this script with PHP-CLI $ php myServer2.php schst@rot3:schst> php5 myServer2.php PEAR constructor called, class=Net_Server_Driver_Fork … 14:30:44 Listening on port 9090. Server started at 14:30:44 … 14:30:50 New co…on from 127.0.0.1 on port 52237, new pid: 31241 … 14:30:50 sending: &quot;Welcome to my server&quot; to: 127.0.0.1:52237 (pid: 31241) … 14:30:53 Received Foo from 127.0.0.1:52237 (pid: 31241) … 14:30:53 sending: &quot;You said: Foo&quot; to: 127.0.0.1:52237 (pid: 31241)
Building a Session Daemon Define a protocol create new session open existing session store value retrieve value some additional commands Implement a callback object  start the Net_Server object
HTTP_SessionServer Out-of-the-box solution available in PEAR require_once 'HTTP/SessionServer.php'; $options = array( 'save_path' => '/tmp' ); $server = &new HTTP_SessionServer('Filesystem', $options); $server->service('localhost', 9090); Uses Net_Server with 'Fork' driver requires ext/pcntl, does not work on windows Provides a client as well
The Protocol Currently supports 13 commands: new, open, close, commit, destroy get, put, exists, remove, get_all, put_all, keys regenerate_id Structure of a command: command arg1 arg2 … Session-Id is stored after executing  open  or  new  (keeps the payload smaller)
The Protocol (2) Server sends  ok  or  err  to indicate success or failure, followed by actual result, e.g. err unknown command Data will be UTF-8 encoded enough theory, example coming up…
The protocol (3) schst@rot3:schst> telnet localhost 9090 Trying 127.0.0.1... Connected to localhost. new ok 8087127fe6cf50e89932dbf0ee8d4855 put foo bar ok put today 2004-11-09 ok keys ok foo|today get today ok 2004-11-09 close ok get foo err No session opened.
Features Different storage containers possible Open a session in read-only-mode Auto-lock a session in write-mode change mode from &quot;write&quot; to &quot;read&quot; (commit) Change the session-Id while keeping the data (for security reasons) easily extendible
Architecture of the server Net_Server HTTP_Session_Server Storage_Filesystem Custom Storage Client Client Client Client Calls onDataReceived Parses data and calls methods on storage Serializes return values
Extending SessionServer Write a new storage container In most cases open(), close(), destroy() and commit() are enough Shared Memory, RDBMS, etc. Implement new commands Extend HTTP_SessionServer Implement _cmd[CommandName] method return an array
Building a client Using fsockopen() $fp = fsockopen('localhost', 9090); fputs($fp, &quot;new\r\n&quot;); $result = fgets($fp, 4096); fclose($fp); Using PEAR::Net_Socket $socket = &new Net_Socket(); $socket->connect('localhost', 9090); $socket->writeLine('new'); $result = $socket->readLine(); $socket->disconnect();
Don't worry: Client included Based on PEAR::Net_Socket Very easy-to-use OO-Interface to HTTP_SessionServer Implements all supported commands Returns PEAR_Error objects on error Automatically disconnects the socket
Client example require_once 'HTTP/SessionServer/Client.php'; $session = &new HTTP_SessionServer_Client('localhost', 9090); $id = $session->create(); $session->put('time', time()); $session->put('foo', 'bar'); $keys = $session->getKeys(); $session->close(); $session2 = &new HTTP_SessionServer_Client('localhost', 9090); $session->open($id, 'r'); $time = $session2->get('time'); $session2->close();
Setting a session save handler session_set_save_handler  ( string open, string close, string read, string write, string destroy, string gc)  Allows you to replace the storage module for internal session functions register callbacks to open,read, write, close and destroy session data
Replacing built-in session handling HTTP_SessionServer provides needed callbacks use session_save_path() to specify host and port No other changes needed require_once 'HTTP/SessionServer/SaveHandler.php'; session_save_path('localhost:9090'); session_start();
The future Work on PHP5 version using stream_socket_server() Implement missing features garbage collection session lifetime Implement a session storage module in C to improve performance Implement more storage containers
What about msession? msession is a daemon written in C similar to HTTP_SessionServer PHP-Extension is available More information at: http://devel.mohawksoft.com/msession.html
The End Thanks for your attention. [email_address] http://www.php-tools.net
Ad

More Related Content

What's hot (20)

Php and MySQL
Php and MySQLPhp and MySQL
Php and MySQL
Tiji Thomas
 
PHP MySQL Workshop - facehook
PHP MySQL Workshop - facehookPHP MySQL Workshop - facehook
PHP MySQL Workshop - facehook
Shashank Skills Academy
 
New Features in PHP 5.3
New Features in PHP 5.3New Features in PHP 5.3
New Features in PHP 5.3
Bradley Holt
 
PHP POWERPOINT SLIDES
PHP POWERPOINT SLIDESPHP POWERPOINT SLIDES
PHP POWERPOINT SLIDES
Ismail Mukiibi
 
Php mysql
Php mysqlPhp mysql
Php mysql
Abu Bakar
 
Short Intro to PHP and MySQL
Short Intro to PHP and MySQLShort Intro to PHP and MySQL
Short Intro to PHP and MySQL
Jussi Pohjolainen
 
PHP Workshop Notes
PHP Workshop NotesPHP Workshop Notes
PHP Workshop Notes
Pamela Fox
 
PHP Web Programming
PHP Web ProgrammingPHP Web Programming
PHP Web Programming
Muthuselvam RS
 
Web Development Course: PHP lecture 1
Web Development Course: PHP lecture 1Web Development Course: PHP lecture 1
Web Development Course: PHP lecture 1
Gheyath M. Othman
 
PHP Basic
PHP BasicPHP Basic
PHP Basic
Yoeung Vibol
 
Overview of PHP and MYSQL
Overview of PHP and MYSQLOverview of PHP and MYSQL
Overview of PHP and MYSQL
Deblina Chowdhury
 
Php Lecture Notes
Php Lecture NotesPhp Lecture Notes
Php Lecture Notes
Santhiya Grace
 
PHP NOTES FOR BEGGINERS
PHP NOTES FOR BEGGINERSPHP NOTES FOR BEGGINERS
PHP NOTES FOR BEGGINERS
Aminiel Michael
 
PHP FUNCTIONS
PHP FUNCTIONSPHP FUNCTIONS
PHP FUNCTIONS
Zeeshan Ahmed
 
lf-2003_01-0269
lf-2003_01-0269lf-2003_01-0269
lf-2003_01-0269
tutorialsruby
 
Introduction to php web programming - get and post
Introduction to php  web programming - get and postIntroduction to php  web programming - get and post
Introduction to php web programming - get and post
baabtra.com - No. 1 supplier of quality freshers
 
Php(report)
Php(report)Php(report)
Php(report)
Yhannah
 
Class 6 - PHP Web Programming
Class 6 - PHP Web ProgrammingClass 6 - PHP Web Programming
Class 6 - PHP Web Programming
Ahmed Swilam
 
Php.ppt
Php.pptPhp.ppt
Php.ppt
Nidhi mishra
 
Resource-Oriented Web Services
Resource-Oriented Web ServicesResource-Oriented Web Services
Resource-Oriented Web Services
Bradley Holt
 

Similar to Session Server - Maintaing State between several Servers (20)

Tips
TipsTips
Tips
mclee
 
Debugging: Rules & Tools
Debugging: Rules & ToolsDebugging: Rules & Tools
Debugging: Rules & Tools
Ian Barber
 
The why and how of moving to PHP 5.4/5.5
The why and how of moving to PHP 5.4/5.5The why and how of moving to PHP 5.4/5.5
The why and how of moving to PHP 5.4/5.5
Wim Godden
 
Heavy Web Optimization: Backend
Heavy Web Optimization: BackendHeavy Web Optimization: Backend
Heavy Web Optimization: Backend
Võ Duy Tuấn
 
php & performance
 php & performance php & performance
php & performance
simon8410
 
Caching and tuning fun for high scalability
Caching and tuning fun for high scalabilityCaching and tuning fun for high scalability
Caching and tuning fun for high scalability
Wim Godden
 
PHP Sessions and Non-Sessions
PHP Sessions and Non-SessionsPHP Sessions and Non-Sessions
PHP Sessions and Non-Sessions
Sven Rautenberg
 
Debugging: Rules And Tools - PHPTek 11 Version
Debugging: Rules And Tools - PHPTek 11 VersionDebugging: Rules And Tools - PHPTek 11 Version
Debugging: Rules And Tools - PHPTek 11 Version
Ian Barber
 
PHP & Performance
PHP & PerformancePHP & Performance
PHP & Performance
毅 吕
 
Facebook的缓存系统
Facebook的缓存系统Facebook的缓存系统
Facebook的缓存系统
yiditushe
 
Caching and tuning fun for high scalability
Caching and tuning fun for high scalabilityCaching and tuning fun for high scalability
Caching and tuning fun for high scalability
Wim Godden
 
Php mysql ppt
Php mysql pptPhp mysql ppt
Php mysql ppt
Karmatechnologies Pvt. Ltd.
 
How to admin
How to adminHow to admin
How to admin
yalegko
 
Exploring Async PHP (SF Live Berlin 2019)
Exploring Async PHP (SF Live Berlin 2019)Exploring Async PHP (SF Live Berlin 2019)
Exploring Async PHP (SF Live Berlin 2019)
dantleech
 
Running Head IMPLEMENTING THE LIST AND SEARCH FEATURES IN THE DIS.docx
Running Head IMPLEMENTING THE LIST AND SEARCH FEATURES IN THE DIS.docxRunning Head IMPLEMENTING THE LIST AND SEARCH FEATURES IN THE DIS.docx
Running Head IMPLEMENTING THE LIST AND SEARCH FEATURES IN THE DIS.docx
cowinhelen
 
Zend Con 2008 Slides
Zend Con 2008 SlidesZend Con 2008 Slides
Zend Con 2008 Slides
mkherlakian
 
4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook
guoqing75
 
HackU PHP and Node.js
HackU PHP and Node.jsHackU PHP and Node.js
HackU PHP and Node.js
souridatta
 
Xdebug - Derick Rethans - Barcelona PHP Conference 2008
Xdebug - Derick Rethans - Barcelona PHP Conference 2008Xdebug - Derick Rethans - Barcelona PHP Conference 2008
Xdebug - Derick Rethans - Barcelona PHP Conference 2008
phpbarcelona
 
The why and how of moving to PHP 5.5/5.6
The why and how of moving to PHP 5.5/5.6The why and how of moving to PHP 5.5/5.6
The why and how of moving to PHP 5.5/5.6
Wim Godden
 
Tips
TipsTips
Tips
mclee
 
Debugging: Rules & Tools
Debugging: Rules & ToolsDebugging: Rules & Tools
Debugging: Rules & Tools
Ian Barber
 
The why and how of moving to PHP 5.4/5.5
The why and how of moving to PHP 5.4/5.5The why and how of moving to PHP 5.4/5.5
The why and how of moving to PHP 5.4/5.5
Wim Godden
 
Heavy Web Optimization: Backend
Heavy Web Optimization: BackendHeavy Web Optimization: Backend
Heavy Web Optimization: Backend
Võ Duy Tuấn
 
php & performance
 php & performance php & performance
php & performance
simon8410
 
Caching and tuning fun for high scalability
Caching and tuning fun for high scalabilityCaching and tuning fun for high scalability
Caching and tuning fun for high scalability
Wim Godden
 
PHP Sessions and Non-Sessions
PHP Sessions and Non-SessionsPHP Sessions and Non-Sessions
PHP Sessions and Non-Sessions
Sven Rautenberg
 
Debugging: Rules And Tools - PHPTek 11 Version
Debugging: Rules And Tools - PHPTek 11 VersionDebugging: Rules And Tools - PHPTek 11 Version
Debugging: Rules And Tools - PHPTek 11 Version
Ian Barber
 
PHP & Performance
PHP & PerformancePHP & Performance
PHP & Performance
毅 吕
 
Facebook的缓存系统
Facebook的缓存系统Facebook的缓存系统
Facebook的缓存系统
yiditushe
 
Caching and tuning fun for high scalability
Caching and tuning fun for high scalabilityCaching and tuning fun for high scalability
Caching and tuning fun for high scalability
Wim Godden
 
How to admin
How to adminHow to admin
How to admin
yalegko
 
Exploring Async PHP (SF Live Berlin 2019)
Exploring Async PHP (SF Live Berlin 2019)Exploring Async PHP (SF Live Berlin 2019)
Exploring Async PHP (SF Live Berlin 2019)
dantleech
 
Running Head IMPLEMENTING THE LIST AND SEARCH FEATURES IN THE DIS.docx
Running Head IMPLEMENTING THE LIST AND SEARCH FEATURES IN THE DIS.docxRunning Head IMPLEMENTING THE LIST AND SEARCH FEATURES IN THE DIS.docx
Running Head IMPLEMENTING THE LIST AND SEARCH FEATURES IN THE DIS.docx
cowinhelen
 
Zend Con 2008 Slides
Zend Con 2008 SlidesZend Con 2008 Slides
Zend Con 2008 Slides
mkherlakian
 
4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook
guoqing75
 
HackU PHP and Node.js
HackU PHP and Node.jsHackU PHP and Node.js
HackU PHP and Node.js
souridatta
 
Xdebug - Derick Rethans - Barcelona PHP Conference 2008
Xdebug - Derick Rethans - Barcelona PHP Conference 2008Xdebug - Derick Rethans - Barcelona PHP Conference 2008
Xdebug - Derick Rethans - Barcelona PHP Conference 2008
phpbarcelona
 
The why and how of moving to PHP 5.5/5.6
The why and how of moving to PHP 5.5/5.6The why and how of moving to PHP 5.5/5.6
The why and how of moving to PHP 5.5/5.6
Wim Godden
 
Ad

More from Stephan Schmidt (17)

Das Web Wird Mobil - Geolocation und Location Based Services
Das Web Wird Mobil - Geolocation und Location Based ServicesDas Web Wird Mobil - Geolocation und Location Based Services
Das Web Wird Mobil - Geolocation und Location Based Services
Stephan Schmidt
 
23 Dinge, die Sie über Software Entwicklung in Teams wissen sollten
23 Dinge, die Sie über Software Entwicklung in Teams wissen sollten23 Dinge, die Sie über Software Entwicklung in Teams wissen sollten
23 Dinge, die Sie über Software Entwicklung in Teams wissen sollten
Stephan Schmidt
 
23 Dinge, die Sie über Software-Entwicklung in Teams wissen sollten
23 Dinge, die Sie über Software-Entwicklung in Teams wissen sollten23 Dinge, die Sie über Software-Entwicklung in Teams wissen sollten
23 Dinge, die Sie über Software-Entwicklung in Teams wissen sollten
Stephan Schmidt
 
Continuous Integration mit Jenkins
Continuous Integration mit JenkinsContinuous Integration mit Jenkins
Continuous Integration mit Jenkins
Stephan Schmidt
 
Die Kunst des Software Design - Java
Die Kunst des Software Design - JavaDie Kunst des Software Design - Java
Die Kunst des Software Design - Java
Stephan Schmidt
 
PHP mit Paul Bocuse
PHP mit Paul BocusePHP mit Paul Bocuse
PHP mit Paul Bocuse
Stephan Schmidt
 
Der Erfolgreiche Programmierer
Der Erfolgreiche ProgrammiererDer Erfolgreiche Programmierer
Der Erfolgreiche Programmierer
Stephan Schmidt
 
23 Dinge, die Sie über Software-Entwicklung in Teams wissen sollten.
23 Dinge, die Sie über Software-Entwicklung in Teams wissen sollten.23 Dinge, die Sie über Software-Entwicklung in Teams wissen sollten.
23 Dinge, die Sie über Software-Entwicklung in Teams wissen sollten.
Stephan Schmidt
 
Die Kunst Des Software Design
Die Kunst Des Software DesignDie Kunst Des Software Design
Die Kunst Des Software Design
Stephan Schmidt
 
Software-Entwicklung Im Team
Software-Entwicklung Im TeamSoftware-Entwicklung Im Team
Software-Entwicklung Im Team
Stephan Schmidt
 
JSON-RPC Proxy Generation with PHP 5
JSON-RPC Proxy Generation with PHP 5JSON-RPC Proxy Generation with PHP 5
JSON-RPC Proxy Generation with PHP 5
Stephan Schmidt
 
Declarative Development Using Annotations In PHP
Declarative Development Using Annotations In PHPDeclarative Development Using Annotations In PHP
Declarative Development Using Annotations In PHP
Stephan Schmidt
 
XML-Socket-Server zur Kommunikation mit Flash
XML-Socket-Server zur Kommunikation mit FlashXML-Socket-Server zur Kommunikation mit Flash
XML-Socket-Server zur Kommunikation mit Flash
Stephan Schmidt
 
Interprozesskommunikation mit PHP
Interprozesskommunikation mit PHPInterprozesskommunikation mit PHP
Interprozesskommunikation mit PHP
Stephan Schmidt
 
PHP im High End
PHP im High EndPHP im High End
PHP im High End
Stephan Schmidt
 
Dynamische Websites mit XML
Dynamische Websites mit XMLDynamische Websites mit XML
Dynamische Websites mit XML
Stephan Schmidt
 
Web 2.0 Mit Der Yahoo User Interface Library
Web 2.0 Mit Der Yahoo User Interface LibraryWeb 2.0 Mit Der Yahoo User Interface Library
Web 2.0 Mit Der Yahoo User Interface Library
Stephan Schmidt
 
Das Web Wird Mobil - Geolocation und Location Based Services
Das Web Wird Mobil - Geolocation und Location Based ServicesDas Web Wird Mobil - Geolocation und Location Based Services
Das Web Wird Mobil - Geolocation und Location Based Services
Stephan Schmidt
 
23 Dinge, die Sie über Software Entwicklung in Teams wissen sollten
23 Dinge, die Sie über Software Entwicklung in Teams wissen sollten23 Dinge, die Sie über Software Entwicklung in Teams wissen sollten
23 Dinge, die Sie über Software Entwicklung in Teams wissen sollten
Stephan Schmidt
 
23 Dinge, die Sie über Software-Entwicklung in Teams wissen sollten
23 Dinge, die Sie über Software-Entwicklung in Teams wissen sollten23 Dinge, die Sie über Software-Entwicklung in Teams wissen sollten
23 Dinge, die Sie über Software-Entwicklung in Teams wissen sollten
Stephan Schmidt
 
Continuous Integration mit Jenkins
Continuous Integration mit JenkinsContinuous Integration mit Jenkins
Continuous Integration mit Jenkins
Stephan Schmidt
 
Die Kunst des Software Design - Java
Die Kunst des Software Design - JavaDie Kunst des Software Design - Java
Die Kunst des Software Design - Java
Stephan Schmidt
 
Der Erfolgreiche Programmierer
Der Erfolgreiche ProgrammiererDer Erfolgreiche Programmierer
Der Erfolgreiche Programmierer
Stephan Schmidt
 
23 Dinge, die Sie über Software-Entwicklung in Teams wissen sollten.
23 Dinge, die Sie über Software-Entwicklung in Teams wissen sollten.23 Dinge, die Sie über Software-Entwicklung in Teams wissen sollten.
23 Dinge, die Sie über Software-Entwicklung in Teams wissen sollten.
Stephan Schmidt
 
Die Kunst Des Software Design
Die Kunst Des Software DesignDie Kunst Des Software Design
Die Kunst Des Software Design
Stephan Schmidt
 
Software-Entwicklung Im Team
Software-Entwicklung Im TeamSoftware-Entwicklung Im Team
Software-Entwicklung Im Team
Stephan Schmidt
 
JSON-RPC Proxy Generation with PHP 5
JSON-RPC Proxy Generation with PHP 5JSON-RPC Proxy Generation with PHP 5
JSON-RPC Proxy Generation with PHP 5
Stephan Schmidt
 
Declarative Development Using Annotations In PHP
Declarative Development Using Annotations In PHPDeclarative Development Using Annotations In PHP
Declarative Development Using Annotations In PHP
Stephan Schmidt
 
XML-Socket-Server zur Kommunikation mit Flash
XML-Socket-Server zur Kommunikation mit FlashXML-Socket-Server zur Kommunikation mit Flash
XML-Socket-Server zur Kommunikation mit Flash
Stephan Schmidt
 
Interprozesskommunikation mit PHP
Interprozesskommunikation mit PHPInterprozesskommunikation mit PHP
Interprozesskommunikation mit PHP
Stephan Schmidt
 
Dynamische Websites mit XML
Dynamische Websites mit XMLDynamische Websites mit XML
Dynamische Websites mit XML
Stephan Schmidt
 
Web 2.0 Mit Der Yahoo User Interface Library
Web 2.0 Mit Der Yahoo User Interface LibraryWeb 2.0 Mit Der Yahoo User Interface Library
Web 2.0 Mit Der Yahoo User Interface Library
Stephan Schmidt
 
Ad

Recently uploaded (20)

2_English_Vocabulary_In_Use_Pre-Intermediate_Cambridge_-_Fourth_Edition (1).pdf
2_English_Vocabulary_In_Use_Pre-Intermediate_Cambridge_-_Fourth_Edition (1).pdf2_English_Vocabulary_In_Use_Pre-Intermediate_Cambridge_-_Fourth_Edition (1).pdf
2_English_Vocabulary_In_Use_Pre-Intermediate_Cambridge_-_Fourth_Edition (1).pdf
ThiNgc22
 
Cloud Stream Part II Mobile Hub V1 Hub Agency.pdf
Cloud Stream Part II Mobile Hub V1 Hub Agency.pdfCloud Stream Part II Mobile Hub V1 Hub Agency.pdf
Cloud Stream Part II Mobile Hub V1 Hub Agency.pdf
Brij Consulting, LLC
 
Freeze-Dried Fruit Powder Market Trends & Growth
Freeze-Dried Fruit Powder Market Trends & GrowthFreeze-Dried Fruit Powder Market Trends & Growth
Freeze-Dried Fruit Powder Market Trends & Growth
chanderdeepseoexpert
 
EquariusAI analytics for business water risk
EquariusAI analytics for business water riskEquariusAI analytics for business water risk
EquariusAI analytics for business water risk
Peter Adriaens
 
www.visualmedia.com digital markiting (1).pptx
www.visualmedia.com digital markiting (1).pptxwww.visualmedia.com digital markiting (1).pptx
www.visualmedia.com digital markiting (1).pptx
Davinder Singh
 
Treis & Friends One sheet - Portfolio IV
Treis & Friends One sheet - Portfolio IVTreis & Friends One sheet - Portfolio IV
Treis & Friends One sheet - Portfolio IV
aparicioregina7
 
Salesforce_Architecture_Diagramming_Workshop (1).pptx
Salesforce_Architecture_Diagramming_Workshop (1).pptxSalesforce_Architecture_Diagramming_Workshop (1).pptx
Salesforce_Architecture_Diagramming_Workshop (1).pptx
reinbauwens1
 
Avoiding the China Tariffs: Save Costs & Stay Competitive
Avoiding the China Tariffs: Save Costs & Stay CompetitiveAvoiding the China Tariffs: Save Costs & Stay Competitive
Avoiding the China Tariffs: Save Costs & Stay Competitive
NovaLink
 
The Rise of Payroll Outsourcing in the UK: Key Statistics for 2025
The Rise of Payroll Outsourcing in the UK: Key Statistics for 2025The Rise of Payroll Outsourcing in the UK: Key Statistics for 2025
The Rise of Payroll Outsourcing in the UK: Key Statistics for 2025
QX Accounting Services Ltd
 
Strategic Enterprise Management - Unit I.pptx
Strategic Enterprise Management - Unit I.pptxStrategic Enterprise Management - Unit I.pptx
Strategic Enterprise Management - Unit I.pptx
PrekshyaRana
 
NewBase 05 May 2025 Energy News issue - 1785 by Khaled Al Awadi_compressed.pdf
NewBase 05 May 2025  Energy News issue - 1785 by Khaled Al Awadi_compressed.pdfNewBase 05 May 2025  Energy News issue - 1785 by Khaled Al Awadi_compressed.pdf
NewBase 05 May 2025 Energy News issue - 1785 by Khaled Al Awadi_compressed.pdf
Khaled Al Awadi
 
Affinity.co Lifecycle Marketing Presentation
Affinity.co Lifecycle Marketing PresentationAffinity.co Lifecycle Marketing Presentation
Affinity.co Lifecycle Marketing Presentation
omiller199514
 
Influence of Career Development on Retention of Employees in Private Univers...
Influence of Career Development on Retention of  Employees in Private Univers...Influence of Career Development on Retention of  Employees in Private Univers...
Influence of Career Development on Retention of Employees in Private Univers...
publication11
 
Yuriy Chapran: Zero Trust and Beyond: OpenVPN’s Role in Next-Gen Network Secu...
Yuriy Chapran: Zero Trust and Beyond: OpenVPN’s Role in Next-Gen Network Secu...Yuriy Chapran: Zero Trust and Beyond: OpenVPN’s Role in Next-Gen Network Secu...
Yuriy Chapran: Zero Trust and Beyond: OpenVPN’s Role in Next-Gen Network Secu...
Lviv Startup Club
 
intra-mart Accel series 2025 Spring updates-en.ppt
intra-mart Accel series 2025 Spring updates-en.pptintra-mart Accel series 2025 Spring updates-en.ppt
intra-mart Accel series 2025 Spring updates-en.ppt
NTTDATA INTRAMART
 
The Peter Cowley Entrepreneurship Event Master 30th.pdf
The Peter Cowley Entrepreneurship Event Master 30th.pdfThe Peter Cowley Entrepreneurship Event Master 30th.pdf
The Peter Cowley Entrepreneurship Event Master 30th.pdf
Richard Lucas
 
Alec Lawler - A Passion For Building Brand Awareness
Alec Lawler - A Passion For Building Brand AwarenessAlec Lawler - A Passion For Building Brand Awareness
Alec Lawler - A Passion For Building Brand Awareness
Alec Lawler
 
AlaskaSilver Corporate Presentation Apr 28 2025.pdf
AlaskaSilver Corporate Presentation Apr 28 2025.pdfAlaskaSilver Corporate Presentation Apr 28 2025.pdf
AlaskaSilver Corporate Presentation Apr 28 2025.pdf
Western Alaska Minerals Corp.
 
Web Design Creating User-Friendly and Visually Engaging Websites - April 2025...
Web Design Creating User-Friendly and Visually Engaging Websites - April 2025...Web Design Creating User-Friendly and Visually Engaging Websites - April 2025...
Web Design Creating User-Friendly and Visually Engaging Websites - April 2025...
TheoRuby
 
TMG - Q3 2025 Earnings Call Slides - v4.pptx
TMG - Q3 2025 Earnings Call Slides - v4.pptxTMG - Q3 2025 Earnings Call Slides - v4.pptx
TMG - Q3 2025 Earnings Call Slides - v4.pptx
Marketing847413
 
2_English_Vocabulary_In_Use_Pre-Intermediate_Cambridge_-_Fourth_Edition (1).pdf
2_English_Vocabulary_In_Use_Pre-Intermediate_Cambridge_-_Fourth_Edition (1).pdf2_English_Vocabulary_In_Use_Pre-Intermediate_Cambridge_-_Fourth_Edition (1).pdf
2_English_Vocabulary_In_Use_Pre-Intermediate_Cambridge_-_Fourth_Edition (1).pdf
ThiNgc22
 
Cloud Stream Part II Mobile Hub V1 Hub Agency.pdf
Cloud Stream Part II Mobile Hub V1 Hub Agency.pdfCloud Stream Part II Mobile Hub V1 Hub Agency.pdf
Cloud Stream Part II Mobile Hub V1 Hub Agency.pdf
Brij Consulting, LLC
 
Freeze-Dried Fruit Powder Market Trends & Growth
Freeze-Dried Fruit Powder Market Trends & GrowthFreeze-Dried Fruit Powder Market Trends & Growth
Freeze-Dried Fruit Powder Market Trends & Growth
chanderdeepseoexpert
 
EquariusAI analytics for business water risk
EquariusAI analytics for business water riskEquariusAI analytics for business water risk
EquariusAI analytics for business water risk
Peter Adriaens
 
www.visualmedia.com digital markiting (1).pptx
www.visualmedia.com digital markiting (1).pptxwww.visualmedia.com digital markiting (1).pptx
www.visualmedia.com digital markiting (1).pptx
Davinder Singh
 
Treis & Friends One sheet - Portfolio IV
Treis & Friends One sheet - Portfolio IVTreis & Friends One sheet - Portfolio IV
Treis & Friends One sheet - Portfolio IV
aparicioregina7
 
Salesforce_Architecture_Diagramming_Workshop (1).pptx
Salesforce_Architecture_Diagramming_Workshop (1).pptxSalesforce_Architecture_Diagramming_Workshop (1).pptx
Salesforce_Architecture_Diagramming_Workshop (1).pptx
reinbauwens1
 
Avoiding the China Tariffs: Save Costs & Stay Competitive
Avoiding the China Tariffs: Save Costs & Stay CompetitiveAvoiding the China Tariffs: Save Costs & Stay Competitive
Avoiding the China Tariffs: Save Costs & Stay Competitive
NovaLink
 
The Rise of Payroll Outsourcing in the UK: Key Statistics for 2025
The Rise of Payroll Outsourcing in the UK: Key Statistics for 2025The Rise of Payroll Outsourcing in the UK: Key Statistics for 2025
The Rise of Payroll Outsourcing in the UK: Key Statistics for 2025
QX Accounting Services Ltd
 
Strategic Enterprise Management - Unit I.pptx
Strategic Enterprise Management - Unit I.pptxStrategic Enterprise Management - Unit I.pptx
Strategic Enterprise Management - Unit I.pptx
PrekshyaRana
 
NewBase 05 May 2025 Energy News issue - 1785 by Khaled Al Awadi_compressed.pdf
NewBase 05 May 2025  Energy News issue - 1785 by Khaled Al Awadi_compressed.pdfNewBase 05 May 2025  Energy News issue - 1785 by Khaled Al Awadi_compressed.pdf
NewBase 05 May 2025 Energy News issue - 1785 by Khaled Al Awadi_compressed.pdf
Khaled Al Awadi
 
Affinity.co Lifecycle Marketing Presentation
Affinity.co Lifecycle Marketing PresentationAffinity.co Lifecycle Marketing Presentation
Affinity.co Lifecycle Marketing Presentation
omiller199514
 
Influence of Career Development on Retention of Employees in Private Univers...
Influence of Career Development on Retention of  Employees in Private Univers...Influence of Career Development on Retention of  Employees in Private Univers...
Influence of Career Development on Retention of Employees in Private Univers...
publication11
 
Yuriy Chapran: Zero Trust and Beyond: OpenVPN’s Role in Next-Gen Network Secu...
Yuriy Chapran: Zero Trust and Beyond: OpenVPN’s Role in Next-Gen Network Secu...Yuriy Chapran: Zero Trust and Beyond: OpenVPN’s Role in Next-Gen Network Secu...
Yuriy Chapran: Zero Trust and Beyond: OpenVPN’s Role in Next-Gen Network Secu...
Lviv Startup Club
 
intra-mart Accel series 2025 Spring updates-en.ppt
intra-mart Accel series 2025 Spring updates-en.pptintra-mart Accel series 2025 Spring updates-en.ppt
intra-mart Accel series 2025 Spring updates-en.ppt
NTTDATA INTRAMART
 
The Peter Cowley Entrepreneurship Event Master 30th.pdf
The Peter Cowley Entrepreneurship Event Master 30th.pdfThe Peter Cowley Entrepreneurship Event Master 30th.pdf
The Peter Cowley Entrepreneurship Event Master 30th.pdf
Richard Lucas
 
Alec Lawler - A Passion For Building Brand Awareness
Alec Lawler - A Passion For Building Brand AwarenessAlec Lawler - A Passion For Building Brand Awareness
Alec Lawler - A Passion For Building Brand Awareness
Alec Lawler
 
Web Design Creating User-Friendly and Visually Engaging Websites - April 2025...
Web Design Creating User-Friendly and Visually Engaging Websites - April 2025...Web Design Creating User-Friendly and Visually Engaging Websites - April 2025...
Web Design Creating User-Friendly and Visually Engaging Websites - April 2025...
TheoRuby
 
TMG - Q3 2025 Earnings Call Slides - v4.pptx
TMG - Q3 2025 Earnings Call Slides - v4.pptxTMG - Q3 2025 Earnings Call Slides - v4.pptx
TMG - Q3 2025 Earnings Call Slides - v4.pptx
Marketing847413
 

Session Server - Maintaing State between several Servers

  • 1. SessionServer :: Maintaining state between several servers Stephan Schmidt 1&1 Internet AG
  • 2. Agenda The need for a session server ext/sockets and ext/pcntl Using Net_Server Designing a protocol Architecture of HTTP_SessionServer Building a client Integrating the built-in session functions The future
  • 3. Why Sessions? HTTP is stateless Requests operate in a sandbox Two requests of the same user may be handled by different apache processes Modern applications require a state Authentication Shopping carts User tracking
  • 4. PHP sessions Built-in functions since PHP4 Data associated with a user is stored on the server Unique Session-Id for each active user, passed between requests Stores data on the filesystem (other containers are possible) Shared Memory Database
  • 5. Disadvantages Data is stored on the web server only accessible via PHP only accessible from this server applications must run on this server no clusters size may be limited (size of /tmp or shared memory segment)
  • 6. The Solution Store session data in one central location accessible from any server accessible by any application accessible by any programming language no overhead (like when using a RDBMS or web service) access must be simple
  • 7. Session Server Stores key value pairs for sessions Daemon that is awaiting connections may be accessed using fsockopen(), fwrite() and fread() very simple protocol Store data on the filesystem, just like PHP's session functions, but need not be on the webserver
  • 8. Building a server with PHP ext/sockets allows you to create daemons: $fd = socket_create( AF_INET, SOCK_STREAM, SOL_TCP ); if(!is_resource($fd)) { die('Could not create socket.'); } socket_bind( $fd, 'localhost', 9090 ); socket_listen( $fd, 10 ); $newFd = socket_accept( $fd ); $text = &quot;Hello world!\n&quot;; socket_write( $newFd, $text, strlen( $text ) ); socket_close($newFd); socket_close($fd);
  • 9. Building a server with PHP (2) run this script in with PHP-CLI $ php myServer.php open a new terminal and execute $ telnet localhost 9090 schst@rot3:schst> telnet localhost 9090 Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. Hello world! Connection closed by foreign host. schst@rot3:schst>
  • 10. Building a server with PHP (3) ext/sockets provides more functions receive data from client using socket_read() set options get information about the client socket_accept() halts script execution Limited to one connection at a time May keep more than one connection open using socket_select() but still sequential
  • 11. Making use of ext/pcntl Implements the Unix style of process creation signal handling process termination That means current process can be copied at runtime parent-process may stop children Not available on Windows
  • 12. Making use of ext/pcntl (2) $children = 5; for ($i=1; $i<=$children; $i++) { $pid = pcntl_fork(); if ($pid === -1) { exit('Could not fork child.'); } elseif ($pid) { continue; } else { printf(&quot;new process created: %s\n&quot;,getmypid()); break; } } // do not exit while(true) { sleep(5); }
  • 13. Making use of ext/pcntl (3) pcntl_fork() forks process and returns new process id If pcntl_fork() returns '0' (zero), current process is the child If master-process is stopped, all children are stopped as well Child-Processes may be stopped without stopping the parent
  • 14. Making use of ext/pcntl (4) run this script in with PHP-CLI $ php myFork.php schst@rot3:schst> php5 myFork.php new process created: 30923 new process created: 30924 new process created: 30925 new process created: 30926 new process created: 30927
  • 15. Making use of ext/pcntl (5) Take a look at the processes $ ps fax | grep myFork schst@rot3:schst> ps fax | grep myFork 30922 pts/0 S+ 0:00 | \_ php5 myFork.php 30923 pts/0 S+ 0:00 | \_ php5 myFork.php 30924 pts/0 S+ 0:00 | \_ php5 myFork.php 30925 pts/0 S+ 0:00 | \_ php5 myFork.php 30926 pts/0 S+ 0:00 | \_ php5 myFork.php 30927 pts/0 S+ 0:00 | \_ php5 myFork.php Kill one process $ kill 30923
  • 16. Confused by low-level code? Use PEAR::Net_Server! Provides generic server class. Has support for pcntl_fork() Triggers callbacks on events New client connects Client sends data Client disconnects …
  • 17. Using Net_Server class Net_Server_Handler_Talkback extends Net_Server_Handler { function onConnect($clientId = 0) { $this->_server->sendData($clientId,&quot;Welcome to my server\n&quot;); } function onReceiveData($clientId = 0, $data = '') { $this->_server->sendData($clientId, &quot;You said: $data&quot;); } } $server = &Net_Server::create('Fork', 'localhost', 9090); $handler = &new Net_Server_Handler_Talkback; $server->setCallbackObject($handler); $server->start();
  • 18. Using Net_Server (2) run this script with PHP-CLI $ php myServer2.php schst@rot3:schst> php5 myServer2.php PEAR constructor called, class=Net_Server_Driver_Fork … 14:30:44 Listening on port 9090. Server started at 14:30:44 … 14:30:50 New co…on from 127.0.0.1 on port 52237, new pid: 31241 … 14:30:50 sending: &quot;Welcome to my server&quot; to: 127.0.0.1:52237 (pid: 31241) … 14:30:53 Received Foo from 127.0.0.1:52237 (pid: 31241) … 14:30:53 sending: &quot;You said: Foo&quot; to: 127.0.0.1:52237 (pid: 31241)
  • 19. Building a Session Daemon Define a protocol create new session open existing session store value retrieve value some additional commands Implement a callback object start the Net_Server object
  • 20. HTTP_SessionServer Out-of-the-box solution available in PEAR require_once 'HTTP/SessionServer.php'; $options = array( 'save_path' => '/tmp' ); $server = &new HTTP_SessionServer('Filesystem', $options); $server->service('localhost', 9090); Uses Net_Server with 'Fork' driver requires ext/pcntl, does not work on windows Provides a client as well
  • 21. The Protocol Currently supports 13 commands: new, open, close, commit, destroy get, put, exists, remove, get_all, put_all, keys regenerate_id Structure of a command: command arg1 arg2 … Session-Id is stored after executing open or new (keeps the payload smaller)
  • 22. The Protocol (2) Server sends ok or err to indicate success or failure, followed by actual result, e.g. err unknown command Data will be UTF-8 encoded enough theory, example coming up…
  • 23. The protocol (3) schst@rot3:schst> telnet localhost 9090 Trying 127.0.0.1... Connected to localhost. new ok 8087127fe6cf50e89932dbf0ee8d4855 put foo bar ok put today 2004-11-09 ok keys ok foo|today get today ok 2004-11-09 close ok get foo err No session opened.
  • 24. Features Different storage containers possible Open a session in read-only-mode Auto-lock a session in write-mode change mode from &quot;write&quot; to &quot;read&quot; (commit) Change the session-Id while keeping the data (for security reasons) easily extendible
  • 25. Architecture of the server Net_Server HTTP_Session_Server Storage_Filesystem Custom Storage Client Client Client Client Calls onDataReceived Parses data and calls methods on storage Serializes return values
  • 26. Extending SessionServer Write a new storage container In most cases open(), close(), destroy() and commit() are enough Shared Memory, RDBMS, etc. Implement new commands Extend HTTP_SessionServer Implement _cmd[CommandName] method return an array
  • 27. Building a client Using fsockopen() $fp = fsockopen('localhost', 9090); fputs($fp, &quot;new\r\n&quot;); $result = fgets($fp, 4096); fclose($fp); Using PEAR::Net_Socket $socket = &new Net_Socket(); $socket->connect('localhost', 9090); $socket->writeLine('new'); $result = $socket->readLine(); $socket->disconnect();
  • 28. Don't worry: Client included Based on PEAR::Net_Socket Very easy-to-use OO-Interface to HTTP_SessionServer Implements all supported commands Returns PEAR_Error objects on error Automatically disconnects the socket
  • 29. Client example require_once 'HTTP/SessionServer/Client.php'; $session = &new HTTP_SessionServer_Client('localhost', 9090); $id = $session->create(); $session->put('time', time()); $session->put('foo', 'bar'); $keys = $session->getKeys(); $session->close(); $session2 = &new HTTP_SessionServer_Client('localhost', 9090); $session->open($id, 'r'); $time = $session2->get('time'); $session2->close();
  • 30. Setting a session save handler session_set_save_handler ( string open, string close, string read, string write, string destroy, string gc) Allows you to replace the storage module for internal session functions register callbacks to open,read, write, close and destroy session data
  • 31. Replacing built-in session handling HTTP_SessionServer provides needed callbacks use session_save_path() to specify host and port No other changes needed require_once 'HTTP/SessionServer/SaveHandler.php'; session_save_path('localhost:9090'); session_start();
  • 32. The future Work on PHP5 version using stream_socket_server() Implement missing features garbage collection session lifetime Implement a session storage module in C to improve performance Implement more storage containers
  • 33. What about msession? msession is a daemon written in C similar to HTTP_SessionServer PHP-Extension is available More information at: http://devel.mohawksoft.com/msession.html
  • 34. The End Thanks for your attention. [email_address] http://www.php-tools.net