Unit 10 ยท Back-End Programming

10.4Review Questions

  1. What happens, step by step, when you request a PHP page?
  2. Difference between a static and a dynamic page?
  3. Why must a login form use POST?
  4. Why is server-side validation required even when JavaScript validation exists?
  5. What does htmlspecialchars() protect against?
  6. What is the difference between a cookie and a session? Where is each stored?
  7. Why must session_start() come before any HTML output?
Show answers
    1. The browser sends an HTTP request for page.php to the web server (after DNS finds the server's IP).
    2. The web server (Apache) sees the .php extension and passes the file to the PHP interpreter.
    3. PHP runs the code, which may query the database (MySQL) and build HTML.
    4. The server sends the generated HTML back in the HTTP response; the browser never sees the PHP code.
    5. The browser renders the HTML and requests any CSS, JavaScript and images.
  1. A static page is a fixed file (HTML) that is sent exactly as stored; every visitor sees the same content. A dynamic page is generated by the server on each request (by PHP, often with database data), so the content can change per user or time, for example a cart, search results or a profile.

  2. With GET, form data is placed in the URL, so the password would appear in the address bar, browser history, bookmarks and server logs, and could be seen or shared. POST sends the data in the request body. (It must still be sent over HTTPS to be encrypted.)

  3. JavaScript runs on the user's computer, so it can be disabled or bypassed (edited in DevTools or skipped by sending requests directly). The server is the only part you control, so it must validate every input to protect the database and other users.

  4. Cross-site scripting (XSS). It converts special characters (<, >, &, ", ') into entities such as &lt;, so text typed by a user is displayed rather than run as HTML or JavaScript.

  5. Both remember information between requests. A cookie is stored in the browser and sent with every request; the user can see and change it, so it must not hold sensitive data. A session stores data on the server; only a random session ID is kept in a cookie (PHPSESSID), so the data is safer.

  6. session_start() needs to send an HTTP header (Set-Cookie). Headers must be sent before the response body, so once any HTML or even a space is output, it is too late, and PHP gives a "headers already sent" warning.