Rename a folder via HTML POST request

I am trying to rename a folder in the uploads folder if an HTML form is submitted (used to edit entry names).

This following code is what I have so far but it isn’t working.

if(isset($_POST['Edit_Client']) == '1')

{

rename("/wp-content/uploads/Directory/Clients/$Client_Name/", "/wp-content/uploads/Directory/Clients/$New_Name/");

}

I have tried changing the file permissions to 777 for the whole path, but that didn’t work.

I tried to require once wp-config and wp-settings but that didn’t work either

Many thanks in advance.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

In order to rename you have to alter your code like bellow. You code was missing absolute path of the directory. That’s why your code was not working. Adding ABSPATH will fix the code.

rename( ABSPATH . "wp-content/uploads/Directory/Clients/$Client_Name", ABSPATH . "wp-content/uploads/Directory/Clients/$New_Name" );

Why not you use WP_Filesystem_Direct. It’s better and fatal-safe. You can easily use that by including these to file to your functions.php

require_once(ABSPATH . '/wp-admin/includes/class-wp-filesystem-base.php');
require_once(ABSPATH . '/wp-admin/includes/class-wp-filesystem-direct.php');

Now from you given code, alter that like this:

if(isset($_POST['Edit_Client']) == '1'){
    $current = ABSPATH . "wp-content/uploads/Directory/Clients/$Client_Name";
    $destination = ABSPATH . "wp-content/uploads/Directory/Clients/$New_Name";

    WP_Filesystem_Direct::move($current,$destination);
}

WP_Filesystem_Direct will automatically check whatever approach will be better. It will try to rename first. If fails then It will make a copy and delete old folder.

Read more about WP_Filesystem_Direct::move & WP_Filesystem_Direct


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x