C.9.4 Exercise 4:

<?php

  • Load the form element helper functions require 'formhelpers.php'; if ($_POST['_submit_check']) {
  • If validate form( ) returns errors, pass them to show form( ) if ($form errors = validate form( )) {

// The submitted data is valid, so process it process form( );

  • else {
  • The form wasn't submitted, so display show form( );

print 'You need to correct the following errors: <ul><li>'; print implode('</li><li>',$errors); print '</li></ul>';

  • the beginning of the form print '<form method="POST" action="'.$_SERVER['PHP_SELF'].'">';
  • the file name print' File name: ';

// the submit button input submit('submit','Show File'); // the hidden submit check variable print '<input type="hidden" name=" submit check" value="1"/>'; // the end of the form print '</form>';

function validate form( ) { $errors = array( ); // filename is required if (! strlen(trim($ POST['filename']))) {

  • errors[ ] = 'Please enter a file name.'; } else {
  • build the full file name from the web server document root // directory, a slash, and the submitted value
  • filename = $_SERVER['DOCUMENT_ROOT'] . '/' . $_POST['filename'];
  • Use realpath to resolve any .. sequences $filename = realpath($filename);
  • make sure $filename begins with the document root directory $docroot_len = strlen($_SERVER['DOCUMENT_ROOT']);

if (substr($filename, 0, $docroot_len) != $_SERVER['DOCUMENT_ROOT']) {

$errors[ ] = 'File name must be under the document root directory.';

return $errors;

function process_form( ) {

// reconstitute the full file name, as in validate form( ) $filename = $_SERVER['DOCUMENT_ROOT'] . '/' . $_POST['filename']; $filename = realpath($filename); // print the contents of the file print file get contents($filename);

C.9.5 Exercise 5:

The new validate_form( ) function that implements the additional rule:

function validate form( ) { $errors = array( ); // filename is required if (! strlen(trim($_POST['filename']))) {

  • errors[ ] = 'Please enter a file name.'; } else {
  • build the full file name from the web server document root // directory, a slash, and the submitted value
  • filename = $_SERVER['DOCUMENT_ROOT'] . '/' . $_POST['filename'];
  • Use realpath to resolve any .. sequences $filename = realpath($filename);
  • make sure $filename begins with the document root directory $docroot_len = strlen($_SERVER['DOCUMENT_ROOT']);

if (substr($filename, 0, $docroot_len) != $_SERVER['DOCUMENT_ROOT']) {

$errors[ ] = 'File name must be under the document root directory.'; } elseif (strcasecmp(substr($filename, -5), '.html') != 0) { $errors[ ] = 'File name must end in .html';

return $errors;

0 0

Post a comment

  • Receive news updates via email from this site