简体   繁体   中英

Adding a variable to a form using PHP

I hope this question was not asked before, but I found nothing by searching.

Now, I have a small problem to solve... I want to enable my website to rename contents of a folder. The website lists all contents of the folder by using scandir. To edit the names there are input fields prefilled with the current names. All of that is done by a for loop. The point is, that I would like to add a variable to the form, that gets transfered via post to my action, when the form is submitted, but without having the variable in an input field. The context is, that I need to somehow get the original file name to the action. My first idea was to just set a $_POST value manually, but this does not work, as this value won't be specific to this form.

Is there a way to do this? Or should I just use a hidden input field, although this does not seem to be the most ellegant solution to me.

Thank you for helping!

EDIT:

    echo "<li><form action='rename.php' method='post'>";
    echo "<input type='text' name='nName' value=$dateiName>";
    echo "<input type='submit' value='ändern'></form></li>";

This is the form that gets created multiple times. If using a hidden input is the way to go, I will use it. Just don't like the idea of having a input field that is invisible.

You need the input field (hidden) with the original value of the file name. Then you have to compare the original value with the value in the text field and if the values are different, then you will rename the file. If you don't have the initial value, you can not find the file to be renamed.

For the sake of "security", you could use a hash of the original filename as the key of your array input :

<input type="text" name="filenames[<?php echo hash('sha256', $originalFileName) ?>]" />

You could then loop like this after submitting the form :

$files = scandir($dir);
foreach ($_POST['filenames'] as $hash => $newname) {
    foreach ($files as $file) {
        if (hash('sha256', $file) === $hash) {
            rename(
                $dir . DIRECTORY_SEPARATOR . $file, 
                $dir . DIRECTORY_SEPARATOR . $newname
            );
        }
    }
}

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