0

I am using this form:

<form class="sfmform" action="" method="post">
    <input type="text" name="dirname"  />
    <input type="submit" class="Button Primary" name="mkdir" value="Makedir" />
</form>

This is how php handles the form:

<?php
    if ($_POST['mkdir']) {
        $DirectoryName = $_POST['dirname'];
        mkdir($dir . '/' . $DirectoryName, 0777, true);
    }
?>

Now i want to protect the form: only characters a-z, A-Z and 0-9 are allowed to input. How can i protect this with php

mitkosoft
  • 5,262
  • 1
  • 13
  • 31
Jack Maessen
  • 1,780
  • 4
  • 19
  • 51
  • Hey Jack, usually you need to use regular expressions( short: regex). I would reccoment looking into php documentation http://php.net/manual/en/function.preg-match.php – Techno May 03 '16 at 15:27
  • Possible duplicate of [PHP - regex to allow letters and numbers only](http://stackoverflow.com/questions/4345621/php-regex-to-allow-letters-and-numbers-only) – The Codesee May 03 '16 at 15:27
  • Use a regex in PHP, Something like `$DirectoryName = preg_replace("/[^A-Za-z0-9]/", '', $_POST['dirname']);` - regex isn't my strong suit, but I think this should work. – Qirel May 03 '16 at 15:27
  • Possible duplicate of [PHP preg\_match - only allow alphanumeric strings and - \_ characters](http://stackoverflow.com/questions/7753365/php-preg-match-only-allow-alphanumeric-strings-and-characters) – Tom Cash May 03 '16 at 15:32
  • http://stackoverflow.com/a/19066870/3298930 – Jose Manuel Abarca Rodríguez May 03 '16 at 15:36

3 Answers3

1

First of all, it is highly dangerous to create files/directory via a form, which is accessibly via web.

To you question, you can for example use preg_replace:

$DirectoryName = preg_replace('#[^a-z0-9]#i', '', $_POST['dirname']);

This will replace all characters except a-z and 0-9 with nothing. (i means case insensitive, so also A-Z).

And don't forget to check, if the directory is already existing...

Fabian N.
  • 1,221
  • 10
  • 18
1

That would be:

if(preg_match('/[^a-z\s]/i',$stringabc))

For anything but letters (a-z), spaces (\s, meaning any kind of whitespace). This returns a bool.

To also allow numbers:

if(preg_match('/[^0-9a-z\s-]/i',$stringabc))
0

It all depends if you want to validate the data once the form is posted, then the regex solution is a good one, or if you want to prevent the user from even entering invalid characters in the first place (which then requires some kind of client-side javascript). You can (and probably should) combine the 2 approaches.

GdR
  • 313
  • 1
  • 8