【问题标题】:How to upload custom file (.txt, .rar, .xml, .zip) in php (wordpress)?如何在 php(wordpress)中上传自定义文件(.txt、.rar、.xml、.zip)?
【发布时间】:2019-03-14 13:14:02
【问题描述】:

我想启用将文件直接上传到根目录。支持的文件扩展名应为:.txt、.rar、.xml、.zip。我正在尝试使用 w3schools 的代码来执行此操作,因为我是 php 和 wordpress 插件开发的初学者。插件有效,左侧管理栏有一个菜单图标,管理页面上有一个上传选项,但是当我“上传”文件时,上传文件夹中没有文件(我首先尝试这样做就像代码在 w3schools 上。代码是:

HTML

<div class="wrap">
<h2>Test file upload page</h2>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</div>

PHP 文件 (upload.php)

<?php 
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
    echo "File is an image - " . $check["mime"] . ".";
    $uploadOk = 1;
} else {
    echo "File is not an image.";
    $uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != 
"jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF 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 "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been 
uploaded.";
} else {
    echo "Sorry, there was an error uploading your file.";
}
}
?>

我知道这不是一个好方法,而且我想要做的事情有 Wordpress 功能,但我只是想尝试这种方式......如果你知道更好的方法,我会感谢您睁开我的眼睛。另外,我还有一个问题:文件上传可以在本地工作吗?我的意思是,我正在使用 MAMP 在 localhost 上做所有事情,这是出于练习目的。

我没有编辑任何代码来支持我需要的文件扩展名,因为我首先想测试它是否适用于图像文件,但事实并非如此。

编辑 1:

我还看到在 php.ini 文件中 file_uploads 指令应该设置为 On:

file_uploads = On

但是,wordpress 目录中没有 php.ini 文件。有没有办法用 wordpress 插件编辑 php.ini 文件?也许这就是问题所在。只是猜测。

【问题讨论】:

    标签: php wordpress file-upload


    【解决方案1】:

    您的代码存在以下问题:

    1. 不需要upload.php 文件,所有内容都应该放在一个文件中,在这种情况下是您的主插件文件。

    2. 由于没有upload.php文件,表单动作应该是空的。

    3. 您的 PHP 代码中的所有内容都应该在 if(isset($_POST["submit"])) { } 中,因为如果没有提交任何内容,您就不需要执行上传脚本中的任何内容。

    4. 您的$target_dir 应该是absolute path,类似于:

      • /home/user/public_html/wp-content/
      • /Users/username/Sites/wp/wp-admin

    这是一个基于您发布的代码的小型工作示例,我使用wp_upload_dir 设置目标目录。在我的测试中,图片被上传到http://localhost/wp-content/2018/10/image.png

    <?php
    /**
     * Plugin Name: (SO) Testing upload
     */
    add_action('admin_menu', function () {
        add_menu_page( 
            'Upload', 
            'Upload', 
            'read', 
            'so_upload', 
            'so_upload_callback', 
            null, 
            6 // position, just after Posts
        );
    });
    
    function so_upload_callback() 
    {
        ?>
        <div class="wrap">
        <h2>Test file upload page</h2>
        <form action="" method="post" enctype="multipart/form-data">
        Select image to upload:
        <input type="file" name="fileToUpload" id="fileToUpload">
        <input type="submit" value="Upload Image" name="submit">
        </form>
        </div>
        <?php
        // Check if image file is a actual image or fake image
        if(isset($_POST["submit"])) {
            $target_dir = wp_upload_dir();
            $target_file = $target_dir['path'] . '/' . basename($_FILES["fileToUpload"]["name"]);
            $uploadOk = 1;
            $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
            $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
            if($check !== false) {
                echo "File is an image - " . $check["mime"] . ".";
                $uploadOk = 1;
            } else {
                echo "File is not an image.";
                $uploadOk = 0;
            }
            // Check if file already exists
            if (file_exists($target_file)) {
                echo "Sorry, file already exists.";
                $uploadOk = 0;
            }
            // Check file size
            if ($_FILES["fileToUpload"]["size"] > 500000) {
                echo "Sorry, your file is too large.";
                $uploadOk = 0;
            }
            // Allow certain file formats
            if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != 
                "jpeg"
            && $imageFileType != "gif" ) {
                echo "Sorry, only JPG, JPEG, PNG & GIF 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 "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been 
                        uploaded.";
                } else {
                    echo "Sorry, there was an error uploading your file.";
                }
            }
    
        }
    }
    

    请注意,以这种方式上传的文件不会显示在 WP 媒体库中。此外,如果代码是真实的,则表单需要一个 nonce 字段以确保安全 (wp_nonce_field)。

    【讨论】:

    • 哇。谢谢你。能否以某种方式完成,以便上传的文件位于网站的根目录(以及 wp-content、wp-admin 等...)。另外,我可以添加另一个菜单页面,例如(上传的文件),然后该页面仅在有上传的文件时显示,所以我可以从那里删除文件?我不是要求你为我这样做,而是给我一些建议以及我应该去哪里看。再次感谢您以如此出色和有用的方式回答我的问题。
    • 是的,请查看有关“绝对路径”的链接,您将找到如何上传到任何您想要的地方。当然,只需使用add_submenu_page() 创建一个页面,您将在其中列出目标目录的内容和图像。在 Google 上,使用“what you want site:stackoverflow.com”,您会发现很多代码可供使用。在Stack OverflowWordPress Development 上查看高级搜索功能,也可以查找内容。祝你好运!
    • 如果有人有类似问题,想上传到root,可以用:get_home_path()代替wp_upload_dir(),然后把$target_file = $target_dir['path'] . '/' . basename($_FILES["fileToUpload"]["name"]);这一行改成$target_file = get_home_path() . '/' . basename($_FILES["fileToUpload"]["name"]);
    猜你喜欢
    • 2015-10-01
    • 1970-01-01
    • 2013-12-16
    • 2015-11-01
    • 2013-02-10
    • 1970-01-01
    • 2018-08-03
    • 1970-01-01
    • 2021-10-21
    相关资源
    最近更新 更多