WEB APPLICATIONS IN PHP

WEB APPLICATIONS IN PHP
Slide Note
Embed
Share

This presentation covers various aspects of developing web applications in PHP, focusing on HTTP wrappers, data verification, input verification, output sanitization, and formatted data URL handling. It delves into topics such as handling HTTP requests, preparing data in superglobal arrays, verifying and sanitizing user input, and ensuring secure output. The content emphasizes best practices and automated solutions for building robust PHP web applications.

  • PHP
  • Web Applications
  • HTTP Protocols
  • Data Security
  • Superglobal Arrays

Uploaded on Feb 22, 2025 | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.

E N D

Presentation Transcript


  1. WEB APPLICATIONS IN PHP 22.02.2025 by koda Petr (v1.0) https://www.ksi.mff.cuni.cz/ special thanks to Martin Kruli

  2. 2 HTTP WRAPPER - REVISION HTTP Request Wrapper Data are automatically prepared in 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 HTTP Response Script output is the response (echo ) Return code can be set by http_response_code() Headers can be modified by a function header('header-line')

  3. 3 HTTP WRAPPER - REVISION Decoded to the $_SERVER array REQUEST_METHOD used method ( GET or POST ) SERVER_PROTOCOL protocol version ( HTTP/1.1 ) REQUEST_URI request part of URL ( /index.php ) REMOTE_ADDR clients IP address HTTP_ACCEPT MIME types that the client accepts HTTP_ACCEPT_LANGUAGE desired translation HTTP_ACCEPT_ENCODING desired encodings HTTP_ACCEPT_CHARSET desired charsets + more info about the server and the client s browser

  4. 4 DATA VERIFICATION/SANITIZATION What? Everything that possibly comes from users: $_GET, $_POST, $_COOKIE, Data that comes from external sources (database, text files, ) When? On input verify correctness Before you start using data in $_GET, $_POST, On output sanitize to prevent injections When data are inserted into HTML, SQL queries,

  5. 5 INPUT VERIFICATION How to Verify Built-in string functions, regular expressions, Filter functions filter_input(), filter_var(), Safely retrieves $_GET['foo'] $foo = filter_input(INPUT_GET, 'foo', FILTER_VALIDATE_INT, $options); Invalid Inputs Ostrich algorithm Attempt to fix (e.g., select a valid part) User error Additional options based on input type (default, range )

  6. 6 OUTPUT SANITIZATION Making sure the output matches target context Automated solutions are preferred How? String and filter functions, regular expressions htmlspecialchars() encoding for HTML urlencode() encoding for URL DBMS-specific functions (mysqli_escape_string()) Better yet, use prepared statements

  7. 7 FORMATTED DATA URL Handling http_build_query() construct URL query string parse_url() Base64 Encode (any) data into text-safe form (6-bits/char) base64_encode(), base64_decode() Not entirely safe for URL though JSON json_encode(), json_decode(), json_last_error() Lists are arrays, collections are stdClass objects

  8. 8 SELECT YOUR CHARSET One Charset to Rule Them All HTML, PHP, database (connection), text files, Determined by the language(s) used Unicode covers almost every language Early incoming, late outgoing conversions Charset in Meta-data Must be in HTTP headers header('Content-Type: text/html; charset=utf-8'); Do not use HTML meta element with http-equiv Except special cases (like saving HTML file locally)

  9. 9 HTTP WRAPPER FILE UPLOADS In form as <input type="file" name=... /> Provide safe way to browse disk files and select one for upload HTTP wrapper handles the file Stores it in temporary location Related metadata are in $_FILES[name] 'tmp_name path to the file in temp directory 'error error code (e.g., UPLOAD_ERR_OK) 'name', 'type', 'size', File exists only as long as the script runs is_uploaded_file() verification move_uploaded_file() a safe way to move files

  10. 10 FILE UPLOAD EXAMPLE <form action="..." method="post" enctype="multipart/form-data"> <input type="file" name="newfile"> </form> Necessary for file upload if ($_SERVER['REQUEST_METHOD'] == 'POST') { if (!empty($_FILES['newfile'])) { if ($_FILES['newfile']['error'] != UPLOAD_ERR_OK) { // Show error message ... } if (!move_uploaded_file($_FILES['newfile']['tmp_name'], 'upload/' . $_FILES['newfile']['name'])) { // Show error message ... } } move an uploaded file $_FILES holds the metadata Path to temporary storage Original file name The uploaded file size is limited! (in php.ini settings) Safe way how to

  11. 11 RAW REQUEST BODY In case the data are sent in special format (e.g., JSON) For other HTTP methods (e.g., PUT) Read-only stream php://input $body = file_get_contents('php://input'); There are other streams worth mentioning php://output php://stdin, php://stdout, php://stderr php://memory, php://temp

  12. 12 POST REQUEST PROCESSING POST Request (a submitted form) Again!!! add/change something Refresh script +read data (create HTML) Client (Browser) Web Server Response (a HTML page)

  13. 13 POST REQUEST PROCESSING Redirect Mechanism in HTTP 3xx response code 301 Moved Permanently 302 Found (originally named Moved Temporarily) 303 See Other Additional header 'Location' has the new URL Browser must try to load the new URL (using GET method) Loops in redirections are detected Creating Redirect in PHP header("Location: my-new-url"); Automatically changes the response code (to 302)

  14. 14 POST REQUEST PROCESSING action.php add/change something POST Request (action.php) Redirect (to index.php) Redirects to a new URL (without updating history) Client (Browser) GET (index.php) Web Server index.php generate HTML (only reads DB) Refresh HTML Page

  15. 15 DEMO Form Submit with Redirect

  16. SESSION MANAGEMENT

  17. 17 SESSION MANAGEMENT Managing User Session Data Intermediate state (not persisted) User identity (after authentication) Work in progress (e.g., a shopping cart) HTTP is stateless Cookies PHP session API Cryptographic approach Security tokens (public data, but digitally signed)

  18. 18 SESSION MANAGEMENT COOKIES 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 are set/modified/removed by setcookie() The function modifies HTTP response headers Cookies sent by browser are loaded to $_COOKIE[]

  19. 19 SESSION MANAGEMENT USING COOKIES FOR AUTHENTICATION Verifies credentials Generates random token and pair it with the user POST (credentials) Saves the cookie Set cookie (user: token) Client (Browser) Database Cookie (user: token) Web Server Resends the cookie with every other request Page with private contents Finds/verifies user (by) token

  20. 20 SESSION MANAGEMENT PHP Session API 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 Automatically loaded when the session is opened and serialized (saved) at the end of the script It can be read and written (incl. unset() on items)

  21. 21 DEMO Sessions

  22. 22 SESSION MANAGEMENT COOKIES [CS] Od 1. ledna vejdou v platnost nov pravidla pro sb r n cookies The General Data Privacy Regulation (GDPR) in the European Union The ePrivacy Directive in the EU The California Consumer Privacy Act https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookiest Set-Cookie: id=a3fWa; Expires=Thu, 21 Oct 2021 07:28:00 GMT; Secure; HttpOnly; SameSite=Strict Expire is relative to the time it was set not the server time. Is only sent to the server with an encrypted request over the HTTPS protocol. Specify whether/when cookies are sent with cross-site requests. A cookie is inaccessible to the JavaScript Document.cookie API; it's only sent to the server.

  23. 23 SESSION MANAGEMENT SECURITY TOKENS Can be generated/verified only at server Has public payload that holds important data E.g., user identity, expiration time, Digitally signed using crypto hash functions payload:salt:hash(payload:salt:secret) Stored only at client side (unlike session IDs) But they can be stolen the same Complicated invalidation See JSON Web Tokens (JWT) for example

  24. DATABASES - MYSQL

  25. 25 MYSQL Original mysql API is deprecated (as of PHP 5.5) MySQL Improved (mysqli) API Dual object/procedural interface Procedural interface is similar to original (deprecated) API Advanced connectivity features Persistent connections, compression, encryption Directly supports transactions MySQL Native Driver (mysqlnd) extension More direct access to MySQL server Additional features (e.g., asynchronous queries)

  26. 26 MYSQLI PROCEDURAL API Establishing connection with MySQL server $mysqli = mysqli_connect("server", "login", "password", "db_name"); Performing queries $res = $mysqli->query( SELECT "); Safe way to include strings in SQL query mysqli_real_escape_string($mysqli, $str); Terminating connection $mysqli->close();

  27. 27 MYSQL RESULTS mysqli::query() result depends on the query type On failure always returns false Modification queries return true on success Data queries (SELECT, ) return mysqli_result obj mysqli_result::fetch_assoc() mysqli_result::fetch_object() mysqli_result::fetch_all($format) mysqli_result::fetch_fields() mysqli_result::num_rows() mysqli_result::free_result()

  28. 28 MYSQLI PREPARED STATEMENTS Placeholders ? can be used for bound variables Prepare new MySQL statement $stmt = mysqli::stmt_init(); mysqli_stmt::prepare("SELECT ..."); Binding parameters (by positional placeholders) mysqli_stmt::bind_param($types, $var1, ); Types string one char ~ one parameter Execute and get result object mysqli_stmt::execute(); $res = mysqli_stmt::get_result();

  29. 29 MYSQL EXAMPLE $mysqli = mysqli_connect("localhost", "login", "passwd", "dbname"); if (!$mysqli) ... // handle connection failure $mysqli->set_charset("utf8"); $stmt = new mysqli_stmt($mysqli, 'SELECT * FROM lectures WHERE student_group = ?'); $studentGroup = '3rdyears'; $stmt->bind_param("s", $studentGroup); $stmt->execute(); $res = $stmt->get_result(); while (($lecture = $res->fetch_object()) !== null) { echo "$lecture->id: $lecture->name"; } $mysqli->close();

  30. 30 PHP FRAMEWORKS Symfony one of the most popular Laravel one of the most popular Slim - micro-framework Nette developed in Czechia (large Czech community) Zend one of the oldest (a bit outdated) CodeIgniter Yii 2 Phalcon CakePHP

  31. TAKEAWAY Verification / Sanitization File upload Sessions MySQL

More Related Content