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
<?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:
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
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.