简体   繁体   中英

how to protect inputfield with php

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 az, AZ and 0-9 are allowed to input. How can i protect this with php

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 az and 0-9 with nothing. ( i means case insensitive, so also AZ).

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

That would be:

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

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

To also allow numbers:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM