How could I only accept "alphanumeric characters" and reject anything else that was s

Discussion in 'Programming' started by mike33pt, Jul 26, 2009.

  1. #1
    Hi all, I need some help with a cookie please.

    In the cookie below I am allowing the cookies data to be set by the data in the url.

    myurl.com/?aid=12345

    If I sent the above url the cookie data would show affiliate as 12345

    <?php
    if (isset($_GET['aid']))
      {
      setcookie('affiliate', $_GET['aid'], time()+60*60*24*60);
      $aid = $_GET['aid'];
      }
    if (isset($_COOKIE['affiliate']))
      {
      $aid = $_COOKIE['affiliate'];
      }
    ?>
    Code (markup):


    Which could be a security problem

    How could I only accept "alphanumeric characters" and reject anything else that was sent in the url?

    Would appreciate your help.

    Thanks

    Mike
     
    mike33pt, Jul 26, 2009 IP
  2. kmap

    kmap Well-Known Member

    Messages:
    2,215
    Likes Received:
    29
    Best Answers:
    2
    Trophy Points:
    135
    #2
    <?php
    
     function alphanumericAndSpace( $string )
        {
            return preg_replace('/[^a-zA-Z0-9\s]/', '', $string);
        }
    
    
    
    if (isset($_GET['aid']))
      {
      setcookie('affiliate', alphanumericAndSpace($_GET['aid']), time()+60*60*24*60);
      $aid = alphanumericAndSpace($_GET['aid']);
      }
    if (isset($_COOKIE['affiliate']))
      {
      $aid = alphanumericAndSpace($_COOKIE['affiliate']);
      }
    ?>
    PHP:
     
    kmap, Jul 26, 2009 IP
  3. mike33pt

    mike33pt Peon

    Messages:
    48
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    That's great thank you. Also to add a bit more security how could I also limit the length of the data string?

    And would this also limit the data sent if it was sent as hex rather than asci text?

    I appreciate your help

    Thanks again

    MIke
     
    mike33pt, Jul 26, 2009 IP
  4. ThePHPMaster

    ThePHPMaster Well-Known Member

    Messages:
    737
    Likes Received:
    52
    Best Answers:
    33
    Trophy Points:
    150
    #4
    You can use substr:

    
    $length = 10;
    return substr (preg_replace('/[^a-zA-Z0-9\s]/', '', $string),0,$length);
    
    PHP:
    Since you are stripping out all characters other than a-zA-Z0-9, you do not have to worry about hex/binary inputs.
     
    ThePHPMaster, Jul 26, 2009 IP