I want to create a plugin that stores IP addresses in a database. Everything works perfectly - except the export function.
My problem: When I press the "Export IP addresses" button, a blank page with the title "WordPress > Error" appears.
Neither does WordPress show me an error on the page, nor does it write an error to my WordPress debug log file. My PHP error log file is also empty.
The only message I get is from the Chrome console (For privacy reasons I have replaced the first part of my URL with [myURL]:
POST [myURL]/wp-admin/admin-post.php 400 (Bad Request) admin-post.php:1
The form data (source code) that Chrome provides me with shows the following:
action=export_ip_addresses&_wpnonce=6b7733bed9&_wp_http_referer=%2Fwp-admin%2Fadmin.php%3Fpage%3Dbot-hunter-import-export
I don't need to mention that no download is triggered.
Now my source code:
I have created a form for this in bot-hunter-admin.php:
<form action="<?php echo esc_url(admin_url('admin-post.php')); ?>" method="post">
<input type="hidden" name="action" value="export_ip_addresses">
<?php wp_nonce_field('export_ips_nonce'); ?>
<input type="submit" value="<?php echo esc_attr__('IP-Adressen exportieren', 'bot-hunter');?>" class="button-primary">
</form>
The bot-hunter-import-export.php should take care of exporting this data to a CSV file:
class Bot_Hunter_Import_Export {
public function __construct() {
add_action('admin_post_export_ip_addresses', array($this, 'handle_export_ip_addresses'));
}
public function handle_export_ip_addresses() {
if (!wp_verify_nonce($_REQUEST['_wpnonce'], 'export_ips_nonce')) {
wp_die('Sicherheitsüberprüfung fehlgeschlagen.');
}
if (!current_user_can('manage_options')) {
wp_die('Sie haben nicht die erforderlichen Berechtigungen.');
}
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="ip-addresses-' . date('Y-m-d_H-i-s') . '.csv"');
$output = fopen('php://output', 'w');
fputcsv($output, array('IP', 'List', 'Type'));
global $wpdb;
$blacklist_ips = $wpdb->get_results("SELECT ip_address, 'blacklist' as list, type FROM {$wpdb->prefix}bot_hunter_blacklist");
foreach ($blacklist_ips as $ip) {
fputcsv($output, array($ip->ip_address, $ip->list, $ip->type));
}
$whitelist_ips = $wpdb->get_results("SELECT ip_address, 'whitelist' as list, 'N/A' as type FROM {$wpdb->prefix}bot_hunter_whitelist");
foreach ($whitelist_ips as $ip) {
fputcsv($output, array($ip->ip_address, $ip->list, $ip->type));
}
fclose($output);
exit;
}
I hope someone here can help me and give me a tip.
If further information is required, I will be happy to publish it here.
Many thanks in advance.
Oliver
I've already done a lot of research, but I'm at a loss as to where the error could lie.