1 / 32

Designing Web Applications in PHP

Designing Web Applications in PHP. Martin Kruli š. Web Application Architectures. Traditional Web Applications. HTTP request. / var /www/ myweb /. `. mod_php. Internet. i ndex.php. Client. Web Server. HTTP response with contents generated by a PHP script. Database.

masongary
Download Presentation

Designing Web Applications in PHP

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Designing Web Applications in PHP Martin Kruliš by Martin Kruliš (v1.2)

  2. Web Application Architectures • Traditional Web Applications HTTP request /var/www/myweb/ ` mod_php Internet index.php Client Web Server HTTP response with contents generated by a PHP script Database by Martin Kruliš (v1.2)

  3. Web Application Architectures • Single Page Applications (SPA) Internet Browser downloads static content (HTML, JS, …) Client AJAX, WebSockets, … Web Server ajax.php HTML document and scripts by Martin Kruliš (v1.2)

  4. Web Application Architectures • Other Shades of Grey • Traditional Applications with AJAX • Isolated operations are handled directly in the browser • Form validationand autocomplete • Paginated view for long repetitive content (tables) • Simple single-click operations (e.g., deleting a record) • Multiple Connected SPAs • Integrating multiple SPA into one larger application which share the user session • Typically used when a larger project is created as a composition of independent smaller projects by Martin Kruliš (v1.2)

  5. Traditional Web Applications • Expressing UI in the Browser • Browser was originally designed as a viewer for static contents (HTML pages) • Hyperlinks as controls • Leading to the same page with different query params • Changing application state of requires HTTP request • Only the view state can be changed (HTTP GET request) • Forms • Smarter forms of hyperlinks (e.g., filter form) • Can use POST request to insert/update/delete data at server side • Single-button forms (like hyperlinks for POST actions) by Martin Kruliš (v1.2)

  6. HTTP Wrapper (Revision) • Request • Automatically parsed into superglobal arrays • $_GET – parameters from request URL • $_POST – parameters posted in HTTP body (form data) • $_FILES – records about uploaded files • $_SERVER – server settings and request headers • $_ENV – environment variables • Response • Script output is included in body of the response • Headers may be modified by a function • header('header-line'); by Martin Kruliš (v1.2)

  7. Dealing with Statelessness • HTTP Is Stateless • Applications require state (logged in user, contents ofa shopping cart, currently selected page, …) Client Side Server Side Sessions Passing onparameters in URL Temporary JS, web storage Database, Files, … Cookies Persistent by Martin Kruliš (v1.2)

  8. Dealing with Statelessness • Passing on URL Parameters • URL query parameters are not automatically kept • Must be manually added to all generated URLs • Hyperlinks, form action fields, redirects, … • Such a task is quite tedious and error prone • Use a framework/function for generating URLs • Automatically adds (sanitized) parameters from $_GET • Or more likely from an object which manages the params. • Other smart features can be added • Removing defaults, merging values, … Example 1 by Martin Kruliš (v1.2)

  9. Dealing with Statelessness • Cookies (Revision) • A way to deal with stateless nature of the HTTP • Key-value pairs (of strings) stored in the web browser • Set by special HTTP response header • Automatically re-sent in headers with every request • Each page (domain) has it own set of cookies • Cookies in PHP • Cookies sent by browser are loaded to $_COOKIE[] • Cookies are set/modified/removed by setcookie() • The function modifies HTTP response headers by Martin Kruliš (v1.2)

  10. Dealing with Statelessness • Session • Identification of a client over multiple HTTP req. • Essential when user authentication is required • Session ID must be kept at both client and server • Client – in URL query parameters or in cookies • Server – special storage with additional associated data • Session Hijacking • One of the greatest security concerns of web apps. • HTTPS must be used when session is maintained • ID must be sufficiently long (hundreds of bits) and regenerated periodically by Martin Kruliš (v1.2)

  11. PHP Session API • Opening Session • Simple call to session_start() method • Checks $_COOKIE and $_GET arrays for PHPSESSID variable which should have the ID • If the variable is missing, new session is started • And a cookie with the new ID is set (if php.ini says so) • Accessing Session Data • In the $_SESSION global array • It can be read and written (incl. unset() on items) by Martin Kruliš (v1.2)

  12. PHP Session API • Removing the Session • session_unset() – clears the session (keeps the ID) • session_destroy() – invalidates the session ID • Others • session_name() – gets/sets name of the variable for the session ID (PHPSESSID by default) • session_id() – get/sets current session ID • session_regenerate_id() – generate a new ID • session_cache_expire(time) – sets time (in minutes) after which the session expires if not used Example 2 by Martin Kruliš (v1.2)

  13. PHP Session API • Session Internals • Sessions are saved to files by default • Can lead to race conditions in some special cases • Optionally SQLite or memcache can be used(configured by session.save_handler in php.ini) • SessionHandlerInterface • Specifies methods for session saving, loading, … • open(), close(), read(), write(), destroy(), gc(), create_sid() • Implemented by SessionHandler class • Performs the saving according to php.ini • session_set_save_handler($handlerObj) Example 3 by Martin Kruliš (v1.2)

  14. Dealing with Statelessness • Where to put which parameters? • URL query ($_GET) • Short term parameters (“changed” by hyperlinks) • Parameters affecting visualization (paging, filters, …) • Parameters that can be (effectively) bookmarked • Session ($_SESSION), or possibly database • Parameters changed only on POST requests • User-related parameters (identity, shopping cart, …) • Parameters that should not be “visible” in URL • Cookies ($_COOKIE) • Long term parameters (lasting between sessions) • User identification, security tokens by Martin Kruliš (v1.2)

  15. Forms • Study Case – Editing Form • Edit personal data of existing user <formaction="?" method="POST"> Full Name:<input name="fullname" type="text" value="Martin Kruliš"> DateofBirth: <input name="born" type="date" value="14.4.1984"> Married:<input name="married" type="checkbox" checked> Children:<input name="children" type="number" value="1"> <input type="submit" value="Save"> </form> Various data types (string, date, bool, and integer respectively) by Martin Kruliš (v1.2)

  16. Forms • Study Case – Editing Form • Major concerns • Appropriate mapping between HTML form and PHP script processing its POST request • Item names, types, … • Data are transferred as strings (no matter orig. type) • Two level sanitization (client side, server side) • What to do when the server side validation fails • Data has to be loaded from the database (existing user) • Mapping DB object data to form elements • Some data may not be editable by the form • Which data to show when the server side validation failed and the form is being re-shown with errors by Martin Kruliš (v1.2)

  17. Redirect Revision • Redirect (303 See Other) after POST add/change something GET (new URL) POST Request Redirects to a new URL(without updating history) Client(Browser) Redirect (new URL) HTML Page Web Server read-only Refresh by Martin Kruliš (v1.2)

  18. Forms • Study Case – Editing Form • Form Component • Each form is represented by one object • Responsible for rendering and HTTP data processing • And handling the serialization or data conversions • Sticky Forms • Form remembers user inputs even if they are incorrect • I.e., even if a result was not saved to the database and the form needs to allow the user fix the input mistakes • Data are stored in a session • Additional identifier is required that is passed to the URL query parameters (in case multiple windows are opened) Example 4 by Martin Kruliš (v1.2)

  19. Flash Messages • Study Case – Flash Messages • Notifications that should appear exactly once • E.g., “the data were saved”, “the e-mail was sent”, … • Non-persistent error messages • Where to put the text (or ID) of such message, if… • The message should not get lost nor it should be displayed long after the operation is finished • The user may click refresh button • The user may use back/forward buttons • The user may copy/bookmark the URL • The HTTP request may be interrupted and refreshed by Martin Kruliš (v1.2)

  20. Web Application Design • Front Controller • Software design pattern that provides centralized entry point for all request (commands) • All URLs point to the same script • Actual action is determined from URL query parameters Action Initializing the libraries, setting up components Controller/Presenter … Action … Front Controller (index.php) HTTP Routing and dispatching Controller/Presenter by Martin Kruliš (v1.2)

  21. Web Application Design • Model-View-Controller • Design pattern that clearly divides responsibilities Handles business logic. Action of the controller is invoked by dispatcher Encapsulates data loading and data manipulation (e.g., in a database) Controller Manipulates Prepares Loads data from View Model Responsible for formatting (presenting) data in HTML (JSON, XML, …) by Martin Kruliš (v1.2)

  22. Web Application Design • Model-View-Presenter • A derivation of MVC pattern • Presenter have similar role as controller • Presenter strictly separates model and view • View should no longer access model directly • Data from model are passed to view by presenter Send events Updates View Presenter Model Prepares Send data by Martin Kruliš (v1.2)

  23. Views • Templates • Libraries that help with formatting the data (HTML) • Simplifying syntax (abstracting from low level PHP) • Providing additional functions for formatting • Date, time, currency, … • Handling data sanitization (preventing script injection) • Handling language translations • The controller/presenter prepares the data for the view and the view fills them into the template • Many approaches to templating exist • Simple frameworks rely on PHP-HTML interleaving, complex ones use their own syntax and preprocessing by Martin Kruliš (v1.2)

  24. Views • Latte Templates Example <h1 n:block=title>Latte Example</h1> <uln:if="$items"> <li n:foreach="$items as $item">{$item|capitalize}</li> </ul> {if ($user)} <h2>User {$user->login}</h2> Name: {$user->name} Home page: <a n:href="$user->homepage">{$user->homepage}</a> {/if} The same text will appear in the title of the page If and foreach are translated in PHP structures Value filtering Alternative syntax for if statement Context-aware escaping by Martin Kruliš (v1.2)

  25. Controller/Presenter • Controller/Presenter • One class that represents one (logical) page • Multiple actions • Each action is a method • Rendering actions • Initialize a template, produce HTML (JSON, XML, …) • Other actions (POST actions) • Update model and respond with redirect • Careful when using POST actions for AJAX calls • Naming convention for classes and methods • Has to reflect routing protocol by Martin Kruliš (v1.2)

  26. Security • Authentication • Verifies identity of a user • E.g., by user credentials, by a certificate, … • User identity must be held despite statelessness • In a (secured) session, in a cookie, … • Password security • Password should not be stored in plain text nor in decryptable form in the database, but rather hashed • <salt>,hashfnc(<salt>,<password>) • The hashfnc could be SHA-256, SHA-512, bcrypt, scrypt, … • PHP has built-in functions for password hashing • crypt(), password_hash(), password_verify() old by Martin Kruliš (v1.2)

  27. HTTP Authentication • Authentication Embedded in HTTP • If the auth. information are provided, they are in • $_SERVER['PHP_AUTH_USER'] • $_SERVER['PHP_AUTH_PW'] • The script can request authentication data header('WWW-Authenticate: Basic realm="Auth test"'); header('HTTP/1.0 401 Unauthorized'); exit; • Potential problems • Password is sent with every request • Logout operation is not very well defined by Martin Kruliš (v1.2)

  28. Security Tokens • Authentication/Access Tokens • Generated once the user is authenticated • Does not have to be private • Server can verify them (e.g., using cryptography) • For instance, a security token can be • user_id:salt:hash(user_id:salt:secret) • Where secret is known only to the server • JSON Web Tokens (JWT) RFC 7519 • Standard for implementing access tokens • Data are base64 encoded JSON • HMAC SHA256 is used for signature Crypto. hash is the signature Example by Martin Kruliš (v1.2)

  29. Authorization • Authorization • Process of verification access rights of the user • Security Model • Defines protected objects, authorities, operations • Simple (state-less) models • Function (object, authority, operation) -> yes/no • More complex models exist • Typically implemented in one class (component) • Roles • Authorities are typically not individual users, but roles • Each user have one (or multiple) roles by Martin Kruliš (v1.2)

  30. Authorization • Security Models Examples • Directory (Capability List) • Authorities have lists of accessible objects • Access List • Protected objects have lists of users (+permissions) • Access Control Matrix • Rows ~ authorities, cols ~ objects, items ~ access rights • Bell-La Padula • Each authority has maximal level of access, each object has minimal required level of access by Martin Kruliš (v1.2)

  31. Authorization • Access Control List (ACL) Example authorizator: setup: - addRole('user') - addRole('editor', 'user') - addRole('admin', 'editor') - addResource('Homepage') - addResource('Archive') - addResource('Users') - allow('user', 'Homepage', 'default') - allow('user', 'Archive', 'default') - allow('user', 'Users', 'default') - allow('user', 'Users', 'show') - allow('editor', 'Users', 'show-private') - allow('editor', 'Archive', 'create') - allow('editor', 'Archive', 'edit') - allow('editor', 'Archive', 'delete') - allow('admin') Authorities (roles) Protected objects (resources) corresponds to controllers here List of all access privileges (what is not explicitly allowed, is denied) Admin is allowed everything by Martin Kruliš (v1.2)

  32. Discussion by Martin Kruliš (v1.2)

More Related