Link to home
Create AccountLog in
PHP

PHP

--

Questions

--

Followers

Top Experts

Avatar of Jorge Batres
Jorge Batres🇺🇸

Help Protecting PHP Script from XSS Injection
I recently posted a question about sanitizing a PHP script, and I got great help in different approaches to this problem. The weird thing is that none of the solutions actually stopped scripts from being injected in the form fields and passed to the PHP Script, so I’m thinking that either, I’m entering the suggested solutions in the wrong file, or the server needs some configuration to have
mysql_real_escape_string()

Open in new window

or
 $input = htmlentities($_POST["input"],ENT_QUOTES);

Open in new window

to work.
I’m attaching some of the files that are called-in in the reservation process, so that maybe you would be kind enough to take a look at them, and give me some suggestion to get this sanitation to work.
For testing we are using a program called Hackbar, which is an add-on for Firefox.

reservations.php
<?
define ("LEVEL", '');
include_once(LEVEL."inc/include.php");
// Capitalizes first letter on each word, added on 12-15-09
$arr = array("First_Name", "Last_Name", "Spouse_Name", "Address", "City",  "Province", "Country", "Name_on_card"); 
foreach ($arr as $field)
{
    $_POST[$field] = strip_tags(strtolower(stripslashes($_POST[$field])));

    $_POST["$field"] = ucwords($_POST["$field"]);
}
// End capitalizing
// Sanitizing inputs suggested by Ray Paseur
/*$db_post = $_POST;
$db_post = array_map('mysql_real_escape_string', $db_post);
$em_post = $_POST;
$em_post = array_map('stripslashes', $em_post);
$em_post = array_map('striptags', $em_post); */

//Sanitation suggested by Dave Baldwin
/*$Price = max(0,floor($_POST["Price"] ));

$check__fields =  $_POST["check__fields"]; 
$check__fields = substr($check__fields,0,64);
$check__fields = mysql_real_escape_string( $check__fields);


$status =  $_POST["status"]; 
$status = substr($status,0,12);
$status = mysql_real_escape_string( $status);

$First_Name =  $_POST["First_Name"]; 
$First_Name = substr($First_Name,0,12);
$First_Name = mysql_real_escape_string( $First_Name);

$Last_Name =  $_POST["Last_Name"]; 
$Last_Name = substr($Last_Name,0,12);
$Last_Name = mysql_real_escape_string( $Last_Name);

$Spouse_Name =  $_POST["Spouse_Name"]; 
$Spouse_Name = substr($Spouse_Name,0,12);
$Spouse_Name = mysql_real_escape_string( $Spouse_Name);

$Marital_Status =  $_POST["Marital_Status"]; 
$Marital_Status = substr($Marital_Status,0,12);
$Marital_Status = mysql_real_escape_string( $Marital_Status);

$Address =  $_POST["Address"]; 
$Address = substr($input,0,48);
$Address = mysql_real_escape_string( $Address);

$City =  $_POST["City"]; 
$City = substr($City,0,20);
$City = mysql_real_escape_string( $City);

$Province =  $_POST["Province"]; 
$Province = substr($Province,0,64);
$Province = mysql_real_escape_string( $Province);

$Zip_Code =  $_POST["Zip_Code"]; 
$Zip_Code = substr($Zip_Code,0,9);
$Zip_Code = mysql_real_escape_string( $Zip_Code);

$Country =  $_POST["Country"]; 
$Country = substr($Country,0,64);
$Country = mysql_real_escape_string( $Country);

$Day_Phone =  $_POST["Day_Phone"]; 
$Day_Phone = substr($Day_Phone,0,20);
$Day_Phone = mysql_real_escape_string( $Day_Phone);

$Night_Phone =  $_POST["Night_Phone"]; 
$Night_Phone = substr($Night_Phone,0,20);
$Night_Phone = mysql_real_escape_string( $Night_Phone);

$Fax =  $_POST["Fax"]; 
$Fax = substr($Fax,0,20);
$Fax = mysql_real_escape_string( $Fax);

$Email =  $_POST["Email"]; 
$Email = substr($Email,0,64);
$Email = mysql_real_escape_string( $Email);

$Best_Time_to_Call =  $_POST["Best_Time_to_Call"]; 
$Best_Time_to_Call = substr($Best_Time_to_Call,0,9);
$Best_Time_to_Call = mysql_real_escape_string( $Best_Time_to_Call);

$Age =  $_POST["Age"]; 
$Age = substr($Age,0,2);
$Age = mysql_real_escape_string( $Age);

$Income =  $_POST["Income"]; 
$Income = substr($Income,0,9);
$Income = mysql_real_escape_string( $Income);

$Card_Number =  $_POST["Card_Number"]; 
$Card_Number = substr($Card_Number,0,16);
$Card_Number = mysql_real_escape_string( $Card_Number);

$Card_Expiration =  $_POST["Card_Expiration"]; 
$Card_Expiration = substr($Card_Expiration,0,32);
$Card_Expiration = mysql_real_escape_string( $Card_Expiration);

$Name_on_card =  $_POST["Name_on_card"]; 
$Name_on_card = substr($Name_on_card,0,64);
$Name_on_card = mysql_real_escape_string( $Name_on_card);

$Card_Type =  $_POST["Card_Type"]; 
$Card_Type = substr($Card_Type,0,64);
$Card_Type = mysql_real_escape_string( $Card_Type);

$Comments =  $_POST["Comments"]; 
$Comments = substr($Comments,0,64);
$Comments = mysql_real_escape_string( $Comments);

$form_type =  $_POST["form_type"]; 
$form_type = substr($form_type,0,64);
$form_type = mysql_real_escape_string( $form_type);

$Resort =  $_POST["Resort"]; 
$Resort = substr($Resort,0,64);
$Resort = mysql_real_escape_string( $Resort);

$Hotel =  $_POST["Hotel"]; 
$Hotel = substr($Hotel,0,64);
$Hotel = mysql_real_escape_string( $Hotel);

$Room_Type =  $_POST["Room_Type"]; 
$Room_Type = substr($Room_Type,0,24);
$Room_Type = mysql_real_escape_string( $Room_Type);

$Arrival_Month =  $_POST["Arrival_Month"]; 
$Arrival_Month = substr($Arrival_Month,0,20);
$Arrival_Month = mysql_real_escape_string( $Arrival_Month);

$Arrival_Date =  $_POST["Arrival_Date"]; 
$Arrival_Date = substr($Arrival_Date,0,2);
$Arrival_Date = mysql_real_escape_string( $Arrival_Date);

$Arrival_Year =  $_POST["Arrival_Year"]; 
$Arrival_Year = substr($Arrival_Year,0,4);
$Arrival_Year = mysql_real_escape_string( $Arrival_Year);

$Checkin_Date =  $_POST["Checkin_Date"]; 
$Checkin_Date = substr($Checkin_Date,0,64);
$Checkin_Date = mysql_real_escape_string( $Checkin_Date);

$Checkout_Date =  $_POST["Checkout_Date"]; 
$Checkout_Date = substr($Checkout_Date,0,64);
$Checkout_Date = mysql_real_escape_string( $Checkout_Date);

$Nights =  $_POST["Nights"]; 
$Nights = substr($Nights,0,7);
$Nights = mysql_real_escape_string( $Nights);

$Tickets =  $_POST["Tickets"]; 
$Tickets = substr($Tickets,0,64);
$Tickets = mysql_real_escape_string( $Tickets);

$Adults =  $_POST["Adults"]; 
$Adults = substr($Adults,0,10);
if(!is_numeric($Adults)) $Adults = 0;   or whatever value you want for a bad input
$Adults = mysql_real_escape_string( $Adults); 

$Juniors =  $_POST["Juniors"]; 
$Juniors = substr($Juniors,0,7);
$Juniors = mysql_real_escape_string( $Juniors); 

$Children =  $_POST["Children"]; 
$Children = substr($Children,0,7);
$Children = mysql_real_escape_string( $Children);*/ 

/*$check__fields = htmlentities($_POST["check__fields"],ENT_QUOTES); Suggested by Yodercm
$status = htmlentities($_POST["status"],ENT_QUOTES);
$Price = htmlentities($_POST["Price"],ENT_QUOTES);
$First_Name = htmlentities($_POST["First_Name"],ENT_QUOTES);
$Last_Name = htmlentities($_POST["Last_Name"],ENT_QUOTES);
$Spouse_Name = htmlentities($_POST["Spouse_Name"],ENT_QUOTES);
$Marital_Status = htmlentities($_POST["Marital_Status"],ENT_QUOTES);
$Address = htmlentities($_POST["Address"],ENT_QUOTES);
$City = htmlentities($_POST["City"],ENT_QUOTES);
$Province = htmlentities($_POST["Province"],ENT_QUOTES);
$Zip_Code = htmlentities($_POST["Zip_Code"],ENT_QUOTES);
$Country = htmlentities($_POST["Country"],ENT_QUOTES);
$Day_Phone = htmlentities($_POST["Day_Phone"],ENT_QUOTES);
$Night_Phone = htmlentities($_POST["Night_Phone"],ENT_QUOTES);
$Fax = htmlentities($_POST["Fax"],ENT_QUOTES);
$Email = htmlentities($_POST["Email"],ENT_QUOTES);
$Best_Time_to_Call = htmlentities($_POST["Best_Time_to_Call"],ENT_QUOTES);
$Age = htmlentities($_POST["Age"],ENT_QUOTES);
$Income = htmlentities($_POST["Income"],ENT_QUOTES);
$Card_Number = htmlentities($_POST["Card_Number"],ENT_QUOTES);
$Card_Expiration = htmlentities($_POST["Card_Expiration"],ENT_QUOTES);
$Name_on_card = htmlentities($_POST["Name_on_card"],ENT_QUOTES);
$Comments = htmlentities($_POST["Comments"],ENT_QUOTES);
$form_type = htmlentities($_POST["form_type"],ENT_QUOTES);
$Resort = htmlentities($_POST["Resort"],ENT_QUOTES);
$Hotel = htmlentities($_POST["Hotel"],ENT_QUOTES);
$Room_Type = htmlentities($_POST["Room_Type"],ENT_QUOTES);
$Arrival_Month = htmlentities($_POST["Arrival_Month"],ENT_QUOTES);
$Arrival_Date = htmlentities($_POST["Arrival_Date"],ENT_QUOTES);
$Arrival_Year = htmlentities($_POST["Arrival_Year"],ENT_QUOTES);
$Checkin_Date = htmlentities($_POST["Checkin_Date"],ENT_QUOTES);
$Checkout_Date = htmlentities($_POST["Checkout_Date"],ENT_QUOTES);
$Nights = htmlentities($_POST["Nights"],ENT_QUOTES);
$Tickets = htmlentities($_POST["Tickets"],ENT_QUOTES);
$Adults = htmlentities($_POST["Adults"],ENT_QUOTES);
$Juniors = htmlentities($_POST["Juniors"],ENT_QUOTES);
$Children = htmlentities($_POST["Children"],ENT_QUOTES);

 End sanitizing */



$user = new user();
$reservation = new reservation();
$form_type = $reservation->loadFields($_REQUEST["form_type"]);
$step = ($_REQUEST["step"]) ? ($_REQUEST["step"]) : ("1");
switch($step) {
        case "1":
                $_REQUEST["form_type"] = $form_type;
                $_REQUEST["yes_no"] = 1;
		$order = array("check__fields", "form_type", "Resort", "Hotel", "Room_Type", "Arrival_Month", "Arrival_Date", "Arrival_Year",
			         "Nights", "Tickets", "Adults", "Juniors", "Children");
                $res = sort_res($reservation->showRecord($_REQUEST,$reservation->lists), $order);
                        for($i = 0; $i < sizeof($res); ++$i){
                        	if(in_array($res[$i]["name"], array("Resort", "Hotel", "Arrival_Month", "Arrival_Date", "Arrival_Year", "Room_Type", "Nights", "Tickets"))){
                          		if (isset($_REQUEST[$res[$i]["name"]])) {
						$res[$i]["type"] = "static";
					}
				}
			}

                $smarty->assign("reservation", $res);
        break;
        case "cc":
		$order = array("check__fields", "form_type", "Resort", "Hotel", "Room_Type", "Arrival_Month", "Arrival_Date", "Arrival_Year", "Checkin_Date", "Checkout_Date", "Nights", "Tickets", "Adults", "Juniors", "Children", "Number_of_Guest", "Price",
				 "First_Name", "Last_Name", "Spouse_Name", "Marital_Status", "Address", "City", "State",
				 "Province", "Country", "Zip_Code", "Day_Phone", "Night_Phone", "Email", "Fax",
				 "Best_Time_to_Call", "Age", "Income", "Card_Number",
				 "Card_Expiration", "Name_on_card", "Comments", "agreement");
                $price = CalculatePrice($_POST);
                $_POST["Price"] = $price["txt"];
                $_POST["Country"] = "United States";
                $guests = 0;
                foreach (array("Adults", "Juniors", "Children") as $type){
                  if(isset($_POST[$type])){
                    $guests += $_POST[$type];
                  }
                }
                $_POST["Number_of_Guest"] = $guests;
                unset($_POST["check__fields"]);
				
                $res = $reservation->showRecord($_POST,$reservation->lists);
                
                for($i = 0; $i < sizeof($res); ++$i) {
                 	if ($res[$i]["name"] == "Checkout_Date") {
                 		$res[$i]["type"] = "static";
                 		$res[$i]["check"] = "Check";
                 		$res[$i]["title"] = "Checkout Date";
                 		$res[$i]["value"] = date("l F jS Y", strtotime("+ $_POST[Nights] days", strtotime($_POST["Arrival_Month"] . " " . $_POST["Arrival_Date"] . " " . $_POST["Arrival_Year"])));
                 	}
                	
                 	if ($res[$i]["name"] == "Checkin_Date") {
                 		$res[$i]["type"] = "static";
                 		$res[$i]["check"] = "Check";
                 		$res[$i]["title"] = "Check In Date";
                 		$res[$i]["value"] = date("l F jS Y", strtotime($_POST["Arrival_Month"] . " " . $_POST["Arrival_Date"] . " " . $_POST["Arrival_Year"]));
                 	}
       
                }
                
 
                $res[] = array(
			    'type' => 'checkbox',
			    'check' => 'Check',
			    'name' => 'agreement',
			    'title' => 'I Agree to the Terms & Conditions',
			    'value' => 'To submit the form you must accept the Terms and Conditions.'
                         );
						 

						 
                $res = sort_res($res, $order);
                for($i = 0; $i < sizeof($res); ++$i){
			if(in_array($res[$i]["name"], array("Resort", "Hotel", "Room_Type", "Arrival_Month", "Arrival_Date", "Arrival_Year", "Checkin_Date", "Checkout_Date",
                                 "Nights", "Tickets", "Adults", "Juniors", "Children", "Number_of_Guest", "Price"))){
				$res[$i]["type"] = "static";
                                $res[$i]["check"] = '';
                        }
                        if ($res[$i]["name"] == "check__fields") {
                          $res[$i]["value"] .= ",agreement,Check";
                        }
		}
                $smarty->assign("reservation", $res);
                break;


        case "2":
		$order = array("check__fields", "form_type", "Resort", "Hotel", "Room_Type", "Arrival_Month", "Arrival_Date", "Arrival_Year", "Checkin_Date", "Checkout_Date", "Nights", "Tickets", "Adults", "Juniors", "Children", "Number_of_Guest", "Price",
				 "First_Name", "Last_Name", "Spouse_Name", "Marital_Status", "Address", "City", "State",
				 "Province", "Country", "Zip_Code", "Day_Phone", "Night_Phone", "Email", "Fax",
				 "Best_Time_to_Call", "Age", "Income", "Card_Number", "Card_Type",
				 "Card_Expiration", "Name_on_card", "Comments");
                $price = CalculatePrice($_POST);
                $_POST["Price"] = $price["txt"];
                $guests = 0;
                foreach (array("Adults", "Juniors", "Children") as $type){
                  if(isset($_POST[$type])){
                    $guests += $_POST[$type];
                  }
                }
                $_POST["Number_of_Guest"] = $guests;
                $_POST["Card_Number"] = ereg_replace("[^0-9]", "", $_POST["Card_Number"]);
		if($_POST["Card_Number"][0] == "5"){
			$_POST["Card_Type"] = "Master Card";
		}
		else if ($_POST["Card_Number"][0] == "4"){
			$_POST["Card_Type"] = "Visa";
		}
		else if (substr($_POST["Card_Number"],0, 2) == "34" or substr($_POST["Card_Number"],0, 2) == "37"){
			$_POST["Card_Type"] = "American Express";
		}
		else if (substr($_POST["Card_Number"], 0, 4) == "6011"){
			$_POST["Card_Type"] = "Discover";
		}
		else{
			$_POST["Card_Type"] = "Unknown";
		}

			// Format the phone numbers
			$_POST['Day_Phone'] = formatPhone($_POST['Day_Phone']);
			$_POST['Night_Phone'] = formatPhone($_POST['Night_Phone']);
			$_POST['Fax'] = formatPhone($_POST['Fax']);

		$res = sort_res($reservation->showRecord($_POST,$reservation->lists), $order);
		$newres = array();
		foreach($res as $item){
			if($item["name"] == "Card_Number"){
				$item["type"] = "hidden";
                                $newres[] = $item;
                                $newres[] =  array(
                                                                                    'type' => 'Juniors',
                                                                                    'check' => '#',
                                                                                    'name' => '',
                                                                                    'title' => 'Card Number',
                                                                                    'value' => substr("****************", 0, strlen($item["value"]) - 4) . substr($item["value"], strlen($item["value"]) - 4, 4)
                                                           );
                        }
                        else{
				$newres[] = $item;
			}
		}
		$smarty->assign("reservation", $newres);
        break;
}


function sort_res($res, $order) {
  
  $newres = array();
  foreach($order as $row) {
    foreach($res as $item) {
      if ($item["name"] == $row) {
        $newres[] = $item;
      }
    }
  }
  return $newres;
} 
  



$smarty->assign("content", "reservation".$step.".html");
$smarty->display("form_".$form_type.".html");

?>
 

Open in new window


db.php
<?php

if (!ISSET($__DB)):
        $__DB = "DB SET";

class DB_Sql {
  var $Host     = "localhost";
  var $Database = "";
  var $User     = "root";
  var $Password = "";

  var $Auto_Free     = 0;     ## Set to 1 for automatic mysql_free_result()
  var $Debug         = 0;     ## Set to 1 for debugging messages.
  var $Halt_On_Error = "yes"; ## "yes" (halt with message), "no" (ignore errors quietly), "report" (ignore error, but spit a warning)
  var $Seq_Table     = "db_sequence";

  var $Record   = array();
  var $Row;

  var $Errno    = 0;
  var $Error    = "";

  var $type     = "mysql";
  var $revision = "1.2";

  var $Link_ID  = 0;
  var $Query_ID = 0;

  function DB_Sql($query = "") {
      $this->query($query);
  }

  function link_id() {
    return $this->Link_ID;
  }

  function query_id() {
    return $this->Query_ID;
  }

  function connect($Database = "", $Host = "", $User = "", $Password = "") {
    /* Handle defaults */
    if ("" == $Database)
      $Database = $this->Database;
    if ("" == $Host)
      $Host     = $this->Host;
    if ("" == $User)
      $User     = $this->User;
    if ("" == $Password)
      $Password = $this->Password;

    /* establish connection, select database */
    if ( 0 == $this->Link_ID ) {

      $this->Link_ID = mysql_pconnect($Host, $User, $Password);
      if (!$this->Link_ID) {
        $this->halt("pconnect($Host, $User, \$Password) failed.");
        return 0;
      }

      if (!@mysql_select_db($Database,$this->Link_ID)) {
        $this->halt("cannot use database ".$this->Database);
        return 0;
      }
    }

    return $this->Link_ID;
  }

  /* public: discard the query result */
  function free() {
      @mysql_free_result($this->Query_ID);
      $this->Query_ID = 0;
  }

  /* public: perform a query */
  function query($Query_String) {
          GLOBAL $logger;
    /* No empty queries, please, since PHP4 chokes on them. */
    if ($Query_String == "")
      /* The empty query string is passed on from the constructor,
       * when calling the class without a query, e.g. in situations
       * like these: '$db = new DB_Sql_Subclass;'
       */
      return 0;

    if (!$this->connect()) {
      return 0; /* we already complained in connect() about that. */
    };

    # New query, discard previous result.
    if ($this->Query_ID) {
      $this->free();
    }

    if ($this->Debug)
      printf("Debug: query = %s<br>\n", $Query_String);

    $this->Query_ID = @mysql_query($Query_String,$this->Link_ID);
    $this->Row   = 0;
          $this->Errno = mysql_errno();
    $this->Error = mysql_error();

    if (!$this->Query_ID) {
            $this->halt("Invalid SQL: ".$Query_String);
            //$logger->log(SQLLOG, "Invalid SQL: ".$Query_String);
    } else {
            //$logger->log(SQLLOG, $Query_String);
    }

    // Will return nada if it fails. Thats fine.
    return $this->Query_ID;
  }

  /* public: walk result set */
  function next_record() {
    if (!$this->Query_ID) {
      $this->halt("next_record called with no query pending.");
      return 0;
    }

    $this->Record = @mysql_fetch_assoc($this->Query_ID);
    $this->Row   += 1;
    $this->Errno  = mysql_errno();
    $this->Error  = mysql_error();

        $stat = is_array($this->Record);
        if (!$stat && $this->Auto_Free) {
      $this->free();
        }
        return $stat;
  }

  /* public: position in result set */
  function seek($pos = 0) {
    $status = @mysql_data_seek($this->Query_ID, $pos);
    if ($status)
      $this->Row = $pos;
    else {
      $this->halt("seek($pos) failed: result has ".$this->num_rows()." rows");

      /* half assed attempt to save the day,
       * but do not consider this documented or even
       * desireable behaviour.
       */
      @mysql_data_seek($this->Query_ID, $this->num_rows());
      $this->Row = $this->num_rows;
      return 0;
    }

    return 1;
  }

  /* public: table locking */
  function lock($table, $mode="write") {
    $this->connect();

    $query="lock tables ";
    if (is_array($table)) {
      while (list($key,$value)=each($table)) {
        if ($key == "read" && $key!=0) {
          $query.="$value read, ";
        } else {
          $query.="$value $mode, ";
        }
      }
      $query=substr($query,0,-2);
    } else {
      $query.="$table $mode";
    }
    $res = @mysql_query($query, $this->Link_ID);
    if (!$res) {
      $this->halt("lock($table, $mode) failed.");
      return 0;
    }
    return $res;
  }

  function unlock() {
    $this->connect();

    $res = @mysql_query("unlock tables");
    if (!$res) {
      $this->halt("unlock() failed.");
      return 0;
    }
    return $res;
  }


  /* public: evaluate the result (size, width) */
  function affected_rows() {
    return @mysql_affected_rows($this->Link_ID);
  }

  function num_rows() {
    return @mysql_num_rows($this->Query_ID);
  }

  function num_fields() {
    return @mysql_num_fields($this->Query_ID);
  }

  /* public: shorthand notation */
  function nf() {
    return $this->num_rows();
  }

  function np() {
    print $this->num_rows();
  }

  function f($Name) {
    return $this->Record[$Name];
  }

  function p($Name) {
    print $this->Record[$Name];
  }

        function mysql_insert_id()
        {
                return mysql_insert_id($this->Link_ID);
        }

  /* public: sequence numbers */
  function nextid($seq_name) {
    $this->connect();

    if ($this->lock($this->Seq_Table)) {
      /* get sequence number (locked) and increment */
      $q  = sprintf("select nextid from %s where seq_name = '%s'",
                $this->Seq_Table,
                $seq_name);
      $id  = @mysql_query($q, $this->Link_ID);
      $res = @mysql_fetch_array($id);

      /* No current value, make one */
      if (!is_array($res)) {
        $currentid = 0;
        $q = sprintf("insert into %s values('%s', %s)",
                 $this->Seq_Table,
                 $seq_name,
                 $currentid);
        $id = @mysql_query($q, $this->Link_ID);
      } else {
        $currentid = $res["nextid"];
      }
      $nextid = $currentid + 1;
      $q = sprintf("update %s set nextid = '%s' where seq_name = '%s'",
               $this->Seq_Table,
               $nextid,
               $seq_name);
      $id = @mysql_query($q, $this->Link_ID);
      $this->unlock();
    } else {
      $this->halt("cannot lock ".$this->Seq_Table." - has it been created?");
      return 0;
    }
    return $nextid;

  }

  /* public: return table metadata */
  function metadata($table='', $full=false) {
    $count = 0;
    $id    = 0;
    $res   = array();

    /*
     * Due to compatibility problems with Table we changed the behavior
     * of metadata();
     * depending on $full, metadata returns the following values:
     *
     * - full is false (default):
     * $result[]:
     *   [0]["table"]  table name
     *   [0]["name"]   field name
     *   [0]["type"]   field type
     *   [0]["len"]    field length
     *   [0]["flags"]  field flags
     *
     * - full is true
     * $result[]:
     *   ["num_fields"] number of metadata records
     *   [0]["table"]  table name
     *   [0]["name"]   field name
     *   [0]["type"]   field type
     *   [0]["len"]    field length
     *   [0]["flags"]  field flags
     *   ["meta"][field name]  index of field named "field name"
     *   The last one is used, if you have a field name, but no index.
     *   Test:  if (isset($result['meta']['myfield'])) { ...
     */

    // if no $table specified, assume that we are working with a query
    // result
    if ($table) {
      $this->connect();
      $id = @mysql_list_fields($this->Database, $table);
      if (!$id)
        $this->halt("Metadata query failed.");
    } else {
      $id = $this->Query_ID;
      if (!$id)
        $this->halt("No query specified.");
    }

    $count = @mysql_num_fields($id);

    // made this IF due to performance (one if is faster than $count if's)
    if (!$full) {
      for ($i=0; $i<$count; $i++) {
        $res[$i]["table"] = @mysql_field_table ($id, $i);
        $res[$i]["name"]  = @mysql_field_name  ($id, $i);
        $res[$i]["type"]  = @mysql_field_type  ($id, $i);
        $res[$i]["len"]   = @mysql_field_len   ($id, $i);
        $res[$i]["flags"] = @mysql_field_flags ($id, $i);
      }
    } else { // full
      $res["num_fields"]= $count;

      for ($i=0; $i<$count; $i++) {
        $res[$i]["table"] = @mysql_field_table ($id, $i);
        $res[$i]["name"]  = @mysql_field_name  ($id, $i);
        $res[$i]["type"]  = @mysql_field_type  ($id, $i);
        $res[$i]["len"]   = @mysql_field_len   ($id, $i);
        $res[$i]["flags"] = @mysql_field_flags ($id, $i);
        $res["meta"][$res[$i]["name"]] = $i;
      }
    }

    // free the result only if we were called on a table
    if ($table) @mysql_free_result($id);
    return $res;
  }

  /* private: error handling */
  function halt($msg) {

    $this->Error = @mysql_error($this->Link_ID);
    $this->Errno = @mysql_errno($this->Link_ID);

    if ($this->Halt_On_Error == "no")
      return;

    $this->haltmsg($msg);

    if ($this->Halt_On_Error != "report")
      die("Session halted.");
  }

  function haltmsg($msg) {
    printf("</td></tr></table><b><hr>\nDatabase error:</b> %s<br>\n", $msg);
    printf("<b>MySQL Error</b>: %s (%s)<br>\n",
      $this->Errno,
      $this->Error);
  }

  function table_names() {
    $this->query("SHOW TABLES");
    $i=0;
    while ($info=mysql_fetch_row($this->Query_ID))
     {
      $return[$i]["table_name"]= $info[0];
      $return[$i]["tablespace_name"]=$this->Database;
      $return[$i]["database"]=$this->Database;
      $i++;
     }
   return $return;
  }
};


class MyDB extends DB_Sql {
        var $classname = "MyDB";

        Function MyDB() {
                GLOBAL $db, $dbhost, $dbuser, $dbpassword;
                $this->Database = $db;
                $this->Host = $dbhost;
                $this->User = $dbuser;
                $this->Password = $dbpassword;
                $this->Halt_On_Error = _Halt_On_Error;
        }
}

$DB = new MyDB();

ENDIF;
?>
<?

class uni_db
{
        // // Properties.
        // // ------------------------
        //
        // var $ERR;
        // var $DB;
        var $DEBUG = false;
        //
        // // Constructor
        // // ---------------------------
        function uni_db($DB )
        {
                if (!get_class($DB ) )
                {
                        print $this->ERR = "Error while new class construction!";
                        return false;
                }
                $this->DB = $DB;
        }
        // Private checking function
        // -------------------------------------
        function checkData($postData )
        {
                if (!is_array($postData ) )
                {
                        $this->ERR = "Error while inserting!";
                        return false;
                }
                return true;
        }
        // Get
        // -------------------------------------------------------
        function uniGet($tableName, $idArr, $where = "" )
        {
                $sql = "SELECT * FROM $tableName ";
                if (is_array($idArr ) && count($idArr ) > 0 )
                {
                        list($idkey, $idval ) = each($idArr );
                        $sql .= " WHERE $idkey = '$idval' ";
                        $f = 1;
                }
                if ($where != "" )
                {
                        if ($f != 1 )
                        {
                                $sql .= " WHERE ";
                        }
                        $sql .= " $where ";
                }

                $this->debug($sql);
                //echo $sql."<BR>";
                $this->DB->query($sql );
                if ($this->DB->num_rows() == 1 )
                {
                        $this->DB->next_record();
                        return stripSlashesArr($this->DB->Record );
                        // return $this->DB->Record;
                }

                return Array();
        }
        // Get list...
        // ----------------------------------------------------------------
        /**
         * uni_db::uniGetList()
         *
         * @param  $tableName
         * @param  $idField
         * @param  $order
         * @param  $start
         * @param  $count
         * @return array
         */
        function uniGetList($tableName, $idField, $order = "", $start = 0, $count = 999999 )
        {
                $sql = "SELECT * FROM $tableName ";
                if (!empty($order ) )
                {
                        $sql .= " ORDER BY $order ";
                }
                if (!empty($count ) )
                {
                        $sql .= " LIMIT " . intval($start ) . ", " . intval($count ) . " ";
                }
                // echo $sql;
                $this->debug($sql);
                $this->DB->query($sql );

                while ($this->DB->next_record() )
                {
                        // extract($DB->Record, EXTR_OVERWRITE);
                        while (list($key, $val ) = each($this->DB->Record ) )
                        {
                                $this->DB->Record[$key] = stripslashes($this->DB->Record[$key] );
                        }
                        // by SavaJr
                        if (!empty($idField ) )
                                $arr[$this->DB->f($idField )] = $this->DB->Record;
                        else
                                $arr[] = $this->DB->Record;
                }
                return (Array )$arr;
        }
        // Get List Where....
        // ----------------------------------------------------------------
        function uniGetListWhere($tableName, $idField, $where, $order = "", $start = 0, $count = 999999 )
        {
                $sql = "SELECT * FROM $tableName WHERE $where";
                if (!empty($order ) )
                {
                        $sql .= " ORDER BY $order ";
                }
                if (!empty($count ) )
                {
                        $sql .= " LIMIT " . intval($start ) . ", " . intval($count ) . " ";
                }
                // dump ($sql);
                $this->debug($sql);
                $this->DB->query($sql );

                while ($this->DB->next_record() )
                {
                        // extract($DB->Record, EXTR_OVERWRITE);
                        while (list($key, $val ) = each($this->DB->Record ) )
                        {
                                $this->DB->Record[$key] = stripslashes($this->DB->Record[$key] );
                        }
                        if (!empty($idField ) )
                                $arr[$this->DB->f($idField )] = $this->DB->Record;
                        else
                                $arr[] = $this->DB->Record;
                }

                return (Array )$arr;
        }
        // Get count
        // ---------------------------------------------------------
        function uniGetCount($tableName, $where = "", $mysql = "" )
        {
                $sql = "SELECT count(*) AS num ";
                if (!empty($mysql ) )
                {
                        $sql .= $mysql;
                } elseif (!empty($where ) )
                {
                        $sql .= "FROM $tableName WHERE $where ";
                }
                else
                {
                        $sql .= "FROM $tableName";
                }
                $this->debug($sql );
                $this->DB->query($sql );
                $this->DB->next_record();
                return $this->DB->f("num" );
        }
        // Insert something into defined table!
        // ------------------------------------------------------------------------
        // $postData = assoc array, where the keys are the table fields names too.
        // $tableName = "table name!"
        // OUTPUT -> id of new record!
        function uniAdd($postData, $tableName )
        {
                if (!$this->checkData($postData ) )
                {
                        return 0;
                }

                $sql = "INSERT INTO $tableName (";

                while (list($key, $val ) = each($postData ) )
                {
                        $sql .= $key . ", ";
                }

                $sql = substr($sql, 0, -2 );
                $sql .= ") VALUES (";
                reset($postData );

                while (list($key, $val ) = each($postData ) )
                {
                        $sql .= "'" . addslashes($val ) . "', ";
                }
                $sql = substr($sql, 0, -2 );
                $sql .= ") ";
                // echo $sql;
                $this->debug($sql );

                $this->DB->query($sql );
                return $this->DB->mysql_insert_id();
        }
        // Update defined(or all) field(s).
        // -----------------------------------------------------------------------
        // $postData = assoc array, where the keys are the table fields names too.
        // $tableName = "table name"
        // $ID = array ( "idfieldname"=>"idvalue" )
        // OUTPUT -> 1/0!
        function uniUpdate($postData, $tableName, $idArr = "" )
        {
                if (!$this->checkData($postData ) )
                {
                        return false;
                }

                $sql = "UPDATE $tableName SET ";
                while (list($key, $val ) = each($postData ) )
                {
                        $sql .= "$key = '" . addslashes($val ) . "', ";
                }
                $sql = substr($sql, 0, -2 );
                if (is_array($idArr ) )
                {
                        list ($idkey, $idval ) = each($idArr );
                        $sql .= " WHERE  $idkey = '$idval' ";
                }
                // dump($sql);
                $this->debug($sql );
                $this->DB->query($sql );

                if ($this->DB->affected_rows() == 0 && empty($this->DB->error ) )
                {
                        $result = 1;
                }
                else
                {
                        $result = $this->DB->affected_rows();
                }
                return $result;
        }
        // Delete defined(or all) field(s).
        // -------------------------------------------------
        function uniDelete($idArr = "", $tableName )
        {
                $sql = "DELETE FROM $tableName ";

                if (is_array($idArr ) )
                {
                        list($idkey, $idval ) = each($idArr );
                        $sql .= " WHERE $idkey = '$idval' ";
                }
                else
                {
                        $sql .= "WHERE " . $idArr;
                }
                $this->debug($sql );
                $this->DB->query($sql );

                return $this->DB->affected_rows();
        }
        // Get custom SQL (aka custom list)...
        // ---------------------------------------------------------
        function uniSQL($sql, $idField )
        {
                // echo $sql;
                $this->DB->query($sql );
                while ($this->DB->next_record() )
                {
                        // extract($DB->Record, EXTR_OVERWRITE);
                        while (list($key, $val ) = each($this->DB->Record ) )
                        {
                                $this->DB->Record[$key] = stripslashes($this->DB->Record[$key] );
                        }
                        if (!empty($idField ) )
                                $arr[$this->DB->f($idField )] = $this->DB->Record[$idField];
                        else
                        {
                                $arr[] = $this->DB->Record;
                        }
                }
                return (Array )$arr;
        }

        Function stripSlashesArr($arr )
        {
                if (is_array($arr ) )
                        foreach ($arr as $key => $val )
                {
                        $arr[$key] = norm($val );
                }
                return $arr;
        }

        function debug($str )
        {
                if ($this->DEBUG )
                {
                        echo $str;
                }
        }
}

$uni_db = new uni_db($DB);

?>
<?
class basedb {

                var $uni_db;
                var $table;
                var $metadata;
                var $dateFieldNames = Array();
                var $debug = false;

                function basedb($uni_db, $table) {
                        if (is_object ($uni_db) && !empty($table)) {
                                $this->uni_db = $uni_db;
                                $this->table = $table;
                                $this->metaData = $this->uni_db->DB->metadata($this->table, true);

                                foreach ($this->metaData as $key => $val) {
                                                if ($val['type'] == "date" || $val['type'] == "datetime")
                                                        $this->dateFieldNames[] = $val[name];
                                }
                        } else {
                                user_error("Bad parameter passed to constructor");
                                exit;
                        }
                }

                function add($arr = Array()) {
                        if (is_array($arr)) {
                                $arr = $this->_formatDates($arr, "toSQL", true);
                                $arr = $this->_checkFields($arr);
                                $res = $this->uni_db->uniAdd($arr, $this->table);
                        } else {
                                $res = 0;
                        }
                        return $res;
                }

                /**
                 * @return int
                 * @param idArr array
                 * @desc Delete record
                 */
                function delete($idArr = Array()) {
                                if (is_array($idArr)) {
                                                $res = $this->uni_db->uniDelete($idArr, $this->table);
                                } else {
                                                $res = false;
                                }
                                return $res;
                }

                /**
                 * @return int
                 * @param arr array
                 * @param idArr array
                 * @desc Update record accorring to given attributes
                 */
                function update($arr, $idArr, $isDatetimePreformed = false) {
                                // Error handling
                                list($key, $val) = $idArr;
                                if (!is_array($idArr) || count($idArr) != 1) {
                                                user_error ("<br>Bad arguments passed");
                                }

                                if (is_array($arr) && is_array($idArr)) {
                                                if(!$isDatetimePreformed)$arr = $this->_formatDates($arr, "toSQL", false);
                                                $arr = $this->_checkFields($arr);
                                                $res = $this->uni_db->uniUpdate($arr, $this->table, $idArr);
                                } else {
                                                $res = 0;
                                                user_error ("<br>Not updated");
                                }
                                return $res;
                }

                /**
                 * @return int
                 * @param query = "" string
                 * @desc Returns number of records from supplied query
                 */
                function count($query = "") {
//                        $res = $this->uni_db->uniGetCount($this->table, $where);
//                        echo $query;
                        $this->uni_db->DB->query($query);
                        $res = $this->uni_db->DB->num_rows();
                        return intval($res);
                }

                /**
                 * @return Array
                 * @param idArr Array
                 * @param where String
                 * @desc Returns complete record information from database according to supplied parameters
                 */
                function get($idArr = Array(), $where = "") {

                        if (is_array($idArr)) {
                                        $res = $this->uni_db->uniGet($this->table, $idArr, $where);
                                        $res = $this->_formatDates($res, "fromSQL", false);
                        } else {
                                        $res = Array();
                        }
                        return $res;
                }

                /**
                 * @return boolean
                 * @param recordArr array
                 * @desc Returns if record(s) exists in the database
                 */
                function exists($recordArr) {
                        assert(is_array($recordArr));
                        $query = "select count(*) as number from ".$this->table." where 1 ";
                        foreach ($recordArr as $field => $value) {
                                // check if field exists in database
                                if (in_array($field, array_keys($this->metaData[meta])))
                                        $query .= " and ".$field." = '".addslashes($value)."'";
                        }
//                        echo $query;
                        $res = $this->plainSQL($query, "number");

                        return ($res[0][number] > 0);
                }

                /**
                 * @return array
                 * @param idField array
                 * @param where string
                 * @param order string
                 * @param start int
                 * @param count int
                 * @desc Returns list of items
                 */
                function getList($idField = "", $where = "", $order = "", $start = 0, $count = "") {
                        //make first parameter optional

                        if (empty($idField) && !empty($this->idField))
                                        $idField = $this->idField;

                        if (!empty($idField)) {
                                        if (empty($where)) {
                                                $res = $this->uni_db->uniGetList($this->table, $idField, $order, $start, $count);
                                        } else {
                                                $res = $this->uni_db->uniGetListWhere($this->table, $idField, $where, $order, $start, $count);
                                        }
                        } else {
                                        $res = Array();
                        }

                        return $res;
                }

                /**
                 * @return array
                 * @param idField = "" string
                 * @param where = "" string
                 * @param valueField = "name" string
                 * @desc Returns list of objects in "short form": key => value
                 */
                function getListShort ($idField = "", $where = "", $valueField = "name") {
                                $list = $this->getList($idField = "", $where);
                                $arr = Array();

                                foreach ($list as $key => $val) {
                                                $arr[$key] = $val[$valueField];
                                }
                                return $arr;
                }

                /**
                 * @return array
                 * @param sql string
                 * @param index_name string
                 * @desc Returns query results as associative array with field names - second parameter as keys
                 */
                function customSQL($sql, $index_name) {
                                return $this->uni_db->uniSQL($sql, $index_name);
                }

                /**
                 * @return array
                 * @param sql sql
                 * @desc Deprecated, alias for query
                 */
                function plainSQL($sql) {
                        return $this->query($sql);
                }

                /**
                 * @return array
                 * @param query string
                 * @desc Execute query and return query results
                 */
                function query($query) {
                        $this->uni_db->DB->query($query);
                        while ($this->uni_db->DB->next_record()) {
                                        while (list($key, $val) = each($this->uni_db->DB->Record))
                                        {
                                                        $this->uni_db->DB->Record[$key] = stripslashes($this->uni_db->DB->Record[$key]);
                                        }
                                        $arr[] = $this->uni_db->DB->Record;
                        }
                        return (Array)$arr;
                }

                function _fromSQLDateTime($datetime = "0000-00-00 00:00:00", $delim = "[/.-]") {
                                list($date, $time) = split (" ", $datetime);
                                list ($hour, $minute, $second) = split ($delim, $time);
                                list ($year, $month, $day) = split ('[/.-]', $date);
                                //return date("Y-m-d H:i:s", mktime ($hour, $minute, $second, $month, $day, $year));
                                return mktime ($hour, $minute, $second, $month, $day, $year);
                }

                function _toSQLDateTime ($datetime = "",  $delim = '[/.-]', $doSetDateNow = false) {
                        // format = 0000-00-00 00:00:00
                        if ($doSetDateNow == true && empty($datetime)) {
                                //return date("Y-m-d H:i:s"); //now
                                return null;
                        } elseif ($doSetDateNow == false && empty($datetime)) {
                                return null;
                        }
                        else {
                                list ($date, $time) = split (" ", $datetime);
                                list ($hour, $minute, $second) = split (":", $time);
                                list ($year, $month, $day) = split ('[/.-]', $date);
                                return date("Y-m-d H:i:s", mktime ($hour, $minute, $second, $month, $day, $year));
                        }
                }

                function _formatDates (&$arr, $direction, $doSetDateNow = false) {
                        if (is_array($this->dateFieldNames))
                        foreach ($this->dateFieldNames as $key => $val) {
                                if ($direction == "fromSQL") {
                                        if ($arr[$val] != null)
                                                $arr[$val] = $this->_fromSQLDateTime($arr[$val], "-");
                                } else {
                                        if (!($doSetDateNow == false && empty($arr[$val])))
                                                $arr[$val] = $this->_toSQLDateTime($arr[$val], "/", $doSetDateNow);
                                }
                        }
                        return $arr;
                }

                function _checkFields ($arr) {
                        assert(is_array($this->metaData[meta]));
                        $fieldNames = array_keys($this->metaData[meta]);

                        if (is_array($arr))
                        foreach ($arr as $key => $val) {
                                        if (in_array($key, $fieldNames)) {
                                                        $recordArr[$key] = $val;
                                        }
                        }
                        return $recordArr;
                }

                function debug($trigger = 1) {
                        $this->uni_db->DB->Debug = (int)$trigger;
                        return $this->uni_db->DB->Debug;
                }

                /*
                **************************************************************************

                Visual part

                **************************************************************************
                */

                function showRecordForm ($templateFormName, $recordArr = Array()) {
                        return $this->show($templateFormName, $recordArr);
                }

                function show ($templateFormName, $recordArr = Array()) {
                        $this->template->assign($recordArr);
                        return $this->template->fetch($templateFormName);
                }

                function showList ($templateFormName = "") {
                                assert(strlen($templateFormName) > 0);
                                $orderList = $this->getList($this->idField);
                                $this->template->assign("list", $orderList);
                                return $this->template->fetch($templateFormName);
                }
}
?>
<?
class easydb extends basedb {

        function easydb() {
                global $uni_db;
                parent::basedb($uni_db, $this->table);
        }

        function getByID($id){
        return $this->get(array($this->idField=>$id));
        }

        function getWhere($where = "", $order = "", $start = 0, $count = ""){
                return $this->getList("", $where, $order, $start, $count);
        }

        function showRecord($values, $lists = array()){
                $record = array();
                $check_fields = '';
                if (is_array($this->RecordFields))
                foreach ($this->RecordFields as $field) {
                        $rec = array();
                        if (count($field) > 1) {
                                if ($field["type"]){
                                        $rec["type"] = $field["type"];
                                        unset($field["type"]);
                                }
                                if ($field["check"]){
                                        $rec["check"] = $field["check"];
                                        unset($field["check"]);
                                }
                                /*if ($field["readonly"]){
                                        $rec["readonly"] = $field["readonly"];
                                        unset($field["readonly"]);
                                } */
                        }
                        list($name, $title) = each($field);
                        $rec["name"]=$name;
                        $rec["title"]=$title;
                        if (is_array($values)) $rec["value"]=$values[$name];
                        if ((is_array($values)) && ($rec["type"] == "password")) $rec["check"]=str_replace("#","",$rec["check"]);
                        if ((count($lists) > 0) && ($rec["type"] == "select" || $rec["type"] == "radio")) {
                                $rec["list"] = $lists[$name];
                        }
                        if ($rec["check"]) $check_fields .= "$rec[name],$rec[check],";
                        $record[] = $rec;
                }
                if ($check_fields != '') $record[] = array("name"=>"check__fields","value"=>substr($check_fields,0,strlen($check_fields)-1),"type"=>"hidden");
                if ($values[$this->idField])
                        $record[] = array("name"=>$this->idField,"value"=>$values[$this->idField],"type"=>"key");
                return $record;
        }

        function showList($arr, $key, $val){
                $list = array();
                if (is_array($arr))
                foreach ($arr as $option) {
                        $list[$option[$key]] = $option[$val];
                }
                return $list;
        }

        function edit($dataArr, $id){
                return parent::update($dataArr, array($this->idField=>$id), true);
        }

        function delete($id){
        return parent::delete(array($this->idField=>$id));
        }

}
?>

Open in new window


functions.php

<?
        function CalculatePrice($params) {
            global $smarty;
            $hotel     = isset($params["Hotel"]) ? $params["Hotel"] : $params["Resort"];
            $room_type = $params["Room_Type"];
            $nights    = $params["Nights"];
            $adults    = isset($params["Adults"]) ?  $params["Adults"] : 0;
            $children  = isset($params["Children"]) ?  $params["Children"] : 0;
            $juniors   = isset($params["Juniors"]) ?  $params["Juniors"] : 0;
            $form_type = isset($params["form_type"]) ?  $params["form_type"] : "";

            $section   = $hotel.":".$room_type;
//            dump($section);

            $mode = 1;
            $smarty->config_load('calculation_high_season.conf',$section);
            $configs = $smarty->get_config_vars();

        if ($configs["BaseNights"]) {
            $season_dates = array();
            calculate_season_price("High",$configs,$params,$season_dates);
            calculate_season_price("Holiday",$configs,$params,$season_dates);
            $season_days  = array_count_values($season_dates);
        }
        else {
            $mode = 0;
            $smarty->config_load('calculation.conf',$section);
            $configs = $smarty->get_config_vars();
        }

            $Currency     = $configs["Currency"];
            $BaseNights   = $configs["BaseNights"];
            $AddPrice     = $configs["AddPrice"];
            $MaxNights    = $configs["MaxNights"];

            $HighPrice    = $configs["HighSeasonPrice"];
            $HighAddPrice = $configs["HighAddPrice"];
            $HolidayPrice = $configs["HolidaySeasonPrice"];
            $BasePrice    = $configs["BasePrice"];


            if ($BaseNights==0) {
                $price = 0;
            }
            elseif ($nights <= $BaseNights) {
                if ($mode) {
                    $price = ($season_days['High']*$HighPrice + $season_days['Holiday']*$HolidayPrice + ($nights-$season_days['High']-$season_days['Holiday'])*$BasePrice)/$BaseNights;
                }
                else {
                    $price = $nights*$BasePrice/$BaseNights;
                }
            }
            elseif ($nights <= $MaxNights) {
                if ($mode) {
                    $price = min($season_days['Holiday'], $BaseNights) * $HolidayPrice;
                    $price += max(min($season_days['High'], $BaseNights - $season_days['Holiday']), 0) * $HighPrice;
                    $price += max(min($nights - $season_days['High'] - $season_days['Holiday'], $BaseNights - $season_days['High'] - $season_days['Holiday']), 0) * $BasePrice;
                    $price /= $BaseNights;
                }
                else {
                    $price = $BasePrice;
                }

                //add additional days
                //calculate number of high season additional days
                $season = end($season_dates);
                for ($night = $nights; $night > $BaseNights; --$night) {
                  if ($season == 'High' and $HighAddPrice) {
                    $price += $HighAddPrice;
                  } else {
                    $price += $AddPrice;
                  }
                  $season = prev($season_dates);
                }
            }
            
			// End of holiday-cancun-cancun-arenas


        //add price of options
        foreach ($params as $key => $value) {
          if (isset($configs[$value])) { //this option is selected and has a price
            $price += $configs[$value];
          }
        }

         $price = round($price,2);
            $r = array( "txt"    => $price ? $configs["Currency"].$price : 'n/a',
                        "decimal"=> (float)$price,
                      );
            return $r;
        }

        function calculate_season_price($type, $configs, $params, &$season_dates) {
           $arrival_date1 = strtotime($params['Arrival_Date'].' '.$params['Arrival_Month']);
           $arrival_date2 = strtotime('+'.$params['Nights'].' days',$arrival_date1);
//echo "<b>".date('Y-m-d',$arrival_date1).' :: '.date('Y-m-d',$arrival_date2)."</b><br>\r\n";

           if ($configs["{$type}SeasonPrice"]!=0 && ($dates=preg_split("/;/",$configs["{$type}SeasonDates"], -1, PREG_SPLIT_NO_EMPTY)))
           for ($i=0; $i<count($dates); $i++) {
               list($dd_mm_1, $dd_mm_2) = preg_split("/[\/-]+/", trim($dates[$i]), 2, PREG_SPLIT_NO_EMPTY);

               if ($dd_mm_1) {
                   $date1 = strtotime($dd_mm_1);
                   $date2 = $dd_mm_2 ? strtotime($dd_mm_2) : $date1;
                   if ($date2<$date1) $date2 = strtotime('+1 year',$date2);
                   if ($date2<$arrival_date1) {
                     $date1 = strtotime('+1 year',$date1);
                     $date2 = strtotime('+1 year',$date2);
                   }
/*
                   if (!($arrival_date2<$date1 || $date2<$arrival_date1))
                       return $configs["{$type}SeasonPrice"];
*/

                   $dd = $arrival_date1;
                   do {
//echo "".date('Y-m-d',$date1).' :: '.date('Y-m-d',$dd).' :: '.date('Y-m-d',$date2)."<br>\r\n";
                      if (!($date2<$dd || $dd<$date1))
                          $season_dates[strftime("%Y%m%d",$dd)] = $type;

                      $dd=strtotime("+1 day",$dd);
                   } while ($dd<$arrival_date2);
               }

            }
        }


        function fetchArray($a,$keys) {
            $r = array();
            if (!is_array($a)) { return $r; }
            if (is_string($keys)) {
              $keys = explode(",",$keys);
            } else if (!is_array($keys)) {
              echo "Unknown 'keys' variable type passed to fetchArray.";
              exit;
            }
            foreach ($keys as $key) {
                $r[$key] = $a[$key];
            }
            return $r;
        }

        function fetchFields($a,$keys) {
            $r = array();
            if (!is_array($a)) { return $r; }
            if (is_string($keys)) {
              $keys = explode(",",$keys);
            } else if (!is_array($keys)) {
              echo "Unknown 'keys' variable type passed to fetchFields.";
              exit;
            }
            foreach ($keys as $key) {
                foreach ($a as $field) {
                    if ($field["name"] == $key) {
                        $r[] = $field;
                    }
                }
            }
            return $r;
        }

        function unsetFields($a,$keys) {
            $r = array();
            if (!is_array($a)) { return $r; }
            if (is_string($keys)) {
              $keys = explode(",",$keys);
            } else if (!is_array($keys)) {
              echo "Unknown 'keys' variable type passed to fetchFields.";
              exit;
            }
                foreach ($a as $field) {
                    if (!in_array($field["name"],$keys)) {
                        $r[] = $field;
                    }
                }
            return $r;
        }

        function unsetKeys(&$a,$keys,$mode = '') {
            if (is_string($keys)) {
              $keys = explode(",",$keys);
            } else if (!is_array($keys)) {
              echo "Unknown 'keys' variable type passed to unsetKeys.";
              exit;
            }
            foreach ($keys as $key) {
                if ($mode == "empty") {
                    if ($a[$key] == '') unset($a[$key]);
                } else {
                    if (isset($a[$key])) {
                        unset($a[$key]);
                    }
                }
            }
        }

        function getMode(){
                $mode = '';
                if ($_REQUEST["mode_delete"]) $mode = "delete";
                if ($_REQUEST["mode_edit"]) $mode = "edit";
                if ($_REQUEST["mode_add"]) $mode = "add";
                return $mode;
        }

        function generateMenu($fullMenu,$allowedSections){
                $menu = array();
                foreach ($fullMenu as $key=>$val){
                        if (in_array($key, $allowedSections)) $menu[$key] = $val;
                }
                return $menu;
        }

/**
 * @return string
 * @param type MIME-TYPE of image
 * @desc Returns 0 if image format is supportedelse return error code. 2-unexpected format, 1-image not supported.
 */
function checkImage($type) {

        $gif = array("image/gif");
        $jpg = array("image/jpg","image/jpeg","image/jpe","image/pjpeg");
        $png = array("image/png");

        if(!in_array($type, $gif) && !in_array($type, $jpg) && !in_array($type, $png)) {
                return 2;
        }

        if(in_array($type, $gif) && (!function_exists("imagecreatefromgif") || !function_exists("imagegif"))) {
                return 1;
        }

        if(in_array($type, $jpg) && (!function_exists("imagecreatefromjpeg") || !function_exists("imagejpeg"))) {
                return 1;
        }

        if(in_array($type, $png) && (!function_exists("imagecreatefrompng") || !function_exists("imagepng"))) {
                return 1;
        }

        return 0;
}

/**
 * @return string
 * @param txt string
 * @param cnt int
 * @desc Returns input string txt truncated to cnt number of characters plus the ending of the truncated sentence.
 */
function shortly($txt, $cnt)
{
        $out = strip_tags($txt);
        $out = substr($out, 0, $cnt);
        $end = substr($txt, $cnt, strlen($txt));
        $point = strpos($end, ".");
        $end = substr($end, 0, $point);
        $out .= $end . ". ";
        return $out;
}


function checkEmail($email)
{
         if (eregi("^[a-z0-9\._]{1,30}@([a-z0-9_-]{1,30}\.){1,5}[a-z]{2,3}$",$email)) {
                 return true;
         }else{
                 return false;
        }
}

function alert($msg) {
        norm($msg);
        print "<script>alert('$msg')</script>";
}

function norm($s) {
   $s = ereg_replace("<","&lt;",$s);
   $s = ereg_replace(">","&gt;",$s);
   $s = ereg_replace("\"","&quot;",$s);
   $s = ereg_replace("'","`",$s);
   $s = str_replace("\xD"," ",$s);
   $s = str_replace("\xA","",$s);
   return $s;
}

function normText (&$val, $key) {
        $val = str_replace("\r\n", " ", $val);
}

function normHTML($s) {
   $s = ereg_replace("\"","",$s);
   $s = ereg_replace("'","",$s);
   return $s;
}

function unnorm($s1){
   $s1 = str_replace("&lt;","<",$s1);
   $s1 = str_replace("&gt;",">",$s1);
   $s1 = str_replace("&quot;","\"",$s1);
   $s1 = str_replace("`","'",$s1);
   return $s1;
}


function limitLength($str, $length) {
        if (strlen($str)>$length)
                return substr($str, 0, $length-3)."...";
        else return $str;
}

function stripSlashesArr($arr) {
        if (is_array($arr))
        foreach ($arr as $key=>$val) {
                if (is_scalar($val))
                        $arr[$key] = stripslashes($val);
        }
        return $arr;
}

function rangeArr($from = 0, $to = 0) {
        while($from <= $to) {
                $arr[$from]=$from;
                $from++;
        }
        return $arr;
}

function outputArr($arr, $selected = 0) {
        foreach($arr as $key=>$val) {
                print "<option value='$key'";
                if ((int)$key == (int)$selected) print " selected";
                print ">$val</option>\n";
        }
}

function beginTag($var) {
        return "<".$var.">";
}

function endTag($var) {
        return "</".$var.">\n";
}

function timeArr() {
        $today = getdate();
        return Array(
                "month1" => $today['mon'],
                "day1" => $today['mday'],
                "year1" => $today['year'],
                "hour1" => $today['hours'],
                "minute1" => $today['minutes'],
                "month2" => $today['mon'],
                "day2" => $today['mday'],
                "year2" => $today['year'],
                "hour2" => $today['hours'],
                "minute2" => $today['minutes'],
                "month" => $today['mon'],
                "day" => $today['mday'],
                "year" => $today['year'],
                "hour" => $today['hours'],
                "minute" => $today['minutes']
        );
}

function getInsertionId($tableName, $DB) {
        $query = "select (max(syndicateid)+1) as id from ".$tableName;
        $DB->query($query);
        $DB->next_record();
        return $DB->f("id");
}

function fromSQLDate($date = "0000-00-00", $delim = "-") {
        list ($year, $month, $day) = split ($delim, substr($date,0,10));
        return date("m-d-Y", mktime (0, 0, 0, $month, $day, $year));
}

function toSQLDate($date = "00-00-0000", $delim = "-") {
        list ($month, $day, $year) = split ($delim, $date);
        return date("Y-m-d", mktime (0, 0, 0, $month, $day, $year));
}

function dump($var) {
        global $dumpCounterRND;
        if (defined("DEBUG")) {
                echo "<hr><pre>".(int)$dumpCounterRND++.". ";

                if (is_array($var)) {
                        print_r($var);
                } else {
                        var_dump($var);
                }

                echo "</pre><hr>";
        }
}

function directoryList ($startDir = "./") {
        $d = dir($startDir);
        while (false !== ($entry = $d->read())) {
                $arr[$entry] = $entry;
        }
        $d->close();
        return $arr;
}

function fileinfo($filename) {
        $fileNameArr = explode(".", $filename);
        $fileNameArr[ext] = $fileNameArr[(count($fileNameArr) - 1)];
        $fileNameArr[name] = $fileNameArr[0];
        return $fileNameArr;
}

function getOriginalFileName ($dir, $ext, $prefix = "", $suffix = "") {
        do {
                $filename = $prefix.mt_rand(1, mt_getrandmax()).$suffix.".".$ext;
        } while (file_exists($dir.$filename));
        return $filename;
}

function handleFileUpload ($files, $fieldName, $imageDir) {
                if (is_uploaded_file($files[$fieldName][tmp_name])) {
                        $fileInfoArr = fileinfo($files[$fieldName][name]);
                        $originalFileName = getOriginalFileName($imageDir, $fileInfoArr[ext]);
                        move_uploaded_file($files[$fieldName][tmp_name], $imageDir.$originalFileName);
                }
                return $originalFileName;
}

function uploadedFilesNumber($arr) {
        $number = 0;
        if (is_array($arr)) {
                foreach ($arr as $key => $val) {
                        if (empty($val[error])) {
                                $number++;
                        }
                }
        }
        return $number;
}

function now() {
        return date("Y-m-d H:i:s");
}

if (!function_exists('array_intersect_assoc')) {
        function array_intersect_assoc ($arr1, $arr2) {
                foreach ($arr1 as $key => $val) {
                        if (!in_array($key, array_keys($arr2)) || ($val != $arr2[$key])) {
                                unset($arr1[$key]);
                        }
                }
                return $arr1;
        }
}

function  pagination($count, $_PER_PAGE=_CLASSIFIED_PER_PAGE) {
        $pages = Ceil( $count / $_PER_PAGE ) ;
        for ($i = 0; $i<$pages; $i++) {
                $arr [$i] = $i;
        }

        return $arr;
}

function generateNameImg ($image) {
        $mass[] = "q";
        $mass[] = "w";
        $mass[] = "e";
        $mass[] = "r";
        $mass[] = "t";
        $mass[] = "y";
        $mass[] = "u";
        $mass[] = "i";
        $mass[] = "o";
        $mass[] = "p";
        $mass[] = "a";
        $mass[] = "s";
        $mass[] = "d";
        $mass[] = "f";
        $mass[] = "g";
        $mass[] = "h";
        $mass[] = "j";
        $mass[] = "k";
        $mass[] = "l";
        $mass[] = "z";
        $mass[] = "x";
        $mass[] = "c";
        $mass[] = "v";
        $mass[] = "b";
        $mass[] = "n";
        $mass[] = "1";
        $mass[] = "2";
        $mass[] = "3";
        $mass[] = "4";
        $mass[] = "5";
        $mass[] = "6";
        $mass[] = "7";
        $mass[] = "8";
        $mass[] = "9";
        $mass[] = "0";

        $num = count($mass);
        $str = "";

        for ($i = 0; $i < 7; $i++) {
                $str .= $mass[rand(0, $num)];
        }

        return $str . strrchr($image, '.');
}

// Form sanitation
$db_post = $_POST;
$db_post = array_map('mysql_real_escape_string', $db_post);
$em_post = $_POST;
$em_post = array_map('stripslashes', $em_post);
$em_post = array_map('striptags', $em_post);

// End sanitation


function formatPhone($phone = '', $convert = false, $trim = true)
    {
    // If we have not entered a phone number just return empty
    if (empty($phone)) {
    return '';
    }
     
    // Strip out any extra characters that we do not need only keep letters and numbers
    $phone = preg_replace("/[^0-9A-Za-z]/", "", $phone);
     
    // Do we want to convert phone numbers with letters to their number equivalent?
    // Samples are: 1-800-TERMINIX, 1-800-FLOWERS, 1-800-Petmeds
    if ($convert == true) {
    $replace = array('2'=>array('a','b','c'),
    '3'=>array('d','e','f'),
    '4'=>array('g','h','i'),
    '5'=>array('j','k','l'),
    '6'=>array('m','n','o'),
    '7'=>array('p','q','r','s'),
    '8'=>array('t','u','v'), '9'=>array('w','x','y','z'));
     
    // Replace each letter with a number
    // Notice this is case insensitive with the str_ireplace instead of str_replace
    foreach($replace as $digit=>$letters) {
    $phone = str_ireplace($letters, $digit, $phone);
    }
    }
     
    // If we have a number longer than 11 digits cut the string down to only 11
    // This is also only ran if we want to limit only to 11 characters
    if ($trim == true && strlen($phone)>11) {
    $phone = substr($phone, 0, 11);
    }
     
    // Perform phone number formatting here
    if (strlen($phone) == 7) {
    return preg_replace("/([0-9a-zA-Z]{3})([0-9a-zA-Z]{4})/", "$1-$2", $phone);
    } elseif (strlen($phone) == 10) {
    return preg_replace("/([0-9a-zA-Z]{3})([0-9a-zA-Z]{3})([0-9a-zA-Z]{4})/", "($1) $2-$3", $phone);
    } elseif (strlen($phone) == 11) {
    return preg_replace("/([0-9a-zA-Z]{1})([0-9a-zA-Z]{3})([0-9a-zA-Z]{3})([0-9a-zA-Z]{4})/", "$1($2) $3-$4", $phone);
    }
     
    // Return original phone if not 7, 10 or 11 digits long
    return $phone;
}

?>

Open in new window

There are 4 more files that are called but I'm not sure if I need to post them here:
Smarty.class.php
smarty_local.class.php
smarty.functions.php
and the configuration file

I Hope this helps find the solution. I have been trying to get this done for days now, so I really appreciate any help I can get.
Thanks,
jbatres

Zero AI Policy

We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads.


Avatar of Member_2_6373554Member_2_6373554

htmlentities() should be enough to prevent XSS attack, as injected code is usually javascript.

As I see you first sanitize the code, but later in the same code you use "dirty" user data from _POST array ..

EDIT: sorry I just saw it,both of your  _POST sanitation blocks in reservations.php are block-commented out.

Avatar of Ray PaseurRay Paseur🇺🇸

The mantra is very simple:  Accept Only Known Good Values.  This is a very different philosophical approach from Exclude All Known Bad Values.  In the first case you are safe because you define your own safety.  In the second case, you are at risk because your attackers get to define the attack.  And they won't tell you about it beforehand.  You can't exclude bad values you were not expecting.

You must use htmlentities() before echoing external input to the client browser.  You must use mysql_real_escape_string() before storing external data in your data base.  These are different functions that cover different issues.  I would recommend against receiving external input and running it through htmlentities() before storing it in the data base.  The htmlentities() function changes the length of the input string and you may fall victim to silent truncation.  Besides, it does not escape the signal characters like the apostrophe and quote.

You may want to learn about array_map() so you can do something like this:

$safe_post = array_map('validation_function', $_POST);

Then you can make the rest of your program references to $safe_post instead of $_POST.
http://php.net/manual/en/function.array-map.php

Avatar of Jorge BatresJorge Batres🇺🇸

ASKER

Thank you Ray for you comment, I wish I had more PHP knowledge to be able to apply the method you suggested.  I’m at a beginner’s level, and I don’t want to sound lazy, but in order for me to make the changes to the script, I really need more instructions as to how to do it.

Thanks
jbatres

Reward 1Reward 2Reward 3Reward 4Reward 5Reward 6

EARN REWARDS FOR ASKING, ANSWERING, AND MORE.

Earn free swag for participating on the platform.


Avatar of Ray PaseurRay Paseur🇺🇸

It's a learning process... Maybe you can start with this book.
http://www.sitepoint.com/books/phpmysql5/

Security is fairly important, and if you're not sure what you're doing it's completely OK to hire a professional developer to help you.  If you're working on a "live" web site, you should consider the benefits of having professional help.  If this is just a hobby and the economic outcomes do not matter, then feel free to experiment with the code and data until you understand what works and what fails.  It takes time!

Avatar of Jorge BatresJorge Batres🇺🇸

ASKER

Yes, I totally agree, and I'm actually looking for someone to help me. I will keep reading and I should learn some more, and I thank you for your advice.
Jbatres

Avatar of Marco GasiMarco Gasi🇪🇸

Security is a complex problem, you can't solve it only that way. For instance, you try to avoid XSS sanitizinig your data but you're using $_REQUEST array which make you vulnerable to CSRF attacks.
Anyway, I'm sorry but I can't help you analyzing all that code: you should try to identify where it is the problem, placing some echo (like echo "Step 1 oK"; echo "Step 2 OK"; and so on), so it will be more easy to understand where the problem is.

A last note: if you are interested in php security, I strongly suggest you this book: "Essential Php Security" by Chris Shiflett (http://phpsecurity.org/). Don't worry: there is no theoretical analisis. It is extremely clear, concise and effective: read it and you'll be happy.
Another very useful book is "php|architect's Guide to PHP Security" by Ilia Alshanetsky (http://www.phparch.com/books/phparchitects-guide-to-php-security/)

Cheers (if you can identify better, where is the problem, I'll be happy to help you)

Free T-shirt

Get a FREE t-shirt when you ask your first question.

We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads.


I use those functions for protection:

htmlspecialchars
addslashes

and this made function:
function xss_clean($data){
	
$data = str_replace(array('&amp;','&lt;','&gt;'), array('&amp;amp;','&amp;lt;','&amp;gt;'), $data);
$data = preg_replace('/(&#*\w+)[\x00-\x20]+;/u', '$1;', $data);
$data = preg_replace('/(&#x*[0-9A-F]+);*/iu', '$1;', $data);
$data = html_entity_decode($data, ENT_COMPAT, 'UTF-8');
 
$data = preg_replace('#(<[^>]+?[\x00-\x20"\'])(?:on|xmlns)[^>]*+>#iu', '$1>', $data);
 
$data = preg_replace('#([a-z]*)[\x00-\x20]*=[\x00-\x20]*([`\'"]*)[\x00-\x20]*j[\x00-\x20]*a[\x00-\x20]*v[\x00-\x20]*a[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu', '$1=$2nojavascript...', $data);
$data = preg_replace('#([a-z]*)[\x00-\x20]*=([\'"]*)[\x00-\x20]*v[\x00-\x20]*b[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu', '$1=$2novbscript...', $data);
$data = preg_replace('#([a-z]*)[\x00-\x20]*=([\'"]*)[\x00-\x20]*-moz-binding[\x00-\x20]*:#u', '$1=$2nomozbinding...', $data);
 
$data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?expression[\x00-\x20]*\([^>]*+>#i', '$1>', $data);
$data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?behaviour[\x00-\x20]*\([^>]*+>#i', '$1>', $data);
$data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:*[^>]*+>#iu', '$1>', $data);
 
$data = preg_replace('#</*\w+:\w[^>]*+>#i', '', $data);
 
do{
        $old_data = $data;
        $data = preg_replace('#</*(?:applet|b(?:ase|gsound|link)|embed|frame(?:set)?|i(?:frame|layer)|l(?:ayer|ink)|meta|object|s(?:cript|tyle)|title|xml)[^>]*+>#i', '', $data);
} while ($old_data !== $data);
 
return htmlspecialchars(strip_tags(addslashes(trim($data))));

Open in new window


Hope this helps!

Avatar of Jorge BatresJorge Batres🇺🇸

ASKER

Thank you modserv, I added your function into my functions.php script but unfortunately I get the following error in server's error log: "PHP Parse error: syntax error, unexpected $end in the last line of code on the page.

Avatar of Marco GasiMarco Gasi🇪🇸

The function is missing a brace. Add } at the end of function to close it.

Reward 1Reward 2Reward 3Reward 4Reward 5Reward 6

EARN REWARDS FOR ASKING, ANSWERING, AND MORE.

Earn free swag for participating on the platform.


Avatar of Jorge BatresJorge Batres🇺🇸

ASKER

Ray, I'm still trying to find someone that could do this work for me privately, but in the mean time I wanted to tell you that I also included in functions.php script your suggestion:
$db_post = $_POST;
$db_post = array_map('mysql_real_escape_string', $db_post);
$em_post = $_POST;
$em_post = array_map('stripslashes', $em_post);
$em_post = array_map('striptags', $em_post);

Open in new window

and although that doesn't break the reservation form, it gets 3 errors from the server's errors log, and I know it is the way I'm implementing it, but I thought it would be worth mentioning to you:

PHP Warning: mysql_real_escape_string() [<a href='function.mysql-real-escape-string'>function.mysql-real-escape-string</a>]: Access denied for user 'apache'@'localhost' (using password: NO)

PHP Warning: mysql_real_escape_string() [<a href='function.mysql-real-escape-string'>function.mysql-real-escape-string</a>]: A link to the server could not be established in ....

PHP Warning: array_map() [<a href='function.array-map'>function.array-map</a>]: The first argument, 'striptags', should be either NULL or a valid callback in ...

Open in new window


It looks like I can't take advantage of
function.mysql-real-escape-string in my server as it is right now. Any suggestion, anyone?
Thanks for your help

Avatar of Ray PaseurRay Paseur🇺🇸

One final note, then I'll sign off on this question.  You have many good learning resources that are suggested here (@marqusG: I am a big fan of Chris Shiflett's work and kept close track of it when he was still living in the Washington, DC area).  

I want to return to the concept of Accept Only Known Good Values with a strong emphasis and a few examples.

Let's say you are expecting to receive a positive integer (maybe an auto_increment key to a row in a MySQL data base).  You expect to receive this key from the URL parameter that looks something like this: /path/to/script.php?key=27.  Here is code that would work correctly to ensure you have a safe input.
// MAKE SURE THE URL PARAMETER IS SOMETHING USABLE
$key = isset($_GET['key']) ? $_GET['key'] : FALSE;
if (ctype_digit($key))
{
    /* SAFE TO USE $key IN A QUERY */
}

Open in new window

Let's examine how this works.  First, we use the ternary operator to assign a value to $key.  The value we assign is either the contents of the URL parameter, or FALSE.  Next we test the value in $key to see if it contains only digits.  This is a sensible test because data base keys can only be positive integers.  If the value in $key passes this test, we can run the query.  If it does not pass this test, we cannot run the query because we do not have a Known Good Value for $key.  Man pages here:
http://us.php.net/manual/en/language.operators.comparison.php
http://us.php.net/manual/en/function.ctype-digit.php
http://us.php.net/manual/en/language.types.php

Validation routines can be as simple as checking for a number, and as complex as your own rules of data validation need to be.  Is your script expecting to receive a valid email address?  You can verify that the email address is well-formed and routable with something like the check_valid_email() function shown in the first code snippet of this article.  But you can only know if the email address actually works for a human being if you send and receive a response.  The article here shows how that "handshake" might work.
https://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_3939-Registration-and-Email-Confirmation-in-PHP.html

Are you looking for the name or abbreviation of a USA state?  Something like this little class will be useful.
<?php // RAY_Class_States.php
error_reporting(E_ALL);

Class States
{

    protected $states;
    protected $abbrs;

    public function __construct()
    {
        $this->states['AK'] = 'Alaska';
        $this->states['AL'] = 'Alabama';
        $this->states['AR'] = 'Arkansas';
        $this->states['AZ'] = 'Arizona';
        $this->states['CA'] = 'California';
        $this->states['CO'] = 'Colorado';
        $this->states['CT'] = 'Connecticut';
        $this->states['DC'] = 'Washington DC';
        $this->states['DE'] = 'Delaware';
        $this->states['FL'] = 'Florida';
        $this->states['GA'] = 'Georgia';
        $this->states['HI'] = 'Hawaii';
        $this->states['IA'] = 'Iowa';
        $this->states['ID'] = 'Idaho';
        $this->states['IL'] = 'Illinois';
        $this->states['IN'] = 'Indiana';
        $this->states['KS'] = 'Kansas';
        $this->states['KY'] = 'Kentucky';
        $this->states['LA'] = 'Louisiana';
        $this->states['MA'] = 'Massachusetts';
        $this->states['MD'] = 'Maryland';
        $this->states['ME'] = 'Maine';
        $this->states['MI'] = 'Michigan';
        $this->states['MN'] = 'Minnesota';
        $this->states['MO'] = 'Missouri';
        $this->states['MS'] = 'Mississippi';
        $this->states['MT'] = 'Montana';
        $this->states['NC'] = 'North Carolina';
        $this->states['ND'] = 'North Dakota';
        $this->states['NE'] = 'Nebraska';
        $this->states['NH'] = 'New Hampshire';
        $this->states['NJ'] = 'New Jersey';
        $this->states['NM'] = 'New Mexico';
        $this->states['NV'] = 'Nevada';
        $this->states['NY'] = 'New York';
        $this->states['OH'] = 'Ohio';
        $this->states['OK'] = 'Oklahoma';
        $this->states['OR'] = 'Oregon';
        $this->states['PA'] = 'Pennsylvania';
        $this->states['RI'] = 'Rhode Island';
        $this->states['SC'] = 'South Carolina';
        $this->states['SD'] = 'South Dakota';
        $this->states['TN'] = 'Tennessee';
        $this->states['TX'] = 'Texas';
        $this->states['UT'] = 'Utah';
        $this->states['VA'] = 'Virginia';
        $this->states['VT'] = 'Vermont';
        $this->states['WA'] = 'Washington';
        $this->states['WI'] = 'Wisconsin';
        $this->states['WV'] = 'West Virginia';
        $this->states['WY'] = 'Wyoming';

        $this->abbrs = array_keys($this->states);
    }

    // GET NAME FROM STATE ABBREVIATION
    public function getName($abbr)
    {
        $abbr = trim(strtoupper($abbr));
        if (!isset($this->states[$abbr])) return FALSE;
        return $this->states[$abbr];
    }

    // GET ALL NAMES FROM STATE ABBREVIATIONS
    public function getAllNames()
    {
        return $this->states;
    }

    // GET STATE ABBREVIATIONS
    public function getAllAbbrs()
    {
        return $this->abbrs;
    }

} // END CLASS States


// TEST CLASS STATES
if (!empty($_GET['s']))
{
   $s  = $_GET['s'];

   // INSTANTIATE THE CLASS
   $st = new States;

   // RETRIEVE AND ECHO THE DATA
   $nm = $st->getname($s);
   echo PHP_EOL . "$s NAME = $nm";

   // GET ALL THE ABBREVIATIONS
   $ab = $st->getallabbrs();
   $tx = implode(',', $ab);
   echo PHP_EOL . "ABBREVIATIONS FOR STATES: $tx";
}
?>
<form>
STATE ABBR:
<input name="s" />
<input type="submit" value="go" />
</form>

Open in new window

Your data validation routines are among the most important pieces of code you will ever write, and it is worth spending plenty of time designing them and testing them exhaustively.  The takeaway message should be this: A carefully written definition of Known Good Values should exist for every variable in your PHP script.  If that sounds like a lot of work, well, it is!  But it is what the professionals do, and it has a lot to do with why we get professional results from our programming.

Best of luck with your project, ~Ray

Avatar of Jorge BatresJorge Batres🇺🇸

ASKER

Thank you Ray, I must say that bringing this type of questions here, is beneficial to a lot of people.

Thanks,
jbatres

Free T-shirt

Get a FREE t-shirt when you ask your first question.

We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads.


Avatar of Jorge BatresJorge Batres🇺🇸

ASKER

User generated imageOk, so far I was able to add modserv suggested function with the assistance of marqusG. The reservation script works with no errors, however the script still allows for scripts to be injected in the html inputs. I'm attaching two screenshots sent to me by the security scanning company. Maybe this will help illustrate what I'm trying to accomplish.
User generated image

Avatar of Marco GasiMarco Gasi🇪🇸

If you say problem is in reservation script, please post the clean version you're actually using, purged of all unused code so we can see what you're really using now (the original version has many commented code).

Ooops, you forgto the attachements :-)

Avatar of Jorge BatresJorge Batres🇺🇸

ASKER

sorry, I was having trouble uploading the attachments, but you can see them now

Reward 1Reward 2Reward 3Reward 4Reward 5Reward 6

EARN REWARDS FOR ASKING, ANSWERING, AND MORE.

Earn free swag for participating on the platform.


Avatar of Jorge BatresJorge Batres🇺🇸

ASKER

ok,
reservations.php
<?
define ("LEVEL", '');
include_once(LEVEL."inc/include.php");
// Capitalizes first letter on each word, added on 12-15-09
$arr = array("First_Name", "Last_Name", "Spouse_Name", "Address", "City",  "Province", "Country", "Name_on_card"); 
foreach ($arr as $field)
{
    $_POST[$field] = strip_tags(strtolower(stripslashes($_POST[$field])));

    $_POST["$field"] = ucwords($_POST["$field"]);
}
// End capitalizing




$user = new user();
$reservation = new reservation();
$form_type = $reservation->loadFields($_REQUEST["form_type"]);
$step = ($_REQUEST["step"]) ? ($_REQUEST["step"]) : ("1");
switch($step) {
        case "1":
                $_REQUEST["form_type"] = $form_type;
                $_REQUEST["yes_no"] = 1;
		$order = array("check__fields", "form_type", "Resort", "Hotel", "Room_Type", "Arrival_Month", "Arrival_Date", "Arrival_Year",
			         "Nights", "Tickets", "Adults", "Juniors", "Children");
                $res = sort_res($reservation->showRecord($_REQUEST,$reservation->lists), $order);
                        for($i = 0; $i < sizeof($res); ++$i){
                        	if(in_array($res[$i]["name"], array("Resort", "Hotel", "Arrival_Month", "Arrival_Date", "Arrival_Year", "Room_Type", "Nights", "Tickets"))){
                          		if (isset($_REQUEST[$res[$i]["name"]])) {
						$res[$i]["type"] = "static";
					}
				}
			}

                $smarty->assign("reservation", $res);
        break;
        case "cc":
		$order = array("check__fields", "form_type", "Resort", "Hotel", "Room_Type", "Arrival_Month", "Arrival_Date", "Arrival_Year", "Checkin_Date", "Checkout_Date", "Nights", "Tickets", "Adults", "Juniors", "Children", "Number_of_Guest", "Price",
				 "First_Name", "Last_Name", "Spouse_Name", "Marital_Status", "Address", "City", "State",
				 "Province", "Country", "Zip_Code", "Day_Phone", "Night_Phone", "Email", "Fax",
				 "Best_Time_to_Call", "Age", "Income", "Card_Number",
				 "Card_Expiration", "Name_on_card", "Comments", "agreement");
                $price = CalculatePrice($_POST);
                $_POST["Price"] = $price["txt"];
                $_POST["Country"] = "United States";
                $guests = 0;
                foreach (array("Adults", "Juniors", "Children") as $type){
                  if(isset($_POST[$type])){
                    $guests += $_POST[$type];
                  }
                }
                $_POST["Number_of_Guest"] = $guests;
                unset($_POST["check__fields"]);
				
                $res = $reservation->showRecord($_POST,$reservation->lists);
                
                for($i = 0; $i < sizeof($res); ++$i) {
                 	if ($res[$i]["name"] == "Checkout_Date") {
                 		$res[$i]["type"] = "static";
                 		$res[$i]["check"] = "Check";
                 		$res[$i]["title"] = "Checkout Date";
                 		$res[$i]["value"] = date("l F jS Y", strtotime("+ $_POST[Nights] days", strtotime($_POST["Arrival_Month"] . " " . $_POST["Arrival_Date"] . " " . $_POST["Arrival_Year"])));
                 	}
                	
                 	if ($res[$i]["name"] == "Checkin_Date") {
                 		$res[$i]["type"] = "static";
                 		$res[$i]["check"] = "Check";
                 		$res[$i]["title"] = "Check In Date";
                 		$res[$i]["value"] = date("l F jS Y", strtotime($_POST["Arrival_Month"] . " " . $_POST["Arrival_Date"] . " " . $_POST["Arrival_Year"]));
                 	}
       
                }
                
 
                $res[] = array(
			    'type' => 'checkbox',
			    'check' => 'Check',
			    'name' => 'agreement',
			    'title' => 'I Agree to the Terms & Conditions',
			    'value' => 'To submit the form you must accept the Terms and Conditions.'
                         );
						 

						 
                $res = sort_res($res, $order);
                for($i = 0; $i < sizeof($res); ++$i){
			if(in_array($res[$i]["name"], array("Resort", "Hotel", "Room_Type", "Arrival_Month", "Arrival_Date", "Arrival_Year", "Checkin_Date", "Checkout_Date",
                                 "Nights", "Tickets", "Adults", "Juniors", "Children", "Number_of_Guest", "Price"))){
				$res[$i]["type"] = "static";
                                $res[$i]["check"] = '';
                        }
                        if ($res[$i]["name"] == "check__fields") {
                          $res[$i]["value"] .= ",agreement,Check";
                        }
		}
                $smarty->assign("reservation", $res);
                break;


        case "2":
		$order = array("check__fields", "form_type", "Resort", "Hotel", "Room_Type", "Arrival_Month", "Arrival_Date", "Arrival_Year", "Checkin_Date", "Checkout_Date", "Nights", "Tickets", "Adults", "Juniors", "Children", "Number_of_Guest", "Price",
				 "First_Name", "Last_Name", "Spouse_Name", "Marital_Status", "Address", "City", "State",
				 "Province", "Country", "Zip_Code", "Day_Phone", "Night_Phone", "Email", "Fax",
				 "Best_Time_to_Call", "Age", "Income", "Card_Number", "Card_Type",
				 "Card_Expiration", "Name_on_card", "Comments");
                $price = CalculatePrice($_POST);
                $_POST["Price"] = $price["txt"];
                $guests = 0;
                foreach (array("Adults", "Juniors", "Children") as $type){
                  if(isset($_POST[$type])){
                    $guests += $_POST[$type];
                  }
                }
                $_POST["Number_of_Guest"] = $guests;
                $_POST["Card_Number"] = ereg_replace("[^0-9]", "", $_POST["Card_Number"]);
		if($_POST["Card_Number"][0] == "5"){
			$_POST["Card_Type"] = "Master Card";
		}
		else if ($_POST["Card_Number"][0] == "4"){
			$_POST["Card_Type"] = "Visa";
		}
		else if (substr($_POST["Card_Number"],0, 2) == "34" or substr($_POST["Card_Number"],0, 2) == "37"){
			$_POST["Card_Type"] = "American Express";
		}
		else if (substr($_POST["Card_Number"], 0, 4) == "6011"){
			$_POST["Card_Type"] = "Discover";
		}
		else{
			$_POST["Card_Type"] = "Unknown";
		}

			// Format the phone numbers
			$_POST['Day_Phone'] = formatPhone($_POST['Day_Phone']);
			$_POST['Night_Phone'] = formatPhone($_POST['Night_Phone']);
			$_POST['Fax'] = formatPhone($_POST['Fax']);

		$res = sort_res($reservation->showRecord($_POST,$reservation->lists), $order);
		$newres = array();
		foreach($res as $item){
			if($item["name"] == "Card_Number"){
				$item["type"] = "hidden";
                                $newres[] = $item;
                                $newres[] =  array(
                                                                                    'type' => 'Juniors',
                                                                                    'check' => '#',
                                                                                    'name' => '',
                                                                                    'title' => 'Card Number',
                                                                                    'value' => substr("****************", 0, strlen($item["value"]) - 4) . substr($item["value"], strlen($item["value"]) - 4, 4)
                                                           );
                        }
                        else{
				$newres[] = $item;
			}
		}
		$smarty->assign("reservation", $newres);
        break;
}


function sort_res($res, $order) {
  
  $newres = array();
  foreach($order as $row) {
    foreach($res as $item) {
      if ($item["name"] == $row) {
        $newres[] = $item;
      }
    }
  }
  return $newres;
} 
  



$smarty->assign("content", "reservation".$step.".html");
$smarty->display("form_".$form_type.".html");

?>

Open in new window

and functions.php
<?
        function CalculatePrice($params) {
            global $smarty;
            $hotel     = isset($params["Hotel"]) ? $params["Hotel"] : $params["Resort"];
            $room_type = $params["Room_Type"];
            $nights    = $params["Nights"];
            $adults    = isset($params["Adults"]) ?  $params["Adults"] : 0;
            $children  = isset($params["Children"]) ?  $params["Children"] : 0;
            $juniors   = isset($params["Juniors"]) ?  $params["Juniors"] : 0;
            $form_type = isset($params["form_type"]) ?  $params["form_type"] : "";

            $section   = $hotel.":".$room_type;
//            dump($section);

            $mode = 1;
            $smarty->config_load('calculation_high_season.conf',$section);
            $configs = $smarty->get_config_vars();

        if ($configs["BaseNights"]) {
            $season_dates = array();
            calculate_season_price("High",$configs,$params,$season_dates);
            calculate_season_price("Holiday",$configs,$params,$season_dates);
            $season_days  = array_count_values($season_dates);
        }
        else {
            $mode = 0;
            $smarty->config_load('calculation.conf',$section);
            $configs = $smarty->get_config_vars();
        }

            $Currency     = $configs["Currency"];
            $BaseNights   = $configs["BaseNights"];
            $AddPrice     = $configs["AddPrice"];
            $MaxNights    = $configs["MaxNights"];

            $HighPrice    = $configs["HighSeasonPrice"];
            $HighAddPrice = $configs["HighAddPrice"];
            $HolidayPrice = $configs["HolidaySeasonPrice"];
            $BasePrice    = $configs["BasePrice"];


            if ($BaseNights==0) {
                $price = 0;
            }
            elseif ($nights <= $BaseNights) {
                if ($mode) {
                    $price = ($season_days['High']*$HighPrice + $season_days['Holiday']*$HolidayPrice + ($nights-$season_days['High']-$season_days['Holiday'])*$BasePrice)/$BaseNights;
                }
                else {
                    $price = $nights*$BasePrice/$BaseNights;
                }
            }
            elseif ($nights <= $MaxNights) {
                if ($mode) {
                    $price = min($season_days['Holiday'], $BaseNights) * $HolidayPrice;
                    $price += max(min($season_days['High'], $BaseNights - $season_days['Holiday']), 0) * $HighPrice;
                    $price += max(min($nights - $season_days['High'] - $season_days['Holiday'], $BaseNights - $season_days['High'] - $season_days['Holiday']), 0) * $BasePrice;
                    $price /= $BaseNights;
                }
                else {
                    $price = $BasePrice;
                }

                //add additional days
                //calculate number of high season additional days
                $season = end($season_dates);
                for ($night = $nights; $night > $BaseNights; --$night) {
                  if ($season == 'High' and $HighAddPrice) {
                    $price += $HighAddPrice;
                  } else {
                    $price += $AddPrice;
                  }
                  $season = prev($season_dates);
                }
            }
            



        //add price of options
        foreach ($params as $key => $value) {
          if (isset($configs[$value])) { //this option is selected and has a price
            $price += $configs[$value];
          }
        }

         $price = round($price,2);
            $r = array( "txt"    => $price ? $configs["Currency"].$price : 'n/a',
                        "decimal"=> (float)$price,
                      );
            return $r;
        }

        function calculate_season_price($type, $configs, $params, &$season_dates) {
           $arrival_date1 = strtotime($params['Arrival_Date'].' '.$params['Arrival_Month']);
           $arrival_date2 = strtotime('+'.$params['Nights'].' days',$arrival_date1);


           if ($configs["{$type}SeasonPrice"]!=0 && ($dates=preg_split("/;/",$configs["{$type}SeasonDates"], -1, PREG_SPLIT_NO_EMPTY)))
           for ($i=0; $i<count($dates); $i++) {
               list($dd_mm_1, $dd_mm_2) = preg_split("/[\/-]+/", trim($dates[$i]), 2, PREG_SPLIT_NO_EMPTY);

               if ($dd_mm_1) {
                   $date1 = strtotime($dd_mm_1);
                   $date2 = $dd_mm_2 ? strtotime($dd_mm_2) : $date1;
                   if ($date2<$date1) $date2 = strtotime('+1 year',$date2);
                   if ($date2<$arrival_date1) {
                     $date1 = strtotime('+1 year',$date1);
                     $date2 = strtotime('+1 year',$date2);
                   }


                   $dd = $arrival_date1;
                   do {

                      if (!($date2<$dd || $dd<$date1))
                          $season_dates[strftime("%Y%m%d",$dd)] = $type;

                      $dd=strtotime("+1 day",$dd);
                   } while ($dd<$arrival_date2);
               }

            }
        }


        function fetchArray($a,$keys) {
            $r = array();
            if (!is_array($a)) { return $r; }
            if (is_string($keys)) {
              $keys = explode(",",$keys);
            } else if (!is_array($keys)) {
              echo "Unknown 'keys' variable type passed to fetchArray.";
              exit;
            }
            foreach ($keys as $key) {
                $r[$key] = $a[$key];
            }
            return $r;
        }

        function fetchFields($a,$keys) {
            $r = array();
            if (!is_array($a)) { return $r; }
            if (is_string($keys)) {
              $keys = explode(",",$keys);
            } else if (!is_array($keys)) {
              echo "Unknown 'keys' variable type passed to fetchFields.";
              exit;
            }
            foreach ($keys as $key) {
                foreach ($a as $field) {
                    if ($field["name"] == $key) {
                        $r[] = $field;
                    }
                }
            }
            return $r;
        }

        function unsetFields($a,$keys) {
            $r = array();
            if (!is_array($a)) { return $r; }
            if (is_string($keys)) {
              $keys = explode(",",$keys);
            } else if (!is_array($keys)) {
              echo "Unknown 'keys' variable type passed to fetchFields.";
              exit;
            }
                foreach ($a as $field) {
                    if (!in_array($field["name"],$keys)) {
                        $r[] = $field;
                    }
                }
            return $r;
        }

        function unsetKeys(&$a,$keys,$mode = '') {
            if (is_string($keys)) {
              $keys = explode(",",$keys);
            } else if (!is_array($keys)) {
              echo "Unknown 'keys' variable type passed to unsetKeys.";
              exit;
            }
            foreach ($keys as $key) {
                if ($mode == "empty") {
                    if ($a[$key] == '') unset($a[$key]);
                } else {
                    if (isset($a[$key])) {
                        unset($a[$key]);
                    }
                }
            }
        }

        function getMode(){
                $mode = '';
                if ($_REQUEST["mode_delete"]) $mode = "delete";
                if ($_REQUEST["mode_edit"]) $mode = "edit";
                if ($_REQUEST["mode_add"]) $mode = "add";
                return $mode;
        }

        function generateMenu($fullMenu,$allowedSections){
                $menu = array();
                foreach ($fullMenu as $key=>$val){
                        if (in_array($key, $allowedSections)) $menu[$key] = $val;
                }
                return $menu;
        }

/**
 * @return string
 * @param type MIME-TYPE of image
 * @desc Returns 0 if image format is supportedelse return error code. 2-unexpected format, 1-image not supported.
 */
function checkImage($type) {

        $gif = array("image/gif");
        $jpg = array("image/jpg","image/jpeg","image/jpe","image/pjpeg");
        $png = array("image/png");

        if(!in_array($type, $gif) && !in_array($type, $jpg) && !in_array($type, $png)) {
                return 2;
        }

        if(in_array($type, $gif) && (!function_exists("imagecreatefromgif") || !function_exists("imagegif"))) {
                return 1;
        }

        if(in_array($type, $jpg) && (!function_exists("imagecreatefromjpeg") || !function_exists("imagejpeg"))) {
                return 1;
        }

        if(in_array($type, $png) && (!function_exists("imagecreatefrompng") || !function_exists("imagepng"))) {
                return 1;
        }

        return 0;
}

/**
 * @return string
 * @param txt string
 * @param cnt int
 * @desc Returns input string txt truncated to cnt number of characters plus the ending of the truncated sentence.
 */
function shortly($txt, $cnt)
{
        $out = strip_tags($txt);
        $out = substr($out, 0, $cnt);
        $end = substr($txt, $cnt, strlen($txt));
        $point = strpos($end, ".");
        $end = substr($end, 0, $point);
        $out .= $end . ". ";
        return $out;
}


function checkEmail($email)
{
         if (eregi("^[a-z0-9\._]{1,30}@([a-z0-9_-]{1,30}\.){1,5}[a-z]{2,3}$",$email)) {
                 return true;
         }else{
                 return false;
        }
}

function alert($msg) {
        norm($msg);
        print "<script>alert('$msg')</script>";
}

function norm($s) {
   $s = ereg_replace("<","&lt;",$s);
   $s = ereg_replace(">","&gt;",$s);
   $s = ereg_replace("\"","&quot;",$s);
   $s = ereg_replace("'","`",$s);
   $s = str_replace("\xD"," ",$s);
   $s = str_replace("\xA","",$s);
   return $s;
}

function normText (&$val, $key) {
        $val = str_replace("\r\n", " ", $val);
}

function normHTML($s) {
   $s = ereg_replace("\"","",$s);
   $s = ereg_replace("'","",$s);
   return $s;
}

function unnorm($s1){
   $s1 = str_replace("&lt;","<",$s1);
   $s1 = str_replace("&gt;",">",$s1);
   $s1 = str_replace("&quot;","\"",$s1);
   $s1 = str_replace("`","'",$s1);
   return $s1;
}


function limitLength($str, $length) {
        if (strlen($str)>$length)
                return substr($str, 0, $length-3)."...";
        else return $str;
}

function stripSlashesArr($arr) {
        if (is_array($arr))
        foreach ($arr as $key=>$val) {
                if (is_scalar($val))
                        $arr[$key] = stripslashes($val);
        }
        return $arr;
}

function rangeArr($from = 0, $to = 0) {
        while($from <= $to) {
                $arr[$from]=$from;
                $from++;
        }
        return $arr;
}

function outputArr($arr, $selected = 0) {
        foreach($arr as $key=>$val) {
                print "<option value='$key'";
                if ((int)$key == (int)$selected) print " selected";
                print ">$val</option>\n";
        }
}

function beginTag($var) {
        return "<".$var.">";
}

function endTag($var) {
        return "</".$var.">\n";
}

function timeArr() {
        $today = getdate();
        return Array(
                "month1" => $today['mon'],
                "day1" => $today['mday'],
                "year1" => $today['year'],
                "hour1" => $today['hours'],
                "minute1" => $today['minutes'],
                "month2" => $today['mon'],
                "day2" => $today['mday'],
                "year2" => $today['year'],
                "hour2" => $today['hours'],
                "minute2" => $today['minutes'],
                "month" => $today['mon'],
                "day" => $today['mday'],
                "year" => $today['year'],
                "hour" => $today['hours'],
                "minute" => $today['minutes']
        );
}

function getInsertionId($tableName, $DB) {
        $query = "select (max(syndicateid)+1) as id from ".$tableName;
        $DB->query($query);
        $DB->next_record();
        return $DB->f("id");
}

function fromSQLDate($date = "0000-00-00", $delim = "-") {
        list ($year, $month, $day) = split ($delim, substr($date,0,10));
        return date("m-d-Y", mktime (0, 0, 0, $month, $day, $year));
}

function toSQLDate($date = "00-00-0000", $delim = "-") {
        list ($month, $day, $year) = split ($delim, $date);
        return date("Y-m-d", mktime (0, 0, 0, $month, $day, $year));
}

function dump($var) {
        global $dumpCounterRND;
        if (defined("DEBUG")) {
                echo "<hr><pre>".(int)$dumpCounterRND++.". ";

                if (is_array($var)) {
                        print_r($var);
                } else {
                        var_dump($var);
                }

                echo "</pre><hr>";
        }
}

function directoryList ($startDir = "./") {
        $d = dir($startDir);
        while (false !== ($entry = $d->read())) {
                $arr[$entry] = $entry;
        }
        $d->close();
        return $arr;
}

function fileinfo($filename) {
        $fileNameArr = explode(".", $filename);
        $fileNameArr[ext] = $fileNameArr[(count($fileNameArr) - 1)];
        $fileNameArr[name] = $fileNameArr[0];
        return $fileNameArr;
}

function getOriginalFileName ($dir, $ext, $prefix = "", $suffix = "") {
        do {
                $filename = $prefix.mt_rand(1, mt_getrandmax()).$suffix.".".$ext;
        } while (file_exists($dir.$filename));
        return $filename;
}

function handleFileUpload ($files, $fieldName, $imageDir) {
                if (is_uploaded_file($files[$fieldName][tmp_name])) {
                        $fileInfoArr = fileinfo($files[$fieldName][name]);
                        $originalFileName = getOriginalFileName($imageDir, $fileInfoArr[ext]);
                        move_uploaded_file($files[$fieldName][tmp_name], $imageDir.$originalFileName);
                }
                return $originalFileName;
}

function uploadedFilesNumber($arr) {
        $number = 0;
        if (is_array($arr)) {
                foreach ($arr as $key => $val) {
                        if (empty($val[error])) {
                                $number++;
                        }
                }
        }
        return $number;
}

function now() {
        return date("Y-m-d H:i:s");
}

if (!function_exists('array_intersect_assoc')) {
        function array_intersect_assoc ($arr1, $arr2) {
                foreach ($arr1 as $key => $val) {
                        if (!in_array($key, array_keys($arr2)) || ($val != $arr2[$key])) {
                                unset($arr1[$key]);
                        }
                }
                return $arr1;
        }
}

function  pagination($count, $_PER_PAGE=_CLASSIFIED_PER_PAGE) {
        $pages = Ceil( $count / $_PER_PAGE ) ;
        for ($i = 0; $i<$pages; $i++) {
                $arr [$i] = $i;
        }

        return $arr;
}

function generateNameImg ($image) {
        $mass[] = "q";
        $mass[] = "w";
        $mass[] = "e";
        $mass[] = "r";
        $mass[] = "t";
        $mass[] = "y";
        $mass[] = "u";
        $mass[] = "i";
        $mass[] = "o";
        $mass[] = "p";
        $mass[] = "a";
        $mass[] = "s";
        $mass[] = "d";
        $mass[] = "f";
        $mass[] = "g";
        $mass[] = "h";
        $mass[] = "j";
        $mass[] = "k";
        $mass[] = "l";
        $mass[] = "z";
        $mass[] = "x";
        $mass[] = "c";
        $mass[] = "v";
        $mass[] = "b";
        $mass[] = "n";
        $mass[] = "1";
        $mass[] = "2";
        $mass[] = "3";
        $mass[] = "4";
        $mass[] = "5";
        $mass[] = "6";
        $mass[] = "7";
        $mass[] = "8";
        $mass[] = "9";
        $mass[] = "0";

        $num = count($mass);
        $str = "";

        for ($i = 0; $i < 7; $i++) {
                $str .= $mass[rand(0, $num)];
        }

        return $str . strrchr($image, '.');
}
//Sanitation suggested by modserv
function xss_clean($data){
	
$data = str_replace(array('&amp;','&lt;','&gt;'), array('&amp;amp;','&amp;lt;','&amp;gt;'), $data);
$data = preg_replace('/(&#*\w+)[\x00-\x20]+;/u', '$1;', $data);
$data = preg_replace('/(&#x*[0-9A-F]+);*/iu', '$1;', $data);
$data = html_entity_decode($data, ENT_COMPAT, 'UTF-8');
 
$data = preg_replace('#(<[^>]+?[\x00-\x20"\'])(?:on|xmlns)[^>]*+>#iu', '$1>', $data);
 
$data = preg_replace('#([a-z]*)[\x00-\x20]*=[\x00-\x20]*([`\'"]*)[\x00-\x20]*j[\x00-\x20]*a[\x00-\x20]*v[\x00-\x20]*a[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu', '$1=$2nojavascript...', $data);
$data = preg_replace('#([a-z]*)[\x00-\x20]*=([\'"]*)[\x00-\x20]*v[\x00-\x20]*b[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu', '$1=$2novbscript...', $data);
$data = preg_replace('#([a-z]*)[\x00-\x20]*=([\'"]*)[\x00-\x20]*-moz-binding[\x00-\x20]*:#u', '$1=$2nomozbinding...', $data);
 
$data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?expression[\x00-\x20]*\([^>]*+>#i', '$1>', $data);
$data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?behaviour[\x00-\x20]*\([^>]*+>#i', '$1>', $data);
$data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:*[^>]*+>#iu', '$1>', $data);
 
$data = preg_replace('#</*\w+:\w[^>]*+>#i', '', $data);
 
do{
        $old_data = $data;
        $data = preg_replace('#</*(?:applet|b(?:ase|gsound|link)|embed|frame(?:set)?|i(?:frame|layer)|l(?:ayer|ink)|meta|object|s(?:cript|tyle)|title|xml)[^>]*+>#i', '', $data);
} while ($old_data !== $data);
 
return htmlspecialchars(strip_tags(addslashes(trim($data))));}
// end sanitation




function formatPhone($phone = '', $convert = false, $trim = true)
    {
    // If we have not entered a phone number just return empty
    if (empty($phone)) {
    return '';
    }
     
    // Strip out any extra characters that we do not need only keep letters and numbers
    $phone = preg_replace("/[^0-9A-Za-z]/", "", $phone);
     
    // Do we want to convert phone numbers with letters to their number equivalent?
    // Samples are: 1-800-TERMINIX, 1-800-FLOWERS, 1-800-Petmeds
    if ($convert == true) {
    $replace = array('2'=>array('a','b','c'),
    '3'=>array('d','e','f'),
    '4'=>array('g','h','i'),
    '5'=>array('j','k','l'),
    '6'=>array('m','n','o'),
    '7'=>array('p','q','r','s'),
    '8'=>array('t','u','v'), '9'=>array('w','x','y','z'));
     
    // Replace each letter with a number
    // Notice this is case insensitive with the str_ireplace instead of str_replace
    foreach($replace as $digit=>$letters) {
    $phone = str_ireplace($letters, $digit, $phone);
    }
    }
     
    // If we have a number longer than 11 digits cut the string down to only 11
    // This is also only ran if we want to limit only to 11 characters
    if ($trim == true && strlen($phone)>11) {
    $phone = substr($phone, 0, 11);
    }
     
    // Perform phone number formatting here
    if (strlen($phone) == 7) {
    return preg_replace("/([0-9a-zA-Z]{3})([0-9a-zA-Z]{4})/", "$1-$2", $phone);
    } elseif (strlen($phone) == 10) {
    return preg_replace("/([0-9a-zA-Z]{3})([0-9a-zA-Z]{3})([0-9a-zA-Z]{4})/", "($1) $2-$3", $phone);
    } elseif (strlen($phone) == 11) {
    return preg_replace("/([0-9a-zA-Z]{1})([0-9a-zA-Z]{3})([0-9a-zA-Z]{3})([0-9a-zA-Z]{4})/", "$1($2) $3-$4", $phone);
    }
     
    // Return original phone if not 7, 10 or 11 digits long
    return $phone;
}

?>

Open in new window


Avatar of Marco GasiMarco Gasi🇪🇸

I see the routine you're using but you are filtering only some elements of the $%_POST array. Looking at the first screenshot you posted above, I see the form element which contains the malicious code is "Adults", but you're not sanitizing it. To be sure, I would do something like this:

$clean = array();
foreach ($_POST as $key=>$value) {
  $clean[$key] = strip_tags(strtolower(stripslashes($_POST[$value])));
}
unset($_POST);//empty $_POST array so you'll never can access to not sanitized data

Do this replacing your actual code

$arr = array("First_Name", "Last_Name", "Spouse_Name", "Address", "City",  "Province", "Country", "Name_on_card");
foreach ($arr as $field)
{
    $_POST[$field] = strip_tags(strtolower(stripslashes($_POST[$field])));

    $_POST["$field"] = ucwords($_POST["$field"]);
}

and then change the entire script to use sanitized data. For instance you'll have to replace

                $price = CalculatePrice($_POST);
                $_POST["Price"] = $price["txt"];
                $_POST["Country"] = "United States";

with
                $price = CalculatePrice($clean);
                $_clean["Price"] = $price["txt"];
                $clean["Country"] = "United States";

Last note: why are you using $_REQUEST? Should its values be in $_POST array? If so, forget $_REQUEST. At that point, you have to use $clean yet.

Cheers

Avatar of Jorge BatresJorge Batres🇺🇸

ASKER

Thank you, Your suggestion actually stopped the malicious script from being loaded! now I'm guessing I need to replace every $_REQUEST reference with $_POST on the reservations.php script correct? the reason I say this is because when I fill the form normaly, only check in date and check outdate are shown and everything else is blank.
Thanks,

Free T-shirt

Get a FREE t-shirt when you ask your first question.

We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads.


Avatar of Marco GasiMarco Gasi🇪🇸

Please, maybe I'm wrong, so correct me if so.

1. your reservation script get all data from a form which has a method='post';
2. so you have no reason to use $_REQUEST because all your data are in $_POST
3. since yu have sanitized all $_POST data storing them in the $clean array, after the sanitization routine you have only to use $clean: no more $_POST nor $_REQUEST. If you have followed my suggestion, using $_REQUEST returns nothing because $_GET has never been filled and $_POST has been emptied by you with unset($_POST);

I say one more time: use only $clean array: is the only one array which contains valid data (and the only one which contains data at all, since we have emptied $_POST array)

If you have some doubt feel free to ask: I'm here ;-)

Avatar of Jorge BatresJorge Batres🇺🇸

ASKER

Thank you so very much, I think you got the solution, and I just have to implement it correctly. When I tried the first time without changing $_REQUEST or $_POST, nothing got transfered to the following step, just empty fields except for Checkin_Date and Checkout_Date, so we are very close. I will try again and I'll post the results in a couple of minutes.
Thanks,
jbatres

Avatar of Jorge BatresJorge Batres🇺🇸

ASKER

I have modified the reservations.php as follows:
<?
define ("LEVEL", '');
include_once(LEVEL."inc/include.php");
$clean = array();
foreach ($_POST as $key=>$value) {
  $clean[$key] = strip_tags(strtolower(stripslashes($_POST[$value])));
}
unset($_POST);//

$user = new user();
$reservation = new reservation();
$form_type = $reservation->loadFields($clean["form_type"]);
$step = ($clean["step"]) ? ($clean["step"]) : ("1");
switch($step) {
        case "1":
                $clean["form_type"] = $form_type;
                $clean["yes_no"] = 1;
		$order = array("check__fields", "form_type", "Resort", "Hotel", "Room_Type", "Arrival_Month", "Arrival_Date", "Arrival_Year",
			         "Nights", "Tickets", "Adults", "Juniors", "Children");
                $res = sort_res($reservation->showRecord($clean,$reservation->lists), $order);
                        for($i = 0; $i < sizeof($res); ++$i){
                        	if(in_array($res[$i]["name"], array("Resort", "Hotel", "Arrival_Month", "Arrival_Date", "Arrival_Year", "Room_Type", "Nights", "Tickets"))){
                          		if (isset($clean[$res[$i]["name"]])) {
						$res[$i]["type"] = "static";
					}
				}
			}
        				/*
        				if($form_type == "cancun"){
                        $newres  = array();
                        foreach($res as $item){
                                $newres[] = $item;
                                if($item["name"] == "Adults"){
                                        $newres[] =  array(
                                        				            'type' => 'Juniors',
                                        				            'check' => '#',
                                        				            'name' => 'Juniors',
                                        				            'title' => 'Juniors (12-17)',
                                        				            'value' => '',
                         	                           );
                                }
                        }
                        $res = $newres;
                }  */
                $smarty->assign("reservation", $res);
        break;
        case "cc":
		$order = array("check__fields", "form_type", "Resort", "Hotel", "Room_Type", "Arrival_Month", "Arrival_Date", "Arrival_Year", "Checkin_Date", "Checkout_Date", "Nights", "Tickets", "Adults", "Juniors", "Children", "Number_of_Guest", "Price",
				 "First_Name", "Last_Name", "Spouse_Name", "Marital_Status", "Address", "City", "State",
				 "Province", "Country", "Zip_Code", "Day_Phone", "Night_Phone", "Email", "Fax",
				 "Best_Time_to_Call", "Age", "Income", "Card_Number",
				 "Card_Expiration", "Name_on_card", "Comments", "agreement");
                $price = CalculatePrice($clean);
                $clean["Price"] = $price["txt"];
                $clean["Country"] = "United States";
                $guests = 0;
                foreach (array("Adults", "Juniors", "Children") as $type){
                  if(isset($clean[$type])){
                    $guests += $clean[$type];
                  }
                }
                $clean["Number_of_Guest"] = $guests;
                unset($clean["check__fields"]);
				
                $res = $reservation->showRecord($clean,$reservation->lists);
                
                for($i = 0; $i < sizeof($res); ++$i) {
                 	if ($res[$i]["name"] == "Checkout_Date") {
                 		$res[$i]["type"] = "static";
                 		$res[$i]["check"] = "Check";
                 		$res[$i]["title"] = "Checkout Date";
                 		$res[$i]["value"] = date("l F jS Y", strtotime("+ $_POST[Nights] days", strtotime($clean["Arrival_Month"] . " " . $clean["Arrival_Date"] . " " . $clean["Arrival_Year"])));
                 	}
                	
                 	if ($res[$i]["name"] == "Checkin_Date") {
                 		$res[$i]["type"] = "static";
                 		$res[$i]["check"] = "Check";
                 		$res[$i]["title"] = "Check In Date";
                 		$res[$i]["value"] = date("l F jS Y", strtotime($clean["Arrival_Month"] . " " . $clean["Arrival_Date"] . " " . $clean["Arrival_Year"]));
                 	}
       
                }
                
//var_dump($res);
                $res[] = array(
			    'type' => 'checkbox',
			    'check' => 'Check',
			    'name' => 'agreement',
			    'title' => 'I Agree to the Terms & Conditions',
			    'value' => 'To submit the form you must accept the Terms and Conditions.'
                         );
						 
//                 $res[] = array(
// 			    'type' => 'static',
// 			    'check' => '',
// 			    'name' => 'Checkout_Date',
// 			    'title' => 'Checkout Date',
// 			    'value' => date("l F jS Y", strtotime("+ $_POST[Nights] days", strtotime($_POST["Arrival_Month"] . " " . $_POST["Arrival_Date"] . " " . $_POST["Arrival_Year"])))
//                          );
						 
// 				$res[] = array(
// 			    'type' => 'static',
// 			    'check' => 'Check',
// 			    'name' => 'Checkin_Date',
// 			    'title' => 'Check In Date',
// 			    'value' => date("l F jS Y", strtotime($_POST["Arrival_Month"] . " " . $_POST["Arrival_Date"] . " " . $_POST["Arrival_Year"]))
//                          );
						 
                $res = sort_res($res, $order);
                for($i = 0; $i < sizeof($res); ++$i){
			if(in_array($res[$i]["name"], array("Resort", "Hotel", "Room_Type", "Arrival_Month", "Arrival_Date", "Arrival_Year", "Checkin_Date", "Checkout_Date",
                                 "Nights", "Tickets", "Adults", "Juniors", "Children", "Number_of_Guest", "Price"))){
				$res[$i]["type"] = "static";
                                $res[$i]["check"] = '';
                        }
                        if ($res[$i]["name"] == "check__fields") {
                          $res[$i]["value"] .= ",agreement,Check";
                        }
		}
                $smarty->assign("reservation", $res);
                break;


        case "2":
		$order = array("check__fields", "form_type", "Resort", "Hotel", "Room_Type", "Arrival_Month", "Arrival_Date", "Arrival_Year", "Checkin_Date", "Checkout_Date", "Nights", "Tickets", "Adults", "Juniors", "Children", "Number_of_Guest", "Price",
				 "First_Name", "Last_Name", "Spouse_Name", "Marital_Status", "Address", "City", "State",
				 "Province", "Country", "Zip_Code", "Day_Phone", "Night_Phone", "Email", "Fax",
				 "Best_Time_to_Call", "Age", "Income", "Card_Number", "Card_Type",
				 "Card_Expiration", "Name_on_card", "Comments");
                $price = CalculatePrice($clean);
                $clean["Price"] = $price["txt"];
                $guests = 0;
                foreach (array("Adults", "Juniors", "Children") as $type){
                  if(isset($clean[$type])){
                    $guests += $clean[$type];
                  }
                }
                $clean["Number_of_Guest"] = $guests;
                $clean["Card_Number"] = ereg_replace("[^0-9]", "", $clean["Card_Number"]);
		if($clean["Card_Number"][0] == "5"){
			$clean["Card_Type"] = "Master Card";
		}
		else if ($clean["Card_Number"][0] == "4"){
			$clean["Card_Type"] = "Visa";
		}
		else if (substr($clean["Card_Number"],0, 2) == "34" or substr($clean["Card_Number"],0, 2) == "37"){
			$clean["Card_Type"] = "American Express";
		}
		else if (substr($clean["Card_Number"], 0, 4) == "6011"){
			$clean["Card_Type"] = "Discover";
		}
		else{
			$clean["Card_Type"] = "Unknown";
		}

			// Format the phone numbers
			$clean['Day_Phone'] = formatPhone($clean['Day_Phone']);
			$clean['Night_Phone'] = formatPhone($clean['Night_Phone']);
			$clean['Fax'] = formatPhone($clean['Fax']);

		$res = sort_res($reservation->showRecord($clean,$reservation->lists), $order);
		$newres = array();
		foreach($res as $item){
			if($item["name"] == "Card_Number"){
				$item["type"] = "hidden";
                                $newres[] = $item;
                                $newres[] =  array(
                                                                                    'type' => 'Juniors',
                                                                                    'check' => '#',
                                                                                    'name' => '',
                                                                                    'title' => 'Card Number',
                                                                                    'value' => substr("****************", 0, strlen($item["value"]) - 4) . substr($item["value"], strlen($item["value"]) - 4, 4)
                                                           );
                        }
                        else{
				$newres[] = $item;
			}
		}
		$smarty->assign("reservation", $newres);
        break;
}


function sort_res($res, $order) {
  
  $newres = array();
  foreach($order as $row) {
    foreach($res as $item) {
      if ($item["name"] == $row) {
        $newres[] = $item;
      }
    }
  }
  return $newres;
} 
  



$smarty->assign("content", "reservation".$step.".html");
$smarty->display("form_".$form_type.".html");

?>

Open in new window

and the form works and goes to the next step, but only two fields are displayed: the Check in date and Check out date. Sorry, I was trying to upload a screenshot but I couldn't for some reason

Reward 1Reward 2Reward 3Reward 4Reward 5Reward 6

EARN REWARDS FOR ASKING, ANSWERING, AND MORE.

Earn free swag for participating on the platform.


Avatar of Jorge BatresJorge Batres🇺🇸

ASKER

here is the screenshot
User generated image

Avatar of Marco GasiMarco Gasi🇪🇸

Please, place this immediately after the sanitization routin and post here the output

echo "<pre>";//make it readable
var_dump($clean);
echo "</pre>";

See if the output is what you're expecting to see or if there is something wrong.

I'll wait for inputs.

Avatar of Jorge BatresJorge Batres🇺🇸

ASKER

it showed this:

array(14) {
  ["step"]=>
  string(0) ""
  ["check__fields"]=>
  string(0) ""
  ["form_type"]=>
  string(0) ""
  ["Room_Type"]=>
  string(0) ""
  ["Arrival_Month"]=>
  string(0) ""
  ["Arrival_Date"]=>
  string(0) ""
  ["Arrival_Year"]=>
  string(0) ""
  ["Nights"]=>
  string(0) ""
  ["Hotel"]=>
  string(0) ""
  ["Adults"]=>
  string(0) ""
  ["Juniors"]=>
  string(0) ""
  ["Children"]=>
  string(0) ""
  ["Tickets"]=>
  string(0) ""
  ["submit2"]=>
  string(0) ""
}

Free T-shirt

Get a FREE t-shirt when you ask your first question.

We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads.


Avatar of Marco GasiMarco Gasi🇪🇸

Wow! Now see if the $_POST contains right data: place this at the top of the script

echo "<pre>";//make it readable
var_dump($_POST);
echo "</pre>";

Avatar of Jorge BatresJorge Batres🇺🇸

ASKER

ok, here it is:

array(14) {
  ["step"]=>
  string(2) "cc"
  ["check__fields"]=>
  string(306) "status,#,First_Name,#,Last_Name,#,Spouse_Name,#,Address,#,City,#,State,#,Zip_Code,#,Country,#,Day_Phone,#,Email,#Email,Arrival_Month,#,Arrival_Date,#,Arrival_Year,#,Resort,#,Room_Type,#,Nights,#,Guest,#,Adults,#,Children,#,Juniors,#,Income,#,Age,#,Card_Type,#,Card_Number,#,Card_Expiration,#,Name_on_card,#"
  ["form_type"]=>
  string(11) "silver-lake"
  ["Room_Type"]=>
  string(17) "One Bedroom Condo"
  ["Arrival_Month"]=>
  string(3) "May"
  ["Arrival_Date"]=>
  string(2) "10"
  ["Arrival_Year"]=>
  string(4) "2012"
  ["Nights"]=>
  string(1) "4"
  ["Hotel"]=>
  string(18) "Silver Lake Resort"
  ["Adults"]=>
  string(1) "1"
  ["Juniors"]=>
  string(1) "1"
  ["Children"]=>
  string(1) "0"
  ["Tickets"]=>
  string(45) "Two 2 Day Disney World Touch of Magic Tickets"
  ["submit2"]=>
  string(25) "Book Your Reservation Now"
}

Avatar of Jorge BatresJorge Batres🇺🇸

ASKER

here is the HTML of the form
<form name="res" method="post" action="https://www.timeshareorlando.com/reservations/data/reservations.php" onsubmit="return YT_CheckForm(this) && validateRooms(this)">
<input type="hidden" name="step" value="cc" />
<input type="hidden" name="check__fields" value="status,#,First_Name,#,Last_Name,#,Spouse_Name,#,Address,#,City,#,State,#,Zip_Code,#,Country,#,Day_Phone,#,Email,#,Arrival_Month,#,Arrival_Date,#,Arrival_Year,#,Resort,#,Room_Type,#,Nights,#,Guest,#,Adults,#,Children,#,Juniors,#,Income,#,Age,#,Card_Type,#,Card_Number,#,Card_Expiration,#,Name_on_card,#" />
<input type="hidden" name="form_type" value="silver-lake" />
<input type="hidden" name="Room_Type" title="Room Type" value="" />
<input type="hidden" name="Arrival_Month" title="Arrival Month" value="" />
<input type="hidden" name="Arrival_Date" title="Arrival Date" value="" />
<input type="hidden" name="Arrival_Year" title="Arrival Year" value="" />
<input type="hidden" name="Nights" title="Number of Nights" value="" />
<input type="hidden" name="Hotel" value="Silver Lake Resort" />
<br style="clear:left" />
<table width="702">
  <tr>
    <td>
         <table id="persons" style="display:none" width="100%" border="0" cellspacing="1" cellpadding="5">
          <tr valign="top" bgcolor="#FFFFFF">
            <td width="26%"><table width="100%" border="0" cellspacing="1" cellpadding="5">
 			  <tr valign="top" bgcolor="#FFFFFF">

                <td width="50%"><font size="2" face="Verdana, Arial, Helvetica, sans-serif"> <span class="style1">Step 4.</span> Number of Adults:(18 yrs +)</font></td>

                <td width="50%"><font size="2" face="Verdana, Arial, Helvetica, sans-serif">
                    <select name="Adults" title="Number of Adults" size="" onchange="getPrice(this.form);">
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                    <option value="4">4</option>
                    </select>

                </font></td>
              </tr>

              <tr valign="top" bgcolor="#FFFFFF">
                <td><font size="2" face="Verdana, Arial, Helvetica, sans-serif"> <span class="style1">Step 5.</span> Number of Juniors:(10 to 17 yrs. of age)</font></td>
                <td><font size="2" face="Verdana, Arial, Helvetica, sans-serif">

                    <select name="Juniors" title="Number of Juniors" size="" onchange="getPrice(this.form);">
                    <option value="">Select</option>
                    <option value="0">0</option>
                    <option value="1">1</option>
                    <option value="2">2</option>
                    </select>

                </font></td>
              </tr>
              <tr valign="top" bgcolor="#FFFFFF">
                <td><font size="2" face="Verdana, Arial, Helvetica, sans-serif"> <span class="style1">Step 6.</span> Number of Children:(Under 10 yrs. of age)</font></td>

                <td><font size="2" face="Verdana, Arial, Helvetica, sans-serif">
                    <select name="Children" title="Number of Children" size="" onchange="getPrice(this.form);">
                    <option value="">Select</option>
                    <option value="0">0</option>
                    <option value="1">1</option>
                    <option value="2">2</option>
                    </select>

                </font></td>
                </tr>
                  <tr valign="top" bgcolor="#FFFFFF">
                <td><font size="2" face="Verdana, Arial, Helvetica, sans-serif"> <span class="style1">Step 7.</span> Choice of Tickets:</font></td>
                <td><font size="2" face="Verdana, Arial, Helvetica, sans-serif">
                    <select name="Tickets" onChange="getPrice(this.form);">
                    <option value="No Tickets" selected="selected">No Tickets</option>
                    <option value="Two 1 Day Disney World Base Tickets">Two 1 Day Disney World Base Tickets</option>
                    <option value="Two 1 Day Universal Studios Base Tickets">Two 1 Day Universal Studios Base Tickets</option>
                    <option value="Two 1 Day SeaWorld Orlando Base Tickets">Two 1 Day SeaWorld Orlando Base Tickets</option>
                    <option value="Two 2 Day Disney World Touch of Magic Tickets">Two 2 Day Disney World Touch of Magic Tickets</option>
                    <option value="Two 7 Day Universal Studios and Islands of Adventure Tickets">Two 7 Day Universal Studios and Islands of Adventure Tickets</option>
                    </select>

                </font></td>
                </tr>                          
              <tr valign="top" bgcolor="#FFFFFF">
                <td colspan="2" style="color:#003399" id="description"></td>

              </tr>
              
			  <!--<tr valign="top" bgcolor="#FFFFFF">
                <td width="30%"><strong><font size="1" face="Verdana, Arial, Helvetica, sans-serif"> <font color="#FF0000">* </font>Tickets:</font></strong></td>
                <td width="70%"><font size="1" face="Verdana, Arial, Helvetica, sans-serif">
                  <input type="text" name="Tickets" value="" />
                </font></td>
              </tr>-->
              
			  <tr valign="top" bgcolor="#FFFFFF">
                <td colspan="2"><strong><font size="2" face="Verdana, Arial, Helvetica, sans-serif"> <font color="#000000">The promotional price for your entire family is:</font></strong><font size="1" face="Verdana, Arial, Helvetica, sans-serif">
                    <span id="packagePrice" style="color:#006633; font-size:2em; font-weight:bold"></span> Not including taxes (13%)

                  </font></td>
                </tr>
              
              <!--tr valign="top" bgcolor="#F0F0F0">
                <td align="center" colspan="2"><strong><font size="1" face="Verdana, Arial, Helvetica, sans-serif">
                        Fields marked with an <font color="#FF0000">*</font> are required fields for the form to be processed.</td>
                </tr-->
            </table>              
            <strong><font size="1" face="Verdana, Arial, Helvetica, sans-serif"><i></i></font></strong></td>
          </tr>
        </table>

        <br />
        <p>

                        <input type="submit" name="submit2" value="Book Your Reservation Now" />
          <input type="reset" value="Re-Calculate" />
  </p>
        <p>&nbsp;</p>

</td>
  </tr>
</table>

</form>

Open in new window


Reward 1Reward 2Reward 3Reward 4Reward 5Reward 6

EARN REWARDS FOR ASKING, ANSWERING, AND MORE.

Earn free swag for participating on the platform.


Avatar of Marco GasiMarco Gasi🇪🇸

Now I have to go. Please be patient. I'll come back later or tomorrow to fix this: now it's a challenge! :-)

Cheers

Avatar of Jorge BatresJorge Batres🇺🇸

ASKER

Thank you very much, I will save everything in a backup file. I will post also a Javascript that might be affecting the form.
Thank you very very much.

ASKER CERTIFIED SOLUTION
Avatar of Marco GasiMarco Gasi🇪🇸

Link to home
membership
Log in or create a free account to see answer.
Signing up is free and takes 30 seconds. No credit card required.
Create Account

Avatar of Jorge BatresJorge Batres🇺🇸

ASKER

It worked! now only the price is not displayed, and the malicious script is not prompting the pop-up message, it only shows in the result of Adults as text :) just the price has to fixed now!
Thanks

Free T-shirt

Get a FREE t-shirt when you ask your first question.

We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads.


Avatar of Jorge BatresJorge Batres🇺🇸

ASKER

Regarding the price, it will be fixed if we can get the following values  capitalized:
 array("First_Name", "Last_Name", "Spouse_Name", "Address", "City",  "Province", "Country", "Name_on_card");

Thanks

Avatar of Marco GasiMarco Gasi🇪🇸

Should this work?

  foreach ($_POST as $key=>$value) {
    $clean[$key] = ucwords(strip_tags(strtolower(stripslashes($value))));
  }

Avatar of Jorge BatresJorge Batres🇺🇸

ASKER

Sorry I had not seen you reply until now, I tried but nothing gets posted, it shows no errors and only the template for the form shows up but nothing from the form itsef

Reward 1Reward 2Reward 3Reward 4Reward 5Reward 6

EARN REWARDS FOR ASKING, ANSWERING, AND MORE.

Earn free swag for participating on the platform.


Avatar of Marco GasiMarco Gasi🇪🇸

foreach ($_POST as $key=>$value) {
    $clean[$key] = strip_tags(strtolower(stripslashes($value)));
    $clean[$key] = ucwords($clean[$key]);
  }

Avatar of Jorge BatresJorge Batres🇺🇸

ASKER

Same thing

Avatar of Jorge BatresJorge Batres🇺🇸

ASKER

I just removed strtolower from your original:
foreach ($_POST as $key=>$value) {
    $clean[$key] = strip_tags(strtolower(stripslashes($value)));
  }

Open in new window

and it works! is this acceptable?

Free T-shirt

Get a FREE t-shirt when you ask your first question.

We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads.


Avatar of Jorge BatresJorge Batres🇺🇸

ASKER

One last thing, originally, I had this piece of code to capitalize stuff that users usually sent in lower case:
$arr = array("First_Name", "Last_Name", "Spouse_Name", "Address", "City",  "Province", "Country", "Name_on_card"); 
foreach ($arr as $field)
{
    $_POST["$field"] = strtolower($_POST["$field"]);
    $_POST["$field"] = ucwords($_POST["$field"]);
}// Capitalizes first letter on each word, added on 12-15-09

Open in new window

do you think that there is a way to accomplish the same with your sanitation?
Thanks,

Avatar of Jorge BatresJorge Batres🇺🇸

ASKER

Using your sanitation, I changed the capitalization to
$arr = array("First_Name", "Last_Name", "Spouse_Name", "Address", "City",  "Province", "Country", "Name_on_card"); 
foreach ($arr as $field)
{
    $clean["$field"] = strtolower($clean["$field"]);
    $clean["$field"] = ucwords($clean["$field"]);
}// Capitalizes first letter on each word, added by Jorge on 12-15-09

Open in new window

And everything works! the pop-up for the malicious script has had the script tags removed and it is no longer injected, only text is injected through the form but no script tags. I'm happy with that, unless you think I should do different.
Thanks,

Avatar of Jorge BatresJorge Batres🇺🇸

ASKER

Last changes, reverted back to your original sanitation including srttolower:
foreach ($_POST as $key=>$value) {
    $clean[$key] = strip_tags(strtolower(stripslashes($value)));
  }

Open in new window

and added
$arr = array("Hotel", "Room_Type", "Arrival_Month", "Checkin_Date", "Checkout_Date", "Tickets", "Marital_Status", "State", "Best_Time_to_Call", "First_Name", "Last_Name", "Spouse_Name", "Address", "City",  "Province", "Country", "Name_on_card", "Card_Type"); 
foreach ($arr as $field)
{  
    $clean["$field"] = ucwords($clean["$field"]);
}

Open in new window

for capitalization. Everything works so far :)
Hopefully this is it. I will run the scan again and I will let you know as soon as it is completed.
Thank you very much for your patience.
jbatres

Reward 1Reward 2Reward 3Reward 4Reward 5Reward 6

EARN REWARDS FOR ASKING, ANSWERING, AND MORE.

Earn free swag for participating on the platform.


Avatar of Marco GasiMarco Gasi🇪🇸

Well, I'm happy. But I don't understand why this code didn't work:

  foreach ($_POST as $key=>$value) {
    $clean[$key] = ucwords(strip_tags(strtolower(stripslashes($value))));
  }
 
I intended replace the original sanitization code with this one and do all in one only step and in my tests it worked fine: have you replaced original sanitization code with this one to test?

Now I go to sleep. Tomorrow I'll come back with some useful suggesiton about security and to be sure all works fine.

Cheers

Avatar of Jorge BatresJorge Batres🇺🇸

ASKER

Yes I did, but only the template loaded without the form itself. I only needed to capitalize the values in the given array, but using your original sanitation and the modified capitalization approach, everything seems to work just fine. I'm running the security scan as we speak, so I let you know either later tonight or tomorrow. Thanks again for all your help and you gave me the correct answer, which I will assign tomorrow before closing the question.
Have a good night!

Avatar of Marco GasiMarco Gasi🇪🇸

Be the problem solved or not, I want add some note about security, since it seems like you're trying to add security code as a little and quick trick. As it is well explained in the Ilia Alshanetsky's book mentioned above, htmlspecialchars and strip_tags don't offer a total defense against XSS and many aspects must be taken in consideration to secure your application. I can't tell you here the book content, but I want strongly recommend tor read it before you go on with your app.

In addition, as the wonderful Shiflett's guide illustrates, a good validation filter can't be massive and generic but must be specific and individual, that is item-per-item. Let's say you have your form with many values: the correct way to validate this form is the most boring and long but the only one really secure.

$months = array("January", "February",...);
foreach ($_POST as $key=>$value) {
  if ($key ==="Arrival_Month") {
    if (in_array($value, $months)){
      $clean[$key] = strip_tags(strtolower(stripslashes($value)));
    }
  }
}

The same type of filtering operation must be don for each form field, even for select, radio and checkboxes: a skilled hacker could build manually http header simulating the post of your form replacing any value with malicious or simply unwanted string.

This is what Ray intended when he said to Accept Only Known Good Values (post id 37932614): if you know what are the possible values for a field you must ensure that the posted value is in one of them.

And if you don't know this? use ctype functions (http://it2.php.net/manual/en/book.ctype.php) to ensure that the posted values is of the expected type: a string must be a string, an int must be an int and so on. If you know a string can't be longer than a certain value, ensure the posted string has the right length...

It's a long, boring work, but it is the only one way to make your site more difficult (not impossible) to attack.

So, if you really want to take care of your application security, read the two books I suggested above and prepare yourself to the hard work. :-)

Cheers

Free T-shirt

Get a FREE t-shirt when you ask your first question.

We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads.


Avatar of Jorge BatresJorge Batres🇺🇸

ASKER

Thank you very much marqusG, I don't mind spending hours doing this, I was wondering if you could please give me the examples as the one you gave me for an array. Must of my values are:
 Single Names (letter only)
 Addresses (alphanumeric)
 Numbers (digits)
 Amounts (price integer I guess)
 Check box (boolean?)

Thanks,
jbatres

Avatar of Jorge BatresJorge Batres🇺🇸

ASKER

Ok I guess this would be the filter for arrival date:

$days = array("1", "2",.......31);
foreach ($_POST as $key=>$value) {
  if ($key ==="Arrival_Date") {
    if (in_array($value, $days)){
      $clean[$key] = strip_tags(strtolower(stripslashes($value)));
    }
  }
}

So in this example, I know that the arrays are months, or days, but what about an array like Best_Time_To_Call ? what would be the name for such a thing? or Tickets?

Avatar of Marco GasiMarco Gasi🇪🇸

About your first post you can do something like this:

foreach ($_POST as $key=>$value) {
  if ($key ==="Single Names") {
    if (ctype_alpha($value)){
      $clean[$key] = strip_tags(strtolower(stripslashes($value)));
    }
  }
  if ($key ==="Addresses") {
    if (ctype_alnum($value)){
      $clean[$key] = strip_tags(strtolower(stripslashes($value)));
    }
  }
  if ($key ==="Numbers") {
    if (ctype_digit($value)){
      $clean[$key] = strip_tags(strtolower(stripslashes($value)));
    }
  }
  if ($key ==="Amounts") {
    if (is_float($value)){
      $clean[$key] = strip_tags(strtolower(stripslashes($value)));
    }
  }
}

Open in new window


For checkboxes, this depends on their name. Keep inmind chekboxes and radios are passed only if
  checked. Let's say you have a checkbox named "Something" and the possible values are only true or false
  if ($key ==="Something") {
    if ($value === true){
      $clean[$key] = strip_tags(strtolower(stripslashes($value)));
    }
  }

Open in new window


About your last post, it depends on how is defined "Best_Time_To_Call": in my opinion, it should be a select with options set to a range of times like 7-9, 9-11 and so on, so you have to work on it depending on your specific form's fields.

You can't get a quick recipe to secure your application, nor a simple copy&paste solution: security is not an extra layer wrapped on your code: its the core of your application because an unsecure application soon  or later will fail.

A last note: please, request attention to the moderator and split point between me and Ray: he has highlighted the foundamental mantra of security and you're now following his suggesiton, not only the mine.

Cheers

Reward 1Reward 2Reward 3Reward 4Reward 5Reward 6

EARN REWARDS FOR ASKING, ANSWERING, AND MORE.

Earn free swag for participating on the platform.


Avatar of Jorge BatresJorge Batres🇺🇸

ASKER

You are absolutely right marqusG,  my apologize to  Ray.

Avatar of Jorge BatresJorge Batres🇺🇸

ASKER

What would be an good
else
conditional at the end of each
if
assuming the value entered is not of the right type?

Avatar of Jorge BatresJorge Batres🇺🇸

ASKER

marqusG, could you send me your email or phone number to batres at msn dot com?
Thanks

Free T-shirt

Get a FREE t-shirt when you ask your first question.

We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads.


Avatar of Jorge BatresJorge Batres🇺🇸

ASKER

marqusG if I do the following:

  foreach ($_POST as $key=>$value) {

if ($key ==="Nights") {
    if (ctype_digit($value)){
      $clean[$key] = strip_tags(strtolower(stripslashes($value)));
    }
  }
 
if ($key ==="Adults") {
    if (ctype_digit($value)){
      $clean[$key] = strip_tags(strtolower(stripslashes($value)));
    }
  }

else $clean[$key] = strip_tags(strtolower(stripslashes($value)));
}

Only the last one (Adults) is filtered by ctype but not the first one, any suggestions?

Avatar of Marco GasiMarco Gasi🇪🇸

First, you don't need to use === to compare two strings
Second, as Ray said, if a value pass the ctype_digit test it is a number so it doesn't contain any other but numbers: no need to strip_tags, strtolower and stripslashes
Third, you can try this:

foreach ($_POST as $key=>$value) {

if ($key ==="Nights") {
    if (ctype_digit($value)){
      $clean[$key] = strip_tags(strtolower(stripslashes($value)));
    }
  }else if ($key ==="Adults") {
    if (ctype_digit($value)){
      $clean[$key] = strip_tags(strtolower(stripslashes($value)));
    }
  } else $clean[$key] = strip_tags(strtolower(stripslashes($value)));
}
PHP

PHP

--

Questions

--

Followers

Top Experts

PHP is a widely-used server-side scripting language especially suited for web development, powering tens of millions of sites from Facebook to personal WordPress blogs. PHP is often paired with the MySQL relational database, but includes support for most other mainstream databases. By utilizing different Server APIs, PHP can work on many different web servers as a server-side scripting language.