我有一个下拉列表,其中填充了使用下面列出的 PHP 从目录中提取的文件,并试图弄清楚如何在选择它们时使用表单中的删除按钮将其删除。
编辑取消链接函数错误已解决。
尝试删除时仍然出现错误: Error.array(1) { ["Action"]=> string(6) "删除"}
<input type="hidden" name="Action" value="EDIT" /><input type="hidden" name="Selection" id="Selection" value="-1"><div>Below is the list of your saved codes. To edit your codes, select it from the list.</div>
<select size="1" name="CodeList" id="CodeList">
<?php
$directory = $directory = 'users/' . $_SESSION['username'];
$filesContents = Array();
$files = scandir( $directory ) ;
foreach( $files as $file )
{
if ( ! is_dir( $file ) )
{
$filesContents[$file] = file_get_contents($directory , $file);
echo '<option value="'. $file .'">' . $file . '</option>';
}
}
?>
删除php脚本。
<?php
session_start();
$directory = $directory = $_SERVER['DOCUMENT_ROOT'] . '/users/' . $_SESSION['username'];
$file_to_delete = $_POST['CodeList'];
if(is_file($directory .'/'. $file_to_delete) && is_writable($directory .'/'. $file_to_delete)) {
if ( unlink ($directory.'/'.$file_to_delete) ) {
echo $file_to_delete . " deleted.";
} else {
echo "Error.";
}
}
?>
<?php var_dump($_POST) ?>
最佳答案
您添加了选项,但没有选项值。选择框应如下所示:
<select name="identifier">
<option value="value_1">Option 1</option>
<option value="value_2">Option 2</option>
</select>
现在,如果您选择选项 2,您应该在帖子数组中获得 value_2:
echo $_POST['identifier']; // prints out 'value_2';
您的选项如下所示:<option>Option x</option>
,这意味着您选择了一个选项,但它没有值(无 value=""
属性)。
如果您查看 PHP 错误,我确实看到了正确的目录名称,但没有附加文件名。
您还应该检查该文件是否存在,以防止出现“没有此类文件”错误:
if(is_file($directory .'/'. $file_to_be_deleted) && is_writable($directory .'/'. $file_to_be_deleted)) {
// delete the file
}
是的,我使用 is_file
和 is_writable
测试,因为is_writable
函数还将返回 true
如果检查的路径是目录。
编辑
要分配值,请按如下方式更改 foreach 循环:
<select size="1" name="CodeList" id="CodeList">
<?php
// fetch files etc.
foreach( $files as $file ) {
if ( ! is_dir( $file ) {
echo '<option value="'. $file .'">' . $file . '</option>';
}
}
哦,顺便说一句:摆脱 get_file_contents()
部分。您没有对那里的文件内容执行任何操作,是吗?
关于javascript - PHP删除错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28980686/