Most of my plugins have an uninstall.php file.
This file runs when the plugin is deleted.
One of the security checks in said file needs to check if the request is actually for said plugin.
if ( ! defined( 'WP_UNINSTALL_PLUGIN' )
|| empty( $_REQUEST )
|| ! isset( $_REQUEST['plugin'] )
|| ! isset( $_REQUEST['action'] )
|| 'name-of-plugin-folder/name-of-plugin-main-file.php' !== $_REQUEST['plugin']
|| 'delete-plugin' !== $_REQUEST['action']
|| ! check_ajax_referer( 'updates', '_ajax_nonce' )
|| ! current_user_can( 'activate_plugins' )
) {
exit;
}
The problem with this is that’s hardcoded and when users rename the plugin, they can’t delete it anymore.
In all other files/actions like activation hook or deactivation hook you can use a Constant populated with plugin_basename( __FILE__ )
.
But of course this will not work in uninstall file, since no other file will run and thus you can’t define a constant, i.g. in the plugin main file, and use it in the uninstall.php
If using plugin_basename( __FILE__ )
inside the uninstall, it will not have the same value as is in $_REQUEST['plugin']
.
It returns plugin-folder-name/uninstall.php
, but the request value is plugin-folder-name/plugin-main-file.php
so…
- You can’t define a constant in main plugin file because that file is not even fired when uninstall is done.
- You can’t detect plugin base name as it returns wrong name inside the very uninstall.php
- But you need to check request is matching…
How do check if Request is indeed for my plugin in said file?
It seems not possible, unless hardcoding it, which then cause issues if a user renames the plugin folder name and tries to delete it after. They’ll have to keep the exact folder name I hardcode, and hardcode is bad anyway.
Would it be enough to just check for folder name (meaning, strip off the part after /
from plugin_basename( __FILE__ )
, then compare if that string is within the Request?
Or would it even be OK to fully omit plugin-folder/plugin-main.php !== $_REQUEST['plugin']
check?
(Note, most plugins I see do not check even for nonce in that file, but as far I know we should check if the request is really for our plugin, even when deleting it.)
Perhaps I am overthinking this one (too)