Form safety

Asked

Viewed 137 times

4

I have the following code:

PHP (server):

if(isset($_POST['subdate']) && !empty($_POST['date'])) {

   $daysOff = array();
   $get_date = explode(',', $_POST['date']);
   foreach ($get_date as $date) {
     $date = explode('-', $date);
     $day = $date[0];
     $month = $date[1];
     $year = $date[2];
     $time_Stamp = mktime(0,0,0,$month,$day,$year);
     $daysOff[] = strftime('%d-%m-%Y', $time_Stamp);
   }

   $daysOff = json_encode($daysOff);
   echo "dates off: " .$daysOff;
}

else {
   $daysOff = json_encode(array("23-09-2015", "15-09-2015"));
   echo "dates off: " .$daysOff;
}

HTML (client)

...
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/pepper-grinder/jquery-ui.css">
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
...
<form method="POST">
    <input id="datepicker" type="date" name="date" autocomplete="off" readonly>
    <br>
    <input type="submit" name="subdate">
</form>
...

Javascript (client)

function datePicker() {

   <?php echo "var datesOff = JSON.parse('" .$daysOff. "');"; ?>
   var daysSelected = [];

   var datepickerOpts = {

      beforeShowDay: function(date){

         var day = $.datepicker.formatDate('dd-mm-yy', date);
         var checkDate = datesOff.indexOf(day);

         if(checkDate == -1) {
             // not found, data available
             return [true, "", "available"];
         }
         else {
            return [false, "", "not available"];
         }
      },
      onSelect: function(date) {

         var index = daysSelected.indexOf(date);

         if(index == -1){
            daysSelected.push(date);
            console.log(daysSelected);
         }
         else {
            daysSelected.splice(index, 1);
            console.log(daysSelected);
         }
         $('input[type="date"]').val(daysSelected);
         // prevent from closing datepicker when clicking date
         $(this).data('datepicker')['inline'] = true;
      },
      onClose: function() {
         $(this).data('datepicker')['inline'] = false;
      },
      dateFormat: 'dd-mm-yy',
      showOn: "both",
      buttonImage: "http://icons.iconarchive.com/icons/icons8/ios7/256/Time-And-Date-Calendar-icon.png",
      buttonImageOnly: true,
      buttonText: "Select date",
      showAnim: "slideDown",
   };

   $('#datepicker').datepicker(datepickerOpts);
}

datePicker();

Everything works very well, starting from the beginning that they will not manually change the value of the input as shown in the image below, which triggers an error on the server, more specifically with the function explodes. I wanted to avoid this, I wish there was a simple check (already tried with Try/catch), ex: if inputs were this format: "dd-mm-aaa,dd-mm-aaaa" is that we move on to the blasts etc... bearing in mind that it has to work also if there is only one date: "dd-mm-aaaa". Other suggestions to avoid triggering errors in this case are also welcome. Example of what happens:

Before submitting, manually change the value:

inserir a descrição da imagem aqui

After submitting:

inserir a descrição da imagem aqui

Errors appear when we try to access the $date, within the cycle we have in the server-side code.

2 answers

4


Most of your problems will be solved with some simple validations, example:

<?php

if(isset($_POST['subdate']) && !empty($_POST['date'])) {

   $daysOff = array();
   $get_date = explode(',', $_POST['date']);
   foreach ($get_date as $date) {

      // Validação com Expressão Regular
      // Apenas com essa validação você pode resolver a maioria dos seus problemas
      if(!preg_match('/^([0-9]{2}\-[0-9]{2}\-[0-9]{4})$/', $date)){
         // Não está no formato NN-NN-NNNN
         // Tome qualquer providencia aqui
      }

      $date = explode('-', $date);

      // Validando a quantidade de elementos retornados pelo explode
      if (count($date) == 3){
         $day = $date[0];
         $month = $date[1];
         $year = $date[2];
         $time_Stamp = mktime(0,0,0,$month,$day,$year);
         $daysOff[] = strftime('%d-%m-%Y', $time_Stamp);
      } else {
         // O explode não resultou em 3 elementos
         // Tome qualquer providencia aqui
      }
   }

   $daysOff = json_encode($daysOff);
   echo "dates off: " .$daysOff;
} else {
   $daysOff = json_encode(array("23-09-2015", "15-09-2015"));
   echo "dates off: " .$daysOff;
}

I commented on the code showing the validations. Keep one thing in mind, whenever receiving user/client data, even if by a javascript library it is crucial to validate this data. Any input data must be validated by the system, especially when the process depends on that data.

I could still do other validations, to check if the data really are dates: Correctly determine if date string is a Valid date in that format

  • Obgado, it was a solution as such that it sought, simple and able to have the work done. but you’re not accepting the right dates either, but I think with a little correction you can manage

  • 1

    It’s already working, you’re wrong [0-2]{4})$ should also be [0-9].... By the way, you mean ^, /, "", $ no preg match? Thanks again

  • 1

    True, I was wrong there [0-2]{4}, already corrected. ^ means "beginning", / are delimiters of the regular expression, $ means "end" and \ is the escape to the literal character - which it contains at the date, this bar is not absolutely necessary, but it is good to avoid possible bugs and bugs @Miguel

0

Well, as you work with forms and we do not know what the customer will go through it would be good to avoid several errors, add a masquerade date in your input. Another thing I usually do in my code is always use Datetime php, a hint for you to work with the date would be more or less like this in the input parameter.

Ex: $newDate = implode('-', array_reverse(explode('/', $date)));

$newDate = new Datetime($newDate);

And in the output parameter you add a treatment to the date.

  • Jose welcome to Stackoverflow in English, read this topic to learn more about Sopt’s questions formatting template, thus improving the quality of your answer and the overall community.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.