1

I want to enable uploading files directly to the root. Supported file extensions should be: .txt, .rar, .xml, .zip. I'm trying to do this with the code from w3schools, as I'm beginner in php and wordpress plugin development. Plugin works, there is a menu icon on the left admin bar, there is an upload option on the admin page, but when I "upload" the file, there is no file in uploads folder (I'm first trying to do just like the code is on w3schools. The code is:

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>

and the PHP file (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.";
}
}
?>

I know that this is not a good approach, and that there are Wordpress functions to to what I'm trying to do, but I just wanted to try this that way... If you know any better way, I would appreciate if you open my eyes. Also, I have another question: Can file upload work on local? I mean, I'm doing everything on localhost with MAMP, and this is for practice purposes.

I haven't edited any of the code to support file extensions I nedded, because I first wanted to test if it works with image files, but it isn't.

EDIT 1:

I also saw that in php.ini file file_uploads directive should be set to On:

file_uploads = On

But, there is no php.ini file in wordpress directory. Is there a way to edit php.ini file with wordpress plugin? Maybe that is the problem. Just guessing.

1 Answer 1

1

You have the following issues with your code:

  1. The upload.php file is not needed, everything should go in a single file, your main plugin file in this case.

  2. As there's no upload.php file, the form action should be empty.

  3. Everything in your PHP code should be inside if(isset($_POST["submit"])) { }, because if nothing was submitted you don't need to execute anything from the upload script.

  4. Your $target_dir should be an absolute path, something like:

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

Here's a small working example based on the code you posted, I'm using wp_upload_dir to set the destination directory. In my test, images were uploaded to 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.";
            }
        }

    }
}

Note that files uploaded this way don't show up on WP media library. Also, if the code is for real, the form needs a nonce field for security (wp_nonce_field).

Sign up to request clarification or add additional context in comments.

3 Comments

Wow. Thank you. Can it be done in a way so files uploaded would be on the root of the website (along with wp-content, wp-admin, etc...). Also, can I add another menu page that will be shown as, for example (Uploaded files) and then that page is shown only if there are files that are uploaded, so from there I can delete files? I'm not aksing you to do that for me, but to give me some advices and where should I look. Thanks again for answering my question in such a great and useful way.
Yes, check the link about "absolute path" that you'll find how to upload wherever you want. Sure, just use add_submenu_page() to create a page where you will list the contents of the target directory with images. On Google, use "what you want site:stackoverflow.com" and you'll find lots of code ready to use. Check the advanced search features here on Stack Overflow and at WordPress Development to find stuff too. Good luck!
If someone have similar problem, and want the upload destination to the root, you can use: get_home_path() instead of wp_upload_dir(), and then change change this line $target_file = $target_dir['path'] . '/' . basename($_FILES["fileToUpload"]["name"]); to $target_file = get_home_path() . '/' . basename($_FILES["fileToUpload"]["name"]);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.