如何在此脚本中添加删除功能以删除服务器

时间:2018-01-23 16:34:00

标签: php wordpress file unlink

我有一个脚本,可以将特定目录文件夹中的所有文件加载到可查看的表中。我也能够成功地将日期上传元素集成并使用$ iterator函数,如下面的代码所示

更新

  • 已编辑的值为复选框输入但仍无法正常工作
  • 从过去的尝试中删除了不必要的代码段
  • 更新了最新的代码并添加了完整的脚本,以便更好地理解,包括CD001的建议

    // Begin Adding Uploader Page Content
    function pdfupload_admin_page(){
    ?>
        <style>
            <?php include '../wp-content/plugins/PDF-Uploader/support-files/stylesheet.css'; ?>
        </style>
        <div class="wrap">
    
        <div id="contact">
    
    
    
            <div style="text-align:center;">
    
    
            <h1>Secure PDF File Upload</h1>
            <p>Adding a watermark to your PDF files is as easy as uploading the file using the form below.<br>
            Upon successful submission of your PDF file you will receive the uploaded PDF files URL which you can then use when linking to the PDF within any page or post you desire.</p>
            <p>The PDF file when linked to using the URL provided will automatically acquire a watermark when loaded within the browser of the specific logged in user as well as the current date and time.</p>
            <form action="" method="post" enctype="multipart/form-data">
        <h3>Select PDF File To Upload:</h3><br>
        <input type="file" name="fileToUpload" id="fileToUpload">
        <input type="submit" value="Upload PDF File" name="submitUpload">
    </form>
    
    <?php
    
        $target_dir = "../wp-content/plugins/PDF-Uploader/";
        $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
        $uploadOk = 1;
        $FileType = pathinfo($target_file,PATHINFO_EXTENSION);
    
        if(isset($_POST["submitUpload"])) {
            if (file_exists($target_file)) {
            echo "Sorry, file already exists.";
            $uploadOk = 0;
        }
        // Check file size
       // if ($_FILES["fileToUpload"]["size"] > 10000000) {
        //    echo "Sorry, your file is too large.";
       //     $uploadOk = 0;
       // }
        // Allow certain file formats
        if($FileType != "pdf") {
            echo "Sorry, only PDF files are allowed.";
            $uploadOk = 0;
        }
        // Check if $uploadOk is set to 0 by an error
        if ($uploadOk == 0) {
            echo "Sorry, your file was not uploaded.";
        // if everything is ok, try to upload file
        } else {
            if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
                echo "File uploaded successfully use the following URL when linking to your PDF <br> https://website.com/wp-content/plugins/PDF-Uploader/watermarked.php?filename=" . basename( $_FILES["fileToUpload"]["name"]). "";
            } else {
                echo "Sorry, there was an error uploading your file.";
            }
        }
        }
        // Check if file already exists
    
        /**
         * FILE DELETION HANDLER  
         */
       $iterator = new FilesystemIterator('../wp-content/plugins/PDF-Uploader/');
    
        function delete_file($iterator, $file) {
            if(!unlink($iterator->getPath() . '/' . $file)) {
                echo "Sorry! your file cannot be deleted. Please try again later";
            }
            else {
                echo "File deleted successfully!";
            }
        }
        if(isset($_POST['submit'])){
            if(!empty($_POST['file'])) { // check if the checkbox was checked.
                foreach($_POST['file'] as $file) {
                    // call delete function here.
                    delete_file($iterator, $file);
                }
            }
            else{
                echo "No file selected. You must select at least one PDF file to be deleted.";
            }
        }
    
    
    ?>
    
    
        </div>
    <?php
     // if ($handle = opendir('../wp-content/plugins/PDF-Uploader/')) {
     //     while (false !== ($file = readdir($handle)))
     //    {
     //        if ($file != "." && $file != ".." && strtolower(substr($file, strrpos($file, '.') + 1)) == 'pdf')
     //       {
      //          $thelist .= '<td><input type="checkbox" name="file[]" value="https://website.com/wp-content/plugins/PDF-Uploader/'.$file.'"></td>';
      //      }
      //  }
    //    closedir($handle);
    //}
    ?>
    <form id="deletionForm" method="post" action="">
    <table>
    <thead>
            <tr style="width:100%;">
                <th style="width:25px;"></th>
                <th style="text-align:left;width:625px;">Filename</th>
                <th style="text-align:right;width:100px;padding-right:20px;">Date Uploaded</th>
            </tr>
        </thead>
    <?php
        // $iterator = new FilesystemIterator('../wp-content/plugins/PDF-Uploader/pdf-watermarker/');
        foreach($iterator as $file){
            //if($file->isFile()){
            if ($file != "." && $file != ".." && strtolower(substr($file, strrpos($file, '.') + 1)) == 'pdf')
            {
                $cTime = new DateTime();
                $cTime->setTimestamp($file->getCTime());
                //echo $file->getFileName() . " file Created " . $cTime->format('Y-m-d h:i:s') .  "<br/>\n";
    ?>
            <tr>
                <td style="width:25px;"><input type="checkbox" name="file[]" value="wp-content/plugins/PDF-Uploader/<?php echo $file->getFileName(); ?>"></td>
                <td style="text-align:left;width:625px;"><a href="https://website.com/wp-content/plugins/PDF-Uploader/<?php echo $file->getFileName(); ?>" target="_blank"><?php echo $file->getFileName(); ?></a></td>
                <td style="text-align:right;width:100px;padding-right:20px;"><?php echo $cTime->format('Y-m-d h:i:s'); ?></td>
            </tr>
    
    <?php
    }
        }
        ?>
    </table>
    <input type="submit" name="submit" value="Delete Selection">
    </form>
        </div>
    
        <?php
    }
    // End Adding Secure PDF Upload Page Content
    

总而言之,我需要找出删除功能无法正常工作的原因,并在脚本中添加排序顺序,以按字母顺序生成结果。

非常感谢任何代码示例。

2 个答案:

答案 0 :(得分:3)

根据手册,文件处理需要<form>中的有效enctype,enctype="multipart/form-data"

手册中的一个例子:

<!-- The data encoding type, enctype, MUST be specified as below -->
<form enctype="multipart/form-data" action="__URL__" method="POST">
    <!-- MAX_FILE_SIZE must precede the file input field -->
    <input type="hidden" name="MAX_FILE_SIZE" value="30000" />
    <!-- Name of input element determines name in $_FILES array -->
    Send this file: <input name="userfile" type="file" />
    <input type="submit" value="Send File" />
</form>

您需要将$_POST['file']的所有引用分别更改为$_FILES['file']['name'] / $_FILES['file']['tmp_name']

手册中还包含处理多个文件,以下是一个示例:

<?php
// In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
// of $_FILES.

$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

echo '<pre>';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
    echo "File is valid, and was successfully uploaded.\n";
} else {
    echo "Possible file upload attack!\n";
}

echo 'Here is some more debugging info:';
print_r($_FILES);

print "</pre>";

?>

使用PHP的错误报告来帮助您进行调试:

但是,在处理复选框时,请勿使用empty(),请使用isset()

if(isset($_POST['file'])) { // check if the checkbox was checked.

您是否想要上传文件有点不清楚。如果是,则需要将<input type="checkbox"更改为文件输入类型<input type="file"

修改

这部分代码应该出错,因为需要使用$thelist = "";

进行空变量声明

即:

<?php 

    if ($handle = opendir('../wp-content/plugins/PDF-Uploader/.')) {

    $thelist = "";
        while (false !== ($file = readdir($handle)))
        {
            if ($file != "." && $file != ".." && strtolower(substr($file, strrpos($file, '.') + 1)) == 'pdf')
            {
                $thelist .= '<td><input type="checkbox" name="file[]" value="../wp-content/plugins/PDF-Uploader/'.$file.'"></td>';
            }
        }
        closedir($handle);
    }
?>

答案 1 :(得分:2)

解决方案(以下说明)

<?php 
// global iterator
$iterator = new FilesystemIterator('../wp-content/plugins/PDF-Uploader/');

function delete_file($iterator, $file) {
    if(!unlink($iterator->getPath() . '/' . $file)) {
        echo "Sorry! your file cannot be deleted. Please try again later";
    }
    else {
        echo "File deleted successfully!";
    }
}

?><!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8" />
<title>Test</title>
</head>

<body>
<?php
if(isset($_POST['submit'])){
    if(!empty($_POST['file'])) { // check if the checkbox was checked.
        foreach($_POST['file'] as $file) {
            // call delete function here.
            delete_file($iterator, $file);
        }
    }
    else{
        echo "No file selected. You must select at least one PDF file to be deleted.";
    }
}
?>

<form method="post" action="">
<table>
    <thead>
        <tr style="width:100%;">
            <th style="width:25px;"></th>
            <th style="text-align:left;width:625px;">Filename</th>
            <th style="text-align:right;width:100px;padding-right:20px;">Date Uploaded</th>
        </tr>
    </thead>
<?php
    foreach($iterator as $file) {
        //if($file->isFile()){
        if ($file != "." && $file != ".." && strtolower(substr($file, strrpos($file, '.') + 1)) == 'pdf')
        {
            $cTime = new DateTime();
            $cTime->setTimestamp($file->getCTime());
            //echo $file->getFileName() . " file Created " . $cTime->format('Y-m-d h:i:s') .  "<br/>\n";
?>
        <tr>
            <td style="width:25px;"><input type="checkbox" name="file[]" value="<?= $file->getFileName(); ?>"></td>
            <td style="text-align:left;width:625px;"><a href="<?= $file; ?>" target="_blank"><?= $file->getFileName(); ?></a></td>
            <td style="text-align:right;width:100px;padding-right:20px;"><input type="text" name="date[]" value="<?= $cTime->format('Y-m-d h:i:s'); ?>"></td>
        </tr>

<?php
}
    }
    ?>
</table>
<input type="submit" name="submit" value="Delete Selection">
</form>

</body>
</html>

<强>解释

由于FilesystemIterator保存了PDF存储库目录的路径,因此我将其定义为脚本顶部的全局变量。然后在需要的地方引用它,因此您需要更改文件路径,只需在$iterator中更改它。

例如,它在循环中使用并传递给delete_file函数。表单本身只发布文件名而不是完整路径。

否则你的确离我们还有很长的路要走。

一些想法

FilesystemIterator类包含检测扩展名的方法,以及文件是.还是..,以便您可以替换:

if ($file != "." && $file != ".." && strtolower(substr($file, strrpos($file, '.') + 1)) == 'pdf')

使用:

if(!$file->isDot() && $file->getExtension() == 'pdf')

这有点整洁。

如果您的应用程序中存在漏洞,未经授权的用户可以上传和执行任何内容(在浏览器中打开),也存在安全问题:例如恶意PHP脚本。

您可以通过Apache配置缓解这种情况 - 一个常见的事情是通过.htaccess文件禁用PHP:

php_flag engine off